branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>Zorqe/DataMiningProjectCTU-13<file_sep>/KnnModel.py
import pandas as pd
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
dataFrameTrain = pd.read_csv('trainDataCombinedCaptureNewFeatureGenerated.csv')
dataFrameTest = pd.read_csv('testDataCombinedCaptureNewFeatureGenerated.csv')
#Mapping taken from tutorial https://www.kaggle.com/parasjindal96/how-to-normalize-dataframe-pandas
#Function to map strings and discretize for discretization
def mapping(data,feature):
featureMap=dict()
count=0
for i in sorted(data[feature].unique(),reverse=True):
featureMap[i]=count
count=count+1
data[feature]=data[feature].map(featureMap)
return data
#Function to normalize all data for similarity calculations is KNN
def normalizeData(dfTrain):
#Normalizing all values between 0 to 15
dfNormalized = ((dfTrain-dfTrain.min())/(dfTrain.max()-dfTrain.min()))*15
dfNormalized = dfNormalized.fillna(0)
return dfNormalized
#Function to predict the class of all entries using the KnnClassifier from Sikit-learn
#Returns the list of predictions
def knnPredict(k, dataFrameTest,dataFrameTrain):
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(dataFrameTrain.drop(['LabelDisc'],axis=1), dataFrameTrain['LabelDisc'])
predictions = knn.predict(dataFrameTest.drop(['LabelDisc'],axis=1))
return predictions
#Drop all columns which we won't use for training data, instead use their discretized values
print("Dropping cols to not train on")
dataFrameTrain = dataFrameTrain.drop(['StartTime','SrcAddr','DstAddr','SrcAddr_App','SrcDst_Sport_unique'], axis=1)
dataFrameTest = dataFrameTest.drop(['StartTime','SrcAddr','DstAddr','SrcAddr_App','SrcDst_Sport_unique'], axis=1)
print("Normalizing data")
dataFrameTrain = normalizeData(dataFrameTrain)
dataFrameTest = normalizeData(dataFrameTest)
#Predicting using the KNN model
k = 5
print("\nPredicting values with k value: " + str(k))
predictions = knnPredict(k, dataFrameTest, dataFrameTrain)
countMaliciousPredicted = np.count_nonzero(predictions == 15.0)
countBackgroundPredicted = np.count_nonzero(predictions == 0.0)
totalMalicious = np.count_nonzero(dataFrameTest['LabelDisc'] == 1)
print("The count of malicious predictions are: " + str( countMaliciousPredicted ) )
print("The count of background predictions are: " + str( countBackgroundPredicted ) )
#Calculating the accuracy
accuracy = accuracy_score(dataFrameTest['LabelDisc'], predictions) *100
print ("The accuracy is: " + str(accuracy)+"%")
correctlyClassified = 0
correctlyClassifiedBackground = 0
index = 0
for classification in list(dataFrameTest.LabelDisc):
if predictions[index] == classification and classification == 15.0:
correctlyClassified += 1
elif predictions[index] == classification and classification == 0.0:
correctlyClassifiedBackground += 1
index += 1
print("The number of correctly classified malicious predictions are: " + str(correctlyClassified))
print("The precision on malicious data classification is: {:0.2f}%\n".format( (correctlyClassified/countMaliciousPredicted)*100))
print("The recall on malicious data classification is: {:0.2f}%\n".format( (correctlyClassified/totalMalicious)*100))
print("The precision on benign data classification is: {:0.2f}%\n".format( (correctlyClassifiedBackground/countBackgroundPredicted)*100))<file_sep>/processData.py
import pandas as pd
import numpy as np
import os
import time
from pathlib import Path
from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder
"""
Input: All 13 binetflow CSV files for the CTU-13 Dataset (Local directory)
Output: Two files, the processed training data, and the processed testing data (Output directory)
Script to perform preprocessing on all 13 CSV files, then discretization, followed by feature generation
The final feature generated files are then merged as follows, training (scenario 1-8 and 11-13) and testing (scenario 9-10)
The merged files are the two final outputs provided by this script
"""
#------------------------------- Functions -----------------------------------------
#Deletes row's where the column values are null,nan,nat, or blank
def deleteNullRow(dataFrame, column):
newDataFrame = dataFrame
#dataframe dropna won't replace empty values only NaN and NaT so convert blank space to NaN then drop
newDataFrame[column].replace('', np.nan, inplace=True)
newDataFrame = newDataFrame.dropna(subset=[column])
return newDataFrame
# Partially inspired from: https://github.com/mgarzon/cybersec/blob/master/MalwareDetection.ipynb
def preprocessData(dataFrame):
'''
This function is used to perform
the necessary operations to
convert the raw data into a
clean data set.
'''
#Outputting number of rows and column names before preprocessing
print("----------Before pre-processing-----------")
print("Number of rows: " + str(len(dataFrame.index)))
print("The columns are: " + str(list(dataFrame)))
#dropping columns specified
listOfFeaturesToDrop = [
'Dir',
'sTos',
'dTos']
# Ignore columns that might not exist (ex. UNB dataset)
dataFrame = dataFrame.drop(listOfFeaturesToDrop, axis=1, errors="ignore")
#Dropping all null value rows from specified columns
dataFrame = deleteNullRow(dataFrame,'Sport')
dataFrame = deleteNullRow(dataFrame,'SrcAddr')
dataFrame = deleteNullRow(dataFrame,'Dport')
dataFrame = deleteNullRow(dataFrame,'DstAddr')
# TODO
#dp.convertColumnToTimeStamp(dataFrame,'StartTime') # ?? already a timestamp
#Outputting number of rows and column names after preprocessing
print("\n----------After pre-processing-----------")
print("Number of rows: " + str(len(dataFrame.index)))
print("The columns are: " + str(list(dataFrame)))
return dataFrame
#Function to perform discretization on the data
def discretizeData(dataFrame):
'''
This function is used discretize the data
'''
dfNew = dataFrame
# Binning technique from
# https://towardsdatascience.com/understanding-feature-engineering-part-1-continuous-numeric-data-da4e47099a7b
quantile_list = [0, .25, .5, .75, 1.] # Change the quantile_list for more or less accuracy
dfNew['TotBytesDisc'] = ""
dfNew['SrcBytesDisc'] = ""
dfNew['TotBytesDisc'] = pd.qcut(dataFrame['TotBytes'], quantile_list, duplicates='drop')
dfNew['SrcBytesDisc'] = pd.qcut(dataFrame['SrcBytes'], quantile_list, duplicates='drop')
# Bin Src/Dest port
# According to 0-1023(WELLKNOWN_PORTNUMBER)
# 1024-49151(REGISTERED_PORTNUMBER)
# 49152-65535(DYNAMIC_PORTNUMBER)
Sport = dataFrame['Sport']#[0x0303].astype('int64')
if(Sport.dtype != 'int64'):
Sport = Sport.apply(lambda x: int(x, 0)) # 0 as base means 10 will be converted to 10 and 0x10 will be converted to 16
dfNew['SportDisc'] = ""
dfNew['SportDisc'] = pd.cut(Sport, [0, 1023, 49151, 65535], duplicates='drop')
Dport = dataFrame['Dport']#[0x0303].astype('int64')
if(Dport.dtype != 'int64'):
Dport = Dport.apply(lambda x: int(x, 0))
dfNew['DportDisc'] = ""
dfNew['DportDisc'] = pd.cut(Dport, [0, 1023, 49151, 65535], duplicates='drop')
#LabelEncoder for unique values for Proto column and stored as column ProtoDisc
le = preprocessing.LabelEncoder()
le.fit(dfNew.Proto.unique())
dfNew["ProtoDisc"] = ""
dfNew.ProtoDisc = le.transform(dfNew.Proto)
#Encoding "label" column to "labelDisc"
#0 = Background/Normal 1=Botnet
dfNew["LabelDisc"] = ""
dfNew['LabelDisc'] = dfNew['Label']
dfNew['LabelDisc'] = dfNew.LabelDisc.replace(r'(^.*Background.*$)', '0')
dfNew['LabelDisc'] = dfNew.LabelDisc.replace(r'(^.*Normal.*$)', '0')
dfNew['LabelDisc'] = dfNew.LabelDisc.replace(r'(^.*Botnet.*$)', '1')
return dfNew
#helper function to count the distinct values of second column
#where SRCaddr's match in rolling window of size windowSize
def countDistinctMatchingForSrcAddr(sliceDF):
'''
This function is a helper function to perform the custom rolling window tasks
'''
SrcAddr = sliceDF["SrcAddr"].iloc[-1] #SrcAddr of the rolling window to calculate for
DstAddr = sliceDF["DstAddr"].iloc[-1]
returnData = pd.DataFrame()
srcAddrRows = sliceDF[sliceDF.SrcAddr == SrcAddr]
destAddrRows = sliceDF[sliceDF.DstAddr == DstAddr]
srcAndDestRows = srcAddrRows[srcAddrRows.DstAddr == DstAddr]
# SrcAddr statistics
returnData["SrcAddr_App"] = [srcAddrRows.shape[0]] #counting total SrcAddr matches
returnData["Src_Dport_unique"] = srcAddrRows.Dport.nunique() #only counting distinct dports by using set
returnData["Src_DstAddr_unique"] = srcAddrRows.DstAddr.nunique()
returnData["Src_Sport_unique"] = srcAddrRows.Sport.nunique()
returnData["Src_TotPkts_mean"] = srcAddrRows.TotPkts.mean()
returnData["Src_TotBytesDisc_mode"] = srcAddrRows.TotBytesDisc.mode() # not quite mean but close enough
# DstAddr statistics
returnData["DstAddr_App"] = [destAddrRows.shape[0]] #counting total DstAddr matches
returnData["Dst_Dport_unique"] = destAddrRows.Dport.nunique()
returnData["Dst_SrcAddr_unique"] = destAddrRows.SrcAddr.nunique()
returnData["Dst_Sport_unique"] = destAddrRows.Sport.nunique()
returnData["Dst_TotPkts_mean"] = destAddrRows.TotPkts.mean()
returnData["Dst_TotBytesDisc_mode"] = destAddrRows.TotBytesDisc.mode() # not quite mean but close enough
# Src+Dstaddr statistics
returnData["SrcDst_Sport_unique"] = srcAndDestRows.Sport.nunique()
returnData["SrcDst_Dport_unique"] = srcAndDestRows.Dport.nunique()
return returnData
#Function to generate connection based features for the source address
def generateSrcAddrFeaturesConnectionBased(dataFrame, windowSize):
dfNew = dataFrame
#How many times the SRCADDRESS has appeared within the last X netflows (SrcAddr_Dis)
#For any of the flow records that SRCADDRESS has appeared within the last X netflows, count the distinct destination ports (Src_Dist_Des_Port)
#For any of the flow records that SRCADDRESS has appeared within the last X netflows, count the distinct destination addresses (Src_Dist_Des_Addr)
#For any of the flow records that SRCADDRESS has appeared within the last X netflows, count the distinct source ports (Src_Dist_Src_Port)
#For any of the flow records that SRCADDRESS AND DSTADDRESS has appeared within the last X netflows, count the distinct source ports
#For any of the flow records that SRCADDRESS AND DSTADDRESS has appeared within the last X netflows, count the distinct destinations ports
#For any of the flow records that SRCADDRESS has appeared within the last X netflows, average the packets
#For any of the flow records that SRCADDRESS has appeared within the last X netflows, average the bytes
additionalCol = []
for i in range(windowSize - 1, len(dfNew.index) + 1):
#Feature generation feedback every 10000 generated rows
if (i%10000 == 0):
print(i)
window = dfNew[i - (windowSize-1):i+1]
slice_df = countDistinctMatchingForSrcAddr(window)
additionalCol.append(slice_df)
# Set the right index
newCol = pd.concat(additionalCol, axis=0)
del additionalCol
newCol.index = np.arange(windowSize - 1, windowSize + len(newCol) - 1)
dfNew = dfNew.join(newCol)
#Dropping beginning rows of size: windowsize since all the generated features are null
dfNew = deleteNullRow(dfNew, 'SrcAddr_App')
return dfNew
#Adjustment Function to further adjust generated features and label encode them to ensure consistency and good data
def adjustFeatures(df):
#Ensuring valid entries in Sport and Dport
df['Sport']=pd.to_numeric(df['Sport'], errors='coerce')
df['Dport']=pd.to_numeric(df['Dport'], errors='coerce')
#Removing invalid entries that've been converted to NaN
df = deleteNullRow(df,'Sport')
df = deleteNullRow(df,'Sport')
df = df.dropna()
stringColsToMap = ['TotBytesDisc','SrcBytesDisc','SportDisc','DportDisc','Src_TotBytesDisc_mode','Dst_TotBytesDisc_mode']
for col in stringColsToMap:
LE = LabelEncoder()
df[col] = LE.fit_transform(df[col])
#Drop the original cols which have already been label encoded
colsAlreadyLabelEncoded = ['Label','Proto']
df = df.drop(colsAlreadyLabelEncoded, axis=1)
return df
#Adjust merged data to maintain common quantile list ranges
def modifyMergedData(dataf):
dataFrame = dataf
#Drop all previous incorrectly computed columns
#Note: State is dropped and not recomputed --> Is not used for training
colsToDrop = ["State","TotBytesDisc","SrcBytesDisc","SportDisc","SportDisc","DportDisc","Src_TotBytesDisc_mode","Dst_TotBytesDisc_mode"]
dataFrame.drop(colsToDrop, axis=1, inplace=True, errors="ignore")
quantile_list = [0, .25, .5, .75, 1.] # Change the quantile_list for more or less accuracy
dataFrame['TotBytesDisc'] = ""
dataFrame['SrcBytesDisc'] = ""
dataFrame['TotBytesDisc'] = pd.qcut(dataFrame['TotBytes'], quantile_list, duplicates='drop')
dataFrame['SrcBytesDisc'] = pd.qcut(dataFrame['SrcBytes'], quantile_list, duplicates='drop')
#Label encode discretized byte vals
le = preprocessing.LabelEncoder()
le.fit(dataFrame.TotBytesDisc.unique())
dataFrame.TotBytesDisc = le.transform(dataFrame.TotBytesDisc)
le = preprocessing.LabelEncoder()
le.fit(dataFrame.SrcBytesDisc.unique())
dataFrame.SrcBytesDisc = le.transform(dataFrame.SrcBytesDisc)
dataFrame['SportDisc'] = ""
dataFrame['DportDisc'] = ""
dataFrame['SportDisc'] = pd.cut(dataFrame['Sport'],[0,1023,49151,65535],labels=[0,1,2])
dataFrame['DportDisc'] = pd.cut(dataFrame['Dport'],[0,1023,49151,65535],labels=[0,1,2])
return dataFrame
#Have all files to clean,discretize,featuregenerate in local directory
#Getting all .csv files(local directory) to be feature generated
localFiles = [file for file in os.listdir('.') if file.endswith(".csv")]
if len(localFiles) == 0:
print("No files to process. Exiting.")
exit()
testingIndexes = []
try:
# If these files are found, put them in testing data
testingIndex1 = localFiles.index("capture20110817.csv") #index of testing scenario 9
testingIndex2 = localFiles.index("capture20110818.csv") #index of testing scenario 10
testingIndexes = [testingIndex1, testingIndex2]
except ValueError:
# Only create training data
pass
# Perform preprocessing, discretizing, and feature generation on each file seperately
processedDataTraining = []
processedDataTesting = []
for scenarioNum,file in enumerate(localFiles):
print("Reading file: "+file)
dataFrame = pd.read_csv(file)
print("Preprocessing file: "+file)
dataFrame = preprocessData(dataFrame)
print("Discretizing file: "+file)
dataFrame = discretizeData(dataFrame)
print("Feature generating file: "+file)
#Window size 10,000
now = time.time()
dataFrame = generateSrcAddrFeaturesConnectionBased(dataFrame,10000)
dataFrame = adjustFeatures(dataFrame)
if scenarioNum in testingIndexes:
#Testing set
processedDataTesting.append(dataFrame)
else:
#Training set
processedDataTraining.append(dataFrame)
def writeToDisk(filename, data):
print("Merging scenario", filename)
dfOut = pd.concat(data)
del data
print("Adjusting merged data for", filename)
modifyMergedData(dfOut)
dfOut.to_csv(filename, encoding='utf-8', index=False)
print(filename + " Created")
#--------------------Outputting files--------------------------
dataFrameOutDir = Path("Output")
dataFrameOutDir.mkdir(parents=True, exist_ok=True)
writeToDisk(dataFrameOutDir / "finalTrainingData.csv", processedDataTraining)
if len(processedDataTesting) > 0:
writeToDisk(dataFrameOutDir / "finalTestingData.csv", processedDataTesting)<file_sep>/runModel.py
import pandas as pd
import os
import pickle
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier
from sklearn.svm import LinearSVC
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
"""
Input: Processed testing data (local directory) and the trained models
Output Display: Predicted classes with classification reports
Script to test all the models: AdaBoost, Gradient Boost, SVM, and Decision Tree
After predicting the classes for the test data the classification reports are printed
"""
#Load the testing dataframe
print("Loading testing data...")
test_dataFrame = pd.read_csv('Output/finalTestingData.csv')
#Dropping values that weren't trained on
test_dataFrame = test_dataFrame.drop(['StartTime','SrcAddr','DstAddr'], axis=1)
#Splitting up the test dataframe into one with only features, other with classifications
test_dataFrame_Classification = test_dataFrame[['LabelDisc']].copy()
test_dataFrame = test_dataFrame.drop(['LabelDisc'], axis=1)
#Getting vals to use for testing
test_data = test_dataFrame.values
test_data_class = test_dataFrame_Classification.values
test_features = test_data[0::]
test_results = test_data_class[0::,0]
#Testing
modelsFolder = "Models"
modelFileNames = [modelsFolder + "/" + file for file in os.listdir(modelsFolder) if file.endswith(".pkl")]
model = None
for model_filename in modelFileNames:
print("\n\nTesting using model "+model_filename+"...")
with open(model_filename, 'rb') as file:
model = pickle.load(file)
predictionClassification = model.predict(test_features)
print("Scikit-learn classification report: ")
print(classification_report(test_dataFrame_Classification.LabelDisc, predictionClassification))
print ('Accuracy = ' + str(accuracy_score(test_results, predictionClassification)) )<file_sep>/trainModel.py
import pandas as pd
import os
import pickle
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier
from sklearn.svm import LinearSVC
from sklearn import tree
from sklearn.ensemble import GradientBoostingClassifier
"""
Input: Processed training data (local directory)
Output: All trained machine learning models
Script to train all the models: AdaBoost, Gradient Boost, SVM, and Decision Tree
Outputs the saved models in a pickle formate to be used by runModel.py
"""
#Load the training dataframe
print("Loading training data...")
train_dataFrame = pd.read_csv('finalTrainingData.csv')
#Drop columns to not train on
print("Dropping columns not required for training...")
train_dataFrame = train_dataFrame.drop(['StartTime','SrcAddr','DstAddr'], axis=1)
#Training classes and data seperated
train_dataframe_Classification = train_dataFrame[['LabelDisc']].copy()
train_dataFrame = train_dataFrame.drop(['LabelDisc'], axis=1)
#Getting the values for the classes and the training data
train_data = train_dataFrame.values
train_data_labels = train_dataframe_Classification.values
#Storing the features to use in model as well as the classifications
train_features = train_data[0::]
train_labels = train_data_labels[0::,0]
#Creating all models to be trained on (except KNN)
models = [
["adaBoostModel", AdaBoostClassifier(RandomForestClassifier(n_estimators = 1000), algorithm="SAMME", n_estimators=500)],
["LinearSVCModel", LinearSVC(max_iter=4000)],
["CART", tree.DecisionTreeClassifier()],
["GradientBoost", GradientBoostingClassifier()]
]
#Training on all models and saving them locally
for modelToTrain in models:
modelName = modelToTrain[0]
model = modelToTrain[1]
print("\n\nModel training for model " + modelName + "...")
#Fit the training data to the model
model = model.fit(train_features, train_labels)
print("Saving model "+ modelName + "...")
model_filename = modelName + ".pkl"
with open(model_filename, 'wb') as file:
pickle.dump(model, file)<file_sep>/README.md
<NAME>
<NAME>
Google Drive File Download Link:
https://drive.google.com/drive/folders/114W78sGZ_F3vhY6IK1YwFu8GnXDMX5ty?usp=sharing
Includes:
- finalTestingData.csv (csv with the feature generated test data)
- finalTrainingData.csv (csv with the feature generated train data)
- adaBoostModel.pkl (Trained adaBoostModel)
- testingDataUNB.csv (UNB malware dataset converted into the CTU dataset format)
- testingDataUNB-filtered.csv (UNB malware dataset with only the Neris and Rbot botnets)
CTU-13 training set has bots:
- Neris
- Rbot
- e4f816462c4fc84bb250e2b1d295bf23_85f9a5247afbe51e64794193f1dd72eb_unpacked (unknown name)
- svchosta
- sogou_explorer_silent_1.4.0.418_2136
- QvodSetuPuls23
- 3d3d%3F%3F%3F%3F.xls
CTU-13 testing set has bots:
- Neris
- Rbot
UNB testing set has bots: (https://www.unb.ca/cic/datasets/botnet.html)
- Neris | IRC | 25967 (5.67%)
- Rbot | IRC | 83 (0.018%)
- Menti | IRC | 2878(0.62%)
- Sogou | HTTP | 89 (0.019%)
- Murlo | IRC | 4881 (1.06%)
- Virut | HTTP | 58576 (12.80%)
- NSIS | P2P | 757 (0.165%)
- Zeus | P2P | 502 (0.109%)
- SMTP Spam | P2P | 21633 (4.72%)
- UDP Storm | P2P | 44062 (9.63%)
- Tbot | IRC | 1296 (0.283%)
- Zero Access | P2P | 1011 (0.221%)
- Weasel | P2P | 42313 (9.25%)
- Smoke Bot | P2P | 78 (0.017%)
- Zeus Control (C&C) | P2P | 31 (0.006%)
- ISCX IRC bot | P2P | 1816 (0.387%)
They have neris and rbot in common.
| f7adfab6dcc9c380225e642149f025bc508637c2 | [
"Markdown",
"Python"
] | 5 | Python | Zorqe/DataMiningProjectCTU-13 | c19b7c7e72a030b033f4323ea6cded9248354b8c | abf19bd408ab1214170f5dc20e955cb73ce3dd42 | |
refs/heads/master | <file_sep># Pixabay
Android Studio Project. Search pictures (with JSON, from Pixabay)
<file_sep>package com.dev.marki.pixabay.Util;
/**
* Created by marki on 07.02.2018.
*/
public class Url {
private final String link ="https://pixabay.com/api/?key=7925845-047526e650d3691a10a353f31&q=";
private final String searchType ="&image_type=";
/*https://pixabay.com/en/photos/?pagi=4
&q=kitten&image_type=all&order=latest&cat=animals&min_width=15&min_height=15*/
}
| 6ea1dfd80a776a3fabc11d0578164b84641ae605 | [
"Markdown",
"Java"
] | 2 | Markdown | markiyurtdas/Pixabay | 482d3ca8f5f76d0fdebe66b14f1c8383d97d48d8 | 8048f274fa1473d01ef112e331258322da4e0fcd | |
refs/heads/master | <file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 03-05-2021 a las 21:54:36
-- Versión del servidor: 10.4.17-MariaDB
-- Versión de PHP: 8.0.2
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `estudiante`
--
CREATE DATABASE IF NOT EXISTS `estudiante` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
USE `estudiante`;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `tb_estudiante`
--
CREATE TABLE `tb_estudiante` (
`id_estudiante` int(11) NOT NULL,
`carnet_estudiante` varchar(6) DEFAULT NULL,
`nom_estudiante` varchar(30) DEFAULT NULL,
`ape_estudiante` varchar(30) DEFAULT NULL,
`edad_estudiante` int(3) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Volcado de datos para la tabla `tb_estudiante`
--
INSERT INTO `tb_estudiante` (`id_estudiante`, `carnet_estudiante`, `nom_estudiante`, `ape_estudiante`, `edad_estudiante`) VALUES
(1001, 'MP1234', 'MATEO', 'CERON', 18),
(1004, 'MP4012', 'MANUEL', 'MARTINEZ', 25);
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `tb_estudiante`
--
ALTER TABLE `tb_estudiante`
ADD PRIMARY KEY (`id_estudiante`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `tb_estudiante`
--
ALTER TABLE `tb_estudiante`
MODIFY `id_estudiante` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1005;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>package recursosEstudiante;
import java.sql.*;
public class ConexionCRUD {
/*ruta de la base de datos el servidor 127.0.0.1m el puerto 306
y el nomobre de la base de daos db_recursos_humanos*/
private final String servidor = "jdbc:mysql://127.0.0.1:3306/estudiante";
//Nombre del usuario (root por defecto) de la base de datos
private final String usuario = "root";
// clave del usuario de la bse de datos
private final String clave = "";
//libreria de mysql
private final String driverConector = "com.mysql.jdbc.Driver";
//opjeto de la clase connection del paquete java.sql
private static Connection conexion;
public ConexionCRUD(){
try{
Class.forName(driverConector); //levantar el driver
//establecer conexion
conexion= DriverManager.getConnection(servidor, usuario, clave);
}catch(ClassNotFoundException | SQLException e){
System.out.println("Conecion fallida! : " + e.getMessage());
}
}
public Connection getConnection(){
return conexion;
}
//metodo guardar
public static void guardarRegistros(String tabla, String campoTabla, String valoresCampos) {
//cargar conexion
ConexionCRUD conectar = new ConexionCRUD();
Connection cone = conectar.getConnection();
try{
//Definir la sentencia sql
String sqlQueryStmt = "INSERT INTO " + tabla + "(" + campoTabla + ") VALUES (" + valoresCampos + ");";
//Establecemos la comunicacion entre nuestra aplicacion java y la base de datos
Statement stmt;
stmt = cone.createStatement();
stmt.executeUpdate(sqlQueryStmt);//Ejecutar la sentencia sql
//cerrar el Statement y la conexion: se cierran en orden inverso de como se han abierto
stmt.close();
cone.close();
System.out.println("Registro guardado correctamente!");
}catch(SQLException e){
System.out.println(e.getMessage());
}
}
//metodo eliminar y actualizar
public void actualizarEliminarRegistro(String tabla, String valoresCamposNuevos, String condicion){
//cargar la conexion
ConexionCRUD conectar = new ConexionCRUD();
Connection cone = conectar.getConnection();
try{
Statement stmt;
String sqlQueryStmt;
//verificar que vaorescamposnuevos venga vacia y asi seleccionar si es borrar o actualizar registro
if(valoresCamposNuevos.isEmpty()){
sqlQueryStmt = "DELETE FROM " + tabla + " WHERE " + condicion + ";";
}else{
sqlQueryStmt = "UPDATE " + tabla + " SET " + valoresCamposNuevos + " WHERE " + condicion + ";";
}
stmt = cone.createStatement();
stmt.executeUpdate(sqlQueryStmt);
stmt.close();
cone.close();
}catch(SQLException ex){
System.out.println("Ha ocurrido el siguiente error: " + ex.getMessage());
}
}
//metodo para consultas
public static void desplegarRegistros(String tablaBuscar, String camposBuscar, String condicionBuscar) throws SQLException {
//cargar la conexion
ConexionCRUD conectar = new ConexionCRUD();
Connection cone = conectar.getConnection();
try{
Statement stmt;
String sqlQueryStmt;
if(condicionBuscar.equals("")){
sqlQueryStmt = "SELECT " + camposBuscar + " FROM " + tablaBuscar + ";";
}else{
sqlQueryStmt = "SELECT " + camposBuscar + " FROM " + tablaBuscar + " WHERE " + condicionBuscar;
}
stmt = cone.createStatement();
stmt.executeQuery(sqlQueryStmt);
//le indicamos que ejecute la consulta de la tabla y le pasamos por argumentos nuestra sentencia
try(ResultSet miResultSet = stmt.executeQuery(sqlQueryStmt)){
if(miResultSet.next()){ //ubica el cursor en la primera fila de la tabla de resultado
ResultSetMetaData metaData = miResultSet.getMetaData();
int numColumnas = metaData.getColumnCount(); //obtiene el numero de columnas de la consulta
System.out.println("<< REGISTROS ALMACENADOS >>");
System.out.println();
for(int i =1; i<= numColumnas; i++){
//muestra los titulos de las colimnas y %-s/t indica la separacion entre columnas
System.out.printf("%-20s\t" , metaData.getColumnName(i));
}
System.out.println();
do{
for(int i=1; i<=numColumnas; i++){
System.out.printf("%-20s\t" , miResultSet.getObject(i));
}
System.out.println();
}while(miResultSet.next());
System.out.println();
}else{
System.out.println("No se han encontrado registros");
}
miResultSet.close();
}finally{
stmt.close();
cone.close();
}
}catch(SQLException ex){
System.out.println("Ha ocurrido el siguiente error: " + ex.getMessage());
}
}
}
<file_sep>package recursosEstudiante;
import java.sql.SQLException;
import java.util.Scanner;
public class Delete {
Delete() throws SQLException{
Scanner leer = new Scanner(System.in);
ConexionCRUD utilerias = new ConexionCRUD();
System.out.println("\n<< ELIMINAR REGISTROS >>");
System.out.println("\nIngresa el id del registro: ");
String idContactoEliminar = leer.next();
//ingreso de datos para actualizar
String tabla="tb_estudiante";
String campos = "*";
String condicion = "id_estudiante = " + idContactoEliminar;
utilerias.desplegarRegistros(tabla, campos, condicion);
System.out.println("Precionar <<Y>> para comfirmar: ");
String confirmarBorrar = leer.next();
if("Y".equals(confirmarBorrar)){
/*Se le deja vacia para el metodo borrar acatualizarEliminarRegistro
envie solamente los parametros de tabla y condicion y poder eliminar*/
String valoresCamposNuevos = "";
utilerias.actualizarEliminarRegistro(tabla, valoresCamposNuevos, condicion);
System.out.println("Registro borrado satisfactoriamente");
}
MenuPrincipal.desplegarMenu();
}
}
| 69a9cd50005185f0ab70522e56b4f316d81df1b9 | [
"Java",
"SQL"
] | 3 | SQL | Morena-20/CRUD_Estudiantes | 1dac50f33f5ef6cc5fb5cdbb116cc0dc91d6a382 | 28ff82d2cb105322c871732ab3f7ad38b25d37f1 | |
refs/heads/master | <repo_name>ilkinzeynalli/ruby<file_sep>/veri_yapilari_odev.rb
ruby
====
#Stack veri yapisinin tanimi]
#LUtfen Html_orneklerini girdiginizde turkce karakter kullanmayin.Yok USC2 hatasi alirsiniz
class Stack
def initialize
@store = Array.new
end
def pop
return(@store.pop())
end
def push(element)
@store.push(element)
self
end
def size
return (@store.length())
end
def isEmpty?
return @store == Array.new
end
end
#Dosyamizdaki fonksiyonlarin filtirlenmes
def html_filtirle()
html_metni = File.open("html_ornek.html","r") do |dosya|
satirlar = dosya.readlines
end
html_metni = html_metni.join().to_s
duzenli_ifade = /(<.+?>)/
eslesme = html_metni.scan(duzenli_ifade)
filtir = []
eslesme.each do |filt|
filtir.push(filt)
end
puts("Html dosyasindaki taglarin filtirlenmis hali")
filtir = filtir.join(" ").split(" ")
dizi = []
filtir.each do |eleman|
if eleman.match(/<[^\/]+?>/) then
dizi.push(eleman)
end
end
print filtir
puts()
puts("HTML dosyamizda ki acik taglar:")
print dizi
puts()
print("Taglar dengelimi?---> Sonuc:")
puts(html_denge(filtir))
end
#Dosyamizdaki taglarin dengeli dengesiz olub olmamisini kontrol eder
def html_denge(taglar)
index = 0
s = Stack.new()
balanced = true
dizi = []
taglar.each do |eleman|
if eleman.match(/<[^\/]+?>/) then
dizi.push(eleman)
end
end
while (index < taglar.length() and balanced == true) do
tag = taglar[index]
if dizi.include?(tag) then
s.push(tag)
else
if s.isEmpty? then
balanced = false
else
top = s.pop()
if not matches(top,tag) then
balanced = false
end
end
end
index = index + 1
end
if balanced and s.isEmpty? then
return true
else
return false
end
end
def matches(openTag,closeTag)
open =["<html>","<head>","<title>","<body>","<center>","<hx>","<b>","<hr>","<p>","<pre","<dl>","<dt>","<ul>","<ol>","<br>"]
close =["</html>","</head>","</title>","</body>","</center>","</hx>","</b>","</hr>","</p>","</pre","</dl>","</dt>","</ul>","</ol>","</br>"]
return open.index(openTag) == close.index(closeTag)
end
def main
html_filtirle
end
main if __FILE__ == $PROGRAM_NAME
| 21da4374db58bc9bca8283021e9d91fd28ff651b | [
"Ruby"
] | 1 | Ruby | ilkinzeynalli/ruby | 3c78c7d91baf32a0603cf87348459e0d3934c752 | 72e6c9c7941c1aebc59c966a65347c1f97e880b0 | |
refs/heads/master | <file_sep>/*
input :
3
6
10
30
Output :
1
2
3
*/
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
//Complete this function
bool isprime(int n);
int exactly3Divisors(int N)
{
//Your code here
int c=1;
if(N<=3)
{
return 0;
}
for(int i=3;i<=sqrt(N);i++)
{
if (isprime(i) && (i*i)<=N)
{
c++;
}
}
return c;
}
bool isprime(int n)
{
int limit=(int)sqrt(n);
for(int i=2;i<=limit;i++)
{
if(n%i==0)
return false;
}
return true;
}
// { Driver Code Starts.
int main()
{
int T;
cin>>T;
while(T--)
{
int N;
cin>>N;
cout<<exactly3Divisors(N)<<endl;
}
return 0;
} // } Driver Code Ends
<file_sep>
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
//You need to complete this function
int digitsInFactorial(int N)
{
if(N<=1)
return 1;
else
{
double di=0;
for(int i=2;i<=N;i++)
{
di+=log10(i);
}
return floor(di)+1;
}
}
// { Driver Code Starts.
int main()
{
int T;
cin>>T;
while(T--)
{
int N;
cin>>N;
cout<<digitsInFactorial(N)<<endl;
}
return 0;
}
// } Driver Code Ends
| d41626d947fdf4eff6c9ddfdae11c8dbecb9f80a | [
"C++"
] | 2 | C++ | silentkillerforever/Geeks-for-Geeks | 545c8945674a7b63222ac732000d86e30fba8692 | 9a2592cca7a1604802be33b9ed3ce4f0c08a6d91 | |
refs/heads/master | <repo_name>xoofoo-xoops-themes/xdt_standard<file_sep>/language/french_iso/script.js
/* $Id: script.js 275 2010-05-24 10:00:13Z kris_fr $ */
/* Localization script */<file_sep>/README.md
xdt_standard
============
theme standard for xoops
| df2887aec3c19cb8f3b6b530f062f749462e23e8 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | xoofoo-xoops-themes/xdt_standard | fdb7322d504ce316023d9d10b59be5180249c9d6 | 9aa2e2c02d96a4798032a02f85d8f44bb70762c3 | |
refs/heads/master | <file_sep>const reverseWords = (str: String) =>
str
.split(" ")
.reduce((revStr: Array<String>, word: String) => [word, ...revStr], [])
.join(" ");
export default reverseWords;
<file_sep>import reverseWords from "./mod.ts";
console.log(reverseWords("This is fun"));
| 2379a809346d9acdb1ee320c344bb7d3583b4d21 | [
"TypeScript"
] | 2 | TypeScript | felipecrs/reverse-words | 19bbfbd20c8e3f3f173ab7bc76ccda0478b961c8 | 6d8843815146f928ea393bc90cbaaba119c433e1 | |
refs/heads/master | <file_sep>from setuptools import setup, find_packages
def load_requirements():
try:
with open("./requirements.txt") as f:
return [line.strip() for line in f.readlines()]
except FileNotFoundError:
print("WARNING: requirements.txt not found")
return []
setup(
name="toraw",
version="0.1.0",
description="",
author="<NAME>",
url="https://github.com/bwulff/toraw",
packages=["toraw"],
package_dir={"toraw": "src/toraw"},
include_package_data=True,
install_requires=load_requirements(),
entry_points="""
[console_scripts]
toraw=toraw:cli
""",
)<file_sep># Convert image files to RAW file (e.g. for Unity heightmaps)
This is a small Python script that will take a 1-channel image file (e.g. PNG) and converts it to a `.raw` file compatible for use in Unity e.g. for Terrain heightmaps.
<file_sep>import click
import numpy as np
from PIL import Image
from numpy import asarray
def convert(infile, outfile=None):
image = Image.open(infile)
data = asarray(image)
print(f"Image size: {data.shape}")
with open(outfile, 'wb') as f:
for y in range(data.shape[0]):
for x in range(data.shape[1]):
v = np.uint16(data[y][x])
f.write(v)
@click.command()
@click.argument("infile")
@click.option("--outfile", default=None, help="specify output filename (default: replace filename extension with .raw)")
def cli(infile, outfile):
if outfile is None:
parts = infile.split('.')
parts[-1] = "raw"
outfile = ".".join(parts)
convert(infile, outfile) | 9b5afc9dba1ef1dd15b016e5d4ab50a15c126cfe | [
"Markdown",
"Python"
] | 3 | Python | bwulff/toraw | fe89297b61578741d81742bdbc302cb20769296d | d66d0f20392abbd23943ce636ebfca3959fc1434 | |
refs/heads/master | <file_sep>/**
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.redisson.api;
import java.util.concurrent.ScheduledExecutorService;
/**
* Distributed implementation of {@link java.util.concurrent.ScheduledExecutorService}
*
* @author <NAME>
*
*/
public interface RScheduledExecutorService extends RExecutorService, ScheduledExecutorService, RScheduledExecutorServiceAsync {
/**
* Cancels scheduled task by id
*
* @see RScheduledFuture#getTaskId()
*
* @param taskId
* @return
*/
boolean cancelScheduledTask(String taskId);
}
| ee9ff621c8e4cd1724efca4544012928581c01e8 | [
"Java"
] | 1 | Java | albertogoya/redisson | 2f797e2c1f09c1d16d48712315b2b6558443191d | cb344c7cc4a93c87b37ed6e8eac2cafefdd85a91 | |
refs/heads/master | <repo_name>ashmoran/language_implementation_patterns<file_sep>/Gemfile
source 'http://rubygems.org'
ruby '1.9.3'
gem 'facets'
gem 'treetop'
group :development do
gem 'guard'
gem 'listen'
gem 'rb-fsevent'
gem 'growl'
gem 'terminal-notifier-guard'
gem 'cucumber'
gem 'guard-cucumber'
gem 'aruba'
gem 'rspec'
gem 'guard-rspec'
gem 'fuubar'
gem 'fakefs'
gem 'lstrip-on-steroids'
gem 'pry'
gem 'awesome_print'
end
<file_sep>/spec/1_getting_started/ch02_basic_parsing/p04_llk_recursive_descent_parser/list_parser_with_assignment_spec.rb
require 'spec_helper'
require '1_getting_started/ch02_basic_parsing/p04_llk_recursive_descent_parser/list_parser_with_assignment'
require '1_getting_started/ch02_basic_parsing/p04_llk_recursive_descent_parser/lexer_lookahead'
require '1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/list_lexer'
require_relative '../p03_ll1_recursive_descent_parser/list_parser_contract'
require_relative 'list_parser_assignment_contract'
module GettingStarted
module BasicParsing
module LLkRecursiveDescentParser
describe "Intergration:", ListParserWithAssignment, "and lexer" do
let(:input) { "[ a = b ]" }
let(:lexer) { LL1RecursiveDescentLexer::ListLexer.new(input) }
let(:lookahead) { LexerLookahead.new(lexer) }
subject(:parser) { ListParserWithAssignment.new(lookahead) }
it "parses lists with assignments" do
expect(parser.list).to be == [ { :a => :b } ]
end
end
describe ListParserWithAssignment do
let(:tokens) {
LL1RecursiveDescentLexer::Token.descriptions_to_tokens(token_descriptions)
}
let(:lexer) { tokens.each }
let(:lookahead) { LexerLookahead.new(lexer) }
subject(:parser) { ListParserWithAssignment.new(lookahead) }
it_behaves_like "a ListParser"
it_behaves_like "a ListParser with assignment"
end
end
end
end<file_sep>/lib/2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/variable_symbol.rb
module AnalyzingLanguages
module TrackingSymbols
module MonolithicScope
class VariableSymbol
attr_reader :name, :type
def initialize(name, type)
@name = name.to_sym
@type = type
end
def ==(other)
other.is_a?(VariableSymbol) &&
@name == other.name &&
@type == other.type
end
def to_s
"<#{@name}:#{@type}>"
end
end
end
end
end<file_sep>/lib/1_getting_started/ch03_enhanced_parsing/p06_memoizing_parser/memoizing_list_parser.rb
require '1_getting_started/errors'
# UNFINISHED!!!
#
# I got bored of this - it's a big refactoring for a relatively minor change,
# and I'm not primarily concerned with how to implement parsers. But I've left
# the unfunished code here in case I decide to return to it some time.
# It passes all the tests :)
module GettingStarted
module EnhancedParsing
module MemoizingParser
class MemoizingListParser
def initialize(replayable_lexer)
@lexer = replayable_lexer
end
def stat
if speculate_stat_list
stat_list
elsif speculate_stat_parallel_assigment
stat_parallel_assignment
else
raise NoViableAlternativeError.new("Expecting <list> or <parallel assignment>")
end
end
def speculate_stat_list
@lexer.speculate do
stat_list
end
rescue RecognitionError => e
false
end
def speculate_stat_parallel_assigment
@lexer.speculate do
stat_parallel_assignment
end
rescue RecognitionError => e
false
end
def stat_list
matched_list = list
match(:eof)
matched_list
end
def stat_parallel_assignment
matched_parallel_assigment = parallel_assignment
match(:eof)
matched_parallel_assigment
end
def list
failed = false
@lexer.if_speculating do
return if already_parsed?(:list)
end
parsed_list = _list
@lexer.if_speculating do
memoize(:list, parsed_list)
end
parsed_list
rescue RecognitionError => e
@lexer.if_speculating do
memoize_failure(:list)
end
raise
end
def _list
[ ].tap do |collected_list|
match(:lbrack)
elements(collected_list)
match(:rbrack)
end
end
def parallel_assignment
lhs = list
match(:equals)
rhs = list
{ lhs => rhs }
end
def elements(collected_list)
first_element(collected_list)
while @lexer.peek.type == :comma
match(:comma)
element(collected_list)
end
end
def first_element(collected_list)
case @lexer.peek.type
when :name, :lbrack
element(collected_list)
when :rbrack
return
else
raise RecognitionError.new(
"Expected :lbrack, :name or :rbrack, found #{@lexer.peek.inspect}"
)
end
end
def element(collected_list)
if @lexer.peek(1).type == :name && @lexer.peek(2).type == :equals
lhs, _, rhs = match(:name), match(:equals), match(:name)
collected_list << { lhs.value.to_sym => rhs.value.to_sym }
elsif @lexer.peek.type == :name
collected_list << @lexer.peek.value.to_sym
match(:name)
elsif @lexer.peek.type == :lbrack
collected_list << list
else
raise RecognitionError.new(
"Expected :name or :lbrack, found #{@lexer.peek.inspect}"
)
end
end
private
def already_parsed?(expression_type)
false
end
def memoize(expression_type, expression)
expression
end
def memoize_failure(expression_type)
nil
end
def match(expected_type)
if @lexer.peek.type == expected_type
consume
else
raise RecognitionError.new(
"Expected #{expected_type.inspect}, found #{@lexer.peek.inspect}"
)
end
end
def consume
@lexer.next
end
end
end
end
end
<file_sep>/spec/2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/language_symbol_spec.rb
require 'spec_helper'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/language_symbol'
module AnalyzingLanguages
module TrackingSymbols
module MonolithicScope
describe LanguageSymbol do
subject(:symbol) { LanguageSymbol.new(:foo) }
its(:to_s) { should be == "foo" }
describe "#==" do
example do
expect(symbol).to be == LanguageSymbol.new(:foo)
end
example do
expect(symbol).to be == LanguageSymbol.new("foo")
end
example do
expect(symbol).to_not be == LanguageSymbol.new(:bar)
end
example do
expect(symbol).to_not be == :foo
end
end
describe "#name" do
its(:name) { should be == :foo }
it "is always a symbol" do
expect(LanguageSymbol.new("foo").name).to be == :foo
end
end
end
end
end
end<file_sep>/lib/2_analyzing_languages/ch06_tracking_symbols/p17_nested_scopes/cymbol2.rb
require_relative 'cymbol2_parser'
module AnalyzingLanguages
module TrackingSymbols
module NestedScopes
class Cymbol2
def initialize
@parser = CymbolNestedParser.new
end
def parse(source)
@parser.parse(source)
end
end
end
end
end<file_sep>/lib/2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/language_symbol.rb
module AnalyzingLanguages
module TrackingSymbols
module MonolithicScope
class LanguageSymbol
attr_reader :name
def initialize(name)
@name = name.to_sym
end
def ==(other)
other.is_a?(LanguageSymbol) && @name == other.name
end
def to_s
@name.to_s
end
end
end
end
end<file_sep>/spec/2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/symbol_table_spec.rb
require 'spec_helper'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/symbol_table'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/language_symbol'
module AnalyzingLanguages
module TrackingSymbols
module MonolithicScope
describe SymbolTable do
subject(:symbol_table) { SymbolTable.new }
describe "#define" do
it "ignores metadata" do
expect {
symbol_table.define(LanguageSymbol.new(:foo), unused: "stuff")
}.to_not raise_error(ArgumentError)
end
end
describe "#resolve" do
context "undefined symbol" do
specify {
expect {
symbol_table.resolve("foo")
}.to raise_error(RuntimeError, "Unknown symbol: foo")
}
it "ignores metadata" do
expect {
symbol_table.resolve("foo", unused: "stuff")
}.to_not raise_error(ArgumentError)
end
end
context "defined symbol" do
let(:symbol) { LanguageSymbol.new(:foo) }
before(:each) do
symbol_table.define(symbol)
end
specify {
expect(symbol_table.resolve("foo")).to equal(symbol)
}
specify {
expect(symbol_table.resolve(:foo)).to equal(symbol)
}
end
end
describe "#to_s" do
before(:each) do
symbol_table.define(LanguageSymbol.new(:foo))
symbol_table.define(LanguageSymbol.new(:bar))
symbol_table.define(LanguageSymbol.new(:baz))
end
it "outputs in alphabetic order" do
expect(symbol_table.to_s).to be ==
"globals: {bar=bar, baz=baz, foo=foo}"
end
end
end
end
end
end<file_sep>/spec/1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/list_lexer_contract.rb
require_relative 'enumerator_contract'
module GettingStarted
module BasicParsing
module LL1RecursiveDescentLexer
shared_examples_for "a ListLexer" do
def tokenize_all_input
begin
loop do
collected_output << lexer.next
end
rescue StopIteration => e
end
end
describe "#peek" do
let(:input) { "[a]" }
it "lets you see the next character" do
expect {
lexer.next
}.to change {
lexer.peek
}.from(Token.new(lbrack: "[")).to(Token.new(name: "a"))
end
end
describe "Enumerator-like properties" do
let(:input) { "" }
def advance_to_end
lexer.next
end
it_behaves_like "an Enumerator"
end
context "valid input" do
before(:each) do
tokenize_all_input
end
context "empty string" do
let(:input) { "" }
it "marks the end of the tokens explicitly" do
expect(output).to be == [ { eof: nil } ]
end
end
context "blank string" do
context "spaces, tabs, newlines" do
let(:input) { " " }
specify {
expect(output).to be == [ { eof: nil } ]
}
end
end
context "lbrack" do
let(:input) { "[" }
specify {
expect(output).to be == [ { lbrack: "[" }, { eof: nil } ]
}
end
context "comma" do
let(:input) { "," }
specify {
expect(output).to be == [ { comma: "," }, { eof: nil } ]
}
end
context "equals" do
let(:input) { "=" }
specify {
expect(output).to be == [ { equals: "=" }, { eof: nil } ]
}
end
context "rbrack" do
let(:input) { "]" }
specify {
expect(output).to be == [ { rbrack: "]" }, { eof: nil } ]
}
end
context "names" do
context "single letter" do
let(:input) { "a" }
specify {
expect(output).to be == [ { name: "a" }, { eof: nil } ]
}
end
context "multi-letter" do
let(:input) { "abcdefghijklmnopqrstuvwxyz" }
specify {
expect(output).to be == [ { name: "abcdefghijklmnopqrstuvwxyz" }, { eof: nil } ]
}
end
context "in a list" do
let(:input) { "[ a, xyz, bc ]" }
specify {
expect(output).to be == [
{ lbrack: "[" },
{ name: "a" },
{ comma: "," },
{ name: "xyz" },
{ comma: "," },
{ name: "bc" },
{ rbrack: "]" },
{ eof: nil }
]
}
end
end
context "delimiters, separators, and spaces" do
let(:input) { " [ \t, \n, ] \n" }
specify {
expect(output).to be == [
{ lbrack: "[" }, { comma: "," }, { comma: "," }, { rbrack: "]" }, { eof: nil }
]
}
end
end
context "invalid input" do
context "invalid characters" do
context "in normal context" do
let(:input) { "@" }
specify {
expect { tokenize_all_input }.to raise_error(ArgumentError, "Invalid character: @")
}
end
context "in a name" do
let(:input) { "a$"}
specify {
expect { tokenize_all_input }.to raise_error(ArgumentError, "Invalid character: $")
}
end
end
end
end
end
end
end<file_sep>/lib/2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/cymbol.rb
require 'treetop'
module AnalyzingLanguages; module TrackingSymbols; module MonolithicScope; end; end; end
Treetop.load(File.dirname(__FILE__) + '/cymbol_monolithic')
require_relative 'cymbol_monolithic_node_classes'
module AnalyzingLanguages
module TrackingSymbols
module MonolithicScope
# Implements Pattern 16: Symbol Table for Monolithic Scope
#
# Note that this is more of an experimental playground than a translation
# of the example in the book. Key points:
#
# * I'm using Treetop, not ANTLR. Mainly because I wanted to learn an
# implementation of Parsing Expression Grammars (mentioned on p56),
# and because Treetop works well in all Ruby runtimes, whereas ANTLR
# needs JRuby if you want access to the latest version. (The Ruby
# target lags behind the Java, C, C++ targets etc.)
#
# * The book produces output with code blocks in the ANTLR grammar.
# I wanted to avoid hijacking the predicate system in Treetop, so the
# way I solve it is closer to Pattern 25: Tree-Based Interpreter. Note
# that it's not a very *good* interpreter, but it does the job of
# spitting out the output we want (or something close enough to it).
class Cymbol
def initialize(symbol_table)
@symbol_table = symbol_table
@parser = CymbolMonolithicParser.new
end
def parse(source)
populate_symbols(tree(source))
end
private
def tree(source)
@parser.parse(source)
end
def populate_symbols(tree)
tree.populate_symbols(@symbol_table)
end
end
end
end
end<file_sep>/lib/2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/symbol_table.rb
module AnalyzingLanguages
module TrackingSymbols
module MonolithicScope
class SymbolTable
def initialize
@symbols = { }
end
def define(symbol, metadata = { })
@symbols[symbol.name] = symbol
end
def resolve(name, metadata = { })
@symbols.fetch(name.to_sym) {
raise "Unknown symbol: #{name}"
}
end
def to_s
"globals: {#{key_value_pairs.join(", ")}}"
end
private
def key_value_pairs
@symbols.keys.sort.map { |key| "#{key}=#{@symbols[key]}" }
end
end
end
end
end<file_sep>/spec/2_analyzing_languages/ch06_tracking_symbols/p17_nested_scopes/method_symbol_spec.rb
require 'spec_helper'
require '2_analyzing_languages/ch06_tracking_symbols/p17_nested_scopes/method_symbol'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/language_symbol'
module AnalyzingLanguages
module TrackingSymbols
module NestedScopes
describe MethodSymbol do
let(:type) { LanguageSymbol.new(:type) }
subject(:symbol) { MethodSymbol.new(:name, type) }
its(:to_s) { should be == "method<name:type>" }
describe "#==" do
example do
expect(symbol).to be == MethodSymbol.new(:name, type)
end
example do
expect(symbol).to be == MethodSymbol.new("name", type)
end
example do
expect(symbol).to_not be == MethodSymbol.new(:bar, type)
end
example do
expect(symbol).to_not be == MethodSymbol.new(:name, LanguageSymbol.new(:wrong_type))
end
example do
expect(symbol).to_not be == :name
end
end
describe "#name" do
its(:name) { should be == :name }
it "is always a symbol" do
expect(MethodSymbol.new("name", :ununused_type).name).to be == :name
end
end
end
end
end
end<file_sep>/lib/1_getting_started/ch02_basic_parsing/p04_llk_recursive_descent_parser/lexer_lookahead.rb
module GettingStarted
module BasicParsing
module LLkRecursiveDescentParser
# Helps implement Pattern 4: LL(k) Recursive-Descent Parser
#
# Major differences from the book example:
#
# * This isn't actually LL(k) because there isn't a fixed size _k_ for
# the lookahead buffer (the book example uses a small circular buffer).
# It's so easy to implement this by shifting a Ruby Array I went with
# the idiomatic solution rather than the memory-efficient one. I'm not
# too bothered about this from a learning point of view because I only
# care about what this does, not how to implement it efficiently.
#
# * This solution uses a separate object rather than rolling the lookahead
# code into the Parser. The code below could be used to add lookahead to
# any lexer, and can feed any parser, even a non-lookahead one (it
# conforms to the ListLexer contract).
class LexerLookahead
def initialize(lexer)
@lexer = lexer
@lexer_empty = false
@buffer = [ ]
end
def peek(lookahead_distance = 1)
fill_buffer(lookahead_distance)
token_or_stop_iteration(@buffer[lookahead_distance - 1])
end
def next
fill_buffer(1)
consume
end
private
def consume
token_or_stop_iteration(@buffer.shift)
end
def fill_buffer(required_size)
(required_size - @buffer.size).times do
harvest
end
end
def harvest
@buffer << @lexer.next
rescue StopIteration
def self.harvest
# NOOP
end
def self.token_or_stop_iteration(token)
raise StopIteration if token.nil?
token
end
end
def token_or_stop_iteration(token)
token
end
end
end
end
end<file_sep>/lib/1_getting_started/ch02_basic_parsing/p04_llk_recursive_descent_parser/list_parser_with_assignment.rb
require '1_getting_started/errors'
module GettingStarted
module BasicParsing
module LLkRecursiveDescentParser
# Implements Pattern 4: LL(k) Recursive-Descent Parser
# (Needs the help of the LexerLookahead)
#
# Major differences from the book example:
#
# * I put the code for the lookahead in a separate class (the rest of
# the discussion is in the LexerLookahead code)
class ListParserWithAssignment
def initialize(lookahead_lexer)
@lexer = lookahead_lexer
end
def list
[ ].tap do |collected_list|
match(:lbrack)
elements(collected_list)
match(:rbrack)
end
end
def elements(collected_list)
first_element(collected_list)
while @lexer.peek.type == :comma
match(:comma)
element(collected_list)
end
end
def first_element(collected_list)
case @lexer.peek.type
when :name, :lbrack
element(collected_list)
when :rbrack
return
else
raise RecognitionError.new(
"Expected :lbrack, :name or :rbrack, found #{@lexer.peek.inspect}"
)
end
end
def element(collected_list)
if @lexer.peek(1).type == :name && @lexer.peek(2).type == :equals
lhs, _, rhs = match(:name), match(:equals), match(:name)
collected_list << { lhs.value.to_sym => rhs.value.to_sym }
elsif @lexer.peek.type == :name
collected_list << @lexer.peek.value.to_sym
match(:name)
elsif @lexer.peek.type == :lbrack
collected_list << list
else
raise RecognitionError.new(
"Expected :name or :lbrack, found #{@lexer.peek.inspect}"
)
end
end
private
def match(expected_type)
if @lexer.peek.type == expected_type
consume
else
raise RecognitionError.new(
"Expected #{expected_type.inspect}, found #{@lexer.peek.inspect}"
)
end
end
def consume
@lexer.next
end
end
end
end
end<file_sep>/spec/1_getting_started/ch02_basic_parsing/p04_llk_recursive_descent_parser/lexer_lookahead_spec.rb
require 'spec_helper'
require '1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/list_lexer'
require '1_getting_started/ch02_basic_parsing/p04_llk_recursive_descent_parser/lexer_lookahead'
require_relative '../p02_ll1_recursive_descent_lexer/list_lexer_contract'
module GettingStarted
module BasicParsing
module LLkRecursiveDescentParser
shared_examples_for "LexerLookahead#peek" do
example do
expect(lexer.peek.value).to be == "["
end
example do
expect(lexer.peek(1).value).to be == "["
end
example do
expect(lexer.peek(2).value).to be == "a"
end
example do
expect(lexer.peek(5).value).to be == "]"
end
example do
expect(lexer.peek(6).to_hash).to be == { eof: nil }
end
example do
expect { lexer.peek(7) }.to raise_error(StopIteration)
end
end
describe LexerLookahead do
describe "lookahead" do
let(:tokens) {
LL1RecursiveDescentLexer::Token.descriptions_to_tokens(
[
{ lbrack: "[" },
{ name: "a" },
{ equals: "=" },
{ name: "b" },
{ rbrack: "]" },
{ eof: nil }
]
)
}
let(:underlying_lexer) { tokens.each }
subject(:lexer) { LexerLookahead.new(underlying_lexer) }
describe "#peek" do
it_behaves_like "LexerLookahead#peek"
end
end
context "wrapping a ListLexer" do
let(:input) { "[ a = b ]" }
let(:underlying_lexer) { LL1RecursiveDescentLexer::ListLexer.new(input) }
subject(:lexer) { LexerLookahead.new(underlying_lexer) }
let(:collected_output) { [ ] }
let(:output) {
collected_output.map { |token| token.to_hash }
}
it_behaves_like "a ListLexer"
describe "#peek" do
it_behaves_like "LexerLookahead#peek"
end
end
end
end
end
end<file_sep>/lib/2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/symbol_table_logger.rb
module AnalyzingLanguages
module TrackingSymbols
module MonolithicScope
# A Decorator for SymbolTable
#
# Note this makes the questionable decision of only logging if location
# metadata is available. Arguable we should have distinct #resolve_at_location
# and #define_at_location methods to be used by clients (I haven't thought
# this through though).
class SymbolTableLogger
def initialize(symbol_table, output_io)
@symbol_table = symbol_table
@output_io = output_io
end
def resolve(symbol_name, metadata = { })
@symbol_table.resolve(symbol_name).tap do |symbol|
log("ref", symbol, metadata)
end
rescue RuntimeError => e # Eek! Seems we were using too geneneral an error class...
log("ref [failed]", symbol_name, metadata)
end
def define(symbol, metadata = { })
log("def", symbol, metadata)
@symbol_table.define(symbol)
end
# Hacked in as part of the NestedScopes code...
# I'm not taking too much care to refactor now
def define_as_scope(symbol, metadata = { })
log("defscope", symbol, metadata)
@symbol_table.define_as_scope(symbol)
end
# Also hacked in
def push_scope
@symbol_table.push_scope
end
# And this
def pop_scope
@symbol_table.pop_scope
end
private
def log(event, item, metadata)
@output_io.puts("#{metadata[:location]}: #{event} #{item}")
end
end
end
end
end<file_sep>/spec/2_analyzing_languages/ch06_tracking_symbols/p17_nested_scopes/cymbol2_parser_spec.rb
require 'spec_helper'
require '2_analyzing_languages/ch06_tracking_symbols/p17_nested_scopes/cymbol2_parser'
RSpec::Matchers.define :parse do
match do |source|
parser.parse(source)
end
end
module AnalyzingLanguages
module TrackingSymbols
module NestedScopes
describe CymbolNestedParser do
subject(:parser) { CymbolNestedParser.new }
# If something goes wrong in here, we're missing a focused example!
describe "a complex program" do
example do
expect(<<-C).to parse
// intro comment
int i = 9;
float j;
int k = i+2;
float f(int x, float y)
{
float i;
{ float z = x+y; i = z; }
return i;
}
void g()
{
f(i, 2);
}
C
end
end
describe "empty program" do
example do
expect("").to parse
end
example do
expect(" ").to parse
end
example do
expect(" \n").to parse
end
example do
expect("\t\t\t").to parse
end
example do
expect("\n\n\n").to parse
end
example do
expect("\n \n\t\n").to parse
end
end
describe "comments" do
example do
expect("// this is a comment\n").to parse
end
example do
expect("// this is a comment").to parse
end
example do
expect(" // this is a comment").to parse
end
end
describe "variable declaration" do
context "without initialization" do
example do
expect("int foo;").to parse
end
example do
expect("int foo ;").to parse
end
example do
expect("float foo;").to parse
end
end
context "with initialization" do
context "to a literal" do
example do
expect("int foo=99;").to parse
end
example do
expect("int foo = 99 ;").to parse
end
end
context "to a variable" do
example do
expect("int foo = x;").to parse
end
end
context "to an arbitrary expression" do
example do
expect("int foo = x + 1;").to parse
end
example do
expect("int foo = x+1;").to parse
end
end
end
end
describe "assignment" do
example do
expect("foo=bar;").to parse
end
example do
expect("foo = bar;").to parse
end
example do
expect("foo = 1;").to parse
end
end
describe "blocks" do
example do
expect("{}").to parse
end
example do
expect("{ }").to parse
end
example do
expect("{ int i; }").to parse
end
example do
expect("{ int i; x = y; }").to parse
end
example do
expect("{
int i;
x = y;
}").to parse
end
example do
expect("{ x = a + b; }").to parse
end
describe "nested" do
example do
expect("{{}}").to parse
end
example do
expect("{ { } }").to parse
end
example do
expect("{
int i;
{
float k;
}
}").to parse
end
end
end
describe "methods" do
describe "definitions" do
example do
expect("int foo(){}").to parse
end
example do
expect("int foo() { }").to parse
end
example do
expect("int foo()\n{ }").to parse
end
example do
expect("int foo(int x) { }").to parse
end
example do
expect("int foo(int x, float y) { }").to parse
end
example do
expect("int foo( int x ,float y ) { }").to parse
end
example do
expect("float f() { int i; }").to parse
end
example do
expect("float f() { return a + b; }").to parse
end
end
describe "calls" do
example do
expect("foo();").to parse
end
example do
expect("foo( ) ;").to parse
end
example do
expect("f(a);").to parse
end
example do
expect("f(a, b);").to parse
end
example do
expect("f(a, b + 1);").to parse
end
end
end
end
end
end
end<file_sep>/lib/1_getting_started/ch03_enhanced_parsing/p05_backtracking_parser/replayable_buffer.rb
require 'forwardable'
module GettingStarted
module EnhancedParsing
module BacktrackingParser
class ReplayableBuffer
extend Forwardable
def_delegator :@buffer, :[]
def_delegator :@buffer, :size
def_delegator :@buffer, :<<
def_delegator :@buffer, :shift
class ArrayProxy
def initialize(buffer = [ ])
@buffer = buffer
end
# Queries
def [](index)
@buffer[index]
end
def size
@buffer.size
end
# Commands
def <<(object)
@buffer << object
end
def shift
@buffer.shift
end
# Support
def dup
ArrayProxy.new(@buffer.dup)
end
def unwrap
raise RuntimeError.new("No mark has been set")
end
end
class TimeMachine
def initialize(buffer, snapshot = nil)
@buffer = buffer
@snapshot = snapshot || buffer.dup
end
# Queries
def [](index)
@snapshot[index]
end
def size
@snapshot.size
end
# Commands
def <<(object)
@snapshot << object
@buffer << object
end
def shift
@snapshot.shift
end
# Support
def dup
TimeMachine.new(self, @snapshot.dup)
end
def unwrap
@buffer
end
end
def initialize
@buffer = ArrayProxy.new
end
def mark
@buffer = TimeMachine.new(@buffer)
end
def release
@buffer = @buffer.unwrap
end
end
end
end
end
<file_sep>/lib/1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/token.rb
module GettingStarted
module BasicParsing
module LL1RecursiveDescentLexer
class Token
attr_reader :type, :value
class << self
def descriptions_to_tokens(descriptions)
descriptions.map { |description| Token.new(description) }
end
end
def initialize(description)
@type = description.keys.first
@value = description.values.first
end
def to_hash
{ @type => @value }
end
def inspect
@type.inspect
end
def ==(other)
@type == other.type && @value == other.value
end
end
end
end
end<file_sep>/spec/1_getting_started/ch03_enhanced_parsing/p05_backtracking_parser/replayable_buffer_spec.rb
require 'spec_helper'
require '1_getting_started/ch03_enhanced_parsing/p05_backtracking_parser/replayable_buffer'
module GettingStarted
module EnhancedParsing
module BacktrackingParser
describe ReplayableBuffer do
subject(:buffer) { ReplayableBuffer.new }
context "used without marking" do
describe "#[]" do
example do
expect(buffer[0]).to be_nil
expect(buffer[1]).to be_nil
expect(buffer[2]).to be_nil
expect(buffer[-1]).to be_nil
end
example do
buffer << :a
buffer << :b
expect(buffer[0]).to be == :a
expect(buffer[1]).to be == :b
expect(buffer[2]).to be_nil
expect(buffer[-1]).to be == :b
end
end
describe "#shift" do
example do
expect(buffer.shift).to be_nil
end
example do
buffer << :a
buffer << :b
expect(buffer.shift).to be == :a
expect(buffer.shift).to be == :b
expect(buffer.shift).to be_nil
end
end
describe "#size" do
example do
expect {
buffer << :a
buffer << :b
}.to change { buffer.size }.from(0).to(2)
end
example do
buffer << :a
buffer << :b
expect { buffer.shift }.to change { buffer.size }.from(2).to(1)
expect { buffer.shift }.to change { buffer.size }.from(1).to(0)
end
end
describe "#release" do
it "raises an error" do
expect {
buffer.release
}.to raise_error(RuntimeError, "No mark has been set")
end
end
end
context "with a mark" do
before(:each) do
buffer << :premark_a
buffer << :premark_b
buffer.mark
end
describe "#shift" do
example do
expect(buffer.shift).to be == :premark_a
expect(buffer.shift).to be == :premark_b
expect(buffer.shift).to be_nil
buffer.release
expect(buffer.shift).to be == :premark_a
expect(buffer.shift).to be == :premark_b
expect(buffer.shift).to be_nil
end
end
describe "#[]" do
example do
buffer.shift
buffer.shift
buffer.release
expect(buffer[0]).to be == :premark_a
expect(buffer[1]).to be == :premark_b
end
end
describe "#size" do
example do
expect { buffer.shift }.to change { buffer.size }.from(2).to(1)
expect { buffer.shift }.to change { buffer.size }.from(1).to(0)
expect { buffer.release }.to change { buffer.size }.from(0).to(2)
end
end
end
context "with two marks" do
describe "releasing both marks" do
before(:each) do
buffer << :a
buffer << :b
buffer << :c
buffer.mark
buffer.mark
end
example do
output_before_release_1 = [ buffer.shift, buffer.shift, buffer.shift ]
expect(output_before_release_1).to be == [ :a, :b, :c ]
buffer.release
output_before_release_2 = [ buffer.shift, buffer.shift, buffer.shift ]
expect(output_before_release_2).to be == [ :a, :b, :c ]
buffer.release
output_before_release_3 = [ buffer.shift, buffer.shift, buffer.shift ]
expect(output_before_release_3).to be == [ :a, :b, :c ]
end
end
describe "shifting between the marks" do
example do
buffer << :a
buffer << :b
buffer.mark
expect(buffer.shift).to be == :a
buffer.mark
expect(buffer.shift).to be == :b
buffer.release
expect(buffer.shift).to be == :b
buffer.release
expect(buffer.shift).to be == :a
expect(buffer.shift).to be == :b
end
end
describe "buffering across two marks" do
before(:each) do
buffer << :a
buffer.mark
buffer << :b
buffer.mark
buffer << :c
end
example do
output_before_release_1 = [ buffer.shift, buffer.shift, buffer.shift ]
expect(output_before_release_1).to be == [ :a, :b, :c ]
buffer.release
output_before_release_2 = [ buffer.shift, buffer.shift, buffer.shift ]
expect(output_before_release_2).to be == [ :a, :b, :c ]
buffer.release
output_before_release_3 = [ buffer.shift, buffer.shift, buffer.shift ]
expect(output_before_release_3).to be == [ :a, :b, :c ]
end
end
end
end
end
end
end
<file_sep>/lib/2_analyzing_languages/ch06_tracking_symbols/p17_nested_scopes/symbol_table.rb
module AnalyzingLanguages
module TrackingSymbols
module NestedScopes
module Scope
def define(symbol)
@symbols[symbol.name] = symbol
end
def resolve(name)
@symbols.fetch(name.to_sym) {
@parent_scope.resolve(name)
}
end
def unwrap
@parent_scope
end
end
class SymbolTable
class DeadEndScope
def resolve(name)
raise "Unknown symbol: #{name}"
end
end
class LocalScope
include Scope
def initialize(parent_scope = :remove_me)
@parent_scope = parent_scope
@symbols = { }
end
def to_s
"symbols: {#{key_value_pairs.join(", ")}}"
end
private
def key_value_pairs
@symbols.keys.sort.map { |key| "#{key}=#{@symbols[key]}" }
end
end
def initialize
@scope = LocalScope.new(DeadEndScope.new)
end
def push_scope
@scope = LocalScope.new(@scope)
end
def pop_scope
@scope = @scope.unwrap
end
def define(symbol, metadata = { })
@scope.define(symbol)
end
def define_as_scope(symbol, metadata = { })
define(symbol)
symbol.wrap(@scope)
@scope = symbol
end
def resolve(name, metadata = { })
@scope.resolve(name)
end
def to_s
@scope.to_s
end
end
end
end
end<file_sep>/lib/1_getting_started/ch03_enhanced_parsing/p05_backtracking_parser/list_parser_with_parallel_assignment.rb
require '1_getting_started/errors'
module GettingStarted
module EnhancedParsing
module BacktrackingParser
class ListParserWithParallelAssignment
def initialize(replayable_lexer)
@lexer = replayable_lexer
end
def stat
if speculate_stat_list
matched_list = list
match(:eof)
matched_list
elsif speculate_stat_parallel_assigment
matched_parallel_assigment = parallel_assignment
match(:eof)
matched_parallel_assigment
else
raise NoViableAlternativeError.new("Expecting <list> or <parallel assignment>")
end
end
def speculate_stat_list
@lexer.speculate do
list
match(:eof)
end
rescue RecognitionError => e
false
end
def speculate_stat_parallel_assigment
@lexer.speculate do
parallel_assignment
match(:eof)
end
rescue RecognitionError => e
false
end
def list
[ ].tap do |collected_list|
match(:lbrack)
elements(collected_list)
match(:rbrack)
end
end
def parallel_assignment
lhs = list
match(:equals)
rhs = list
{ lhs => rhs }
end
def elements(collected_list)
first_element(collected_list)
while @lexer.peek.type == :comma
match(:comma)
element(collected_list)
end
end
def first_element(collected_list)
case @lexer.peek.type
when :name, :lbrack
element(collected_list)
when :rbrack
return
else
raise RecognitionError.new(
"Expected :lbrack, :name or :rbrack, found #{@lexer.peek.inspect}"
)
end
end
def element(collected_list)
if @lexer.peek(1).type == :name && @lexer.peek(2).type == :equals
lhs, _, rhs = match(:name), match(:equals), match(:name)
collected_list << { lhs.value.to_sym => rhs.value.to_sym }
elsif @lexer.peek.type == :name
collected_list << @lexer.peek.value.to_sym
match(:name)
elsif @lexer.peek.type == :lbrack
collected_list << list
else
raise RecognitionError.new(
"Expected :name or :lbrack, found #{@lexer.peek.inspect}"
)
end
end
private
def match(expected_type)
if @lexer.peek.type == expected_type
consume
else
raise RecognitionError.new(
"Expected #{expected_type.inspect}, found #{@lexer.peek.inspect}"
)
end
end
def consume
@lexer.next
end
end
end
end
end
<file_sep>/lib/1_getting_started/errors.rb
class RecognitionError < RuntimeError; end
class NoViableAlternativeError < RuntimeError; end<file_sep>/spec/1_getting_started/ch02_basic_parsing/p04_llk_recursive_descent_parser/list_parser_assignment_contract.rb
shared_examples_for "a ListParser with assignment" do
context "list with assignment" do
let(:token_descriptions) {
[
{ lbrack: "[" },
{ name: "a" },
{ equals: "=" },
{ name: "b" },
{ rbrack: "]" },
{ eof: nil }
]
}
specify {
expect(parser.list).to be == [ { :a => :b } ]
}
end
end
<file_sep>/spec/1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/enumerator_contract.rb
shared_examples_for "an Enumerator" do
context "at the start" do
specify {
expect(subject.next).to_not be_nil
}
specify {
expect(subject.peek).to_not be_nil
}
specify {
peeked_value = subject.peek
expect(subject.next).to be == peeked_value
}
end
context "at the end" do
before(:each) do
advance_to_end
end
specify {
expect { subject.next }.to raise_error(StopIteration)
}
specify {
expect { subject.peek }.to raise_error(StopIteration)
}
end
end
<file_sep>/spec/2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/variable_symbol_spec.rb
require 'spec_helper'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/variable_symbol'
module AnalyzingLanguages
module TrackingSymbols
module MonolithicScope
describe VariableSymbol do
let(:type) { LanguageSymbol.new(:type) }
subject(:symbol) { VariableSymbol.new(:name, type) }
its(:to_s) { should be == "<name:type>" }
describe "#==" do
example do
expect(symbol).to be == VariableSymbol.new(:name, type)
end
example do
expect(symbol).to be == VariableSymbol.new("name", type)
end
example do
expect(symbol).to_not be == VariableSymbol.new(:bar, type)
end
example do
expect(symbol).to_not be == VariableSymbol.new(:name, LanguageSymbol.new(:wrong_type))
end
example do
expect(symbol).to_not be == :name
end
end
describe "#name" do
its(:name) { should be == :name }
it "is always a symbol" do
expect(VariableSymbol.new("name", :ununused_type).name).to be == :name
end
end
end
end
end
end<file_sep>/spec/1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/enumerator_spec.rb
require 'spec_helper'
require_relative 'enumerator_contract'
# Prove that the Enumerator interface we depend on works how we think it does
describe "a real Enumerator" do
subject(:array_enumerator) { [ { eof: nil } ].each }
def advance_to_end
array_enumerator.next
end
it_behaves_like "an Enumerator"
end<file_sep>/lib/2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/cymbol_monolithic_node_classes.rb
require 'treetop'
module AnalyzingLanguages; module TrackingSymbols; module MonolithicScope; end; end; end
Treetop.load(File.dirname(__FILE__) + '/cymbol_monolithic')
require_relative 'variable_symbol'
module AnalyzingLanguages
module TrackingSymbols
module MonolithicScope
# Module for Treetop
module CymbolMonolithic
class ::Treetop::Runtime::SyntaxNode
def populate_symbols(symbol_table)
return unless elements
elements.each do |element|
element.populate_symbols(symbol_table)
end
end
private
def location
"line #{input.line_of(interval.first)}"
end
end
class VarDeclaration < Treetop::Runtime::SyntaxNode
def populate_symbols(symbol_table)
var_type = symbol_table.resolve(type.name, location: location)
if assignment
assignment.populate_symbols(symbol_table)
end
symbol_table.define(VariableSymbol.new(var_name.name, var_type), location: location)
end
end
class VarExpression < Treetop::Runtime::SyntaxNode
def populate_symbols(symbol_table)
symbol_table.resolve(type.name, location: location)
end
end
class CymbolSymbol < Treetop::Runtime::SyntaxNode
def name
text_value
end
def populate_symbols(symbol_table)
symbol_table.resolve(name, location: location)
end
end
end
end
end
end<file_sep>/spec/1_getting_started/ch02_basic_parsing/p03_ll1_recursive_descent_parser/list_parser_spec.rb
require 'spec_helper'
require '1_getting_started/ch02_basic_parsing/p03_ll1_recursive_descent_parser/list_parser'
require '1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/list_lexer'
require_relative 'list_parser_contract'
module GettingStarted
module BasicParsing
module LL1RecursiveDescentParser
describe "Intergration:", ListParser, "and lexer" do
let(:input) { "[ a, [ x, [ i, j ] ], b ]" }
let(:lexer) { LL1RecursiveDescentLexer::ListLexer.new(input) }
subject(:parser) { ListParser.new(lexer) }
it "parses lists!" do
expect(parser.list).to be == [ :a, [ :x, [ :i, :j ] ], :b ]
end
end
describe ListParser do
it_behaves_like "a ListParser"
let(:tokens) {
LL1RecursiveDescentLexer::Token.descriptions_to_tokens(token_descriptions)
}
let(:lexer) { tokens.each }
subject(:parser) { ListParser.new(lexer) }
end
end
end
end<file_sep>/spec/1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/list_lexer_spec.rb
require 'spec_helper'
require '1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/list_lexer'
require_relative 'list_lexer_contract'
module GettingStarted
module BasicParsing
module LL1RecursiveDescentLexer
describe ListLexer do
subject(:lexer) { ListLexer.new(input) }
let(:collected_output) { [ ] }
let(:output) {
collected_output.map { |token| token.to_hash }
}
it_behaves_like "a ListLexer"
end
end
end
end<file_sep>/spec/1_getting_started/ch02_basic_parsing/p03_ll1_recursive_descent_parser/list_parser_contract.rb
shared_examples_for "a ListParser" do
# The example in the book (deliberately?) avoids this case, but it's an obvious
# TDD bootstrapping case, and turned out to be not too difficult to implement
# compared to the Java example
context "empty list" do
let(:token_descriptions) {
[
{ lbrack: "[" },
{ rbrack: "]" },
{ eof: nil }
]
}
specify {
expect(parser.list).to be == [ ]
}
end
context "list with a name" do
let(:token_descriptions) {
[
{ lbrack: "[" },
{ name: "a" },
{ rbrack: "]" },
{ eof: nil }
]
}
specify {
expect(parser.list).to be == [ :a ]
}
end
context "list with a multiple names" do
let(:token_descriptions) {
[
{ lbrack: "[" },
{ name: "a" },
{ comma: "," },
{ name: "b" },
{ comma: "," },
{ name: "c" },
{ rbrack: "]" },
{ eof: nil }
]
}
specify {
expect(parser.list).to be == [ :a, :b, :c ]
}
end
context "list of lists" do
let(:token_descriptions) {
[
{ lbrack: "[" },
{ name: "a" },
{ comma: "," },
{ lbrack: "[" },
{ name: "x" },
{ comma: "," },
{ name: "y" },
{ rbrack: "]" },
{ comma: "," },
{ name: "b" },
{ rbrack: "]" },
{ eof: nil }
]
}
specify {
expect(parser.list).to be == [ :a, [ :x, :y ], :b ]
}
end
context "empty list in a list" do
let(:token_descriptions) {
[
{ lbrack: "[" },
{ name: "a" },
{ comma: "," },
{ lbrack: "[" },
{ rbrack: "]" },
{ comma: "," },
{ name: "b" },
{ rbrack: "]" },
{ eof: nil }
]
}
specify {
expect(parser.list).to be == [ :a, [ ], :b ]
}
end
context "list of list of lists to prove to Bobby my code really works" do
let(:token_descriptions) {
[
{ lbrack: "[" },
{ name: "a" },
{ comma: "," },
{ lbrack: "[" },
{ name: "x" },
{ comma: "," },
{ lbrack: "[" },
{ name: "i" },
{ comma: "," },
{ name: "j" },
{ rbrack: "]" },
{ rbrack: "]" },
{ comma: "," },
{ name: "b" },
{ rbrack: "]" },
{ eof: nil }
]
}
specify {
expect(parser.list).to be == [ :a, [ :x, [ :i, :j ] ], :b ]
}
end
context "invalid input" do
context "no list" do
let(:token_descriptions) {
[
{ eof: nil }
]
}
specify {
expect { parser.list }.to raise_error(RecognitionError, "Expected :lbrack, found :eof")
}
end
context "unclosed list" do
let(:token_descriptions) {
[
{ lbrack: "[" },
{ eof: nil }
]
}
specify {
expect { parser.list }.to raise_error(
RecognitionError, "Expected :lbrack, :name or :rbrack, found :eof"
)
}
end
context "missing name before a comma" do
let(:token_descriptions) {
[
{ lbrack: "[" },
{ comma: "," },
{ rbrack: "]" },
{ eof: nil }
]
}
specify {
expect { parser.list }.to raise_error(
RecognitionError, "Expected :lbrack, :name or :rbrack, found :comma"
)
}
end
context "missing name after a comma" do
let(:token_descriptions) {
[
{ lbrack: "[" },
{ name: "a" },
{ comma: "," },
{ rbrack: "]" },
{ eof: nil }
]
}
specify {
expect { parser.list }.to raise_error(
RecognitionError, "Expected :name or :lbrack, found :rbrack"
)
}
end
end
end<file_sep>/spec/1_getting_started/ch03_enhanced_parsing/p05_backtracking_parser/list_parser_with_parallel_assignment_spec.rb
require 'spec_helper'
require '1_getting_started/ch03_enhanced_parsing/p05_backtracking_parser/list_parser_with_parallel_assignment'
require '1_getting_started/ch03_enhanced_parsing/p05_backtracking_parser/lexer_replayable_lookahead'
require '1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/list_lexer'
require_relative '../../ch02_basic_parsing/p03_ll1_recursive_descent_parser/list_parser_contract'
require_relative '../../ch02_basic_parsing/p04_llk_recursive_descent_parser/list_parser_assignment_contract'
require_relative 'list_parser_with_parallel_assignment_contract'
module GettingStarted
module EnhancedParsing
module BacktrackingParser
describe "Intergration:", ListParserWithParallelAssignment, "and lexer" do
let(:input) { "[ a ] = [ b ]" }
let(:lexer) { BasicParsing::LL1RecursiveDescentLexer::ListLexer.new(input) }
let(:lookahead) { LexerReplayableLookahead.new(lexer) }
subject(:parser) { ListParserWithParallelAssignment.new(lookahead) }
describe "statements" do
context "a list" do
let(:input) { "[ a = b, c, d ]" }
example do
expect(parser.stat).to be == [ { :a => :b }, :c, :d ]
end
end
context "a parallel assignment" do
let(:input) { "[ a, b ] = [ c, d ]" }
example do
expect(parser.stat).to be == { [ :a, :b ] => [ :c, :d ] }
end
end
end
end
describe ListParserWithParallelAssignment do
let(:tokens) {
BasicParsing::LL1RecursiveDescentLexer::Token.descriptions_to_tokens(token_descriptions)
}
let(:lexer) { tokens.each }
let(:lookahead) { LexerReplayableLookahead.new(lexer) }
subject(:parser) { ListParserWithParallelAssignment.new(lookahead) }
it_behaves_like "a ListParser"
it_behaves_like "a ListParser with assignment"
it_behaves_like "a ListParser with parallel assignment"
end
end
end
end<file_sep>/spec/1_getting_started/ch03_enhanced_parsing/p05_backtracking_parser/list_parser_with_parallel_assignment_contract.rb
shared_examples_for "a ListParser with parallel assignment" do
describe "statements" do
context "a list" do
let(:token_descriptions) {
[
{ lbrack: "[" },
{ name: "a" }, { equals: "=" }, { name: "b" }, { comma: "," },
{ name: "c" }, { comma: "," },
{ name: "d" },
{ rbrack: "]" },
{ eof: nil }
]
}
specify {
expect(parser.list).to be == [ { :a => :b }, :c, :d ]
}
end
context "a parallel assignment" do
let(:token_descriptions) {
[
{ lbrack: "[" },
{ name: "a" }, { comma: "," }, { name: "b" },
{ rbrack: "]" },
{ equals: "=" },
{ lbrack: "[" },
{ name: "c" }, { comma: "," }, { name: "d" },
{ rbrack: "]" },
{ eof: nil }
]
}
specify {
expect(parser.stat).to be == { [ :a, :b ] => [ :c, :d ] }
}
end
context "invalid statement" do
# "[ a ] b"
let(:token_descriptions) {
[
{ lbrack: "[" },
{ name: "a" },
{ rbrack: "]" },
{ name: "b" },
{ eof: nil }
]
}
specify {
expect {
parser.stat
}.to raise_error(
NoViableAlternativeError, "Expecting <list> or <parallel assignment>"
)
}
end
end
end<file_sep>/lib/2_analyzing_languages/ch06_tracking_symbols/p17_nested_scopes/cymbol2_parser.rb
require 'treetop'
require_relative 'method_symbol'
require_relative '../p16_monolithic_scope/variable_symbol'
module AnalyzingLanguages; module TrackingSymbols; module NestedScopes; end; end; end
Treetop.load(File.dirname(__FILE__) + '/cymbol_nested')
module AnalyzingLanguages
module TrackingSymbols
module NestedScopes
# Module for Treetop
module CymbolNested
class ::Treetop::Runtime::SyntaxNode
def walk(symbol_table)
return unless elements
elements.each do |element|
element.walk(symbol_table)
end
end
private
def location
"line #{input.line_of(interval.first)}"
end
end
class MethodDefinition < Treetop::Runtime::SyntaxNode
def walk(symbol_table)
method_type = symbol_table.resolve(type.name, location: location)
symbol_table.define_as_scope(MethodSymbol.new(name.name, method_type), location: location)
parameters.each do |parameter|
parameter_type = symbol_table.resolve(parameter.type.name, location: location)
symbol_table.define(
MonolithicScope::VariableSymbol.new(parameter.name.name, parameter_type),
location: location
)
end
body.walk(symbol_table)
end
end
class CymbolBlock < Treetop::Runtime::SyntaxNode
def walk(symbol_table)
symbol_table.push_scope
elements.each do |element|
element.walk(symbol_table)
end
end
end
class ParameterList < Treetop::Runtime::SyntaxNode
def each(&block)
parameters.each(&block)
end
# We can only handle one - as it happens the book example only uses one
def parameters
[ first_parameter ]
end
end
class VarDeclaration < Treetop::Runtime::SyntaxNode
def walk(symbol_table)
var_type = symbol_table.resolve(type.name, location: location)
if initialization
initialization.walk(symbol_table)
end
symbol_table.define(
MonolithicScope::VariableSymbol.new(var_name.name, var_type),
location: location
)
end
end
class CymbolSymbol < Treetop::Runtime::SyntaxNode
def name
text_value
end
def walk(symbol_table)
symbol_table.resolve(name, location: location)
end
end
end
end
end
end<file_sep>/spec/1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/token_spec.rb
require 'spec_helper'
require '1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/token'
module GettingStarted
module BasicParsing
module LL1RecursiveDescentLexer
describe Token do
subject(:token) { Token.new(token_type: "token_value") }
its(:type) { should be == :token_type }
its(:value) { should be == "token_value" }
its(:inspect) { should be == ":token_type" } # Only used for errors so far
its(:to_hash) { should be == { token_type: "token_value" } }
describe "#==" do
it "knows equality" do
expect(token).to be == Token.new(token_type: "token_value")
end
it "compares type" do
expect(token).to_not be == Token.new(wrong_token_type: "token_value")
end
it "compares value" do
expect(token).to_not be == Token.new(token_type: "wrong_token_value")
end
end
describe ".descriptions_to_tokens" do
example do
expect(
Token.descriptions_to_tokens([{ a: "one" }, { b: "two" }])
).to be == [
Token.new(a: "one"), Token.new(b: "two")
]
end
end
end
end
end
end<file_sep>/spec/2_analyzing_languages/ch06_tracking_symbols/p17_nested_scopes/symbol_table_spec.rb
require 'spec_helper'
require '2_analyzing_languages/ch06_tracking_symbols/p17_nested_scopes/symbol_table'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/language_symbol'
module AnalyzingLanguages
module TrackingSymbols
module NestedScopes
# Easy access to the existing LanguageSymbol
include MonolithicScope
describe SymbolTable do
subject(:symbol_table) { SymbolTable.new }
context "single scope" do
describe "#define" do
it "ignores metadata" do
expect {
symbol_table.define(LanguageSymbol.new(:foo), unused: "stuff")
}.to_not raise_error(ArgumentError)
end
end
describe "#resolve" do
context "undefined symbol" do
specify {
expect {
symbol_table.resolve("foo")
}.to raise_error(RuntimeError, "Unknown symbol: foo")
}
it "ignores metadata" do
expect {
symbol_table.resolve("foo", unused: "stuff")
}.to_not raise_error(ArgumentError)
end
end
context "defined symbol" do
let(:symbol) { LanguageSymbol.new(:foo) }
before(:each) do
symbol_table.define(symbol)
end
specify {
expect(symbol_table.resolve("foo")).to equal(symbol)
}
specify {
expect(symbol_table.resolve(:foo)).to equal(symbol)
}
end
end
describe "#to_s" do
before(:each) do
symbol_table.define(LanguageSymbol.new(:foo))
symbol_table.define(LanguageSymbol.new(:bar))
symbol_table.define(LanguageSymbol.new(:baz))
end
it "outputs in alphabetic order" do
expect(symbol_table.to_s).to be ==
"symbols: {bar=bar, baz=baz, foo=foo}"
end
end
end
describe "nested scopes" do
let(:symbol) { LanguageSymbol.new(:foo) }
before(:each) do
symbol_table.define(symbol)
symbol_table.push_scope
end
it "gives access to the higher scope" do
expect(symbol_table.resolve(:foo)).to equal(symbol)
end
describe "overriding" do
let(:new_foo) { LanguageSymbol.new(:foo) }
before(:each) do
symbol_table.define(new_foo)
end
it "lets you override a symbol" do
expect(symbol_table.resolve(:foo)).to equal(new_foo)
end
it "lets you pop the scope tree to get the old symbol back" do
symbol_table.pop_scope
expect(symbol_table.resolve(:foo)).to equal(symbol)
end
it "updates #to_s" do
pending
end
end
end
describe "scope symbols" do
# Using a mock here bleeds some implementation details of the aggregate,
# we should probably remove this if we get a suitable integration test
let(:scope_symbol) {
mock("ScopeSymbol", name: :bar, wrap: nil, resolve: :trust_passed_through)
}
it "defines the symbol" do
symbol_table.define_as_scope(scope_symbol)
expect(symbol_table.resolve(:bar)).to equal(:trust_passed_through)
end
it "ignores metadata" do
expect {
symbol_table.define_as_scope(scope_symbol, unused: "stuff")
}.to_not raise_error(ArgumentError)
end
it "pushes the symbol as a scope" do
symbol_table.define(LanguageSymbol.new(:moo))
scope_symbol.should_receive(:wrap) do |parent_scope|
expect(parent_scope.resolve(:moo))
end
symbol_table.define_as_scope(scope_symbol)
end
it "uses the pushed scope" do
symbol_table.define_as_scope(scope_symbol)
scope_symbol.should_receive(:resolve).with(:baz)
symbol_table.resolve(:baz)
end
end
end
end
end
end<file_sep>/spec/1_getting_started/ch03_enhanced_parsing/p05_backtracking_parser/lexer_replayable_lookahead_spec.rb
require 'spec_helper'
require '1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/list_lexer'
require '1_getting_started/ch03_enhanced_parsing/p05_backtracking_parser/lexer_replayable_lookahead'
require_relative '../../ch02_basic_parsing/p02_ll1_recursive_descent_lexer/list_lexer_contract'
module GettingStarted
module EnhancedParsing
module BacktrackingParser
shared_examples_for "LexerReplayableLookahead#peek" do
example do
expect(lexer.peek.value).to be == "["
end
example do
expect(lexer.peek(1).value).to be == "["
end
example do
expect(lexer.peek(2).value).to be == "a"
end
example do
expect(lexer.peek(5).value).to be == "]"
end
example do
expect(lexer.peek(6).to_hash).to be == { eof: nil }
end
example do
expect { lexer.peek(7) }.to raise_error(StopIteration)
end
end
shared_examples_for "LexerReplayableLookahead#speculate" do
specify {
lexer.speculate do
expect(lexer.peek.value).to be == "["
expect(lexer.next.value).to be == "["
expect(lexer.next.value).to be == "a"
end
}
specify {
lexer.next
expect {
lexer.speculate do
lexer.next
end
}.to_not change { lexer.peek.value }
}
specify {
expect(lexer.peek.value).to be == "["
lexer.speculate do
lexer.next
expect(lexer.peek.value).to be == "a"
lexer.speculate do
lexer.next
expect(lexer.peek.value).to be == "="
end
expect(lexer.peek.value).to be == "a"
end
expect(lexer.peek.value).to be == "["
}
describe "#if_speculating" do
specify {
should_not_receive(:was_speculating)
lexer.if_speculating do
was_speculating
end
}
specify {
should_receive(:was_speculating)
lexer.speculate do
lexer.if_speculating do
was_speculating
end
end
}
specify {
should_receive(:was_speculating)
lexer.speculate do
lexer.speculate do
# nothing here
end
lexer.if_speculating do
was_speculating
end
end
}
end
describe "error handling" do
it "(re-)raises errors" do
expect {
lexer.speculate do
raise "re-raised error"
end
}.to raise_error(RuntimeError, "re-raised error")
end
it "is not disturbed by errors" do
lexer.speculate do
lexer.next
lexer.next
raise "ignored error"
end rescue nil
expect(lexer.next.value).to be == "["
expect(lexer.next.value).to be == "a"
end
end
end
describe LexerReplayableLookahead do
describe "lookahead" do
let(:tokens) {
BasicParsing::LL1RecursiveDescentLexer::Token.descriptions_to_tokens(
[
{ lbrack: "[" },
{ name: "a" },
{ equals: "=" },
{ name: "b" },
{ rbrack: "]" },
{ eof: nil }
]
)
}
let(:underlying_lexer) { tokens.each }
subject(:lexer) { LexerReplayableLookahead.new(underlying_lexer) }
describe "#peek" do
it_behaves_like "LexerReplayableLookahead#peek"
end
describe "#speculate" do
it_behaves_like "LexerReplayableLookahead#speculate"
end
end
context "wrapping a ListLexer" do
let(:input) { "[ a = b ]" }
let(:underlying_lexer) { BasicParsing::LL1RecursiveDescentLexer::ListLexer.new(input) }
subject(:lexer) { LexerReplayableLookahead.new(underlying_lexer) }
let(:collected_output) { [ ] }
let(:output) {
collected_output.map { |token| token.to_hash }
}
it_behaves_like "a ListLexer"
describe "#peek" do
it_behaves_like "LexerReplayableLookahead#peek"
end
describe "#speculate" do
it_behaves_like "LexerReplayableLookahead#speculate"
end
end
end
end
end
end<file_sep>/spec/2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/symbol_table_logger_spec.rb
require 'spec_helper'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/symbol_table'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/symbol_table_logger'
module AnalyzingLanguages
module TrackingSymbols
module MonolithicScope
describe SymbolTableLogger do
let(:symbol_table) { mock(SymbolTable, define: nil, resolve: :resolved_symbol) }
let(:output_io) { StringIO.new }
def output
output_io.rewind
output_io.read.chomp
end
subject(:logger) { SymbolTableLogger.new(symbol_table, output_io) }
describe "#resolve" do
specify {
symbol_table.should_receive(:resolve).with(:symbol_name)
logger.resolve(:symbol_name).should be == :resolved_symbol
}
specify {
logger.resolve(:symbol_name, location: "line 1")
expect(output).to be == "line 1: ref resolved_symbol"
}
end
describe "#define" do
specify {
logger.define(:symbol, location: "line 1")
expect(output).to be == "line 1: def symbol"
}
specify {
symbol_table.should_receive(:define).with(:symbol)
logger.define(:symbol)
}
end
end
end
end
end<file_sep>/lib/1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/list_lexer.rb
require_relative 'token'
module GettingStarted
module BasicParsing
module LL1RecursiveDescentLexer
# Implements Pattern 2: LL(1) Recursive-Descent Lexer
#
# Note that there are two main differences from the example implementation:
#
# * I don't use a Token class (which is just a dumb struct in the Java
# example), this can be more easily implemented in Ruby with simple hashes.
#
# * I set about solving this using standard Ruby iterators with blocks,
# which makes some bits more idiomatic and some bits more complex. The
# Java example looks ahead to the next character, whereas with blocks
# we have to `redo` if we detect we've entered a different token type.
# Because of this, the code has ended up with a State implementation,
# albeit a slightly wacky one.
#
# * There's the minor difference that I forgot to allow parsing capital
# letters in names. Oops.
#
# ERRATA: I just realised that the whole point of LL(1) is to *look ahead*
# and therefore this implementation using blocks misses the point. Sight.
# Oh well, from the outside, it's behaviourally equivalent, ie passes all
# the same tests it would do if we weren't `redo`ing enumerator blocks.
# I'm not going to refactor it unless I have to.
class ListLexer
def initialize(input)
@input = input
# Hack to work around the fact I didn't implement this as a pull system
@tokens = tokenize_all.each
end
def peek
@tokens.peek
end
def next
@tokens.next
end
private
def tokenize_all
[ ].tap do |tokens|
tokenize do |token|
tokens << token
end
end
end
def tokenize(&block)
switch_to_mode(:normal)
@input.chars.each do |char|
match_result =
catch :state_changed do
match(char, &block)
end
redo if match_result == :state_changed
end
finish(&block)
end
def match_normal(char, &block)
case char
when " ", "\t", "\n"
when "["
yield(Token.new(lbrack: char))
when ","
yield(Token.new(comma: char))
when "="
yield(Token.new(equals: char))
when "]"
yield(Token.new(rbrack: char))
when "a".."z"
switch_to_mode(:name)
throw(:state_changed, :state_changed)
else
raise ArgumentError.new("Invalid character: #{char}")
end
end
def match_name(char, &block)
case char
when "a".."z"
@name << char
else
yield(Token.new(name: @name))
switch_to_mode(:normal)
throw(:state_changed, :state_changed)
end
end
def finish_normal(&block)
yield(Token.new(eof: nil))
end
def finish_name(&block)
yield(Token.new(name: @name))
yield(Token.new(eof: nil))
end
# This is an insane way to implement the State pattern, but I've left it in purely
# because it's so ridiculous, and this is only the first pattern in the book
def switch_to_mode(mode)
@name = ""
singleton_class.send(:alias_method, :match, :"match_#{mode}")
singleton_class.send(:alias_method, :finish, :"finish_#{mode}")
end
end
end
end
end<file_sep>/spec/1_getting_started/ch03_enhanced_parsing/p06_memoizing_parser/memoizing_list_parser_spec.rb
require 'spec_helper'
require '1_getting_started/ch03_enhanced_parsing/p06_memoizing_parser/memoizing_list_parser'
require '1_getting_started/ch03_enhanced_parsing/p05_backtracking_parser/lexer_replayable_lookahead'
require '1_getting_started/ch02_basic_parsing/p02_ll1_recursive_descent_lexer/list_lexer'
require_relative '../../ch02_basic_parsing/p03_ll1_recursive_descent_parser/list_parser_contract'
require_relative '../../ch02_basic_parsing/p04_llk_recursive_descent_parser/list_parser_assignment_contract'
require_relative '../p05_backtracking_parser/list_parser_with_parallel_assignment_contract'
module GettingStarted
module EnhancedParsing
module MemoizingParser
# The spec for this is identical to the backtracking parser, only the
# implementation differs. I've decided not to write any specs to prove
# eg performance or memory usage, as for my purposes I only want to
# understand what is going on, not be able to implement these efficiently
# myself.
describe MemoizingListParser do
let(:tokens) {
BasicParsing::LL1RecursiveDescentLexer::Token.descriptions_to_tokens(token_descriptions)
}
let(:lexer) { tokens.each }
let(:lookahead) { BacktrackingParser::LexerReplayableLookahead.new(lexer) }
subject(:parser) { MemoizingListParser.new(lookahead) }
it_behaves_like "a ListParser"
it_behaves_like "a ListParser with assignment"
it_behaves_like "a ListParser with parallel assignment"
end
end
end
end
<file_sep>/lib/1_getting_started/ch02_basic_parsing/p03_ll1_recursive_descent_parser/list_parser.rb
require '1_getting_started/errors'
module GettingStarted
module BasicParsing
module LL1RecursiveDescentParser
# Implements Pattern 3: LL(1) Recursive-Descent Parser
#
# Two major differences from the book examples:
#
# * We turn the tokens into a Ruby array (ie we do something with them
# other than detect errors). This is pretty easy as we just need a
# Collecting Parameter.
#
# * We handle the empty list case. I didn't notice this was excluded
# from the grammar, but the discussion on p40 hints at why. Turns out
# even in this simple case it's much harder to parse optional elements,
# as it means we have to treat the first element of a list differently
# (because "[ ]" is valid but "[ a, ]" is not, which is what a naive
# parser gives you).
class ListParser
def initialize(lexer)
@lexer = lexer
@lookahead = @lexer.next
end
def list
[ ].tap do |collected_list|
match(:lbrack)
elements(collected_list)
match(:rbrack)
end
end
def elements(collected_list)
first_element(collected_list)
while @lookahead.type == :comma
match(:comma)
element(collected_list)
end
end
def first_element(collected_list)
case @lookahead.type
when :name, :lbrack
element(collected_list)
when :rbrack
return
else
raise RecognitionError.new(
"Expected :lbrack, :name or :rbrack, found #{@lookahead.type.inspect}"
)
end
end
def element(collected_list)
case @lookahead.type
when :name
collected_list << @lookahead.value.to_sym
match(:name)
when :lbrack
collected_list << list
else
raise RecognitionError.new(
"Expected :name or :lbrack, found #{@lookahead.type.inspect}"
)
end
end
private
def match(expected_type)
if @lookahead.type == expected_type
consume
else
raise RecognitionError.new(
"Expected #{expected_type.inspect}, found #{@lookahead.type.inspect}"
)
end
end
def consume
@lookahead = @lexer.next
end
end
end
end
end<file_sep>/spec/spec_helper.rb
require 'ap'
require 'fakefs/spec_helpers'
require 'lstrip-on-steroids'
RSpec.configure do |config|
config.filter_run(focus: true)
config.run_all_when_everything_filtered = true
end
<file_sep>/spec/2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/cymbol_spec.rb
require 'spec_helper'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/cymbol'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/symbol_table'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/symbol_table_logger'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/language_symbol'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/variable_symbol'
module AnalyzingLanguages
module TrackingSymbols
module MonolithicScope
describe Cymbol do
let(:symbol_table) { mock(SymbolTable, resolve: nil, define: nil) }
let(:cymbol) { Cymbol.new(symbol_table) }
context "an uninitialised variable" do
let(:source) { "float j;" }
specify {
symbol_table.should_receive(:resolve).with("float", hash_including(location: "line 1"))
cymbol.parse(source)
}
end
context "an initialized variable" do
let(:source) { "int i = 9;" }
let(:int) { LanguageSymbol.new(:int) }
before(:each) do
symbol_table.stub(resolve: int)
end
specify {
symbol_table.should_receive(:resolve).with(
"int", hash_including(location: "line 1")
).ordered
symbol_table.should_receive(:define).with(
VariableSymbol.new(:i, LanguageSymbol.new(:int)),
hash_including(location: "line 1")
).ordered
cymbol.parse(source)
}
end
context "a variable initialized with an expression" do
let(:source) { "int k = i + 2;" }
let(:float) { LanguageSymbol.new(:float) }
before(:each) do
symbol_table.stub(resolve: float)
end
specify {
symbol_table.should_receive(:resolve).with(
"int", hash_including(location: "line 1")
).ordered
symbol_table.should_receive(:resolve).with(
"i", hash_including(location: "line 1")
).ordered
symbol_table.should_receive(:define).with(
VariableSymbol.new(:k, float), hash_including(location: "line 1")
).ordered
cymbol.parse(source)
}
end
end
describe Cymbol, "from the book" do
let(:symbol_table) { SymbolTable.new }
subject(:cymbol) { Cymbol.new(symbol_table_for_parser) }
let(:source) {
-%{
int i = 9;
float j;
int k = i+2;
}
}
before(:each) do
# Bypass any logging
symbol_table.define(LanguageSymbol.new(:int))
symbol_table.define(LanguageSymbol.new(:float))
end
context "but with no logging" do
let(:symbol_table_for_parser) { symbol_table }
specify {
expect { cymbol.parse(source) }.to_not raise_error
}
end
context "with logging as described" do
let(:output_io) { StringIO.new }
def output
output_io.rewind
output_io.read.chomp
end
let(:symbol_table_for_parser) { SymbolTableLogger.new(symbol_table, output_io) }
# Changed slightly because to produce the same output as the book
# requires an inordinate increase in complexity in the code
#
# Test output from the book:
# line 1: ref int
# line 1: def i
# line 2: ref float
# line 2: def j
# line 3: ref int
# line 3: ref to <i:int>
# line 3: def k
specify {
cymbol.parse(source)
expect(output.to_s).to be == -%{
line 1: ref int
line 1: def <i:int>
line 2: ref float
line 2: def <j:float>
line 3: ref int
line 3: ref <i:int>
line 3: def <k:int>
}
}
# We don't write this to the output just to avoid having to pass an IO in to Cymbol
specify {
cymbol.parse(source)
expect(symbol_table.to_s).to be ==
"globals: {float=float, i=<i:int>, int=int, j=<j:float>, k=<k:int>}"
}
end
end
end
end
end<file_sep>/lib/1_getting_started/ch03_enhanced_parsing/p05_backtracking_parser/lexer_replayable_lookahead.rb
require_relative 'replayable_buffer'
module GettingStarted
module EnhancedParsing
module BacktrackingParser
class LexerReplayableLookahead
def initialize(lexer)
@lexer = lexer
@lexer_empty = false
@buffer = ReplayableBuffer.new
@speculating = [ false ]
end
def peek(lookahead_distance = 1)
fill_buffer(lookahead_distance)
token_or_stop_iteration(@buffer[lookahead_distance - 1])
end
def next
fill_buffer(1)
consume
end
def speculate(&block)
@speculating.push(true)
@buffer.mark
yield
ensure
@speculating.pop
@buffer.release
end
def if_speculating(&block)
yield if @speculating.last
end
private
def consume
token_or_stop_iteration(@buffer.shift)
end
def fill_buffer(required_size)
(required_size - @buffer.size).times do
harvest
end
end
def harvest
@buffer << @lexer.next
rescue StopIteration
def self.harvest
# NOOP
end
def self.token_or_stop_iteration(token)
raise StopIteration if token.nil?
token
end
end
def token_or_stop_iteration(token)
token
end
end
end
end
end
<file_sep>/spec/2_analyzing_languages/ch06_tracking_symbols/p17_nested_scopes/cymbol2_spec.rb
require 'spec_helper'
require '2_analyzing_languages/ch06_tracking_symbols/p17_nested_scopes/cymbol2'
require '2_analyzing_languages/ch06_tracking_symbols/p17_nested_scopes/symbol_table'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/symbol_table_logger'
require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/language_symbol'
# require '2_analyzing_languages/ch06_tracking_symbols/p16_monolithic_scope/variable_symbol'
module AnalyzingLanguages
module TrackingSymbols
module NestedScopes
include MonolithicScope
describe Cymbol2, "from the book" do
let(:symbol_table) { SymbolTable.new }
let(:symbol_table_logger) { SymbolTableLogger.new(symbol_table, output_io) }
let(:output_io) { StringIO.new }
def output
output_io.rewind
output_io.read.chomp
end
subject(:cymbol) { Cymbol2.new }
before(:each) do
# Bypass any logging
symbol_table.define(LanguageSymbol.new(:int))
symbol_table.define(LanguageSymbol.new(:float))
end
let(:source) {
-%{
// global scope
float f(int x)
{
float i;
{ float z = x+y; i = z; }
}
}
}
specify {
cymbol.parse(source).walk(symbol_table_logger)
# Changed a bit: I made it as close as I felt was worth it,
# but some stuff is quite hard (eg assignment, unless we start)
# extending the symbol table for this
expect(output.to_s).to be == -%{
line 2: ref float
line 2: defscope method<f:float>
line 2: ref int
line 2: def <x:int>
line 4: ref float
line 4: def <i:float>
line 5: ref float
line 5: ref <x:int>
line 5: ref [failed] y
line 5: def <z:float>
line 5: ref <i:float>
line 5: ref <z:float>
}
}
end
end
end
end<file_sep>/README.markdown
# Language Implementation Patterns
My workthrough of the book [Language Implementation Patterns][lipbook] by [<NAME>][parrt].
[lipbook]: http://pragprog.com/book/tpdsl/language-implementation-patterns
[parrt]: http://www.cs.usfca.edu/~parrt/
<file_sep>/lib/2_analyzing_languages/ch06_tracking_symbols/p17_nested_scopes/method_symbol.rb
require_relative 'symbol_table'
module AnalyzingLanguages
module TrackingSymbols
module NestedScopes
class MethodSymbol
include Scope
attr_reader :name, :type
def initialize(name, type)
@name = name.to_sym
@type = type
@symbols = { } # Hackety hackety hack
end
def ==(other)
other.is_a?(MethodSymbol) &&
@name == other.name &&
@type == other.type
end
def wrap(parent_scope)
@parent_scope = parent_scope
end
def to_s
"method<#{@name}:#{@type}>"
end
end
end
end
end | 88dc429a8b45a587e6dce5882c083a7bc9f0a84d | [
"Markdown",
"Ruby"
] | 47 | Ruby | ashmoran/language_implementation_patterns | fa9923cd9c51c069b719cbf7247e407535d9dc70 | e89ed786e3ce554f5fab18fd3c9adc4af3301c01 | |
refs/heads/master | <file_sep>import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.mockito.*;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class RentACatTest {
/**
* The test fixture for this JUnit test. Test fixture: a fixed state of a set of
* objects used as a baseline for running tests. The test fixture is initialized
* using the @Before setUp method which runs before every test case. The test
* fixture is removed using the @After tearDown method which runs after each
* test case.
*/
RentACat r; // Object to test
Cat c1; // First mock cat object
Cat c2; // Second mock cat object
Cat c3; // Third mock cat object
@Before
public void setUp() throws Exception {
// Turn on automatic bug injection in the Cat class, to emulate a buggy Cat.
// Your unit tests should work regardless of these bugs if you mock all Cats.
Cat._bugInjectionOn = true;
// INITIALIZE THE TEST FIXTURE
// 1. Create a new RentACat object and assign to r
r = RentACat.createInstance();
// 2. Create a mock Cat with ID 1 and name "Jennyanydots", assign to c1
// TODO: Fill in
c1 = Mockito.mock(Cat.class);
Mockito.when(c1.getId()).thenReturn(1);
Mockito.when(c1.getName()).thenReturn("Jennyanydots");
// 3. Create a mock Cat with ID 2 and name "Old Deuteronomy", assign to c2
// TODO: Fill in
c2 = Mockito.mock(Cat.class);
Mockito.when(c2.getId()).thenReturn(2);
Mockito.when(c2.getName()).thenReturn("Old Deuteronomy");
// 4. Create a mock Cat with ID 3 and name "Mistoffelees", assign to c3
// TODO: Fill in
c3 = Mockito.mock(Cat.class);
Mockito.when(c3.getId()).thenReturn(3);
Mockito.when(c3.getName()).thenReturn("Mistoffelees");
// Hint: You will have to stub the mocked Cats to make them behave as if the ID
// is 1 and name is "Jennyanydots", etc.
}
@After
public void tearDown() throws Exception {
// Not necessary strictly speaking since the references will be overwritten in
// the next setUp call anyway and Java has automatic garbage collection.
r = null;
c1 = null;
c2 = null;
c3 = null;
}
/**
* Test case for Cat getCat(int id).
* Preconditions: r has no cats.
* Execution steps: Call getCat(2).
* Postconditions: Return value is null.
*/
@Test
public void testGetCatNullNumCats0() {
assertNull(r.getCat(2));
}
/**
* Test case for Cat getCat(int id).
* Preconditions: c1, c2, and c3 are added to r using addCat(Cat c).
* Execution steps: Call getCat(2).
* Postconditions: Return value is not null.
* Returned cat has an ID of 2.
*/
@Test
public void testGetCatNumCats3() {
r.addCat(c1);
r.addCat(c2);
r.addCat(c3);
assert(r.getCat(2).getId() == 2) : "getcat shoud be 2";
}
/**
* Test case for boolean catAvailable(int id).
* Preconditions: r has no cats.
* Execution steps: Call catAvailable(2).
* Postconditions: Return value is false.
*/
@Test
public void testCatAvailableFalseNumCats0() {
assert(r.catAvailable(2)==false) : "No cats but catAvailable(2) returns true";
}
/**
* Test case for boolean catAvailable(int id).
* Preconditions: c1, c2, and c3 are added to r using addCat(Cat c).
* c3 is rented.
* c1 and c2 are not rented.
* Execution steps: Call catAvailable(2).
* Postconditions: Return value is true.
*/
@Test
public void testCatAvailableTrueNumCats3() {
r.addCat(c1);
r.addCat(c2);
r.addCat(c3);
r.rentCat(3);
assert(r.catAvailable(2) == true) : "3 cats and cat 2 is not rented but catAvailable(2) returns false";
}
/**
* Test case for boolean catAvailable(int id).
* Preconditions: c1, c2, and c3 are added to r using addCat(Cat c).
* c2 is rented.
* c1 and c3 are not rented.
* Execution steps: Call catAvailable(2).
* Postconditions: Return value is false.
*/
@Test
public void testCatAvailableFalseNumCats3() {
r.addCat(c1);
r.addCat(c2);
r.addCat(c3);
r.rentCat(2);;
assert(r.catAvailable(2) == false) : "3 cats and cat 2 is rented but catAvailable(2) returns true";
}
/**
* Test case for boolean catExists(int id).
* Preconditions: r has no cats.
* Execution steps: Call catExists(2).
* Postconditions: Return value is false.
*/
@Test
public void testCatExistsFalseNumCats0() {
assert(r.catExists(2)==false) : "No cats but catExists(2) returns true";
}
/**
* Test case for boolean catExists(int id).
* Preconditions: c1, c2, and c3 are added to r using addCat(Cat c).
* Execution steps: Call catExists(2).
* Postconditions: Return value is true.
*/
@Test
public void testCatExistsTrueNumCats3() {
r.addCat(c1);
r.addCat(c2);
r.addCat(c3);
assert(r.catExists(2)==true) : "3 cats but catExists(2) returns false";
}
/**
* Test case for String listCats().
* Preconditions: r has no cats.
* Execution steps: Call listCats().
* Postconditions: Return value is "".
*/
@Test
public void testListCatsNumCats0() {
assert(r.listCats().equals("")) : "No cats but listCats() returns non-empty string expected:<[]> but was:<[empty]>";
}
/**
* Test case for String listCats().
* Preconditions: c1, c2, and c3 are added to r using addCat(Cat c).
* Execution steps: Call listCats().
* Postconditions: Return value is "ID 1. Jennyanydots\nID 2. Old
* Deuteronomy\nID 3. Mistoffelees\n".
*/
@Test
public void testListCatsNumCats3() {
r.addCat(c1);
r.addCat(c2);
r.addCat(c3);
String ret = "ID 1. Jennyanydots\nID 2. Old Deuteronomy\nID 3. Mistoffelees\n";
assert(r.listCats().equals(ret)) : "3 cats and listCats() does not return the expected string expected:<ID 1. Jennyanydots[\r\n" +
"ID 2. Old Deuteronomy\r\n" +
"ID 3. Mistoffelees\r\n" +
"]> but was:<ID 1. Jennyanydots[ ID 2. Old Deuteronomy ID 3. Mistoffelees ]>";
}
/**
* Test case for boolean rentCat(int id).
* Preconditions: r has no cats.
* Execution steps: Call rentCat(2).
* Postconditions: Return value is false.
*/
@Test
public void testRentCatFailureNumCats0() {
assert(r.rentCat(2) == false) : "No cats but rentCat(2) returns true";
}
/**
* Test case for boolean rentCat(int id).
* Preconditions: c1, c2, and c3 are added to r using addCat(Cat c).
* c2 is rented.
* Execution steps: Call rentCat(2).
* Postconditions: Return value is false.
* c1.rentCat(), c2.rentCat(), c3.rentCat() are never called.
*
* Hint: See Example/NoogieTest.java in testBadgerPlayCalled method to see an
* example of behavior verification.
*/
@Test
public void testRentCatFailureNumCats3() {
r.addCat(c1);
r.addCat(c2);
r.addCat(c3);
r.rentCat(2);
assert(r.rentCat(2)==false) : "3 cats and cat 2 is rented but rentCat(2) returns true";
Mockito.verify(c1,Mockito.times(0)).rentCat();
Mockito.verify(c2,Mockito.times(0)).rentCat();
Mockito.verify(c3,Mockito.times(0)).rentCat();
}
/**
* Test case for boolean returnCat(int id).
* Preconditions: r has no cats.
* Execution steps: Call returnCat(2).
* Postconditions: Return value is false.
*/
@Test
public void testReturnCatFailureNumCats0() {
assert(r.returnCat(2)==false) : "No cats but returnCat(2) returns true";
}
/**
* Test case for boolean returnCat(int id).
* Preconditions: c1, c2, and c3 are added to r using addCat(Cat c).
* c2 is rented.
* Execution steps: Call returnCat(2).
* Postconditions: Return value is true.
* c2.returnCat() is called exactly once.
* c1.returnCat() and c3.returnCat are never called.
*
* Hint: See Example/NoogieTest.java in testBadgerPlayCalled method to see an
* example of behavior verification.
*/
@Test
public void testReturnCatNumCats3() {
r.addCat(c1);
r.addCat(c2);
r.addCat(c3);
c2.rentCat();;
assert(r.returnCat(2)==true);
Mockito.verify(c1,Mockito.times(0)).returnCat();
Mockito.verify(c2,Mockito.times(1)).returnCat();
Mockito.verify(c3,Mockito.times(0)).returnCat();
}
}
<file_sep>// Generated by Selenium IDE
import org.junit.Test;
import org.junit.Before;
import org.junit.After;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.IsNot.not;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Alert;
import org.openqa.selenium.Keys;
import java.util.*;
import java.net.MalformedURLException;
import java.net.URL;
public class RedditCatsTest {
private WebDriver driver;
private Map<String, Object> vars;
JavascriptExecutor js;
@Before
public void setUp() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
driver = new ChromeDriver(options);
js = (JavascriptExecutor) driver;
vars = new HashMap<String, Object>();
}
@After
public void tearDown() {
driver.quit();
}
@Test
public void fUNTITLE() {
driver.get("https://www.reddit.com/r/cats/");
driver.manage().window().setSize(new Dimension(966, 990));
driver.findElement(By.xpath("//div[@id=\'SHORTCUT_FOCUSABLE_DIV\']/div[2]/div/div/div/div[2]/div/div/div/div/div/h1")).click();
assertThat(driver.getTitle(), is("Cats"));
}
@Test
public void fUNJOINBUTTONEXISTS() {
driver.get("https://www.reddit.com/r/cats/");
driver.manage().window().setSize(new Dimension(969, 990));
driver.findElement(By.cssSelector(".\\_3I4Wpl_rl6oTm02aWPZayD")).click();
assertThat(driver.findElement(By.xpath("//div[@id=\'SHORTCUT_FOCUSABLE_DIV\']/div[2]/div/div/div/div[2]/div/div/div/div/div[2]/button")).getText(), is("JOIN"));
}
@Test
public void fUNRULE3() {
driver.get("https://www.reddit.com/r/cats/");
driver.manage().window().setSize(new Dimension(977, 990));
driver.findElement(By.cssSelector(".\\_3I4Wpl_rl6oTm02aWPZayD")).click();
// The rules box is located in the bottom right corner
assertThat(driver.findElement(By.xpath("//div[@id=\'SHORTCUT_FOCUSABLE_DIV\']/div[2]/div/div/div/div[2]/div[3]/div[2]/div/div[5]/div/div[2]/div[3]/div/div[2]/div")).getText(), is("No NSFW, animal abuse, or cruelty"));
}
@Test
public void fUNRULES11ITEMS() {
driver.get("https://www.reddit.com/r/cats/");
driver.manage().window().setSize(new Dimension(981, 990));
driver.findElement(By.cssSelector(".\\_3I4Wpl_rl6oTm02aWPZayD")).click();
{
WebElement element = driver.findElement(By.cssSelector(".\\_2RkQc9Gtsq3cPQNZLYv4zc"));
Actions builder = new Actions(driver);
builder.moveToElement(element).perform();
}
// 11th element present
{
List<WebElement> elements = driver.findElements(By.xpath("//div[@id=\'SHORTCUT_FOCUSABLE_DIV\']/div[2]/div/div/div/div[2]/div[3]/div[2]/div/div[5]/div/div[2]/div[11]/div/div/div"));
assert(elements.size() > 0);
}
// 12th element not present
{
List<WebElement> elements = driver.findElements(By.xpath("//div[@id=\'SHORTCUT_FOCUSABLE_DIV\']/div[2]/div/div/div/div[2]/div[3]/div[2]/div/div[5]/div/div[2]/div[12]/div/div/div"));
assert(elements.size() == 0);
}
}
@Test
public void fUNSIGNUPLINK() {
driver.get("https://www.reddit.com/r/cats/");
driver.manage().window().setSize(new Dimension(972, 990));
driver.findElement(By.cssSelector(".\\_3I4Wpl_rl6oTm02aWPZayD")).click();
// variable for sign up button
{
WebElement element = driver.findElement(By.xpath("//a[contains(@href, \'https://www.reddit.com/register/?dest=https%3A%2F%2Fwww.reddit.com%2Fr%2Fcats%2F\')]"));
String attribute = element.getAttribute("href");
vars.put("signUp", attribute);
}
// link should be the same
assertEquals(vars.get("signUp").toString(), "https://www.reddit.com/register/?dest=https%3A%2F%2Fwww.reddit.com%2Fr%2Fcats%2F");
}
@Test
public void fUNSEARCHSMELLYCAT() {
driver.get("https://www.reddit.com/r/cats/");
driver.manage().window().setSize(new Dimension(974, 990));
driver.findElement(By.cssSelector(".\\_3I4Wpl_rl6oTm02aWPZayD")).click();
{
WebElement element = driver.findElement(By.cssSelector(".\\_2RkQc9Gtsq3cPQNZLYv4zc"));
Actions builder = new Actions(driver);
builder.moveToElement(element).perform();
}
driver.findElement(By.id("header-search-bar")).click();
driver.findElement(By.id("header-search-bar")).sendKeys("smelly cat");
driver.findElement(By.id("header-search-bar")).sendKeys(Keys.ENTER);
// list of results will display the search term "smelly cat" at the top above "Search results"
assertThat(driver.findElement(By.cssSelector(".\\_3j9XjJayuKq7dJ8huVnCuS")).getText(), is("smelly cat"));
}
}
| 104f72a2018693a712cd911ba23481e72bddc609 | [
"Java"
] | 2 | Java | vahob/cs1632 | a06a1ab81435b2bc2418bb839e56cebffd844828 | 2d0b9d5f743f795f086c907e4c3c11efb6a836a8 | |
refs/heads/master | <file_sep><?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass="App\Repository\CurrencyRepository")
*/
//create Currency database
class Currency
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
public function getId(): ?int
{
return $this->id;
}
// validation assert
/**
* @ORM\Column(type="text")
* @Assert\Currency
**/
private $name;
//getters and setters
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
}
<file_sep># currency-calculator
Currency Calcylator - Readme file
For the needs of our project, we used PHP framework, Symfony 4 and we were programming mostly in PHP and JavaScript.
Also we used CSS and Bootstrap for stylesheet and twig template engine for our pages.
First of all we built ourController.php for rendering the pages and get used it as our server. After we set the requirements we needed,
we created our routes: Home (for home page), login (for login page), admin (for administrator page) and delete
(for deleting the currencies from administrator page).
On home page (templates/pages/index.html.twig) we have a form where there are the options of base currency,
amount (if it is empty, a prompt message shows up and reloads the page) and exchange.
After user gives his options and click the calculation button, a JavaScript function make the calculation and send the proper message
on the screen.
On administrator page (templates/pages/admin.html.twig) we have access after log in authentication (templates/pages/login.html.twig),
the administrator has the ability to add and delete a currency for the home page. The currency must be validated.
Furthermore we created a JavaScript file (public/index.js) with a function which makes the calculation of currencies after getting APIs
for them and sends the proper message to home page and also a callback function which deletes from the database and by extension from the
screen, the currencies from administrator page.
Finally, for our database we created an Entity with the use of Composer (src/Enity/Currency.php).
Composer also helped us for the annotations, form creation (for administrator page), validator and authentication
(creation of config/security.yaml where you can find username (administrator) and password for login page).
<file_sep>function currencyCalculation(){
var base = document.querySelector(".base").value;
var amount = document.querySelector(".amount").value;
var exchange = document.querySelector(".exchange").value;
var request = new XMLHttpRequest();
// get API for the currencies
request.open("GET", "https://api.exchangeratesapi.io/latest?base=" + base);
request.onload = function(){
var data = JSON.parse(request.responseText);
var keyNames = Object.keys(data.rates);
var values = Object.values(data.rates);
console.log(keyNames);
if (amount === ""){
alert("Please fill the 'Amount' box!");
location.reload();
}
if (base === exchange){
var result = amount;
} else {
for (var i = 0; i < keyNames.length; i++){
if (keyNames[i] === exchange){
var result = (amount) * (values[i]);
break;
}
}
}
document.querySelector(".show-result").innerHTML = "Today, " + data.date + ", " + amount + " " + base + " are equal to " + result + " " + exchange + "!"
};
request.send();
}
// callback function for deleting currency
var currencies = document.querySelectorAll(".admin-currencies");
for (var i = 0; i < currencies.length; i++){
currencies[i].addEventListener("click", function(e){
if (e.target.className === "btn btn-danger btn-sm"){
var id = e.target.getAttribute("id");
var route = `/currency-calculator/public/delete/${id}`;
var newReq = new XMLHttpRequest();
newReq.open("DELETE", route);
newReq.onload = function(){
location.reload();
};
newReq.send();
}
});
}
<file_sep><?php
namespace App\Controller;
use App\Entity\Currency;
//requirements
use Symfony\Component\HttpFoundation\Response;
//use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
//create ourController
class ourController extends Controller{
/**
* @Route("/", name="home")
* @Method({"GET"})
**/
public function index(){
$currencies = $this->getDoctrine()->getRepository(Currency::class)->findAll();
return $this->render('pages/index.html.twig', array("currencies" => $currencies));
}
/**
* @Route("/login", name="login")
* @Method({"GET", "POST"})
*/
public function login(AuthenticationUtils $authenticationUtils){
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('pages/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
]);
}
/**
* @Route("/admin", name="admin")
* @Method({"GET", "POST"})
**/
public function adminPage(Request $request, ValidatorInterface $validator){
$currency = new Currency();
// form creation
$form = $this->createFormBuilder($currency)
->add("name", TextType::class, array("attr" => array("class" => "form-control admin-form")))
->add("save", SubmitType::class, array("label" => "Add", "attr" => array("class" => "btn btn-primary btn-add")))
->getForm();
$form->handleRequest($request);
//get data from the form to database
if($form->isSubmitted() && $form->isValid()){
$currency = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($currency);
$entityManager->flush();
return $this->redirectToRoute("admin");
}
$currencies = $this->getDoctrine()->getRepository(Currency::class)->findAll();
return $this->render('pages/admin.html.twig', array("form" => $form->createView(), "currencies" => $currencies));
}
/**
* @Route("/delete/{id}", name="delete")
* @Method({"DELETE"})
**/
public function delete(Request $request, $id){
//delete from database
$currency = $this->getDoctrine()->getRepository(Currency::class)->find($id);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($currency);
$entityManager->flush();
$response = new Response();
$response->send();
}
/**
* @Route("/logout", name="logout")
* @Method({"GET"})
**/
}
?>
| e37d474a4269594a2df3e29dcfd5c8b8fa28dddb | [
"Markdown",
"JavaScript",
"PHP"
] | 4 | PHP | vstogiannis/currency-calculator | cbb95d61934679c5fa9a0a01ed3635020c6d5035 | 0cf8325d281354bb3aafc3a94c00f894066d95db | |
refs/heads/master | <repo_name>liyuan837/leolder<file_sep>/src/main/java/com/liyuan/demo/controller/HeroController.java
package com.liyuan.demo.controller;
import com.liyuan.demo.entity.Hero;
import com.liyuan.demo.service.HeroService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author:LiYuan
* @description:
* @Date:Create in 15:28 2018/2/8
* @Modified By:
*/
@RestController
@RequestMapping("/hero")
public class HeroController {
@Autowired
private HeroService heroService;
@GetMapping("/get")
public Map<String,Object> list(){
Map<String,Object> modelMap = new HashMap<>();
List<Hero> list = heroService.queryAll();
modelMap.put("list",list);
return modelMap;
}
@GetMapping("/get/{id}")
public Map<String,Object> find(@PathVariable("id") Integer id){
Map<String,Object> modelMap = new HashMap<>();
Hero hero = heroService.findById(id);
modelMap.put("hero",hero);
return modelMap;
}
@PostMapping("/post")
public Map<String,Object> post(@RequestBody Hero hero){
Map<String,Object> modelMap = new HashMap<>();
Integer id = heroService.saveHero(hero);
hero.setId(id);
modelMap.put("hero",hero);
return modelMap;
}
@PostMapping("/put")
public Map<String,Object> put(@RequestBody Hero hero){
Map<String,Object> modelMap = new HashMap<>();
Integer result = heroService.updateHero(hero);
modelMap.put("hero",hero);
return modelMap;
}
@GetMapping("/delete/{id}")
public Map<String,Object> delete(@PathVariable("id") Integer id){
Map<String,Object> modelMap = new HashMap<>();
Integer result = heroService.deleteHero(id);
modelMap.put("result","deleteSuccess");
return modelMap;
}
/**
* 实现文件上传
* */
@RequestMapping(value="/fileUpload",method = RequestMethod.POST)
@ResponseBody
public String fileUpload(MultipartFile file){
if(file.isEmpty()){
return "false";
}
String fileName = file.getOriginalFilename();
String path = System.getProperty("user.dir") + "/uploadFile" ;
System.out.println(path);
File dest = new File(path + "/" + fileName);
if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest); //保存文件
return "true";
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
}
}
//文件下载相关代码
@RequestMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "1.png";// 设置文件名,根据业务需要替换成要下载的文件名
System.out.println(fileName);
if (fileName != null) {
//设置文件路径
String realPath = "D:/workspace_idea/leolder/leolder/uploadFile/";
File file = new File(realPath , fileName);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
}
<file_sep>/src/main/java/wechat/util/CertHttpUtil.java
package wechat.util;
public class CertHttpUtil {
//
// private static int socketTimeout = 10000;// 连接超时时间,默认10秒
// private static int connectTimeout = 30000;// 传输超时时间,默认30秒
// private static RequestConfig requestConfig;// 请求器的配置
// private static CloseableHttpClient httpClient;// HTTP请求器
//
// public static Map<String,String> refundOrder(Order order) throws Exception{
// //创建退款订单
// RefundOrder refundOrder = new RefundOrder();
// refundOrder.setAppid(ConstantsUtil.appid);
// refundOrder.setMch_id(ConstantsUtil.mchId);
// refundOrder.setNonce_str(UUID.randomUUID().toString().replace("-", "").substring(0,32));
// refundOrder.setOut_refund_no(ConstantsUtil.mchId);
// refundOrder.setOut_refund_no(order.getBackcode());
// refundOrder.setOut_trade_no(order.getOrdercode());
// refundOrder.setTotal_fee((int) (1));
// refundOrder.setRefund_fee((int) (1));
// refundOrder.setOp_user_id(ConstantsUtil.mchId);
// refundOrder.setSign(createSign(refundOrder));
//
// //将集合转换成xml
// String requestXML =MessageUtil.messageToXml(refundOrder).replace("__", "_");
// System.out.println("请求:"+requestXML);
// //带证书的post
//// String resXml = CertHttpUtil.postData(ConstantsUtil.refundUrl, requestXML);
// String resXml = postData(ConstantsUtil.refundUrl, requestXML);
// System.out.println("结果:"+resXml);
// //解析xml为集合,请打断点查看resXml详细信息
// Map<String,String> resultMap = MessageUtil.parseXml(resXml);
//
// return resultMap;
// }
//
// /**
// * 通过Https往API post xml数据
// *
// * @param url
// * API地址
// * @param xmlObj
// * 要提交的XML数据对象
// * @return
// * @throws Exception
// */
// public static String postData(String url, String xmlObj) throws Exception {
// // 加载证书
// try {
// initCert();
// } catch (Exception e) {
// e.printStackTrace();
// }
// String result = null;
// HttpPost httpPost = new HttpPost(url);
// // 得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别
// StringEntity postEntity = new StringEntity(xmlObj, "UTF-8");
// httpPost.addHeader("Content-Type", "text/xml");
// httpPost.setEntity(postEntity);
// // 根据默认超时限制初始化requestConfig
// requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
// .setConnectTimeout(connectTimeout).build();
// // 设置请求器的配置
// httpPost.setConfig(requestConfig);
// try {
// HttpResponse response = null;
// try {
// response = httpClient.execute(httpPost);
// } catch (IOException e) {
// e.printStackTrace();
// }
// HttpEntity entity = response.getEntity();
// try {
// result = EntityUtils.toString(entity, "UTF-8");
// } catch (IOException e) {
// e.printStackTrace();
// }
// } finally {
// httpPost.abort();
// }
// return result;
// }
//
// /**
// * 加载证书
// *
// */
// private static void initCert() throws Exception {
// // 证书密码,默认为商户ID
// String key = ConstantsUtil.mchId;
// // 证书的路径
// String path = ConstantsUtil.certPath;
// // 指定读取证书格式为PKCS12
// KeyStore keyStore = KeyStore.getInstance("PKCS12");
// // 读取本机存放的PKCS12证书文件
// FileInputStream instream = new FileInputStream(new File(path));
// try {
// // 指定PKCS12的密码(商户ID)
// keyStore.load(instream, key.toCharArray());
// } finally {
// instream.close();
// }
// SSLContext sslcontext = SSLContexts.custom()
// .loadKeyMaterial(keyStore, key.toCharArray()).build();
// // 指定TLS版本
// SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
// sslcontext, new String[] { "TLSv1" }, null,
// SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
// // 设置httpclient的SSLSocketFactory
// httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
// }
//
// // 生成退款单sign
// private static String createSign(RefundOrder refundOrder) {
// SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
// /**
// * 组装请求参数 按照ASCII排序
// */
// parameters.put("appid", refundOrder.getAppid());
// parameters.put("mch_id", refundOrder.getMch_id());
// parameters.put("nonce_str", refundOrder.getNonce_str());
// parameters.put("out_trade_no", refundOrder.getOut_trade_no());
// parameters.put("out_refund_no", refundOrder.getOut_refund_no());
// parameters.put("total_fee", refundOrder.getTotal_fee());
// parameters.put("refund_fee",refundOrder.getRefund_fee());
// parameters.put("op_user_id", refundOrder.getOp_user_id());
//
// StringBuffer sb = new StringBuffer();
// Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序(升序)
// Iterator it = es.iterator();
// while (it.hasNext()) {
// Map.Entry entry = (Map.Entry) it.next();
// String k = (String) entry.getKey();
// Object v = entry.getValue();
// if (null != v && !"".equals(v) && !"sign".equals(k)
// && !"key".equals(k)) {
// sb.append(k + "=" + v + "&");
// }
// }
// sb.append("key=" + ConstantsUtil.payKey);
// String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
// return sign;
//
// }
}<file_sep>/src/main/java/wechat/util/WxPayUtils.java
package wechat.util;
import wechat.constants.ConstantsUtil;
import wechat.pojo.JsAPIConfig;
import wechat.pojo.UnifiedOrder;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
public class WxPayUtils {
/**
* 统一下单
*
* @Title: unifiedOrder
* @Description: TODO
* @param: @param openId 微信用户openId
* @param: @param order 系统订单信息
* @param: @param callbackUrl 回调路径
* @param: @return
* @param: @throws Exception
* @return: String prepay_id
*/
// public static JsAPIConfig unifiedOrder(HttpServletRequest request, String openId, Order order,
// String callbackUrl) throws Exception {
// //[1]创建统一订单对象
// UnifiedOrder unifiedOrder = new UnifiedOrder();
// unifiedOrder.setAppid(ConstantsUtil.appid);
//
// unifiedOrder.setBody("desc");
// unifiedOrder.setMch_id(ConstantsUtil.mchId);
//
// String nonce = UUID.randomUUID().toString().replace("-", "").substring(0,32);
// unifiedOrder.setNonce_str(nonce);
// unifiedOrder.setNotify_url(callbackUrl);
//
// unifiedOrder.setOpenid(openId);
// unifiedOrder.setOut_trade_no(order.getOrdercode());
//
// //服务器端ip
// unifiedOrder.setSpbill_create_ip(getRemoteIpAddr(request));
//
// //测试付款:1分
// unifiedOrder.setTotal_fee((int)(order.getTotalprice()*100));
//
// //生成统一订单签名
// String sign = createSign(unifiedOrder);
// unifiedOrder.setSign(sign);
//
// //[2]转化成xml
// String xml = MessageUtil.messageToXml(unifiedOrder).replace("__", "_");
//
// System.out.println("统一下单XML:"+xml);
//
// //[3]统一下单,并返回获取prepay_id:
// String resultXml = httpsRequest(ConstantsUtil.unifiedOrderUrl,xml);
//
// System.out.println("统一下单返回结果"+resultXml);
//
// //[4]解析返回数据
// Map<String,String> resultMap = MessageUtil.parseXml(resultXml);
//
// if(resultMap.get("return_code").equals("SUCCESS")){
// //通信成功
// //System.out.println("通信成功,提示信息:"+resultMap.get("return_msg"));
//
// if(resultMap.get("result_code").equals("SUCCESS")){
// //统一下单成功,生成JSAPIconfig对象
// System.out.println("统一下单成功,提示信息:"+resultMap.get("return_msg"));
// return createPayConfig(resultMap,unifiedOrder);
//
// }else{
// //统一下单失败
// //System.out.println("统一下单失败,错误信息:"+resultMap.get("return_msg"));
// JsAPIConfig config = new JsAPIConfig();
// config.setResult_msg("unifiedOrder_fail");
// return config;
// }
//
// }else
// {
// //通信失败
// //System.out.println("通信失败,错误信息:"+resultMap.get("return_msg"));
// JsAPIConfig config = new JsAPIConfig();
// config.setResult_msg("unifiedOrder_fail");
// return config;
//
// }
//
//
//
// }
/**
* 生成支付配置
* @Title: createPayConfig
* @Description: TODO
* @param @param preayId 统一下单prepay_id
* @param @return
* @param @throws Exception
* @return JsAPIConfig
* @throws
*/
public static JsAPIConfig createPayConfig(Map<String,String> resultMap,UnifiedOrder unifiedOrder) throws Exception {
JsAPIConfig config = new JsAPIConfig();
config.setResult_msg("SUCCESS");
String nonce = UUID.randomUUID().toString().replace("-", "").substring(0,32);
String timestamp = Long.toString(System.currentTimeMillis() / 1000);
String packageName = "prepay_id="+resultMap.get("prepay_id");
config.setAppId(ConstantsUtil.appid);
config.setNonce(nonce);
config.setTimestamp(timestamp);
config.setPackageName(packageName);
String signature = createSignature(config);
config.setSignature(signature);
return config;
}
//获取客户端真实的IP
public static String getRemoteIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
//生成统一下单sign
private static String createSign(UnifiedOrder unifiedOrder){
SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
/**
* 组装请求参数
* 按照ASCII排序
*/
parameters.put("appid",unifiedOrder.getAppid());
parameters.put("body", unifiedOrder.getBody());
parameters.put("mch_id", unifiedOrder.getMch_id());
parameters.put("nonce_str", unifiedOrder.getNonce_str());
parameters.put("out_trade_no", unifiedOrder.getOut_trade_no());
parameters.put("notify_url", unifiedOrder.getNotify_url());
parameters.put("spbill_create_ip", unifiedOrder.getSpbill_create_ip());
parameters.put("total_fee",unifiedOrder.getTotal_fee());
parameters.put("trade_type",unifiedOrder.getTrade_type());
parameters.put("openid", unifiedOrder.getOpenid());
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序(升序)
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
if(null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + ConstantsUtil.payKey);
String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
return sign;
}
//生成调起支付的signature
private static String createSignature(JsAPIConfig config){
SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
/**
* 组装请求参数
* 按照ASCII排序
*/
parameters.put("appId",ConstantsUtil.appid);
parameters.put("nonceStr",config.getNonce());
parameters.put("package", config.getPackageName());
parameters.put("signType", config.getSignType());
parameters.put("timeStamp", config.getTimestamp());
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序(升序)
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
if(null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + ConstantsUtil.payKey);
String signature = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
return signature;
}
public static String httpsRequest(String requestUrl, String xmlStr) {
try{
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
OutputStream outputStream = connection.getOutputStream();
outputStream.write(xmlStr.getBytes("UTF-8"));
outputStream.close();
// 从输入流读取返回内容
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
connection.disconnect();
return buffer.toString();
}catch(Exception ex){
ex.printStackTrace();
}
return "";
}
}
<file_sep>/src/main/java/wechat/servlet/JSApiServlet.java
package wechat.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import wechat.constants.ConstantsUtil;
import wechat.util.Sha1Util;
import wechat.util.SignUtil;
import wechat.util.TokenThread;
/**
* 请求获取Jsapi_ticket,以求在页面上调用微信js
*/
public class JSApiServlet extends HttpServlet {
private static final long serialVersionUID = 4440739483644821986L;
/**
* 请求校验(确认请求来自微信服务器)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 微信加密签名
String signature = request.getParameter("signature");
// 时间戳
String timestamp = request.getParameter("timestamp");
// 随机数
String nonce = request.getParameter("nonce");
// 随机字符串
String echostr = request.getParameter("echostr");
PrintWriter out = response.getWriter();
// 请求校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
out.print(echostr);
}
out.close();
out = null;
}
/**
* 处理微信服务器发来的消息
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
request.setCharacterEncoding("UTF-8");
response.setHeader("Content-type", "text/html;charset=UTF-8");
getConfig(request, response);
}
public void getConfig(HttpServletRequest request,HttpServletResponse response){
//获取appId
String appid = ConstantsUtil.appid;
//获取页面路径(前端获取时采用location.href.split('#')[0]获取url)
String url = request.getParameter("url");
//获取access_token
//String access_token = CommonUtil.getToken(appid, appsecret).getAccessToken();
//获取ticket
//String jsapi_ticket = CommonUtil.getJSApiTicket(access_token);
String jsapi_ticket = TokenThread.jsapiTicket;
//获取Unix时间戳(java时间戳为13位,所以要截取最后3位,保留前10位)
String timeStamp = String.valueOf(System.currentTimeMillis()).substring(0, 10);
//创建有序的Map用于创建签名串
SortedMap<String, String> params = new TreeMap<String, String>();
params.put("jsapi_ticket", jsapi_ticket);
params.put("timestamp", timeStamp);
String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
params.put("noncestr", uuid);
params.put("url", url);
//签名
String signature = "";
try {
signature = Sha1Util.createSHA1Sign(params);
}catch (Exception e) {
e.printStackTrace();
}
//得到签名再组装到Map里
params.put("signature", signature);
//传入对应的appId
params.put("appId", appid);
//组装完毕,回传
try {
JSONArray jsonArray = JSONArray.fromObject(params);
// System.out.println(jsonArray.toString());
PrintWriter out = response.getWriter();
out.print(jsonArray);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/src/main/java/wechat/util/TokenThread.java
package wechat.util;
import wechat.constants.ConstantsUtil;
import wechat.pojo.Token;
/**
* 线程,获取accessToken
* 用于保存获取到的access_token和jsapiTicket
*/
public class TokenThread implements Runnable
{
public static String appid = ConstantsUtil.appid;
public static String appsecret = ConstantsUtil.appsecret;
public static Token accessToken = null;
public static String jsapiTicket = null;
//两小时运行一次
public void run()
{
while (true)
{
try
{
//先获取accessToken
accessToken =CommonUtil.getToken(appid, appsecret);
System.out.println("获取到accessToken:"+accessToken);
if (null != accessToken)
{
//通过凭证accessToken调用微信API接口,来获取jsapi的ticket
jsapiTicket = CommonUtil.getJSApiTicket(accessToken.getAccessToken());
if (null != jsapiTicket)
{
// 休眠7000秒:如果获取成功,则7000s内不需要在获取
System.out.println("获取到jsapiTicket:"+jsapiTicket);
Thread.sleep((accessToken.getExpiresIn() - 200) * 1000);
}
else
{
//如果获取失败,则60s后再次尝试获取
Thread.sleep(60 * 1000);
}
}
else
{
// 如果access_token为null,60秒后再获取
Thread.sleep(60 * 1000);
}
}
catch (InterruptedException e)
{
try
{
Thread.sleep(60 * 1000);
}
catch (InterruptedException e1)
{
}
}
}
}
}
<file_sep>/src/main/java/wechat/servlet/InitServlet.java
package wechat.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import wechat.constants.ConstantsUtil;
import wechat.util.TokenThread;
/**
* 中控服务器:实现定时获取凭证access_token,在启动的时候实例化并调用其init()方法
*/
public class InitServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void init() throws ServletException
{
// 未配置APPID、APPSECRET时不启动线程
if ("".equals(TokenThread.appid) || "".equals(TokenThread.appsecret))
{
System.out.println("请先配置appID和appSecret...");
}
else
{
// 启动定时获取access_token的线程
new Thread(new TokenThread()).start();
}
//加载证书
ConstantsUtil.certPath = this.getClass().getClassLoader().getResource("apiclient_cert.p12").getPath();
System.out.println("加载证书路径:"+ConstantsUtil.certPath);
}
}
<file_sep>/src/main/java/com/liyuan/demo/constants/ConstantUtils.java
package com.liyuan.demo.constants;
/**
* 项目常量类
* @author Administrator
*
*/
public class ConstantUtils {
//项目域名地址
public static final String serverPath = "http://www.dyjkglass.com/";
}
| 730202cf298d0e45f9d31bee996be16ec5795d1d | [
"Java"
] | 7 | Java | liyuan837/leolder | 01040f5dda4e6db697d19a38699e3ae3de662efa | 36a97fd8db303515c724243a4f2766e987a4a65e | |
refs/heads/master | <file_sep>A small experiment to generate the badges for speakers at Codemotion. To generate the list of badges, run the following:
```
python -m SimpleHTTPServer 8000
```
Tne open http://localhost:8000 with either Firefox or Explorer. Printing with background images seems to be extremely brittle cross-browser; with Chrome it will not work at all, Firefox may pixelate the image, Explorer with PDF995 works just fine.
Remember to set the page size according to your print CSS (A5 portrait would be the usual). <file_sep>//fetch('agenda.json')
fetch('https://www.koliseo.com/codemotion/codemotion-madrid/r4p/5753906952929280/agenda', {
method: 'get',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(function(response) {
return response.json();
})
.then(function(agenda) {
var speakers = {};
agenda.days.forEach(function(day) {
day.tracks.forEach(function(track) {
track.slots.forEach(function(slot) {
var contents = slot.contents;
if (contents && contents.type == 'TALK') {
contents.authors.forEach(function(author) {
speakers[author.id] = author
})
}
})
})
})
console.log(speakers);
var speakerValues = [];
for (var s in speakers) {
speakerValues.push(speakers[s]);
}
speakerValues.sort(function(s1, s2) {
return s1.name.localeCompare(s2.name);
});
document.getElementsByClassName('badges')[0].innerHTML = speakerValues.map(function(speaker) {
var twitter = !speaker.twitterAccount? '' : ('<br><div class="twitter">@' + speaker.twitterAccount + '</div>');
return '<section class="badge"><div class="cutting-top"></div><div class="badge-contents"><img class="avatar" src="' + speaker.avatar + '"><div class="name">' +
speaker.name + twitter + '</div></div><div class="cutting-bottom"></div></section>'
}).join('');
})
.catch(function(e) {
console.error(e.message);
document.getElementsByClassName('badges')[0].innerHTML = e.message;
}); | e73515906e28ae0a5a2a2fe937b6495bc204dbaf | [
"Markdown",
"JavaScript"
] | 2 | Markdown | icoloma/codemotion-badges | ad36879a92005dc5a0f7df61fc8efe74158c1329 | 9dce6e29df9eae247cdd01edbf5b30346bde4f7e | |
refs/heads/master | <repo_name>SamaherAlattas/Game<file_sep>/main.js
let level1=['C','R','T','A','m','o','o','n']
let level=['b','a','r','i','l','l','n','g','e','d']
let level3=['','']
let words1=['CART','CAR','RAT','moon','no','on']
let words=['bring','ball','bread','bed','big','ring']
let user=[]
let x= Math.floor(Math.random() * 6) //understand
let b=0;
// let words=[]
let score=[]
let play=[]
let next= false
// $(".nav").append('<li>'+level1[0]+'</li>');
$(document).ready(function(){
$('.next').hide()
$('.again').hide()
console.log('jjjjjjj')
showLetters();
})
function showLetters(){
//show the letters to the ueser
for (let i = 0; i < level.length; i++) {
$(".nav").append('<li class="A">'+level[i]+'</li>');
}
// prebeing the list of word elements
for (let j = 0; j < words[x].length; j++) {
$(".board").append('<li class='+j+'></li>');
}
}
// moving itereting to full letters
function MakeWord(event){
console.log('works')
console.log('x '+x)
console.log('SS '+words[x].length)
while (true) {
console.log('while')
if($('.board .'+b).text()==""|| $('.board .'+b).text()==null){ //if the lettel place is empty
console.log('yes its empyu')
$('.board .'+b).html('<p>'+$(event.target).text()+'</p>') //git input feom ueser and full the same indes
play.push($(event.target).text()) // save uerer input
console.log(play)
console.log('b '+b)
b++;
break;
}
}
if(play.length==words[x].length){
let word = play.join("")
let flag= false;
console.log('rr '+word)
for (let i = 0; i < words.length; i++) {
if(word == words[i]){ //if the word esest in woed arry
// swal({
// title: "Win",
// text: 'Braaavoooooo',
// html: true,
// });
$('.next').show()
$('.again').show()
$('.resrtBtn').hide()
// $('body').append('<button class="next" >continue</button>')
swal('win :)')
console.log('win :)')
flag=true;
}
}
if(!flag){
swal('lose :(')
console.log('lose :(')
}
}
}
function resetButton(){
console.log('RESET')
b=0// to remove letter by letter
console.log(b)
console.log("AA "+words[x].length)
while (b < words[x].length) {
console.log('before '+ $('.board .'+b).text())
$('.board .'+b).html(null) // make the board empty-- remove
console.log('text '+$('.board .'+b).text())
play.pop()
b++;
}
b=0;// make it zero so it start over
console.log("play "+play)
}
//reset button
$('.resrtBtn').on('click',resetButton)
//click on the letter
$(".nav").on('click', MakeWord)
<file_sep>/README.md
# project
<h3>List technologies :</h3>
1-html
2-css
3-Javascript
4-jQuery
5-GitHub
<h3>wireframes :</h3>
At first, I created a starting page, then a page with letters, and the user will make a word from existing letters.
And then the word is "correct" or "incorrect" will appear.
<h3>Describe how you solved for the winner :</h3>
In the function we define the amount of correct possible words
<h3> favorite functions work :</h3>
swal({
title: "Win",
text: 'Braaavoooooo',
html: true,
});
$('body').append('<button>continue</button>')
// swal('win :)')
console.log('win :)')
flag=true;
}
}
if(!flag){
swal('lose :)')
console.log('lose :(')
}
}
something i did and we didn't cover in class is (SweetAlert2)
# ![](/images/1.jpg)
https://pages.git.generalassemb.ly/samaheralattas/project/
| 764b664354d10ccd0e2f10d3a4c0b2e4cf42068f | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | SamaherAlattas/Game | 3c1c6a9b1bb3470698b02cac13505c8b72b38ce1 | d70aa0592be054e4011801cbc862124844a75bc4 | |
refs/heads/master | <file_sep>
package controllers.chapter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.validation.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import repositories.ParadeRepository;
import services.AreaService;
import services.ChapterService;
import services.FloatService;
import services.ParadeService;
import controllers.AbstractController;
import domain.Area;
import domain.Chapter;
import domain.Parade;
@Controller
@RequestMapping("/parade")
public class ParadeChapterController extends AbstractController {
@Autowired
ChapterService chapterService;
@Autowired
ParadeService paradeService;
@Autowired
FloatService floatService;
@Autowired
AreaService areaService;
@Autowired
ParadeRepository paradeRepository;
@RequestMapping(value = "/chapter/list", method = RequestMethod.GET)
public ModelAndView list() {
ModelAndView res;
final Collection<Parade> parades = this.paradeService.findParadesByChapterId();
final List<Boolean> finalModes = new ArrayList<>();
finalModes.add(true);
finalModes.add(false);
res = new ModelAndView("parade/chapter/list");
res.addObject("parades", parades);
res.addObject("requestURI", "parade/chapter/list.do");
res.addObject("finalModes", finalModes);
return res;
}
@Autowired
Validator validator;
@RequestMapping(value = "/chapter/editStatus", method = RequestMethod.POST, params = "save")
public ModelAndView save(@ModelAttribute Parade parade, final BindingResult binding) {
ModelAndView result;
try {
final Parade paradeOld = this.paradeRepository.findOne(parade.getId());
final String subm = "SUBMITTED";
Assert.isTrue(paradeOld.getStatus() == "SUBMITTED" || paradeOld.getStatus() == subm || paradeOld.getStatus().contains("SUBMITTED"));
parade = this.paradeService.reconstructChapter(parade, binding);
this.paradeService.saveStatus(parade);
result = new ModelAndView("redirect:list.do");
} catch (final ValidationException oops) {
result = this.createEditModelAndView(parade);
} catch (final Throwable oops) {
result = this.createEditModelAndView(parade, "parade.commit.error");
}
return result;
}
@RequestMapping(value = "/chapter/create", method = RequestMethod.GET)
public ModelAndView create() {
ModelAndView res;
Parade parade;
parade = this.paradeService.create();
res = this.createEditModelAndView(parade);
return res;
}
@RequestMapping(value = "/chapter/editStatus", method = RequestMethod.GET)
public ModelAndView edit(@RequestParam final int paradeId) {
ModelAndView result;
Parade parade;
parade = this.paradeService.findOne(paradeId);
//Area de la parade
final Area area = this.areaService.getParadeArea(paradeId);
//Se comprueba que la parade pertenece a la área que gestiona el chapter logeado
final Chapter cha = this.chapterService.findByPrincipal();
Assert.isTrue(area == cha.getArea());
Assert.isTrue(parade.getFinalMode() == false);
result = this.createEditModelAndView(parade);
return result;
}
@RequestMapping(value = "/chapter/editStatus", method = RequestMethod.POST, params = "delete")
public ModelAndView delete(final Parade parade, final BindingResult binding) {
ModelAndView result;
try {
this.paradeService.delete(parade);
result = new ModelAndView("redirect:list.do");
} catch (final Throwable oops) {
result = this.createEditModelAndView(parade, "parade.commit.error");
}
return result;
}
protected ModelAndView createEditModelAndView(final Parade parade) {
ModelAndView result;
result = this.createEditModelAndView(parade, null);
return result;
}
protected ModelAndView createEditModelAndView(final Parade parade, final String message) {
ModelAndView result;
final Collection<Parade> parades = this.paradeService.findParadesByChapterId();
result = new ModelAndView("parade/chapter/editStatus");
result.addObject("parades", parades);
result.addObject("parade", parade);
result.addObject("message", message);
return result;
}
}
<file_sep>
package services;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import repositories.AdministratorRepository;
import security.Authority;
import security.LoginService;
import security.UserAccount;
import utilities.TickerGenerator;
import domain.Actor;
import domain.Administrator;
import domain.Box;
import domain.Customisation;
import domain.Message;
import domain.SocialProfile;
import forms.AdministratorForm;
@Service
@Transactional
public class AdministratorService {
// Repository
@Autowired
private AdministratorRepository administratorRepository;
// Services
@Autowired
public ActorService actorService;
@Autowired
public FinderService finderService;
@Autowired
public CustomisationService customisationService;
@Autowired
public SocialProfileService socialProfileService;
public AdministratorService() {
super();
}
// Simple CRUD
// 8.1
public Administrator create() {
// User can't be logged to register
// final Authority a = new Authority();
// final Authority b = new Authority();
// final Authority c = new Authority();
// final Authority d = new Authority();
// final Authority e = new Authority();
// final UserAccount user = LoginService.getPrincipal();
// a.setAuthority(Authority.ADMIN);
// b.setAuthority(Authority.HANDYWORKER);
// c.setAuthority(Authority.CUSTOMER);
// d.setAuthority(Authority.REFEREE);
// e.setAuthority(Authority.SPONSOR);
// Assert.isTrue(!(user.getAuthorities().contains(a) || user.getAuthorities().contains(b) || user.getAuthorities().contains(c) || user.getAuthorities().contains(d) || user.getAuthorities().contains(e)));
Administrator result;
result = new Administrator();
// Actor
// final Box trash = new Box();
// final Box out = new Box();
// final Box spam = new Box();
// final Box in = new Box();
// trash.setName("trash");
// in.setName("in");
// out.setName("out");
// spam.setName("spam");
// out.setPredefined(true);
// in.setPredefined(true);
// spam.setPredefined(true);
// trash.setPredefined(true);
final Collection<Box> predefined = new ArrayList<Box>();
// predefined.add(in);
// predefined.add(out);
// predefined.add(spam);
// predefined.add(trash);
// result.setBoxes(predefined);
final UserAccount newUser = new UserAccount();
final Authority f = new Authority();
f.setAuthority(Authority.MEMBER);
newUser.addAuthority(f);
result.setUserAccount(newUser);
result.setSocialProfiles(new ArrayList<SocialProfile>());
result.setName("");
result.setEmail("");
result.setAddress("");
result.setSurname("");
result.setPhoneNumber("");
result.setPhoto("");
// Administrator
return result;
}
// Returns logged administrator
public Administrator findByPrincipal() {
Administrator res;
UserAccount userAccount;
userAccount = LoginService.getPrincipal();
Assert.notNull(userAccount);
res = this.findByUserAccount(userAccount);
Assert.notNull(res);
return res;
}
// 11.1
// public Administrator findByFixUpTask(final FixUpTask fixUpTask) {
// // Logged user must be a handyWorker
// final Authority a = new Authority();
// final UserAccount user = LoginService.getPrincipal();
// a.setAuthority(Authority.HANDYWORKER);
// Assert.isTrue(user.getAuthorities().contains(a));
//
// Administrator res;
// res = this.administratorRepository.findFixUpTask(fixUpTask.getId());
// return res;
// }
// Returns logged administrator from his or her userAccount
public Administrator findByUserAccount(final UserAccount userAccount) {
Administrator res;
Assert.notNull(userAccount);
res = this.administratorRepository.findByUserAccountId(userAccount.getId());
return res;
}
public Collection<Administrator> findAll() {
return this.administratorRepository.findAll();
}
public Administrator save(final Administrator mem) {
// Restrictions
Assert.isTrue(mem.getBan() != true);
if (mem.getId() == 0) {
Collection<Box> boxes = actorService.createPredefinedBoxes();
mem.setBoxes(boxes);
final Md5PasswordEncoder encoder = new Md5PasswordEncoder();
final String oldpass = mem.getUserAccount().getPassword();
final String hash = encoder.encodePassword(oldpass, null);
final UserAccount cuenta = mem.getUserAccount();
cuenta.setPassword(<PASSWORD>);
mem.setUserAccount(cuenta);
// final Box in1 = new Box();
// in1.setName("In");
// in1.setPredefined(true);
// final Box in = this.boxService.save(in1);
//
// final Collection<Box> boxesPredefined = new ArrayList<Box>();
// boxesPredefined.add(in);
// cus.setBoxes(boxesPredefined);
}
return this.administratorRepository.save(mem);
}
public Administrator findOne(final int administratorId) {
Administrator c;
Assert.notNull(administratorId);
Assert.isTrue(administratorId != 0);
c = this.administratorRepository.findOne(administratorId);
Assert.notNull(c);
return c;
}
public Administrator reconstruct(final AdministratorForm administratorForm, final BindingResult binding) {
final Administrator administrator = this.create();
Assert.isTrue(administratorForm.isConditionsAccepted());
final Authority adm = new Authority();
adm.setAuthority(Authority.ADMIN);
Assert.isTrue(administratorForm.getUserAccount().getAuthorities().contains(adm));
final Collection<Authority> colAdm = new ArrayList<Authority>();
final Authority memb = new Authority();
memb.setAuthority(Authority.ADMIN);
colAdm.add(memb);
//Assert.isTrue(memberForm.getUserAccount().getAuthorities() == colMem);
//Damos valores a los atributos del member que devolveremos con los datos que nos llegan
administrator.setAddress(administratorForm.getAddress());
administrator.setEmail(administratorForm.getEmail());
administrator.setMiddleName(administratorForm.getMiddleName());
administrator.setName(administratorForm.getName());
administrator.setPhoneNumber(administratorForm.getPhoneNumber());
administrator.setPhoto(administratorForm.getPhoto());
administrator.setSurname(administratorForm.getSurname());
administrator.setUserAccount(administratorForm.getUserAccount());
// member.setFlagSpam(memberForm.isFlagSpam());
// member.setPolarityScore(memberForm.getPolarityScore());
// member.setBan(memberForm.getBan());
administrator.setBan(false);
return administrator;
}
@Autowired
private Validator validator;
public Administrator reconstruct(final Administrator administrator, final BindingResult binding) {
Administrator res;
//Check authority
final Authority a = new Authority();
final UserAccount user = administrator.getUserAccount();
a.setAuthority(Authority.ADMIN);
Assert.isTrue(user.getAuthorities().contains(a) && user.getAuthorities().size() == 1);
if (administrator.getId() == 0)
res = administrator;
else {
res = this.administratorRepository.findOne(administrator.getId());
res.setName(administrator.getName());
res.setEmail(administrator.getEmail());
res.setMiddleName(administrator.getMiddleName());
res.setSurname(administrator.getSurname());
res.setAddress(administrator.getAddress());
res.setPhoneNumber(administrator.getPhoneNumber());
res.setPhoto(administrator.getPhoto());
this.validator.validate(res, binding);
}
return res;
}
public void calculateScoreApp() {
Integer score = 0;
final List<Customisation> cus = new ArrayList<>(this.customisationService.findAll());
final Customisation cus1 = cus.get(0);
final List<String> positive = new ArrayList<String>(cus1.getPositiveWords());
final List<String> negative = new ArrayList<String>(cus1.getNegativeWords());
final List<Actor> la = new ArrayList<>(this.actorService.findAll());
Double res1 = null;
for (final Actor a : la) {
final List<Box> lb = new ArrayList<>(a.getBoxes());
for (final Box b : lb)
if (b.getName().contains("out box")) {
final List<Message> lm = new ArrayList<>(b.getMessages());
for (final Message m : lm) {
final String text = m.getBody();
for (final String p : positive)
if (text.contains(p))
score++;
for (final String n : negative)
if (text.contains(n))
score--;
}
break;
}
if ((score >= -10 || score <= 10))
res1 = new Double(score / 10);
else if (score <= 100 || score >= -100)
res1 = new Double(score / 100);
else if (score <= 1000 || score >= -1000)
res1 = new Double(score / 1000);
a.setPolarityScore(res1);
}
}
public void leave() {
final Administrator logAdministrator = this.findByPrincipal();
logAdministrator.setAddress("Unknown");
logAdministrator.setBan(true);
logAdministrator.setEmail("<EMAIL>");
logAdministrator.setMiddleName("Unknown");
logAdministrator.setName("Unknown");
logAdministrator.setPhoneNumber("Unknown");
logAdministrator.setPhoto("http://www.unknown.com");
logAdministrator.setPolarityScore(0);
for (final SocialProfile sp : logAdministrator.getSocialProfiles())
this.socialProfileService.deleteLeave(sp);
logAdministrator.setSocialProfiles(null);
logAdministrator.setSurname("Unknown");
final UserAccount ua = logAdministrator.getUserAccount();
final String tick1 = TickerGenerator.tickerLeave();
ua.setUsername("Unknown" + tick1);
final String pass1 = TickerGenerator.generateTicker();
final Md5PasswordEncoder encoder = new Md5PasswordEncoder();
final String pass2 = encoder.encodePassword(pass1, null);
ua.setPassword(pass2);
logAdministrator.setUserAccount(ua);
}
}
<file_sep>package controllers.brotherhood;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import domain.Parade;
import domain.Segment;
import services.ParadeService;
import services.SegmentService;
@Controller
@RequestMapping("/parade/segment")
public class ParadeSegmentController {
@Autowired
private SegmentService segmentService;
@Autowired
private ParadeService paradeService;
private Parade paradeACT;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView list(@RequestParam int paradeId) {
ModelAndView result;
Parade parade = this.paradeService.findOne(paradeId);
this.paradeACT = parade;
final List<Segment> segments = this.segmentService.getSegmentsByParade(parade);
if(segments==null){
return new ModelAndView("redirect:/welcome/index.do");
}
result = new ModelAndView("parade/segment/list");
result.addObject("segments", segments);
result.addObject("requestURI", "/parade/segment/list.do");
return result;
}
@RequestMapping(value = "/create", method = RequestMethod.GET)
public ModelAndView create() {
ModelAndView result;
Segment segment;
segment = this.segmentService.create(this.paradeACT.getId());
result = this.createEditModelAndView(segment, this.paradeACT);
return result;
}
@RequestMapping(value = "/edit", method = RequestMethod.GET)
public ModelAndView edit(@RequestParam final int segmentId) {
ModelAndView result;
Segment segment;
segment = this.segmentService.findOne(segmentId);
Assert.notNull(segment);
if(this.paradeACT.getSegments().size()==segment.getSegmentOrder()){
result = this.createEditModelAndView(segment,this.paradeACT);
}else{
result = this.list(this.paradeACT.getId());
}
return result;
}
@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "save")
public ModelAndView save(@Valid final Segment segment, final BindingResult binding) {
ModelAndView result;
if (binding.hasErrors())
result = this.createEditModelAndView(segment, this.paradeACT);
else
try {
if(this.segmentService.isCorrectDate(segment, this.paradeACT)){
this.paradeService.saveSegmentInParade(segment,this.paradeACT);
result = this.list(this.paradeACT.getId());
}else{
result = this.createEditModelAndView(segment,this.paradeACT, "segment.commit.error");
}
} catch (final Throwable oops) {
result = this.createEditModelAndView(segment,this.paradeACT, "segment.commit.error");
}
return result;
}
@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "delete")
public ModelAndView delete(final Segment segment, final BindingResult binding) {
ModelAndView result;
try {
this.paradeService.deleteSegmentInParade(segment, paradeACT);
result = this.list(this.paradeACT.getId());
} catch (final Throwable oops) {
result = this.createEditModelAndView(segment,this.paradeACT);
}
return result;
}
protected ModelAndView createEditModelAndView(Segment segment,Parade parade) {
ModelAndView result;
result = this.createEditModelAndView(segment,parade, null);
return result;
}
protected ModelAndView createEditModelAndView(Segment segment, Parade parade, String messageCode) {
ModelAndView result;
result = new ModelAndView("parade/segment/edit");
result.addObject("segment", segment);
result.addObject("parade",parade);
result.addObject("message", messageCode);
return result;
}
//-------------------------DISPLAY-----------------------------------
@RequestMapping(value = "/display", method = RequestMethod.GET)
public ModelAndView display(@RequestParam final int segmentId) {
ModelAndView result;
Segment segment;
segment = this.segmentService.findOne(segmentId);
Assert.notNull(segment);
result = this.createDisplayModelAndView(segment);
return result;
}
protected ModelAndView createDisplayModelAndView(final Segment segment) {
ModelAndView result;
result = this.createDisplayModelAndView(segment, null);
return result;
}
protected ModelAndView createDisplayModelAndView(final Segment segment, final String messageCode) {
ModelAndView result;
result = new ModelAndView("parade/segment/display");
result.addObject("segment", segment);
result.addObject("messageCode", messageCode);
return result;
}
}
<file_sep>
package repositories;
import java.util.Collection;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.Administrator;
import domain.Brotherhood;
import domain.Member;
@Repository
public interface DashboardRepository extends JpaRepository<Administrator, Integer> {
//12.3.1
@Query("select min(e.size) from Brotherhood b join b.enrolements e where e.status ='APPROVED'")
double minMembers();
@Query("select max(e.size) from Brotherhood b join b.enrolements e where e.status ='APPROVED'")
double maxMembers();
@Query("select avg(e.size) from Brotherhood b join b.enrolements e where e.status ='APPROVED'")
double avgMembers();
@Query("select stddev(e.size) from Brotherhood b join b.enrolements e where e.status ='APPROVED'")
double stddevMembers();
//12.3.2
@Query("select b from Brotherhood b join b.enrolements e where e.status='APPROVED' and e.dropOutMoment is null order by count(e) desc")
Collection<Brotherhood> largestBrotherhoods();
//12.3.3
@Query("select b from Brotherhood b join b.enrolements e where e.status='APPROVED' and e.dropOutMoment is null order by count(e) asc")
Collection<Brotherhood> smallestBrotherhoods();
//12.3.4
@Query("select 1.0 * count(r)/(select count(r1) from Request r1), r.procession.title, r.status from Request r group by r.status, r.procession")
List<Object[]> requestRatioByProcession();
//12.3.5 in service
//12.3.6
@Query("select 1.0 * count(r1)/(select count(r) from Request r) from Request r1 group by r1.status")
List<Double> requestRatio();
//12.3.7
@Query("select distinct m from Member m join m.requests r1 where r1.status='APPROVED' group by m.id having count(r1)> 0.1 * m.requests.size")
Collection<Member> membersWith10PercentRequestsApproved();
//12.3.8
@Query("select e.position.positionEng, count(e) from Enrolement e group by e.position")
List<Object[]> positionHistogram();
//22.2.1
@Query("select 1.0 * count(b)/(select count(b1) from Brotherhood b1) from Area a join a.brotherhoods b")
double ratioBrotherhoodsPerArea();
@Query("select a.brotherhoods.size from Area a")
Collection<Double> countBrotherhoodsPerArea();
@Query("select min(a.brotherhoods.size) from Area a")
double minBrotherhoodsPerArea();
@Query("select max(a.brotherhoods.size) from Area a")
double maxBrotherhoodsPerArea();
@Query("select avg(a.brotherhoods.size) from Area a")
double avgBrotherhoodsPerArea();
@Query("select stddev(a.brotherhoods.size) from Area a")
double stddevBrotherhoodsPerArea();
//22.2.2
@Query("select min(f.processions.size) from Finder f")
double minFinderResults();
@Query("select max(f.processions.size) from Finder f")
double maxFinderResults();
@Query("select avg(f.processions.size) from Finder f")
double avgFinderResults();
@Query("select stddev(f.processions.size) from Finder f")
double stddevFinderResults();
//22.2.3
@Query("select 1.0 * count(f)/(select count(f1) from Finder f1) from Finder f where f.keyword is null and f.startDate is null and f.endDate is null and f.area is null")
double ratioEmptyFinders();
}
<file_sep>
package domain;
import java.util.Collection;
import java.util.List;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
@Entity
@Access(AccessType.PROPERTY)
public class Customisation extends DomainEntity {
//ATRIBUTOS DEL SISTEMA.
public List<String> negativeWords;
public List<String> positiveWords;
public Integer finderDuration;
public Integer resultsNumber;
public String systemName;
public String bannerURL;
public Collection<String> welcomeMessage;
public List<String> spamWords;
public String phoneNumberCountryCode;
public List<String> messagePriorities;
public List<String> creditCardMakes;
public Double fare;
public Integer vatPercentage;
public enum negativeWords { //En principio no hace falta
NOT, BAD, HORRIBLE, AVERAGE, DISASTER
};
public enum positiveWords {
GOOD, FANTASTIC, EXCELLENT, GREAT, AMAZING, TERRIFIC, BEAUTIFUL
}
@Column
@ElementCollection(targetClass = String.class)
public List<String> getNegativeWords() {
return this.negativeWords;
}
public void setNegativeWords(final List<String> negativeWords) {
this.negativeWords = negativeWords;
}
@Column
@ElementCollection(targetClass = String.class)
public List<String> getPositiveWords() {
return this.positiveWords;
}
public void setPositiveWords(final List<String> positiveWords) {
this.positiveWords = positiveWords;
}
@Min(value = 1L)
@Max(value = 24)
@NotNull
public Integer getFinderDuration() {
return this.finderDuration;
}
public void setFinderDuration(final Integer finderDuration) {
this.finderDuration = finderDuration;
}
@NotNull
@Min(value = 1L)
@Max(value = 100)
public Integer getResultsNumber() {
return this.resultsNumber;
}
public void setResultsNumber(final Integer resultsNumber) {
this.resultsNumber = resultsNumber;
}
@NotBlank
public String getSystemName() {
return this.systemName;
}
public void setSystemName(final String systemName) {
this.systemName = systemName;
}
@NotBlank
public String getBannerURL() {
return this.bannerURL;
}
public void setBannerURL(final String bannerURL) {
this.bannerURL = bannerURL;
}
@ElementCollection(targetClass = String.class)
public Collection<String> getWelcomeMessage() {
return this.welcomeMessage;
}
public void setWelcomeMessage(final Collection<String> welcomeMessage) {
this.welcomeMessage = welcomeMessage;
}
@Column
@ElementCollection(targetClass = String.class)
public List<String> getSpamWords() {
return this.spamWords;
}
public void setSpamWords(final List<String> spamWords) {
this.spamWords = spamWords;
}
@NotBlank
public String getPhoneNumberCountryCode() {
return this.phoneNumberCountryCode;
}
public void setPhoneNumberCountryCode(final String phoneNumberCountryCode) {
this.phoneNumberCountryCode = phoneNumberCountryCode;
}
@Column
@ElementCollection(targetClass = String.class)
public List<String> getMessagePriorities() {
return this.messagePriorities;
}
public void setMessagePriorities(final List<String> messagePriorities) {
this.messagePriorities = messagePriorities;
}
@ElementCollection(targetClass = String.class)
public List<String> getCreditCardMakes() {
return this.creditCardMakes;
}
public void setCreditCardMakes(final List<String> creditCardMakes) {
this.creditCardMakes = creditCardMakes;
}
@NotNull
@Min(value = 0)
public Double getFare() {
return this.fare;
}
//Esto puede dar fallos porque es un Long y no un double.
public void setFare(final Double fare) {
this.fare = fare;
}
@Min(value = 0L)
@Max(value = 100)
@NotNull
public Integer getVatPercentage() {
return this.vatPercentage;
}
public void setVatPercentage(final Integer vatPercentage) {
this.vatPercentage = vatPercentage;
}
}
<file_sep>
package services;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import repositories.InceptionRecordRepository;
import domain.Brotherhood;
import domain.InceptionRecord;
@Service
@Transactional
public class InceptionRecordService {
@Autowired
private InceptionRecordRepository inceptionRecordRepository;
@Autowired
private BrotherhoodService brotherhoodService;
public InceptionRecord create() {
final InceptionRecord res = new InceptionRecord();
return res;
}
public InceptionRecord save(final InceptionRecord inc) {
Assert.notNull(inc);
final Brotherhood b = this.brotherhoodService.findByPrincipal();
boolean test = false;
if (inc.getId() != 0) {
if (b.getInceptionRecord().getId() == inc.getId())
test = true;
Assert.isTrue(test, "You are not the owner of this inception record");
}
if (inc.getId() == 0) {
b.setInceptionRecord(inc);
this.brotherhoodService.save(b);
}
return this.inceptionRecordRepository.save(inc);
}
public void delete(final InceptionRecord inc) {
Assert.notNull(inc);
final Brotherhood b = this.brotherhoodService.findByPrincipal();
b.setInceptionRecord(null);
this.brotherhoodService.save(b);
this.inceptionRecordRepository.delete(inc);
}
public InceptionRecord findOne(final int id) {
return this.inceptionRecordRepository.findOne(id);
}
public Collection<InceptionRecord> findAll() {
return this.inceptionRecordRepository.findAll();
}
}
<file_sep>drop database if exists `Acme-Madruga`;
create database `Acme-Madruga`;
<file_sep>procession.list = Processions list
procession.name = Name
procession.parentCategory = Parent procession
procession.edit = Edit
procession.delete = Delete
procession.edit.link = Edit
procession.delete.link = Delete
procession.list.create = New procession
procession.save = Save
procession.cancel = Cancel
procession.nombre = Name
procession.mandatory = Some mandatory fields are blank.
procession.commit.error = Errors
procession.confirm.delete = Delete this procession?
procession.list.request = Requests list
procession.ob = Fields with * are mandatory
procession.float = Floats* (Hold control key to select more than one float)
procession.true = Yes
procession.false = No
procession.title = Title*
procession.description = Description*
procession.departureDate = Departure date*
procession.ticker = Ticker
procession.finalMode = Final mode*<file_sep>package converters;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import domain.Customisation;
@Component
@Transactional
public class CustomisationToStringConverter implements Converter<Customisation, String>{
@Override
public String convert(Customisation referee) {
String result;
if(referee == null){
result = null;
}else{
result = String.valueOf(referee.getId());
}
return result;
}
}<file_sep>
package repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.Area;
@Repository
public interface AreaRepository extends JpaRepository<Area, Integer> {
@Query("select p.brotherhood.area from Parade p where p.id = ?1")
Area getParadeArea(int id);
}
<file_sep>
package repositories;
import java.util.Collection;
import java.util.Date;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.Procession;
@Repository
public interface ProcessionRepository extends JpaRepository<Procession, Integer> {
@Query("select p from Procession p where p.brotherhood.id = ?1")
Collection<Procession> findByBrotherhoodId(int brotherhoodId);
@Query("select p from Request r join r.procession p where r.id=?1")
Procession findByRequestId(Integer requestId);
@Query("select p from Procession p where p.finalMode='1'")
Collection<Procession> findAllFinalMode();
//Finder
@Query("select p from Procession p where p.title like %?1% or p.description like %?1%")
Collection<Procession> findProcessionsByKeyword(String keyword);
@Query("select p from Procession p where p.brotherhood.area.id=?1")
Collection<Procession> findProcessionsByAreaId(int id);
@Query("select p from Procession p where p.departureDate > ?1")
Collection<Procession> findProcessionsByMinimumDate(Date minDate);
@Query("select p from Procession p where p.departureDate < ?1")
Collection<Procession> findProcessionsByMaximumDate(Date maxDate);
@Query("select p from Procession p where p.departureDate between ?1 and ?2")
Collection<Procession> findProcessionsByDateRange(Date min, Date max);
@Query("select p from Procession p join p.brotherhood.enrolements e where e.id=?1")
Collection<Procession> findByEnrolementId(int id);
@Query("select p from Procession p join p.brotherhood.enrolements e where e.id=?1 and e.status='APPROVED'")
Collection<Procession> findByEnrolementIdApproved(int id);
@Query("select p from Procession p where p.finalMode='1' and p.departureDate>=?1")
Collection<Procession> findAllFinalModeRequests(Date today);
}
<file_sep>
package controllers;
import java.util.Collection;
import javax.validation.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import repositories.MemberRepository;
import security.Authority;
import security.UserAccount;
import services.MemberService;
import domain.Member;
import forms.MemberForm;
@Controller
@RequestMapping("/member")
public class MemberController extends AbstractController {
@Autowired
MemberService memberService;
@Autowired
MemberRepository memberRepository;
// Constructors -----------------------------------------------------------
public MemberController() {
super();
}
// Edition ------------------------------
@RequestMapping(value = "/register", method = RequestMethod.GET)
public ModelAndView edit() {
final ModelAndView res;
// Member member;
//
// member = this.memberService.create();
// res = this.createEditModelAndView(member);
Authority authority;
Collection<Authority> authorities;
UserAccount userAccount;
userAccount = new UserAccount();
authorities = userAccount.getAuthorities();
authority = new Authority();
authority.setAuthority(Authority.MEMBER);
authorities.add(authority);
userAccount.setAuthorities(authorities);
final MemberForm memberForm = new MemberForm();
memberForm.setUserAccount(userAccount);
res = this.createEditModelAndView(memberForm);
return res;
}
@RequestMapping(value = "/register", method = RequestMethod.POST, params = "save")
public ModelAndView save(@ModelAttribute final MemberForm memberForm, final BindingResult binding) {
ModelAndView result;
try {
Assert.isTrue(memberForm.isConditionsAccepted(), "conditionsAccepted");
final Member member = this.memberService.reconstruct(memberForm, binding);
final String vacia = "";
if (!member.getEmail().isEmpty() || member.getEmail() != vacia)
Assert.isTrue(member.getEmail().matches("^[A-z0-9]+@[A-z0-9.]+$") || member.getEmail().matches("^[A-z0-9 ]+ <[A-z0-9]+@[A-z0-9.]+>$"), "Wrong email");
this.memberService.save(member);
result = new ModelAndView("redirect:/welcome/index.do");
} catch (final ValidationException oops) {
result = this.createEditModelAndView(memberForm);
} catch (final Throwable oops) {
if (oops.getMessage() == "Wrong email")
result = this.createEditModelAndView(memberForm, "member.email.error");
else if (oops.getMessage() == "conditionsAccepted")
result = this.createEditModelAndView(memberForm, "member.conditionsError");
else
result = this.createEditModelAndView(memberForm, "member.comit.error");
}
return result;
}
// Ancillary methods ------------------------------
protected ModelAndView createEditModelAndView(final MemberForm memberForm) {
ModelAndView result;
result = this.createEditModelAndView(memberForm, null);
return result;
}
protected ModelAndView createEditModelAndView(final MemberForm memberForm, final String message) {
ModelAndView result;
result = new ModelAndView("member/register");
result.addObject("memberForm", memberForm);
result.addObject("message", message);
return result;
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView list(@RequestParam final int brotherhoodId) {
final ModelAndView res;
final Collection<Member> members = this.memberRepository.membersByBrotherhood(brotherhoodId);
res = new ModelAndView("member/list");
res.addObject("requestURI", "member/list.do");
res.addObject("members", members);
return res;
}
}
<file_sep>
package services;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import repositories.LegalRecordRepository;
import domain.Brotherhood;
import domain.LegalRecord;
@Service
@Transactional
public class LegalRecordService {
@Autowired
private LegalRecordRepository legalRecordRepository;
@Autowired
private BrotherhoodService brotherhoodService;
public LegalRecord create() {
final LegalRecord res = new LegalRecord();
return res;
}
public LegalRecord save(final LegalRecord leg) {
Assert.notNull(leg);
final Brotherhood b = this.brotherhoodService.findByPrincipal();
boolean test = false;
if (leg.getId() != 0) {
for (final LegalRecord lr : b.getLegalRecords())
if (lr.getId() == leg.getId())
test = true;
Assert.isTrue(test, "You are not the owner of this legal record");
}
if (leg.getId() == 0) {
final Collection<LegalRecord> legsOld = b.getLegalRecords();
legsOld.add(leg);
b.setLegalRecords(legsOld);
this.brotherhoodService.save(b);
}
return this.legalRecordRepository.save(leg);
}
public void delete(final LegalRecord leg) {
Assert.notNull(leg);
final Brotherhood b = this.brotherhoodService.findByPrincipal();
final Collection<LegalRecord> legsOld = b.getLegalRecords();
legsOld.remove(leg);
b.setLegalRecords(legsOld);
this.brotherhoodService.save(b);
this.legalRecordRepository.delete(leg);
}
public LegalRecord findOne(final int id) {
return this.legalRecordRepository.findOne(id);
}
public Collection<LegalRecord> findAll() {
return this.legalRecordRepository.findAll();
}
}
<file_sep>
package services;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import repositories.DashboardRepository;
import security.Authority;
import security.LoginService;
import security.UserAccount;
import domain.Brotherhood;
import domain.Member;
import domain.Procession;
@Service
@Transactional
public class DashboardService {
@Autowired
public DashboardRepository dashboardRepository;
@Autowired
public ProcessionService processionService;
public DashboardService() {
super();
}
private boolean checkAdmin() {
final Authority a = new Authority();
final UserAccount user = LoginService.getPrincipal();
a.setAuthority(Authority.ADMIN);
return user.getAuthorities().contains(a);
}
//12.3.1
public double minMembers() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.minMembers();
}
public double maxMembers() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.maxMembers();
}
public double avgMembers() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.avgMembers();
}
public double stddevMembers() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.stddevMembers();
}
//12.3.2
public Collection<Brotherhood> largestBrotherhoods() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.largestBrotherhoods();
}
//12.3.3
public Collection<Brotherhood> smallestsBrotherhoods() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.smallestBrotherhoods();
}
//12.3.4
public List<Object[]> requestRatioByProcession() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.requestRatioByProcession();
}
//12.3.5
public Collection<Procession> processionsOrganizedIn30Days() {
Assert.isTrue(this.checkAdmin());
final List<Procession> processions = new ArrayList<Procession>(this.processionService.findAll());
final List<Procession> processionsQ = new ArrayList<Procession>(processions);
for (final Procession p : processions) {
final long diffInMillies = Math.abs(p.getDepartureDate().getTime() - Calendar.getInstance().getTime().getTime());
final long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
if (diff >= 30)
processionsQ.remove(p);
}
return processionsQ;
}
//12.3.6
public List<Double> requestRatio() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.requestRatio();
}
//12.3.7
public Collection<Member> membersWith10PercentRequestsApproved() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.membersWith10PercentRequestsApproved();
}
//12.3.8
public List<Object[]> positionHistogram() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.positionHistogram();
}
//22.2.1
public double ratioBrotherhoodsPerArea() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.ratioBrotherhoodsPerArea();
}
public Collection<Double> countBrotherhoodsPerArea() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.countBrotherhoodsPerArea();
}
public double minBrotherhoodsPerArea() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.minBrotherhoodsPerArea();
}
public double maxBrotherhoodsPerArea() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.maxBrotherhoodsPerArea();
}
public double avgBrotherhoodsPerArea() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.avgBrotherhoodsPerArea();
}
public double stddevBrotherhoodsPerArea() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.stddevBrotherhoodsPerArea();
}
//22.2.2
public double avgFinderResults() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.avgFinderResults();
}
public double minFinderResults() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.minFinderResults();
}
public double maxFinderResults() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.maxFinderResults();
}
public double stddevFinderResults() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.stddevFinderResults();
}
//22.2.3
public double ratioEmptyFinders() {
Assert.isTrue(this.checkAdmin());
return this.dashboardRepository.ratioEmptyFinders();
}
}
<file_sep>
package controllers.brotherhood;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import repositories.LegalRecordRepository;
import services.LegalRecordService;
import controllers.AbstractController;
import domain.LegalRecord;
@Controller
@RequestMapping("/legalrecord/brotherhood")
public class LegalRecordBrotherhoodController extends AbstractController {
@Autowired
private LegalRecordService legalRecordService;
@Autowired
private LegalRecordRepository legalRecordRepository;
////////////////
////CREATE//////
////////////////
@RequestMapping(value = "/create", method = RequestMethod.GET)
public ModelAndView create() {
ModelAndView res;
LegalRecord legalRecord;
legalRecord = this.legalRecordService.create();
res = this.createEditModelAndView(legalRecord);
return res;
}
protected ModelAndView createEditModelAndView(final LegalRecord legalRecord) {
ModelAndView result;
result = this.createEditModelAndView(legalRecord, null);
return result;
}
protected ModelAndView createEditModelAndView(final LegalRecord legalRecord, final String message) {
ModelAndView result;
result = new ModelAndView("legalrecord/brotherhood/edit");
result.addObject("legalRecord", legalRecord);
result.addObject("message", message);
return result;
}
////////////////////
///////EDIT/////////
////////////////////
@RequestMapping(value = "/edit", method = RequestMethod.GET)
public ModelAndView edit(@RequestParam final int legalRecordId) {
ModelAndView result;
LegalRecord legalRecord;
legalRecord = this.legalRecordRepository.findOne(legalRecordId);
Assert.notNull(legalRecord);
result = this.createEditModelAndView(legalRecord);
return result;
}
@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "save")
public ModelAndView save(@Valid final LegalRecord legalRecord, final BindingResult binding) {
ModelAndView result;
if (binding.hasErrors())
result = this.createEditModelAndView(legalRecord);
else
try {
this.legalRecordService.save(legalRecord);
result = new ModelAndView("redirect:../../");
} catch (final Throwable oops) {
result = this.createEditModelAndView(legalRecord, "record.commit.error");
}
return result;
}
////////////////////
///////DELETE///////
////////////////////
@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "delete")
public ModelAndView delete(final LegalRecord legalRecord, final BindingResult binding) {
ModelAndView result;
try {
this.legalRecordService.delete(legalRecord);
result = new ModelAndView("redirect:../../");
} catch (final Throwable oops) {
result = this.createEditModelAndView(legalRecord, "record.commit.error");
}
return result;
}
}
<file_sep>
package services;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import repositories.MemberRepository;
import security.Authority;
import security.LoginService;
import security.UserAccount;
import utilities.TickerGenerator;
import domain.Actor;
import domain.Box;
import domain.Brotherhood;
import domain.Customisation;
import domain.Enrolement;
import domain.Finder;
import domain.Member;
import domain.SocialProfile;
import forms.MemberForm;
@Service
@Transactional
public class MemberService {
@Autowired
public MemberRepository memberRepository;
@Autowired
public AdministratorService administratorService;
@Autowired
public ActorService actorService;
@Autowired
public FinderService finderService;
@Autowired
public CustomisationService customisationService;
@Autowired
public SocialProfileService socialProfileService;
//Constructor
public MemberService() {
super();
}
public Member create() {
// User can't be logged to register
// final Authority a = new Authority();
// final Authority b = new Authority();
// final Authority c = new Authority();
// final Authority d = new Authority();
// final Authority e = new Authority();
// final UserAccount user = LoginService.getPrincipal();
// a.setAuthority(Authority.ADMIN);
// b.setAuthority(Authority.HANDYWORKER);
// c.setAuthority(Authority.CUSTOMER);
// d.setAuthority(Authority.REFEREE);
// e.setAuthority(Authority.SPONSOR);
// Assert.isTrue(!(user.getAuthorities().contains(a) || user.getAuthorities().contains(b) || user.getAuthorities().contains(c) || user.getAuthorities().contains(d) || user.getAuthorities().contains(e)));
Member result;
result = new Member();
// Actor
// final Box trash = new Box();
// final Box out = new Box();
// final Box spam = new Box();
// final Box in = new Box();
// trash.setName("trash");
// in.setName("in");
// out.setName("out");
// spam.setName("spam");
// out.setPredefined(true);
// in.setPredefined(true);
// spam.setPredefined(true);
// trash.setPredefined(true);
final Collection<Box> predefined = new ArrayList<Box>();
// predefined.add(in);
// predefined.add(out);
// predefined.add(spam);
// predefined.add(trash);
// result.setBoxes(predefined);
final UserAccount newUser = new UserAccount();
final Authority f = new Authority();
f.setAuthority(Authority.MEMBER);
newUser.addAuthority(f);
result.setUserAccount(newUser);
result.setSocialProfiles(new ArrayList<SocialProfile>());
result.setName("");
result.setEmail("");
result.setAddress("");
result.setSurname("");
result.setPhoneNumber("");
result.setPhoto("");
// Member
result.setFinder(new Finder());
return result;
}
public Collection<Member> membersByBrotherhood(final Brotherhood brotherhood) {
return this.memberRepository.membersByBrotherhood(brotherhood.getId());
}
//Simple CRUD
public Member findOne(final Member member) {
return this.memberRepository.findOne(member.getId());
}
public Member findOnePrincipal() {
final Authority a1 = new Authority();
a1.setAuthority(Authority.MEMBER);
final Actor a = this.actorService.findByPrincipal();
Assert.isTrue(a.getUserAccount().getAuthorities().contains(a1));
final Member m = new Member();
m.setId(a.getId());
final Member res = this.findOne(m);
return res;
}
// Returns logged member
public Member findByPrincipal() {
Member res;
UserAccount userAccount;
userAccount = LoginService.getPrincipal();
Assert.notNull(userAccount);
res = this.findByUserAccount(userAccount);
Assert.notNull(res);
return res;
}
public Member findByUserAccount(final UserAccount userAccount) {
Member res;
Assert.notNull(userAccount);
res = this.memberRepository.findByUserAccountId(userAccount.getId());
return res;
}
public Collection<Member> findAll() {
return this.memberRepository.findAll();
}
public Member save(final Member mem) {
// Restrictions
Assert.isTrue(mem.getBan() != true);
final String pnumber = mem.getPhoneNumber();
final Customisation cus = ((List<Customisation>) this.customisationService.findAll()).get(0);
final String cc = cus.getPhoneNumberCountryCode();
if (pnumber.matches("^[0-9]{4,}$"))
mem.setPhoneNumber(cc.concat(pnumber));
if (mem.getId() == 0) {
Collection<Box> boxes = actorService.createPredefinedBoxes();
mem.setBoxes(boxes);
final Md5PasswordEncoder encoder = new Md5PasswordEncoder();
final String oldpass = mem.getUserAccount().getPassword();
final String hash = encoder.encodePassword(oldpass, null);
final UserAccount cuenta = mem.getUserAccount();
cuenta.setPassword(<PASSWORD>);
mem.setUserAccount(cuenta);
// final Box in1 = new Box();
// in1.setName("In");
// in1.setPredefined(true);
// final Box in = this.boxService.save(in1);
//
// final Collection<Box> boxesPredefined = new ArrayList<Box>();
// boxesPredefined.add(in);
// cus.setBoxes(boxesPredefined);
final Finder f = new Finder();
f.setMoment(new Date());
final Finder fin = this.finderService.save(f);
mem.setFinder(fin);
}
return this.memberRepository.save(mem);
}
public Member memberByEnrolemetId(final Integer enrolementId) {
return this.memberRepository.memberByEnrolementId(enrolementId);
}
public List<Member> membersByEnrolemetId(final Collection<Enrolement> enrolements) {
// TODO Auto-generated method stub
final List<Member> res = new ArrayList<>();
for (final Enrolement e : enrolements)
res.add(this.memberByEnrolemetId(e.getId()));
return res;
}
public Member findOne(final int memberId) {
Member c;
Assert.notNull(memberId);
Assert.isTrue(memberId != 0);
c = this.memberRepository.findOne(memberId);
Assert.notNull(c);
return c;
}
public Member findByRequestId(final int requestId) {
return this.memberRepository.findByRequestId(requestId);
}
public Member reconstruct(final MemberForm memberForm, final BindingResult binding) {
final Member member = this.create();
Assert.isTrue(memberForm.isConditionsAccepted());
final Authority mem = new Authority();
mem.setAuthority(Authority.MEMBER);
Assert.isTrue(memberForm.getUserAccount().getAuthorities().contains(mem));
final Collection<Authority> colMem = new ArrayList<Authority>();
final Authority memb = new Authority();
memb.setAuthority(Authority.MEMBER);
colMem.add(memb);
//Assert.isTrue(memberForm.getUserAccount().getAuthorities() == colMem);
//Damos valores a los atributos del member que devolveremos con los datos que nos llegan
member.setAddress(memberForm.getAddress());
member.setEmail(memberForm.getEmail());
member.setMiddleName(memberForm.getMiddleName());
member.setName(memberForm.getName());
member.setPhoneNumber(memberForm.getPhoneNumber());
member.setPhoto(memberForm.getPhoto());
member.setSurname(memberForm.getSurname());
member.setUserAccount(memberForm.getUserAccount());
// member.setFlagSpam(memberForm.isFlagSpam());
// member.setPolarityScore(memberForm.getPolarityScore());
// member.setBan(memberForm.getBan());
member.setBan(false);
member.setFinder(new Finder());
return member;
}
@Autowired
private Validator validator;
public Member reconstruct(final Member member, final BindingResult binding) {
Member res;
//Check authority
final Authority a = new Authority();
final UserAccount user = member.getUserAccount();
a.setAuthority(Authority.MEMBER);
Assert.isTrue(user.getAuthorities().contains(a) && user.getAuthorities().size() == 1);
if (member.getId() == 0)
res = member;
else {
res = this.memberRepository.findOne(member.getId());
// res.setBan(member.getBan());
// res.setFlagSpam(member.isFlagSpam());
// res.setBoxes(member.getBoxes());
// res.setEnrolements(member.getEnrolements());
// res.setRequests(member.getRequests());
// res.setSocialProfiles(member.getSocialProfiles());
//res.setUserAccount(member.getUserAccount());
res.setName(member.getName());
res.setEmail(member.getEmail());
res.setMiddleName(member.getMiddleName());
res.setSurname(member.getSurname());
res.setAddress(member.getAddress());
res.setPhoneNumber(member.getPhoneNumber());
res.setPhoto(member.getPhoto());
System.out.println("debug test");
this.validator.validate(res, binding);
}
return res;
}
public void leave() {
final Member logMember = this.findByPrincipal();
logMember.setAddress("Unknown");
logMember.setBan(true);
logMember.setEmail("<EMAIL>");
logMember.setMiddleName("Unknown");
logMember.setName("Unknown");
logMember.setPhoneNumber("Unknown");
logMember.setPhoto("http://www.unknown.com");
logMember.setPolarityScore(0);
for (final SocialProfile sp : logMember.getSocialProfiles())
this.socialProfileService.deleteLeave(sp);
logMember.setSocialProfiles(null);
logMember.setSurname("Unknown");
final UserAccount ua = logMember.getUserAccount();
final String tick1 = TickerGenerator.tickerLeave();
ua.setUsername("Unknown" + tick1);
final String pass1 = TickerGenerator.generateTicker();
final Md5PasswordEncoder encoder = new Md5PasswordEncoder();
final String pass2 = encoder.encodePassword(pass1, null);
ua.setPassword(pass2);
logMember.setUserAccount(ua);
}
}
<file_sep>
package repositories;
import java.util.Collection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.Member;
@Repository
public interface MemberRepository extends JpaRepository<Member, Integer> {
@Query("select m from Member m join m.enrolements m1 where m1.brotherhood.id=?1 and m1.status='APPROVED'")
public Collection<Member> membersByBrotherhood(int id);
@Query("select m from Member m join m.enrolements m1 where m1.id=?1")
public Member memberByEnrolementId(int id);
@Query("select m from Member m where m.userAccount.id = ?1")
Member findByUserAccountId(int userAccount);
@Query("select m from Member m join m.requests r where r.id = ?1")
Member findByRequestId(int requestId);
}
<file_sep>
package repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.Finder;
@Repository
public interface FinderRepository extends JpaRepository<Finder, Integer> {
@Query("select m.finder from Member m where m.id=?1")
Finder getFinderMember(int id);
}
<file_sep>
package domain;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.CascadeType;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Access(AccessType.PROPERTY)
public class Brotherhood extends Actor {
private String title;
private Date stablishmentDate;
private Collection<String> urls;
private Collection<Enrolement> enrolements;
private Area area;
private Collection<LegalRecord> legalRecords;
private InceptionRecord inceptionRecord;
private Collection<LinkRecord> linkRecords;
private Collection<PeriodRecord> periodRecords;
@ManyToOne(optional = true)
public Area getArea() {
return this.area;
}
public void setArea(final Area area) {
this.area = area;
}
@OneToMany(mappedBy = "brotherhood")
public Collection<Enrolement> getEnrolements() {
return this.enrolements;
}
public void setEnrolements(final Collection<Enrolement> enrolements) {
this.enrolements = enrolements;
}
@NotBlank
public String getTitle() {
return this.title;
}
public void setTitle(final String title) {
this.title = title;
}
@NotNull
@Past
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy-MM-dd")
public Date getStablishmentDate() {
return this.stablishmentDate;
}
public void setStablishmentDate(final Date stablishmentDate) {
this.stablishmentDate = stablishmentDate;
}
@ElementCollection
public Collection<String> getUrls() {
return this.urls;
}
public void setUrls(final Collection<String> urls) {
this.urls = urls;
}
@Valid
@OneToMany(cascade = CascadeType.ALL)
public Collection<LegalRecord> getLegalRecords() {
return this.legalRecords;
}
public void setLegalRecords(final Collection<LegalRecord> legalRecords) {
this.legalRecords = legalRecords;
}
@Valid
@OneToOne(cascade = CascadeType.ALL, optional=true)
public InceptionRecord getInceptionRecord() {
return this.inceptionRecord;
}
public void setInceptionRecord(final InceptionRecord inceptionRecord) {
this.inceptionRecord = inceptionRecord;
}
@Valid
@OneToMany(cascade = CascadeType.ALL)
public Collection<LinkRecord> getLinkRecords() {
return this.linkRecords;
}
public void setLinkRecords(final Collection<LinkRecord> linkRecords) {
this.linkRecords = linkRecords;
}
@Valid
@OneToMany(cascade = CascadeType.ALL)
public Collection<PeriodRecord> getPeriodRecords() {
return this.periodRecords;
}
public void setPeriodRecords(final Collection<PeriodRecord> periodRecords) {
this.periodRecords = periodRecords;
}
}
<file_sep>
package repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.Chapter;
@Repository
public interface ChapterRepository extends JpaRepository<Chapter, Integer> {
@Query("select c from Chapter c where c.userAccount.id = ?1")
Chapter findByUserAccountId(int userAccount);
}
<file_sep>
package controllers;
import java.util.Collection;
import javax.validation.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import repositories.AreaRepository;
import security.Authority;
import security.UserAccount;
import services.BrotherhoodService;
import domain.Area;
import domain.Brotherhood;
import domain.InceptionRecord;
import domain.LegalRecord;
import domain.LinkRecord;
import domain.PeriodRecord;
import forms.BrotherhoodForm;
@Controller
@RequestMapping("/brotherhood")
public class BrotherhoodController extends AbstractController {
@Autowired
BrotherhoodService brotherhoodService;
@Autowired
AreaRepository areaRepository;
// Constructors -----------------------------------------------------------
public BrotherhoodController() {
super();
}
// Edition ------------------------------
@RequestMapping(value = "/register", method = RequestMethod.GET)
public ModelAndView edit() {
ModelAndView res;
Authority authority;
Collection<Authority> authorities;
UserAccount userAccount;
userAccount = new UserAccount();
authorities = userAccount.getAuthorities();
authority = new Authority();
authority.setAuthority(Authority.BROTHERHOOD);
authorities.add(authority);
userAccount.setAuthorities(authorities);
final BrotherhoodForm brotherhoodForm = new BrotherhoodForm();
brotherhoodForm.setUserAccount(userAccount);
res = this.createEditModelAndView(brotherhoodForm);
//brotherhood = this.brotherhoodService.create();
//res = this.createEditModelAndView(brotherhood);
return res;
}
@RequestMapping(value = "/register", method = RequestMethod.POST, params = "save")
public ModelAndView save(@ModelAttribute final BrotherhoodForm brotherhoodForm, final BindingResult binding) {
ModelAndView result;
try {
Assert.isTrue(brotherhoodForm.isConditionsAccepted(), "conditionsAccepted");
final Brotherhood brotherhood = this.brotherhoodService.reconstruct(brotherhoodForm, binding);
final String vacia = "";
if (!brotherhood.getEmail().isEmpty() || brotherhood.getEmail() != vacia)
Assert.isTrue(brotherhood.getEmail().matches("^[A-z0-9]+@[A-z0-9.]+$") || brotherhood.getEmail().matches("^[A-z0-9 ]+ <[A-z0-9]+@[A-z0-9.]+>$"), "Wrong email");
this.brotherhoodService.save(brotherhood);
result = new ModelAndView("redirect:/welcome/index.do");
} catch (final ValidationException oops) {
result = this.createEditModelAndView(brotherhoodForm);
} catch (final Throwable oops) {
if (oops.getMessage() == "Wrong email")
result = this.createEditModelAndView(brotherhoodForm, "brotherhood.email.error");
else if (oops.getMessage() == "conditionsAccepted")
result = this.createEditModelAndView(brotherhoodForm, "member.conditionsError");
else
result = this.createEditModelAndView(brotherhoodForm, "brotherhood.comit.error");
}
if (!brotherhoodForm.isConditionsAccepted())
result = this.createEditModelAndView(brotherhoodForm, "brotherhood.conditionsError");
return result;
}
// Ancillary methods ------------------------------
protected ModelAndView createEditModelAndView(final BrotherhoodForm brotherhoodForm) {
ModelAndView result;
result = this.createEditModelAndView(brotherhoodForm, null);
return result;
}
protected ModelAndView createEditModelAndView(final BrotherhoodForm brotherhoodForm, final String message) {
ModelAndView result;
final Collection<Area> areas = this.areaRepository.findAll();
result = new ModelAndView("brotherhood/register");
result.addObject("areas", areas);
result.addObject("brotherhoodForm", brotherhoodForm);
result.addObject("message", message);
return result;
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView list() {
final ModelAndView res;
final Collection<Brotherhood> brotherhoods = this.brotherhoodService.findAll();
res = new ModelAndView("brotherhood/list");
res.addObject("requestURI", "brotherhood/list.do");
res.addObject("brotherhoods", brotherhoods);
return res;
}
@RequestMapping(value = "/showRecords", method = RequestMethod.GET)
public ModelAndView showRecords(@RequestParam final int brotherhoodId) {
ModelAndView res;
Brotherhood brotherhood;
//brotherhood = this.brotherhoodService.findByPrincipal();
brotherhood = this.brotherhoodService.findOne(brotherhoodId);
res = this.createShowRecordsModelAndView(brotherhood);
return res;
}
protected ModelAndView createShowRecordsModelAndView(final Brotherhood brotherhood) {
ModelAndView result;
result = this.createShowRecordsModelAndView(brotherhood, null);
return result;
}
protected ModelAndView createShowRecordsModelAndView(final Brotherhood brotherhood, final String message) {
final ModelAndView result;
UserAccount userAccount;
userAccount = brotherhood.getUserAccount();
final Collection<LegalRecord> legalRecords = brotherhood.getLegalRecords();
final Collection<PeriodRecord> periodRecords = brotherhood.getPeriodRecords();
final InceptionRecord inceptionRecord = brotherhood.getInceptionRecord();
final Collection<LinkRecord> linkRecords = brotherhood.getLinkRecords();
result = new ModelAndView("brotherhood/showRecords");
result.addObject("brotherhood", brotherhood);
result.addObject("legalRecords", legalRecords);
result.addObject("periodRecords", periodRecords);
result.addObject("inceptionRecord", inceptionRecord);
result.addObject("linkRecords", linkRecords);
result.addObject("message", message);
result.addObject("userAccount", userAccount);
return result;
}
}
<file_sep>
package repositories;
import java.util.Collection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.Enrolement;
@Repository
public interface EnrolementRepository extends JpaRepository<Enrolement, Integer> {
@Query("select e from Member m join m.enrolements e where e.brotherhood.id=?1 and m.id=?2")
public Enrolement findEnrolementByIds(Integer brotherhoodId, Integer memberId);
@Query("select e from Member m join m.enrolements e where m.id=?1")
public Collection<Enrolement> findEnrolementsByMemberId(Integer memberId);
@Query("select e1 from Member m join m.enrolements e1 where m.id=?1 and e1.brotherhood.id=?2")
public Enrolement existEnrolement(Integer memberId, Integer brotherhoodId);
@Query("select e from Enrolement e where e.brotherhood.id=?1 and e.status='PENDING'")
public Collection<Enrolement> enrolementsPending(Integer brotherhoodId);
}
<file_sep>
package repositories;
import java.util.Collection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.Actor;
import domain.Message;
@Repository
public interface MessageRepository extends JpaRepository<Message, Integer> {
@Query("select m.recipients from Message m where m.id =?1")
public Collection<Actor> getRecipientsWorking(int idmsj);
}
<file_sep>
package domain;
import java.util.Collection;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
@Access(AccessType.PROPERTY)
public class Area extends DomainEntity {
private String name;
private Collection<String> pictures;
private Collection<Brotherhood> brotherhoods;
@OneToMany(mappedBy = "area")
public Collection<Brotherhood> getBrotherhoods() {
return this.brotherhoods;
}
public void setBrotherhoods(final Collection<Brotherhood> brotherhoods) {
this.brotherhoods = brotherhoods;
}
@NotBlank
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
@ElementCollection(targetClass = String.class)
@NotEmpty
public Collection<String> getPictures() {
return this.pictures;
}
public void setPictures(final Collection<String> pictures) {
this.pictures = pictures;
}
}
<file_sep>procession.list = Lista de procesiones
procession.name = Nombre
procession.parentCategory = Categoría padre
procession.edit = Editar
procession.delete = Eliminar
procession.edit.link = Editar
procession.delete.link = Eliminar
procession.list.create = Nueva procesión
procession.save = Guardar
procession.cancel = Cancelar
procession.nombre = Nombre
procession.mandatory = Algunos campos obligatorios están en blanco.
procession.commit.error = Se encontraron errores
procession.confirm.delete = ¿Eliminar esta procesión?
procession.list.request = Lista de peticiones
procession.ob = Los parámetros marcados con * son obligatorios.
procession.float = Pasos* (Mantén pulsado control para seleccionar más de uno)
procession.true = Sí
procession.false = No
procession.title = Título*
procession.description = Descripción*
procession.departureDate = Fecha de salida*
procession.ticker = Ticker
procession.finalMode = Modo final*<file_sep>record.list = Records
record.edit = Edit
record.show = See details
record.create = Create
record.save = Save
record.delete = Delete
record.cancel = Cancel
record.obligatorio = The fields marked with * are required
record.title = Title* :
record.description = Description* :
record.legalName = Legal name* :
record.applicableLaws = Applicable laws :
record.vatNumber = VAT :
record.link = Link :
record.startYear = Start year :
record.endYear = End year :
record.photos = Photos :
legalRecord.create = Create legal record
linkRecord.create = Create link record
periodRecord.create = Create period record
inceptionRecord.create = Create inception record
record.mandatory = (Fields with * are mandatory)
record.confirm.delete = Delete this record?
record.commit.error.blank = Error. The introduced values are incorrect or blank.
record.commit.error = Errors<file_sep>
package controllers.requests.brotherhood;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import services.BrotherhoodService;
import services.MemberService;
import services.ParadeService;
import services.RequestService;
import controllers.AbstractController;
import domain.Parade;
import domain.Request;
@Controller
@RequestMapping("/requests/brotherhood")
public class RequestBrotherhoodController extends AbstractController {
@Autowired
MemberService memberService;
@Autowired
ParadeService paradeService;
@Autowired
RequestService requestService;
@Autowired
BrotherhoodService brotherhoodService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView show(@RequestParam final int paradeId) {
final ModelAndView res;
final Parade p;
final Collection<Request> requests = this.requestService.findByParadeId(paradeId);
final Parade p1 = new Parade();
p1.setId(paradeId);
p = this.paradeService.findOne(p1);
this.brotherhoodService.checkBrotherhoodOwnsParade(p);
res = new ModelAndView("requests/list");
res.addObject("parade", p);
res.addObject("requests", requests);
res.addObject("brotherhoodView", true);
return res;
}
@RequestMapping(value = "/accept", method = RequestMethod.GET)
public ModelAndView acceptRequest(@RequestParam final int requestIdA) {
final ModelAndView res;
final Request r;
final Request r1 = new Request();
r1.setId(requestIdA);
r = this.requestService.findOne(r1);
this.requestService.checkRequestOwnsBrotherhood(r);
res = this.createEditModelAndView(r, "APPROVED", null);
return res;
}
@RequestMapping(value = "/reject", method = RequestMethod.GET)
public ModelAndView rejectRequest(@RequestParam final int requestIdR) {
final ModelAndView res;
final Request r;
final Request r1 = new Request();
r1.setId(requestIdR);
r = this.requestService.findOne(r1);
this.requestService.checkRequestOwnsBrotherhood(r);
res = this.createEditModelAndView(r, "REJECTED", null);
return res;
}
private ModelAndView createEditModelAndView(final Request r, final String status, final String messageCode) {
ModelAndView res;
final List<Integer> li = new ArrayList<>(this.requestService.suggestPosition(r.getParade()));
res = new ModelAndView("requests/edit");
res.addObject("row", li.get(0));
res.addObject("column", li.get(1));
res.addObject("request", r);
res.addObject("status", status);
res.addObject("brotherhoodView", true);
res.addObject("message", messageCode);
res.addObject("formAction", "requests/brotherhood/edit.do");
String redirect = "requests/brotherhood/list.do?paradeId=";
redirect = redirect + r.getParade().getId();
res.addObject("formBack", redirect);
return res;
}
@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "save")
public ModelAndView save(Request r, final BindingResult binding) {
ModelAndView res;
if (r.getRowPosition() != 0 && r.getColumnPosition() != 0)
if (this.requestService.checkPosition(r) == true) {
res = this.createEditModelAndView(r, "APPROVED", "error.position.selected");
return res;
}
r = this.requestService.reconstructBrotherhood(r, binding);
if (binding.hasErrors())
res = this.createEditModelAndView(r, r.getStatus(), "error.request");
else
try {
this.requestService.checkPositionBeforeSave(r);
final Request r1 = this.requestService.saveDirectly(r);
String redirect = "redirect:list.do?paradeId=";
redirect = redirect + r1.getParade().getId();
res = new ModelAndView(redirect);
} catch (final Throwable oops) {
res = this.createEditModelAndView(r, r.getStatus(), "error.request");
}
return res;
}
}
<file_sep>
package controllers;
import java.util.Collection;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import security.Authority;
import security.UserAccount;
import services.AdministratorService;
import domain.Administrator;
import domain.Box;
import domain.SocialProfile;
import forms.AdministratorForm;
@Controller
@RequestMapping("/administrator/administrator")
public class AdministratorAdministratorController extends AbstractController {
@Autowired
private AdministratorService administratorService;
// Constructors -----------------------------------------------------------
public AdministratorAdministratorController() {
super();
}
////////////////////////////
//////////EDIT//////////////
////////////////////////////
@RequestMapping(value = "/edit", method = RequestMethod.GET)
public ModelAndView edit() {
ModelAndView res;
final Administrator administrator;
administrator = this.administratorService.findByPrincipal();
//customer = this.customerService.findOne(customerId);
res = this.createEditModelAndView(administrator);
return res;
}
@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "save")
public ModelAndView save(@Valid final Administrator administrator, final BindingResult binding) {
ModelAndView result;
try { //name, surname, address, email, title, departure
Assert.notNull(administrator.getName());
Assert.isTrue(administrator.getName() != "");
Assert.notNull(administrator.getEmail());
Assert.isTrue(administrator.getEmail() != "");
Assert.notNull(administrator.getAddress());
Assert.isTrue(administrator.getAddress() != "");
} catch (final Throwable error) {
result = this.createEditModelAndView(administrator, "administrator.mandatory");
return result;
}
final Administrator administratorMod = this.administratorService.reconstruct(administrator, binding);
if (binding.hasErrors())
result = this.createEditModelAndView(administrator);
else
try {
final String vacia = "";
if (!administratorMod.getEmail().isEmpty() || administratorMod.getEmail() != vacia)
Assert.isTrue(administratorMod.getEmail().matches("^[A-z0-9]+@$") || administratorMod.getEmail().matches("^[A-z0-9 ]+ <[A-z0-9]+@>$"), "Wrong email");
this.administratorService.save(administratorMod);
result = new ModelAndView("redirect:../../");
} catch (final Throwable error) {
if (error.getMessage() == "Wrong email")
result = this.createEditModelAndView(administratorMod, "administrator.email.error");
else
result = this.createEditModelAndView(administratorMod, "administrator.comit.error");
System.out.println(error.getMessage());
}
return result;
}
protected ModelAndView createEditModelAndView(final Administrator administrator) {
ModelAndView result;
result = this.createEditModelAndView(administrator, null);
return result;
}
protected ModelAndView createEditModelAndView(final Administrator administrator, final String message) {
ModelAndView result;
Collection<Box> boxes;
final Collection<SocialProfile> socialProfiles;
UserAccount userAccount;
boxes = administrator.getBoxes();
socialProfiles = administrator.getSocialProfiles();
userAccount = administrator.getUserAccount();
result = new ModelAndView("administrator/edit");
result.addObject("administrator", administrator);
result.addObject("boxes", boxes);
result.addObject("socialProfiles", socialProfiles);
result.addObject("message", message);
result.addObject("userAccount", userAccount);
return result;
}
////////////////////////////
//////////CREATE////////////
////////////////////////////
@RequestMapping(value = "/create", method = RequestMethod.GET)
public ModelAndView create() {
ModelAndView res;
Authority authority;
Collection<Authority> authorities;
UserAccount userAccount;
userAccount = new UserAccount();
authorities = userAccount.getAuthorities();
authority = new Authority();
authority.setAuthority(Authority.ADMIN);
authorities.add(authority);
userAccount.setAuthorities(authorities);
final AdministratorForm adminForm = new AdministratorForm();
adminForm.setUserAccount(userAccount);
res = this.createCreateModelAndView(adminForm);
//return res;
// administrator = this.administratorService.create();
// res = this.createCreateModelAndView(administrator);
return res;
}
protected ModelAndView createCreateModelAndView(final AdministratorForm administratorForm) {
ModelAndView result;
result = this.createCreateModelAndView(administratorForm, null);
return result;
}
protected ModelAndView createCreateModelAndView(final AdministratorForm administratorForm, final String message) {
ModelAndView result;
result = new ModelAndView("administrator/create");
result.addObject("administratorForm", administratorForm);
result.addObject("message", message);
return result;
}
@RequestMapping(value = "/create", method = RequestMethod.POST, params = "save")
public ModelAndView saveCreate(@Valid final AdministratorForm administratorForm, final BindingResult binding) {
ModelAndView result;
try { //name, surname, address, email, title, departure
;
Assert.notNull(administratorForm.getEmail());
Assert.isTrue(administratorForm.getEmail() != "");
} catch (final Throwable error) {
result = this.createCreateModelAndView(administratorForm, "administrator.mandatory");
return result;
}
if (!administratorForm.isConditionsAccepted())
result = this.createCreateModelAndView(administratorForm, "member.conditionsError");
else {
final Administrator administrator = this.administratorService.reconstruct(administratorForm, binding);
if (binding.hasErrors())
result = this.createCreateModelAndView(administratorForm);
else
try {
final String vacia = "";
if (!administrator.getEmail().isEmpty() || administrator.getEmail() != vacia)
Assert.isTrue(administrator.getEmail().matches("^[A-z0-9]+@$") || administrator.getEmail().matches("^[A-z0-9 ]+ <[A-z0-9]+@>$"), "Wrong email");
this.administratorService.save(administrator);
result = new ModelAndView("redirect:../../");
} catch (final Throwable error) {
if (error.getMessage() == "Wrong email")
result = this.createCreateModelAndView(administratorForm, "administrator.email.error");
else
result = this.createCreateModelAndView(administratorForm, "administrator.comit.error");
System.out.println(error.getMessage());
}
}
return result;
}
////////////////////////////
//////////DELETE////////////
////////////////////////////
@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "leave")
public ModelAndView saveLeave(final Administrator administrator, final BindingResult binding) {
ModelAndView result;
if (binding.hasErrors())
result = this.createEditModelAndView(administrator);
else
try {
this.administratorService.leave();
result = new ModelAndView("redirect:../../j_spring_security_logout");
} catch (final Throwable error) {
if (error.getMessage() == "Wrong email")
result = this.createEditModelAndView(administrator, "brotherhood.email.error");
else
result = this.createEditModelAndView(administrator, "brotherhood.comit.error");
System.out.println(error.getMessage());
}
return result;
}
////////////////////////////
///////////SHOW/////////////
////////////////////////////
@RequestMapping(value = "/show", method = RequestMethod.GET)
public ModelAndView show() {
ModelAndView res;
Administrator administrator;
administrator = this.administratorService.findByPrincipal();
//brotherhood = this.brotherhoodService.findOne(brotherhoodId);
res = this.createShowModelAndView(administrator);
return res;
}
protected ModelAndView createShowModelAndView(final Administrator administrator) {
ModelAndView result;
result = this.createShowModelAndView(administrator, null);
return result;
}
protected ModelAndView createShowModelAndView(final Administrator administrator, final String message) {
ModelAndView result;
// Collection<Box> boxes;
// final Collection<SocialProfile> socialProfiles;
// final Collection<Endorsement> endorsements;
// final Collection<FixUpTask> fixUpTasks;
UserAccount userAccount;
// fixUpTasks = brotherhood.getFixUpTasks();
// boxes = brotherhood.getBoxes();
// socialProfiles = brotherhood.getSocialProfiles();
// endorsements = brotherhood.getEndorsements();
userAccount = administrator.getUserAccount();
// if (socialProfiles.isEmpty())
// * socialProfiles = null;
// * if (endorsements.isEmpty())
// * endorsements = null;
//if (boxes.isEmpty())
// boxes = null;
result = new ModelAndView("administrator/show");
result.addObject("administrator", administrator);
// result.addObject("boxes", boxes);
// result.addObject("socialProfiles", socialProfiles);
result.addObject("message", message);
// result.addObject("endorsements", endorsements);
// result.addObject("fixUpTasks", fixUpTasks);
result.addObject("userAccount", userAccount);
return result;
}
}
<file_sep>
package controllers.brotherhood;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import security.UserAccount;
import services.BrotherhoodService;
import domain.Brotherhood;
import domain.InceptionRecord;
import domain.LegalRecord;
import domain.LinkRecord;
import domain.PeriodRecord;
@Controller
@RequestMapping("/history/brotherhood")
public class HistoryBrotherhoodController {
@Autowired
private BrotherhoodService brotherhoodService;
@RequestMapping(value = "/showHistory", method = RequestMethod.GET)
public ModelAndView showHistory() {
ModelAndView res;
Brotherhood brotherhood;
brotherhood = this.brotherhoodService.findByPrincipal();
//brotherhood = this.brotherhoodService.findOne(brotherhoodId);
res = this.createShowRecordsModelAndView(brotherhood);
return res;
}
protected ModelAndView createShowRecordsModelAndView(final Brotherhood brotherhood) {
ModelAndView result;
result = this.createShowRecordsModelAndView(brotherhood, null);
return result;
}
protected ModelAndView createShowRecordsModelAndView(final Brotherhood brotherhood, final String message) {
final ModelAndView result;
UserAccount userAccount;
userAccount = brotherhood.getUserAccount();
final Collection<LegalRecord> legalRecords = brotherhood.getLegalRecords();
final Collection<PeriodRecord> periodRecords = brotherhood.getPeriodRecords();
final InceptionRecord inceptionRecord = brotherhood.getInceptionRecord();
final Collection<LinkRecord> linkRecords = brotherhood.getLinkRecords();
result = new ModelAndView("history/brotherhood/showHistory");
result.addObject("brotherhood", brotherhood);
result.addObject("legalRecords", legalRecords);
result.addObject("periodRecords", periodRecords);
result.addObject("inceptionRecord", inceptionRecord);
result.addObject("linkRecords", linkRecords);
result.addObject("message", message);
result.addObject("userAccount", userAccount);
return result;
}
}
<file_sep>parade.list = Parades list
parade.name = Name
parade.parentCategory = Parent parade
parade.edit = Edit
parade.delete = Delete
parade.edit.link = Edit
parade.delete.link = Delete
parade.list.create = New parade
parade.save = Save
parade.cancel = Cancel
parade.nombre = Name
parade.mandatory = Some mandatory fields are blank.
parade.commit.error = Errors. Remember that reject reason is mandatory if status is "Rejected".
parade.confirm.delete = Delete this parade?
parade.status = Status
parade.rejectReason = Reject reason
parade.list.request = Requests list
parade.ob = Fields with * are mandatory
parade.float = Floats* (Hold control key to select more than one float)
parade.true = Yes
parade.false = No
parade.title = Title*
parade.description = Description*
parade.departureDate = Departure date*
parade.ticker = Ticker
parade.finalMode = Final mode*
parade.segment.list = Segments<file_sep>
package repositories;
import java.util.Collection;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.Administrator;
import domain.Brotherhood;
import domain.Chapter;
import domain.Member;
@Repository
public interface DashboardRepository extends JpaRepository<Administrator, Integer> {
//12.3.1
@Query("select min(e.size) from Brotherhood b join b.enrolements e where e.status ='APPROVED'")
double minMembers();
@Query("select max(e.size) from Brotherhood b join b.enrolements e where e.status ='APPROVED'")
double maxMembers();
@Query("select avg(e.size) from Brotherhood b join b.enrolements e where e.status ='APPROVED'")
double avgMembers();
@Query("select stddev(e.size) from Brotherhood b join b.enrolements e where e.status ='APPROVED'")
double stddevMembers();
//12.3.2
@Query("select b from Brotherhood b join b.enrolements e where e.status='APPROVED' and e.dropOutMoment is null order by count(e) desc")
Collection<Brotherhood> largestBrotherhoods();
//12.3.3
@Query("select b from Brotherhood b join b.enrolements e where e.status='APPROVED' and e.dropOutMoment is null order by count(e) asc")
Collection<Brotherhood> smallestBrotherhoods();
//12.3.4
@Query("select 1.0 * count(r)/(select count(r1) from Request r1), r.parade.title, r.status from Request r group by r.status, r.parade")
List<Object[]> requestRatioByParade();
//12.3.5 in service
//12.3.6
@Query("select 1.0 * count(r1)/(select count(r) from Request r) from Request r1 group by r1.status")
List<Double> requestRatio();
//12.3.7
@Query("select distinct m from Member m join m.requests r1 where r1.status='APPROVED' group by m.id having count(r1)> 0.1 * m.requests.size")
Collection<Member> membersWith10PercentRequestsApproved();
//12.3.8
@Query("select e.position.positionEng, count(e) from Enrolement e group by e.position")
List<Object[]> positionHistogram();
//22.2.1
@Query("select 1.0 * count(b)/(select count(b1) from Brotherhood b1) from Area a join a.brotherhoods b")
double ratioBrotherhoodsPerArea();
@Query("select a.brotherhoods.size from Area a")
Collection<Double> countBrotherhoodsPerArea();
@Query("select min(a.brotherhoods.size) from Area a")
double minBrotherhoodsPerArea();
@Query("select max(a.brotherhoods.size) from Area a")
double maxBrotherhoodsPerArea();
@Query("select avg(a.brotherhoods.size) from Area a")
double avgBrotherhoodsPerArea();
@Query("select stddev(a.brotherhoods.size) from Area a")
double stddevBrotherhoodsPerArea();
//22.2.2
@Query("select min(f.parades.size) from Finder f")
double minFinderResults();
@Query("select max(f.parades.size) from Finder f")
double maxFinderResults();
@Query("select avg(f.parades.size) from Finder f")
double avgFinderResults();
@Query("select stddev(f.parades.size) from Finder f")
double stddevFinderResults();
//22.2.3
@Query("select 1.0 * count(f)/(select count(f1) from Finder f1) from Finder f where f.keyword is null and f.startDate is null and f.endDate is null and f.area is null")
double ratioEmptyFinders();
//---------------------------------ACME PARADE-----------------------------------
@Query("select max(1 + b.periodRecords.size + b.legalRecords.size + b.linkRecords.size) from Brotherhood b")
double maxNumRecordsPerHistory();
@Query("select min(1 + b.periodRecords.size + b.legalRecords.size + b.linkRecords.size) from Brotherhood b")
double minNumRecordsPerHistory();
@Query("select avg(1 + b.periodRecords.size + b.legalRecords.size + b.linkRecords.size)from Brotherhood b")
double avgNumRecordsPerHistory();
@Query("select stddev(1 + b.periodRecords.size + b.legalRecords.size + b.linkRecords.size)from Brotherhood b")
double stddevNumRecordsPerHistory();
@Query("select b from Brotherhood b join b.periodRecords p join b.legalRecords l join b.linkRecords li order by (1 + count(p) + count(l) + count(li))")
Collection<Brotherhood> largestHistoryBrotherhood();
@Query("select b from Brotherhood b where (1 + b.periodRecords.size + b.legalRecords.size + b.linkRecords.size)>?1 *1.0")
Collection<Brotherhood> largerThanAvgHistoryBrotherhood(double avgHistory);
//Queries de la B
@Query("select 1.0 * count(a)/(select count(a1) from Area a1) from Area a where a.id not in (select a.id from Chapter c join c.area a)")
double ratioAreasNoChapter();
@Query("select count(p)*1.0/(select count(c) from Chapter c) from Parade p join p.brotherhood b1 where b1 in (select b from Chapter c join c.area.brotherhoods b)")
double avgParadesPerChapter();
@Query("select 1.0 *count(p) from Parade p join p.brotherhood b1 where b1 in (select b from Chapter c join c.area.brotherhoods b) and p.finalMode=1 group by b1.area")
Collection<Double> countParadesPerChapter();
@Query("select c from Chapter c , Parade p where p.brotherhood member of c.area.brotherhoods group by c having count(p)>=1.1*?1")
Collection<Chapter> chapterMoreParadesThanAvg(Double avg);
@Query("select 1.0 * count(p1)/(select count(p2) from Parade p2 where p2.finalMode='1') from Parade p1 where p1.finalMode='0'")
double ratioParadesDraftModevsFinalMode();
@Query("select 1.0 * count(p1)/(select count(p2) from Parade p2) from Parade p1 where p1.finalMode='1' group by p1.status")
Collection<Double> ratioParadesFinalModeGroupedByStatus();
}
<file_sep>package services;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import repositories.ActorRepository;
import repositories.SocialProfileRepository;
import security.LoginService;
import security.UserAccount;
import domain.Actor;
import domain.SocialProfile;
@Transactional
@Service
public class SocialProfileService {
@Autowired
private SocialProfileRepository socialProfileRepository;
@Autowired
private ActorRepository actorRepository;
public SocialProfile create(){
return new SocialProfile();
}
public Collection<SocialProfile> findAll(){
return socialProfileRepository.findAll();
}
public SocialProfile findOne(int socialProfileId){
return socialProfileRepository.findOne(socialProfileId);
}
public SocialProfile save(SocialProfile socialProfile){
return socialProfileRepository.save(socialProfile);
}
public void delete(SocialProfile socialProfile){
socialProfileRepository.delete(socialProfile);
final UserAccount actual = LoginService.getPrincipal();
final Actor a = this.actorRepository.getActor(actual);
a.getSocialProfiles().remove(socialProfile);
}
public void deleteLeave(final SocialProfile socialProfile) {
this.socialProfileRepository.delete(socialProfile);
}
public void saveMyProfile(SocialProfile socialProfile) {
final UserAccount actual = LoginService.getPrincipal();
final Actor a = this.actorRepository.getActor(actual);
final SocialProfile profile = this.socialProfileRepository.save(socialProfile);
if (!a.getSocialProfiles().contains(socialProfile)) {
final Collection<SocialProfile> profiles = a.getSocialProfiles();
profiles.add(profile);
a.setSocialProfiles(profiles);
}
}
public Collection<SocialProfile> findMyProfiles() {
Collection<SocialProfile> res = new ArrayList<SocialProfile>();
final UserAccount actual = LoginService.getPrincipal();
final Actor a = this.actorRepository.getActor(actual);
if(a.getSocialProfiles()==null){
a.setSocialProfiles(res);
this.actorRepository.save(a);
return res;
}
return a.getSocialProfiles();
}
}
<file_sep>
package converters;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import domain.Enrolement;
@Component
@Transactional
public class EnrolementToStringConverter implements Converter<Enrolement, String> {
@Override
public String convert(final Enrolement enrolement) {
String res;
if (enrolement == null)
res = null;
else
res = String.valueOf(enrolement.getId());
return res;
}
}
<file_sep>
package controllers.members;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import services.BrotherhoodService;
import services.EnrolementService;
import services.MemberService;
import services.PositionService;
import controllers.AbstractController;
import domain.Brotherhood;
import domain.Enrolement;
import domain.Member;
import domain.Position;
@Controller
@RequestMapping("/members/brotherhood")
public class MembersBrotherhoodController extends AbstractController {
@Autowired
MemberService memberService;
@Autowired
PositionService positionService;
@Autowired
BrotherhoodService brotherhoodService;
@Autowired
EnrolementService enrolementService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView list() {
final ModelAndView res;
final Collection<Member> members;
final Brotherhood b = this.brotherhoodService.findOnePrincipal();
members = this.memberService.membersByBrotherhood(b);
res = new ModelAndView("members/list");
res.addObject("members", members);
res.addObject("requestURI", "members/brotherhood/list.do");
return res;
}
@RequestMapping(value = "/show", method = RequestMethod.GET)
public ModelAndView show(@RequestParam final int memberId) {
final ModelAndView res;
final Member member;
final Brotherhood b;
final Enrolement enrolement;
final Member m = new Member();
m.setId(memberId);
member = this.memberService.findOne(m);
b = this.brotherhoodService.findOnePrincipal();
enrolement = this.enrolementService.findEnrolementByIds(b, member);
this.brotherhoodService.checkBrotherhood2(enrolement);
res = new ModelAndView("members/show");
res.addObject("member", member);
res.addObject("enrolement", enrolement);
return res;
}
@RequestMapping(value = "/show", method = RequestMethod.POST, params = "delete")
public ModelAndView deleteMember(final Member m, final BindingResult binding) {
ModelAndView res;
try {
this.brotherhoodService.deleteMember(m);
res = new ModelAndView("redirect:list.do");
} catch (final Throwable oops) {
res = new ModelAndView("redirect:list.do");
}
return res;
}
@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "edit")
public ModelAndView editMember(final Enrolement e, final BindingResult binding) {
ModelAndView res;
try {
final Enrolement e1 = this.enrolementService.findOne(e);
this.brotherhoodService.checkBrotherhood(e1);
res = this.createEditModelAndView(e1);
} catch (final Throwable oops) {
res = new ModelAndView("redirect:list.do");
}
return res;
}
@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "save")
public ModelAndView saveMember(Enrolement e, final BindingResult binding) {
ModelAndView res;
e = this.enrolementService.reconstruct2(e, binding);
try {
this.brotherhoodService.checkBrotherhood(e);
this.enrolementService.saveDirectly(e);
res = new ModelAndView("redirect:list.do");
} catch (final Throwable oops) {
res = new ModelAndView("redirect:list.do");
}
return res;
}
private ModelAndView createEditModelAndView(final Enrolement e1) {
ModelAndView res;
res = this.createEditModelAndView(e1, null);
return res;
}
private ModelAndView createEditModelAndView(final Enrolement e1, final String messageCode) {
ModelAndView res;
res = new ModelAndView("members/edit");
final List<Position> lp = new ArrayList<>(this.positionService.findAll());
res.addObject("enrolement", e1);
res.addObject("message", messageCode);
res.addObject("listPositions", lp);
return res;
}
}
<file_sep>
package services;
import java.util.ArrayList;
import javax.validation.ConstraintViolationException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import utilities.AbstractTest;
import domain.LegalRecord;
import domain.PeriodRecord;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:spring/junit.xml"
})
@Transactional
public class PeriodRecordServiceTest extends AbstractTest {
//SUT
@Autowired
private PeriodRecordService prs;
/**
* THIS TEST IS FOR TESTING THE REQUIREMENT #1
* THERE ARE 2 GOOD TESTING CASES, AND 9 BAD TESTING CASES
* COVERED INSTRUCTIONS IN THIS TEST: 100%
* COVERED INSTRUCTIONS IN LegalRecordService: 73.7%
* COVERED DATA IN THIS TEST: 75%
* */
@Test
public void editRecord() {
final Object testingData[][] = {
/**
* TESTING REQUIREMENT #1
* POSITIVE TEST
* COVERED INSTRUCTIONS: 100%
* COVERED DATA: 20%
* */
{
"brotherhood1", "periodRecord1", null
},
/**
* TESTING REQUIREMENT #1
* NEGATIVE TEST: YOU CANNOT EDIT A LEGAL RECORD IF YOU ARE NOT THE OWNER
* (Expected IllegalArgumentException)
* COVERED INSTRUCTIONS: 100%
* COVERED DATA: 20%
* */
{
"brotherhood2", "periodRecord1", IllegalArgumentException.class
}
};
for (int i = 0; i < testingData.length; i++)
this.template((String) testingData[i][0], super.getEntityId((String) testingData[i][1]), (Class<?>) testingData[i][2]);
}
protected void template(final String username, final int id, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
this.authenticate(username);
final PeriodRecord lr = this.prs.findOne(id);
this.prs.save(lr);
this.unauthenticate();
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
@Test
public void createRecord() {
final PeriodRecord savetest = this.prs.create();
savetest.setDescription("Sample");
savetest.setTitle("SAMPLE");
savetest.setEndYear(2021);
savetest.setPhotos(new ArrayList<String>());
savetest.setStartYear(2020);
final PeriodRecord savetest2 = this.prs.create();
savetest2.setDescription("");
savetest2.setTitle("SAMPLE");
savetest2.setEndYear(2021);
savetest2.setPhotos(new ArrayList<String>());
savetest2.setStartYear(2020);
final PeriodRecord savetest3 = this.prs.create();
savetest3.setDescription("Sample");
savetest3.setTitle("");
savetest3.setEndYear(2021);
savetest3.setPhotos(new ArrayList<String>());
savetest3.setStartYear(2020);
final PeriodRecord savetest4 = this.prs.create();
savetest4.setDescription("Sample");
savetest4.setTitle("SAMPLE");
savetest4.setEndYear(null);
savetest4.setPhotos(new ArrayList<String>());
savetest4.setStartYear(2020);
final PeriodRecord savetest5 = this.prs.create();
savetest5.setDescription("Sample");
savetest5.setTitle("SAMPLE");
savetest5.setEndYear(2021);
savetest5.setPhotos(new ArrayList<String>());
savetest5.setStartYear(null);
final PeriodRecord savetest6 = this.prs.create();
savetest6.setDescription(null);
savetest6.setTitle("SAMPLE");
savetest6.setEndYear(2021);
savetest6.setPhotos(new ArrayList<String>());
savetest6.setStartYear(2020);
final PeriodRecord savetest7 = this.prs.create();
savetest7.setDescription("Sample");
savetest7.setTitle(null);
savetest7.setEndYear(2021);
savetest7.setPhotos(new ArrayList<String>());
savetest7.setStartYear(2020);
final PeriodRecord savetest8 = this.prs.create();
savetest8.setDescription("Sample");
savetest8.setTitle("SAMPLE");
savetest8.setEndYear(2021);
savetest8.setPhotos(new ArrayList<String>());
savetest8.setStartYear(2020);
final PeriodRecord savetest9 = this.prs.create();
savetest9.setDescription("A very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long text");
savetest9.setTitle("A very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long textA very long text");
savetest9.setEndYear(2021);
savetest9.setPhotos(new ArrayList<String>());
savetest9.setStartYear(2020);
final Object testingData[][] = {
/**
* TESTING REQUIREMENT #1
* POSITIVE TEST
* COVERED INSTRUCTIONS: 100%
* COVERED DATA: 20%
* */
{
"brotherhood1", savetest, null
},
/**
* TESTING REQUIREMENT #1
* NEGATIVE TEST: YOU CANNOT EDIT A LINK RECORD WITH EMPTY OR NULL VALUES
* (Expected ConstraintViolationException)
* COVERED INSTRUCTIONS: 100%
* COVERED DATA: 20%
* */
{
"brotherhood1", savetest2, ConstraintViolationException.class
},
/**
* TESTING REQUIREMENT #1
* NEGATIVE TEST: YOU CANNOT EDIT A LINK RECORD WITH EMPTY OR NULL VALUES
* (Expected ConstraintViolationException)
* COVERED INSTRUCTIONS: 100%
* COVERED DATA: 20%
* */
{
"brotherhood1", savetest3, ConstraintViolationException.class
},
/**
* TESTING REQUIREMENT #1
* NEGATIVE TEST: YOU CANNOT EDIT A LINK RECORD WITH EMPTY OR NULL VALUES
* (Expected ConstraintViolationException)
* COVERED INSTRUCTIONS: 100%
* COVERED DATA: 20%
* */
{
"brotherhood1", savetest4, ConstraintViolationException.class
},
/**
* TESTING REQUIREMENT #1
* NEGATIVE TEST: YOU CANNOT EDIT A LINK RECORD WITH EMPTY OR NULL VALUES
* (Expected ConstraintViolationException)
* COVERED INSTRUCTIONS: 100%
* COVERED DATA: 20%
* */
{
"brotherhood1", savetest5, ConstraintViolationException.class
},
/**
* TESTING REQUIREMENT #1
* NEGATIVE TEST: YOU CANNOT EDIT A LINK RECORD WITH EMPTY OR NULL VALUES
* (Expected ConstraintViolationException)
* COVERED INSTRUCTIONS: 100%
* COVERED DATA: 20%
* */
{
"brotherhood1", savetest6, ConstraintViolationException.class
},
/**
* TESTING REQUIREMENT #1
* NEGATIVE TEST: YOU CANNOT EDIT A LINK RECORD WITH EMPTY OR NULL VALUES
* (Expected ConstraintViolationException)
* COVERED INSTRUCTIONS: 100%
* COVERED DATA: 20%
* */
{
"brotherhood1", savetest7, ConstraintViolationException.class
},
/**
* TESTING REQUIREMENT #1
* NEGATIVE TEST: YOU CANNOT EDIT A LINK RECORD WITH EMPTY OR NULL VALUES
* (Expected ConstraintViolationException)
* COVERED INSTRUCTIONS: 100%
* COVERED DATA: 20%
* */
{
"brotherhood1", savetest8, ConstraintViolationException.class
},
/**
* TESTING REQUIREMENT #1
* NEGATIVE TEST: YOU CANNOT EDIT A LINK RECORD WITH EMPTY OR NULL VALUES
* (Expected ConstraintViolationException)
* COVERED INSTRUCTIONS: 100%
* COVERED DATA: 20%
* */
{
"brotherhood1", savetest9, ConstraintViolationException.class
},
};
for (int i = 0; i < testingData.length; i++)
this.template2((String) testingData[i][0], (PeriodRecord) testingData[i][1], (Class<?>) testingData[i][2]);
}
protected void template2(final String username, final PeriodRecord lr, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
this.authenticate(username);
this.prs.save(lr);
this.unauthenticate();
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
}
<file_sep>
package controllers.chapter;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import services.ParadeService;
import services.SegmentService;
import controllers.AbstractController;
import domain.Parade;
import domain.Segment;
@Controller
@RequestMapping("/chapter/segment")
public class ParadeChapterSegmentController extends AbstractController {
@Autowired
private ParadeService paradeService;
@Autowired
private SegmentService segmentService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView list(@RequestParam final int paradeId) {
ModelAndView result;
final Parade parade = this.paradeService.findOne(paradeId);
final List<Segment> segments = this.segmentService.getSegmentsByParade(parade);
result = new ModelAndView("chapter/segment/list");
result.addObject("segments", segments);
result.addObject("requestURI", "/chapter/segment/list.do");
return result;
}
}
<file_sep>
package domain;
import java.util.Collection;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.validation.constraints.Min;
import org.hibernate.validator.constraints.NotBlank;
@Entity
@Access(AccessType.PROPERTY)
public class LegalRecord extends Record {
private String legalName;
private Collection<String> applicableLaws;
private Integer vatNumber;
@NotBlank
public String getLegalName() {
return this.legalName;
}
public void setLegalName(final String legalName) {
this.legalName = legalName;
}
@ElementCollection
public Collection<String> getApplicableLaws() {
return this.applicableLaws;
}
public void setApplicableLaws(final Collection<String> applicableLaws) {
this.applicableLaws = applicableLaws;
}
@Min(0)
public Integer getVatNumber() {
return this.vatNumber;
}
public void setVatNumber(final Integer vatNumber) {
this.vatNumber = vatNumber;
}
}
<file_sep>
package repositories;
import java.util.Collection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.Request;
@Repository
public interface RequestRepository extends JpaRepository<Request, Integer> {
@Query("select r from Request r where r.parade.id = ?1")
Collection<Request> findByParadeId(int paradeId);
@Query("select r from Member m join m.requests r where r.parade.id=?1 and m.id=?2")
public Request findRequestByIds(Integer paradeId, Integer memberId);
@Query("select r from Member m join m.requests r where m.id=?1")
public Collection<Request> findRequestByMemberId(Integer memberId);
@Query("select r from Request r join r.parade p where p.id=?1")
public Collection<Request> findRequestByParadeId(Integer paradeId);
@Query("select r from Member m join m.requests r where m.id=?1 and r.parade.id=?2")
public Request existRequest(Integer memberId, Integer paradeId);
@Query("select r from Request r where r.parade.id=?1 and r.status='PENDING'")
public Collection<Request> requestPending(Integer paradeId);
@Query("select r from Request r where r.parade.id=?1 and r.status='APPROVED'")
public Collection<Request> findAllApproved(Integer paradeId);
@Query("select r from Request r join r.parade p where r.rowPosition=?1 and r.columnPosition=?2 and p.id=?3")
public Request checkPosition(Integer row, Integer column, Integer paradeId);
}
<file_sep>
package domain;
import java.util.Collection;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.URL;
@Entity
@Access(AccessType.PROPERTY)
public class Sponsorship extends DomainEntity {
private String banner;
private Boolean isActive;
private String targetURL;
private Collection<Parade> parades;
private CreditCard creditCard;
@NotBlank
@URL
public String getTargetURL() {
return this.targetURL;
}
public void setTargetURL(final String targetURL) {
this.targetURL = targetURL;
}
@NotBlank
public String getBanner() {
return this.banner;
}
public void setBanner(final String banner) {
this.banner = banner;
}
public void setIsActive(final Boolean isActive) {
this.isActive = isActive;
}
@NotNull
public Boolean getIsActive() {
return this.isActive;
}
public void setIsActive(final boolean isActive) {
this.isActive = isActive;
}
@ManyToMany
public Collection<Parade> getParades() {
return this.parades;
}
public void setParades(final Collection<Parade> parades) {
this.parades = parades;
}
@NotNull
@ManyToOne(optional = false)
public CreditCard getCreditCard() {
return this.creditCard;
}
public void setCreditCard(final CreditCard creditCard) {
this.creditCard = creditCard;
}
}
<file_sep>
package controllers.brotherhood;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import services.BrotherhoodService;
import services.FloatService;
import services.ProcessionService;
import controllers.AbstractController;
import domain.Brotherhood;
import domain.Procession;
@Controller
@RequestMapping("/procession")
public class ProcessionBrotherhoodController extends AbstractController {
@Autowired
BrotherhoodService brotherhoodService;
@Autowired
ProcessionService processionService;
@Autowired
FloatService floatService;
@RequestMapping(value = "/brotherhood/list", method = RequestMethod.GET)
public ModelAndView list() {
ModelAndView res;
final Brotherhood bro = this.brotherhoodService.findByPrincipal();
final Collection<Procession> processions = this.processionService.findByBrotherhoodId(bro.getId());
final List<Boolean> finalModes = new ArrayList<>();
finalModes.add(true);
finalModes.add(false);
res = new ModelAndView("procession/brotherhood/list");
res.addObject("processions", processions);
res.addObject("requestURI", "procession/brotherhood/list.do");
res.addObject("finalModes", finalModes);
return res;
}
@Autowired
Validator validator;
@RequestMapping(value = "/brotherhood/edit", method = RequestMethod.POST, params = "save")
public ModelAndView save(@ModelAttribute final Procession procession, final BindingResult binding) {
ModelAndView result;
Procession procMod;
try {
Assert.notNull(procession.getDescription());
Assert.isTrue(procession.getDescription() != "");
Assert.notNull(procession.getDepartureDate());
Assert.notNull(procession.getFloats());
Assert.isTrue(procession.getFloats().isEmpty() == false);
Assert.notNull(procession.getTitle());
Assert.isTrue(procession.getTitle() != "");
} catch (final Throwable error) {
result = this.createEditModelAndView(procession, "procession.mandatory");
return result;
}
try {
procMod = this.processionService.reconstruct(procession, binding);
this.validator.validate(procMod, binding);
if (binding.hasErrors())
result = this.createEditModelAndView(procMod);
else {
this.processionService.save(procMod);
result = new ModelAndView("redirect:list.do");
}
} catch (final Throwable oops) {
result = this.createEditModelAndView(procession, "procession.commit.error");
}
return result;
}
@RequestMapping(value = "/brotherhood/create", method = RequestMethod.GET)
public ModelAndView create() {
ModelAndView res;
Procession procession;
procession = this.processionService.create();
res = this.createEditModelAndView(procession);
return res;
}
@RequestMapping(value = "/brotherhood/edit", method = RequestMethod.GET)
public ModelAndView edit(@RequestParam final int processionId) {
ModelAndView result;
Procession procession;
final Brotherhood brotherhood = this.brotherhoodService.findByPrincipal();
procession = this.processionService.findOne(processionId);
Assert.isTrue(procession.getBrotherhood().getId() == brotherhood.getId());
Assert.isTrue(procession.getFinalMode() == false);
result = this.createEditModelAndView(procession);
return result;
}
@RequestMapping(value = "/brotherhood/edit", method = RequestMethod.POST, params = "delete")
public ModelAndView delete(final Procession procession, final BindingResult binding) {
ModelAndView result;
try {
this.processionService.delete(procession);
result = new ModelAndView("redirect:list.do");
} catch (final Throwable oops) {
result = this.createEditModelAndView(procession, "procession.commit.error");
}
return result;
}
protected ModelAndView createEditModelAndView(final Procession procession) {
ModelAndView result;
result = this.createEditModelAndView(procession, null);
return result;
}
protected ModelAndView createEditModelAndView(final Procession procession, final String message) {
ModelAndView result;
final Brotherhood bro = this.brotherhoodService.findByPrincipal();
final Collection<domain.Float> floats = this.floatService.findByBrotherhoodId(bro.getId());
result = new ModelAndView("procession/edit");
result.addObject("floats", floats);
result.addObject("procession", procession);
result.addObject("message", message);
return result;
}
}
<file_sep>record.list = Crónicas
record.edit = Editar
record.show = Ver detalles
record.create = Crear
record.save = Guardar
record.delete = Borrar
record.cancel = Cancelar
record.obligatorio = Los campos marcados con * son obligatorios
record.title = Título* :
record.description = Descripción* :
record.legalName = Nombre legal* :
record.applicableLaws = Leyes aplicables :
record.vatNumber = IVA :
record.link = Enlace :
record.startYear = Año de inicio :
record.endYear = Año de fin :
record.photos = FotosS :
legalRecord.create = Crear crónica legal
linkRecord.create = Crear crónica de enlace
periodRecord.create = Crear crónica periódica
inceptionRecord.create = Crear crónica inicial
record.mandatory = (Los campos con * son obligatorios)
record.confirm.delete = ¿Eliminar esta crónica?
record.commit.error.blank = Error. The introduced values are incorrect or blank.
record.commit.error = Errors<file_sep>
package controllers.enrolements;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import services.BrotherhoodService;
import services.EnrolementService;
import services.MemberService;
import controllers.AbstractController;
import domain.Brotherhood;
import domain.Enrolement;
import domain.Member;
@Controller
@RequestMapping("/enrolements/member")
public class EnrolementsMemberController extends AbstractController {
@Autowired
MemberService memberService;
@Autowired
BrotherhoodService brotherhoodService;
@Autowired
EnrolementService enrolementService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView list() {
final ModelAndView res;
final Collection<Enrolement> enrolements;
final Member member = this.memberService.findOnePrincipal();
enrolements = this.enrolementService.findEnrolementsByMemberId(member);
res = new ModelAndView("enrolements/list");
res.addObject("enrolements", enrolements);
res.addObject("memberView", true);
res.addObject("requestURI", "enrolements/member/list.do");
return res;
}
@RequestMapping(value = "/create", method = RequestMethod.GET)
public ModelAndView create() {
final ModelAndView res;
final Enrolement e;
e = this.enrolementService.create();
res = this.createEditModelAndView(e);
return res;
}
@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "save")
public ModelAndView save(Enrolement e, final BindingResult binding) {
ModelAndView res;
e = this.enrolementService.reconstruct(e, binding);
if (binding.hasErrors())
res = this.createEditModelAndView(e);
else
try {
this.enrolementService.save(e);
res = new ModelAndView("redirect:list.do");
} catch (final Throwable oops) {
res = this.createEditModelAndView(e, "error.enrolement");
}
return res;
}
protected ModelAndView createEditModelAndView(final Enrolement e) {
ModelAndView res;
res = this.createEditModelAndView(e, null);
return res;
}
protected ModelAndView createEditModelAndView(final Enrolement e, final String messageCode) {
ModelAndView res;
res = new ModelAndView("enrolements/edit");
final Member m = this.memberService.findByPrincipal();
final List<Brotherhood> lb = new ArrayList<>(this.brotherhoodService.findAllNotApproved(m));
res.addObject("memberView", true);
res.addObject("enrolement", e);
res.addObject("message", messageCode);
res.addObject("listBrotherhoods", lb);
return res;
}
}
<file_sep>package services;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import domain.Customisation;
import repositories.CustomisationRepository;
@Transactional
@Service
public class CustomisationService {
@Autowired
private CustomisationRepository customisationRepository;
public Customisation create(){
return new Customisation();
}
public Collection<Customisation> findAll(){
return customisationRepository.findAll();
}
public Customisation findOne(int customisationId){
return customisationRepository.findOne(customisationId);
}
public Customisation save(Customisation customisation){
return customisationRepository.save(customisation);
}
public void delete(Customisation customisation){
customisationRepository.delete(customisation);
}
public Customisation getCustomisation(){
List<Customisation> x = new ArrayList<Customisation>();
x.addAll(this.findAll());
Customisation res;
res = x.get(0);
return res;
}
}
<file_sep>parade.list = Lista de desfiles
parade.name = Nombre
parade.parentCategory = Categoría padre
parade.edit = Editar
parade.delete = Eliminar
parade.edit.link = Editar
parade.delete.link = Eliminar
parade.list.create = Nuevo desfile
parade.save = Guardar
parade.cancel = Cancelar
parade.nombre = Nombre
parade.mandatory = Algunos campos obligatorios están en blanco.
parade.commit.error = Se encontraron errores. Recuerda que la razón de rechazo es obligatoria si el estado es "Rejected".
parade.confirm.delete = ¿Eliminar este desfile?
parade.status = Estado
parade.rejectReason = Razón de rechazo
parade.list.request = Lista de peticiones
parade.ob = Los parámetros marcados con * son obligatorios.
parade.float = Pasos* (Mantén pulsado control para seleccionar más de uno)
parade.true = Sí
parade.false = No
parade.title = Título*
parade.description = Descripción*
parade.departureDate = Fecha de salida*
parade.ticker = Ticker
parade.finalMode = Modo final*
parade.segment.list = Segmentos
| e603553595ffa76051f6c208470644e6ad8cf52c | [
"Java",
"SQL",
"INI"
] | 44 | Java | apcm/DTIID02 | 5616c64812e5bc55707d5fb6e2824153484124c4 | 47f1f4b849c41859e2f3b57d083e0be9b4fc8ffe | |
refs/heads/main | <file_sep>import tkinter as tk
# function to load any button clicks into a global variable that will be displayed on screen
def press(item):
global expression
# concatenate button presses into variable expression
expression += str(item)
# set StringVar equation to value of expression variable
equation.set(expression)
# funtion to clear the global variable expression to default
def clear():
global expression
# set expression to no text and set equation to expression
expression = ""
equation.set(expression)
# function to run the current calculation and get result
def enter():
global expression
# use eval() function to evaluate the expression and turn it into a string
total = str(eval(expression))
# set equation to the value of the result of the eval() function
equation.set(total)
# reset global expression variable
expression = ""
# create window, set window title, size, and constant size
window = tk.Tk()
window.title("PyCalc")
window.geometry("210x255")
window.resizable(False, False)
# global variable expression and StringVar equation
expression = ""
equation = tk.StringVar()
# create text display window and set its value to be that of StringVar equation
text = tk.Entry(window, textvariable=equation, width=32).grid(row=0, column=0, columnspan=4, padx=5, pady=5)
# create layout of calculator window using grid manager and call correct funtion and arguments for button presses
button_clr = tk.Button(window, text=' C ', width=10, command=lambda: clear()).grid(row=2, column=0, columnspan=2, padx=5, pady=5)
button_div = tk.Button(window, text=' / ', width=3, command=lambda: press('/')).grid(row=2, column=2, padx=5, pady=5)
button_mult = tk.Button(window, text=' * ', width=3, command=lambda: press('*')).grid(row=2, column=3, padx=5, pady=5)
button_sub = tk.Button(window, text=' - ', width=3, command=lambda: press('-')).grid(row=3, column=3, padx=5, pady=5)
button_add = tk.Button(window, text=' + ', width=3, command=lambda: press('+')).grid(row=4, column=3, padx=5, pady=5)
button_mod = tk.Button(window, text=' % ', width=3, command=lambda: press('%')).grid(row=5, column=3, padx=5, pady=5)
button_dec = tk.Button(window, text=' . ', width=3, command=lambda: press('>')).grid(row=6, column=0, padx=5, pady=5)
button_enter = tk.Button(window, text=' = ', width=10, command=enter).grid(row=6, column=2, columnspan=2, padx=5, pady=5)
button1 = tk.Button(window, text=' 1 ', command=lambda: press('1'), width=3).grid(row=3, column=0, padx=5, pady=5)
button2 = tk.Button(window, text=' 2 ', command=lambda: press('2'), width=3).grid(row=3, column=1, padx=5, pady=5)
button3 = tk.Button(window, text=' 3 ', command=lambda: press('3'), width=3).grid(row=3, column=2, padx=5, pady=5)
button4 = tk.Button(window, text=' 4 ', command=lambda: press('4'), width=3).grid(row=4, column=0, padx=5, pady=5)
button5 = tk.Button(window, text=' 5 ', command=lambda: press('5'), width=3).grid(row=4, column=1, padx=5, pady=5)
button6 = tk.Button(window, text=' 6 ', command=lambda: press('6'), width=3).grid(row=4, column=2, padx=5, pady=5)
button7 = tk.Button(window, text=' 7 ', command=lambda: press('7'), width=3).grid(row=5, column=0, padx=5, pady=5)
button8 = tk.Button(window, text=' 8 ', command=lambda: press('8'), width=3).grid(row=5, column=1, padx=5, pady=5)
button9 = tk.Button(window, text=' 9 ', command=lambda: press('9'), width=3).grid(row=5, column=2, padx=5, pady=5)
button0 = tk.Button(window, text=' 0 ', command=lambda: press('0'), width=3).grid(row=6, column=1, padx=5, pady=5)
# start the calculator window
window.mainloop()<file_sep># PyCalc
A simple GUI calculator using TKInter graphics
You've seen it before, now see it again in this mediocre and ultimately pointless recreation of... a Calculator!
You need never math with your stupid brain again.
| 62d695fa4f3d575271b142c9757af414d1ae6dfd | [
"Markdown",
"Python"
] | 2 | Python | dainebigham/python-gui-calculator | 41e7b21d87c3f50434d916610320dcd3d4906f3e | ec41682001fa568aaacd977bab8ffe373a732d95 | |
refs/heads/master | <repo_name>tbelahi/rackcity<file_sep>/js/audiocontroller.js
define(function (require)
{
var javascriptNode;
function initAudio(url, audioContext, source, analyser, audioProcessCallback)
{
var buffer;
var audioBuffer;
// Load
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
// filter for testing low freq's alone
var filter = audioContext.createBiquadFilter();
filter.type = "lowpass";
filter.frequency.value = 50;
// filter.gain.value = -20;
javascriptNode = audioContext.createScriptProcessor(1024, 1, 1);
javascriptNode.onaudioprocess = audioProcessCallback;
// fake gain for script processor bug workaround
var gainNode = audioContext.createGain();
// gainNode.gain.value = 0;
request.onload = function() {
audioContext.decodeAudioData(request.response, function(buffer) {
source.buffer = buffer;
source.loop = true;
source.connect(analyser);
// filter.connect(analyser);
analyser.connect(gainNode);
gainNode.connect(audioContext.destination);
javascriptNode.connect(gainNode);
source.start(0.0);
}, function(e) {
console.log("error" + e);
});
};
request.send();
}
function getAverageVolume(array) {
var values = 0;
var average;
var length = array.length;
// get all the frequency amplitudes
for (var i = 0; i < length; i++) {
values += array[i];
}
average = values / length;
return average;
}
return {
initAudio: initAudio
}
});<file_sep>/js/rackcity.js
define(function (require)
{
var proj4 = require('proj4'),
audioController = require('audiocontroller');
var scene;
var all_features, small_roads, large_roads, buildings;
var center_xy;
var large_roads_lines, small_road_lines;
var building_dots = [], building_top_dots = [];
var lowsMidsHighsBuildingsGroups = [];
function setup(sc)
{
scene = sc;
}
function init3D(data, center_pt)
{
console.log("RackCity::init()");
console.log(data);
all_features = data;
small_roads = data['small_roads'];
large_roads = data['large_roads'];
buildings = data['buildings'];
lowsMidsHighsBuildingsGroups = [];
//get center pt xy projection for normalizing other points
center_xy = proj4('EPSG:4326', 'EPSG:3785', center_pt);
initHomeLine();
//build roads and buildings
small_road_lines = drawRoads(small_roads);
large_roads_lines = drawRoads(large_roads);
drawBuildings(buildings);
}
function initHomeLine()
{
var vertexShader =
//'uniform float[512] spectrum;\n' +
'varying float vHeight;' +
'void main() {\n' +
' vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n' +
' vHeight = position.y;\n' +
' gl_Position = projectionMatrix * mvPosition;\n' +
'}';
var fragmentShader =
'varying float vHeight;' +
'void main() {\n' +
' float a = 1.0;\n' +
' if(vHeight > 750.0) a = 0.0;\n' +
' else if(vHeight > 400.0) a = (750.0 - vHeight) / 400.0;\n' +
' gl_FragColor = vec4( 0.8, 0.8, 0.8, a );\n' +
'}';
var uniforms = {
spectrum: { type: 'f', values:[] }
} ;
var material = new THREE.ShaderMaterial({
//uniforms: uniforms,
vertexShader: vertexShader,
fragmentShader: fragmentShader,
transparent: true
});
material.linewidth = 3;
//place line up from center
var line_geom = new THREE.Geometry();
var bottom = new THREE.Vector3(0, 0, 0);
var top = new THREE.Vector3(0, 750, 0);
line_geom.vertices.push(bottom);
line_geom.vertices.push(top);
var line = new THREE.Line(line_geom, material);
scene.add(line);
}
function drawRoads(container)
{
var vertexShader =
'uniform float burst;\n' +
'varying float vPercent;\n' +
'varying float vDist;\n' +
'void main() {\n' +
' vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n' +
' vDist = distance(vec2(0,0), position.xz);\n' +
' vPercent = 1.0;\n' +
' gl_Position = projectionMatrix * mvPosition;\n' +
'}';
var fragmentShader =
'uniform float burst;\n' +
'varying float vPercent;\n' +
'varying float vDist;\n' +
'void main() {\n' +
' float a = 1.0;\n' +
' if(vDist > 850.0 )\n' +
' a = 0.0;\n' +
' else if(vDist > 500.0)\n' +
' a = (850.0 - vDist) / 500.0;\n' +
' gl_FragColor = vec4( 1.0, 1.0, 1.0, a );//1.0 );\n' +
'}';
var uniforms = {
burst: { type:'f', value: 0.0 }
};
var material = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: vertexShader,
fragmentShader: fragmentShader,
transparent: true
});
material.linewidth = 2;
var allLines = [];
for(var i = 0; i < container.length; i++)
{
var geometry = new THREE.Geometry();
var pts = container[i];
for(var j = 0; j < pts.length; j++)
{
var latlng = [pts[j].lon, pts[j].lat];
var pt_xy = proj4('EPSG:4326', 'EPSG:3785', latlng);
var vec3 = new THREE.Vector3(
pt_xy[1] - center_xy[1],
0,
pt_xy[0] - center_xy[0]
);
geometry.vertices.push(vec3);
}
var line = new THREE.Line(geometry, material);
allLines.push(line);
scene.add(line);
}
return allLines;
}
function drawBuildings(container)
{
var particleShaderVertex =
'uniform float pointSize;\n' +
'uniform float volume;\n' +
'uniform float alpha;\n' +
'void main() {\n' +
' vec4 mvPosition = modelViewMatrix * vec4( position.x, position.y * volume, position.z, 1.0 );\n' +
' gl_PointSize = pointSize;\n' +
' vec4 pos = projectionMatrix * mvPosition;\n' +
' gl_Position = vec4(pos.x, pos.y, pos.z, pos.w);\n' +
'}';
var particleShaderFragment =
'uniform vec3 color;\n' +
'uniform float alpha;\n' +
'void main() {\n' +
' gl_FragColor = vec4( color, alpha );\n' +
'}';
// uniforms
var uniforms = {
color: { type: "c", value: new THREE.Color( 0xd1effd ) },
volume: { type: "f", value: 0 },
pointSize: { type: "f", value: 2 },
alpha: { type: "f", value: 0.5 },
};
var material = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: particleShaderVertex,
fragmentShader: particleShaderFragment,
transparent: true
});
var clouds = [];
var topDotsGeom = new THREE.Geometry();
var topDotsMaterial = material.clone();
topDotsMaterial.uniforms.pointSize.value = 3.0;
topDotsMaterial.uniforms.alpha.value = .88;
topDotsMaterial.uniforms.color.value = new THREE.Color(0xffffff);
var buildingsByHeight = [];
//sort buildings by height
for(var i = 0; i < container.length; i++)
{
var height = Math.round(container[i]['height']);
if(isNaN(height))
height = Math.round(container[i]['ele']);
if(isNaN(height))
height = Math.round(container[i]['levels']) * 4;
if(isNaN(height))
height = 20;
buildingsByHeight.push({ ht:height, id:i });
}
function compare(a,b) {
if (a.ht < b.ht)
return -1;
if (a.ht > b.ht)
return 1;
return 0;
}
buildingsByHeight.sort(compare); // low to high
//chunk through height arrays in thirds
var i,j,temparray,chunk = buildingsByHeight.length / 3;
for (i=0,j=buildingsByHeight.length; i<j; i+=chunk)
{
temparray = buildingsByHeight.slice(i,i+chunk);
lowsMidsHighsBuildingsGroups.push(createBuildingGroup(temparray));
}
function createBuildingGroup(tempArray)
{
var group = {};
var geometry = new THREE.Geometry();
for(var k = 0; k < tempArray.length; k++)
{
var height = tempArray[k].ht;
var pts = container[tempArray[k].id]['pts'];
for(var h = 0; h < height; h++)
{
if(h % 4 == 0 && h != height - 1)
{
for(var j = 0; j < pts.length; j++)
{
var latlng = [pts[j].lon, pts[j].lat];
var pt_xy = proj4('EPSG:4326', 'EPSG:3785', latlng);
var vec3 = new THREE.Vector3(
pt_xy[1] - center_xy[1],
h * 5,
pt_xy[0] - center_xy[0]
);
geometry.vertices.push(vec3);
}
}
//do something when its top
if(h == height - 1)
{
for(var j = 0; j < pts.length; j++)
{
var latlng = [pts[j].lon, pts[j].lat];
var pt_xy = proj4('EPSG:4326', 'EPSG:3785', latlng);
var vec3 = new THREE.Vector3(
pt_xy[1] - center_xy[1],
h * 5,
pt_xy[0] - center_xy[0]
);
topDotsGeom.vertices.push(vec3);
}
}
}
//draw top and bottom
drawBuildingOutline(pts, height);
}
var mesh = new THREE.PointCloud( geometry, material );
var topDotsMesh = new THREE.PointCloud( topDotsGeom, topDotsMaterial );
// add it to the scene
scene.add(mesh);
scene.add(topDotsMesh);
group.mainMesh = mesh;
group.topDotsMesh = topDotsMesh;
return group;
}
}
function drawBuildingOutline(pts, height)
{
var geometry = new THREE.Geometry();
for(var j = 0; j < pts.length; j++)
{
var latlng = [pts[j].lon, pts[j].lat];
var pt_xy = proj4('EPSG:4326', 'EPSG:3785', latlng);
var vec3 = new THREE.Vector3(
pt_xy[1] - center_xy[1],
0, //height === undefined ? 0 : height * 5,
pt_xy[0] - center_xy[0]
);
geometry.vertices.push(vec3);
}
var line = new THREE.Line(geometry, new THREE.LineBasicMaterial({
color: 0x4d576e
}));
scene.add(line);
}
var duration;
/**
* initAudio()
* pass URL to start audioContext for managing visualization
**/
function initAudio(track, sc_client_id)
{
console.log("RackCity::initAudio() ");
console.log(track);
var url = track.stream_url + "?client_id=" + sc_client_id;
duration = track.duration;
$("#title").text(track.title);
$("#songinfo").show();
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext();
var sampleRate = audioContext.sampleRate;
var beatdetect = new FFT.BeatDetect(1024, sampleRate);
var source = audioContext.createBufferSource();
source.onended = function() {
console.log("song over"); //well this shit doesnt work
}
var analyser = audioContext.createAnalyser();
analyser.smoothingTimeConstant = 0.85;
analyser.fftSize = 2048;
var bassSize = 0;
var trebSize = 0;
audioController.initAudio(url, audioContext, source, analyser, function()
{
var array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(array);
var floats = new Float32Array(analyser.frequencyBinCount);
analyser.getFloatTimeDomainData(floats);
beatdetect.detect(floats);
//todo - push all this to the shader along with
//texture filled with actual float array of sound buffer
if(beatdetect.isKick() ) bassSize = 4;//.75; //console.log("isKick()");
if(bassSize > 0) bassSize -= .25;
drawLines(bassSize, large_roads_lines);
if(beatdetect.isSnare() ) trebSize = 2.75;// console.log("isSnare()");
if(trebSize > 0) trebSize -= .05;
drawLines(trebSize, small_road_lines);
var lowsMidsHighs = [
getAverageVolume(array.subarray(750, 1024)),
getAverageVolume(array.subarray(180, 750)),
getAverageVolume(array.subarray(0, 180))
];
for(var i = 0; i < lowsMidsHighsBuildingsGroups.length; i++)
{
var bldg = lowsMidsHighsBuildingsGroups[i];
bldg.mainMesh.material.uniforms.volume.value = map(lowsMidsHighs[i], 40, 230, .35, 1.1);
bldg.topDotsMesh.material.uniforms.volume.value = map(lowsMidsHighs[i], 40, 230, .35, 1.1);
}
});
}
function map(value, start1, stop1, start2, stop2)
{
return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1));
}
function drawLines(size, lines)
{
if(size > 0.0);
{
for(var i = 0; i < lines.length; i++)
{
var line = lines[i];
line.material.linewidth = size;
line.material.uniforms.burst.value = size;
}
}
}
function getAverageVolume(array) {
var values = 0;
var average;
var length = array.length;
// get all the frequency amplitudes
for (var i = 0; i < length; i++) {
values += array[i];
}
average = values / length;
return average;
}
// function finishLoad() {
// source.buffer = audioBuffer;
// source.loop = true;
// source.start(0.0);
// // startViz();
// }
function update()
{
}
function formatTime(seconds)
{
minutes = Math.floor(seconds / 60);
minutes = (minutes >= 10) ? minutes : "0" + minutes;
seconds = Math.floor(seconds % 60);
seconds = (seconds >= 10) ? seconds : "0" + seconds;
return minutes + ":" + seconds;
}
return {
setup:setup,
init3D:init3D,
initAudio:initAudio,
update:update
};
});
| 50366cf4f5d3901c7ffaf28d929dc08e35db10a8 | [
"JavaScript"
] | 2 | JavaScript | tbelahi/rackcity | e50283136e1b8595ceb7de8d79541325d60f0460 | 721a35ee7c89f2b580d5c50ef1c8d4c23cb9c1a8 | |
refs/heads/master | <repo_name>iibrahimli/se_polish_calc<file_sep>/src_polish_calc/src/CMakeLists.txt
project(polish_calc)
set(polish_calc_source main.cpp)
add_executable(${PROJECT_NAME} ${polish_calc_source})<file_sep>/src_polish_calc/include/element.hpp
#ifndef ELEMENT_HPP
#define ELEMENT_HPP
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <stack>
#include <cmath>
namespace pc{
union element;
size_t num_operands(char op);
bool eval_op(char op, std::stack<element>& opst);
std::vector<double> _get_operands_from_stack(std::stack<element>& st, size_t n_ops);
// a map from operations to number of operands
std::unordered_map<char, size_t> _n_operands({
{'+', 2},
{'-', 2},
{'*', 2},
{'/', 2},
{'^', 2},
{'r', 1}
});
};
// an operator code or a number
union pc::element{
unsigned long _op;
double _num;
// initialize with an operation
element(char op){
_num = std::numeric_limits<double>::quiet_NaN();
((char*)(&_op))[0] = op;
}
// initialize with a number
element(double num){
_num = num;
}
// check if union contains an operation
bool is_op() const{
return std::isnan(_num);
}
// returns the char of operation
char get_op() const{
if(!is_op()) std::runtime_error("Tried to get operation while the element holds a nummber");
return ((char*)(&_op))[0];
}
};
// returns number of needed operands for the operator (ex: 2 if op = '+')
size_t pc::num_operands(char op){
auto n = _n_operands.find(op);
if( n != _n_operands.end())
return n->second;
else{
std::runtime_error("Unsupported operation character: " + std::to_string(op));
return 0;
}
}
// gets N_OPS elements from the top of ST (from oldest to newest)
std::vector<double> pc::_get_operands_from_stack(std::stack<element>& st, size_t n_ops){
std::vector<double> ops;
// check whether there are enough numbers in the stack
if(st.size() < n_ops){
std::runtime_error("Stack contains less numbers than needed");
return ops;
}
for(size_t i=0; i<n_ops; ++i){
ops.push_back(st.top()._num);
st.pop();
}
// reverse the order so that the oldest element is first in the vector
std::reverse(ops.begin(), ops.end());
return ops;
}
// evaluates the operation modifying the stack as necessary (popping operands
// and pushing the result) and returns boolean indicating success
bool pc::eval_op(char op, std::stack<element>& opst){
auto oper = _n_operands.find(op);
if( oper != _n_operands.end()){
// op is a valid operation
double res = 0;
auto ops = _get_operands_from_stack(opst, num_operands(op));
switch(oper->first){
case '+':
// addition
res = ops[0] + ops[1];
break;
case '-':
// subtraction
res = ops[0] - ops[1];
break;
case '*':
// multiplication
res = ops[0] * ops[1];
break;
case '/':
// division
res = ops[0] / ops[1];
break;
case '^':
// power
res = std::pow(ops[0], ops[1]);
break;
case 'r':
// sqrt
res = std::sqrt(ops[0]);
break;
}
opst.push(element(res));
return true;
}
else{
std::runtime_error("Unsupported operation character: " + std::to_string(op));
return false;
}
}
std::ostream& operator<<(std::ostream& os, const pc::element& el){
if(el.is_op()) os << el.get_op();
else os << el._num;
return os;
}
#endif<file_sep>/src_polish_calc/src/main.cpp
#include <iostream>
#include <string>
#include "pc.hpp"
using namespace std;
using namespace pc;
int main(int argc, const char *argv[]){
if(argc != 2){
cout << "No single expression provided" << endl;
return 1;
}
polish_calc calc;
string expr = argv[1];
cout << calc.eval_string(expr) << endl;
return 0;
}<file_sep>/src_polish_calc/include/pc.hpp
#ifndef PC_HPP
#define PC_HPP
#include <iostream>
#include <sstream>
#include <stack>
#include <cmath>
#include "element.hpp"
namespace pc{
class polish_calc;
};
class pc::polish_calc{
public:
// adds an element to the stack and executes if element contains an operation
void add_element(element el){
if(el.is_op()){
// element represents an operation
// evaluates an operator on the given stack (modifies the stack)
// the reason for this implementation is that the number of operands to an operator
// is not fixed, and it is even possible to add support for operators accepting more
// than 2 operands in future
if(!eval_op(el.get_op(), _opstack))
std::runtime_error("Error evaluating operation '" + std::to_string(el.get_op()) + "'");
}
else{
// element is a number
_opstack.push(el);
}
}
// just for convenience
void add_op(char op){
add_element(element(op));
}
// just for convenience
void add_num(double num){
add_element(element(num));
}
// evaluates a given expression string (MUST be space-separated) (ex: '2 4 + 5 *' will produce 30)
double eval_string(const std::string& expr){
std::istringstream in(expr);
double tmp_num;
char tmp_op;
while(in){
// ignore spaces
if(std::isspace(in.peek()) || in.peek() == '\0'){
in.ignore(1);
continue;
}
else{
// a digit means that we need to read a number
if(std::isdigit(in.peek())){
if(!(in >> tmp_num)) break;
add_element(element(tmp_num));
}
// read in a character
else{
if(!(in >> tmp_op)) break;
add_element(element(tmp_op));
}
}
}
// expression done, but there are extra numbers left on the stack
if(_opstack.size() > 1)
std::cout << "\nStack has " << _opstack.size() << " numbers left. Check the expression maybe" << std::endl;
return _opstack.top()._num;
}
// result of operation (in "manual mode", i.e used with add_*())
double get_result(){
if(_opstack.size() != 1) return std::numeric_limits<double>::quiet_NaN();
return _opstack.top()._num;
}
// returns number of elements on the stack
size_t num_elements(){
return _opstack.size();
}
// clears the contents of the stack
void clear_stack(){
while(!_opstack.empty()) _opstack.pop();
}
private:
std::stack<element> _opstack; // operation stack
};
#endif<file_sep>/README.md
[![Build Status](https://travis-ci.com/iibrahimli/se_polish_calc.svg?branch=master)](https://travis-ci.com/iibrahimli/se_polish_calc)
## SE Project: Reverse Polish Notation Calculator
This is a small PW project for my Software Engineering course to get used to
* CMake
* CppUnit
* Git
* Travis CI
<file_sep>/src_polish_calc/test/expr_test.hpp
#include <cppunit/TestCase.h>
#include <cppunit/TestSuite.h>
#include <cppunit/TestCaller.h>
#include "pc.hpp"
class expr_test : public CppUnit::TestFixture {
private:
pc::polish_calc calc;
int N_NUMS = 10;
public:
void setUp() {}
void tearDown() {}
void test_expr(){
std::string expr = "5 4 + 6 - 2 ^ 2 ^ r 4 *"; // -> 36
CPPUNIT_ASSERT_DOUBLES_EQUAL(calc.eval_string(expr), 36.0, 0.0001);
calc.clear_stack();
// big string test
expr = "";
for(int i=0; i<N_NUMS; ++i) expr += (std::string(" ") + std::to_string(1.0));
for(int i=0; i<N_NUMS-1; ++i) expr += (std::string(" ") + "+");
CPPUNIT_ASSERT_DOUBLES_EQUAL(N_NUMS, calc.eval_string(expr), 0.0001);
}
static CppUnit::Test *suite(){
CppUnit::TestSuite *ts = new CppUnit::TestSuite("String expression evaluation test");
ts->addTest(new CppUnit::TestCaller<expr_test>("test_expr", &expr_test::test_expr));
return ts;
}
};<file_sep>/src_polish_calc/test/main.cpp
#include <cppunit/ui/text/TestRunner.h>
#include "api_test.hpp"
#include "expr_test.hpp"
using namespace std;
int main(){
CppUnit::TextUi::TestRunner runner;
runner.addTest(api_test::suite());
runner.addTest(expr_test::suite());
runner.run();
}<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(polish_calc LANGUAGES CXX)
include_directories("src_polish_calc/include/")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -std=c++11 -Wextra -g")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wextra -std=c++11 -O3")
SET (CMAKE_LIBRARY_OUTPUT_DIRECTORY
${PROJECT_BINARY_DIR}/bin
CACHE PATH
"Single Directory for all"
)
SET (CMAKE_RUNTIME_OUTPUT_DIRECTORY
${PROJECT_BINARY_DIR}/bin
CACHE PATH
"Single Directory for all"
)
SET (CMAKE_ARCHIVE_OUTPUT_DIRECTORY
${PROJECT_BINARY_DIR}/lib
CACHE PATH
"Single Directory for all"
)
enable_testing()
add_subdirectory(src_polish_calc/src)
add_subdirectory(src_polish_calc/test)<file_sep>/src_polish_calc/test/CMakeLists.txt
project(polish_calc_test)
add_executable(tests main.cpp)
target_link_libraries(tests cppunit)
add_test(NAME "cppunit" COMMAND "tests")<file_sep>/src_polish_calc/test/api_test.hpp
#include <cppunit/TestCase.h>
#include <cppunit/TestSuite.h>
#include <cppunit/TestCaller.h>
#include "pc.hpp"
class api_test : public CppUnit::TestFixture {
private:
pc::polish_calc calc;
int N_NUMS = 500000;
public:
void setUp() {}
void tearDown() {}
void test_api(){
CPPUNIT_ASSERT(calc.num_elements() == 0);
calc.add_num(5.556);
calc.add_num(5.556);
CPPUNIT_ASSERT(calc.num_elements() == 2);
calc.clear_stack();
CPPUNIT_ASSERT(calc.num_elements() == 0);
// large volume addition test
for(int i=0; i<N_NUMS; ++i) calc.add_num(1);
for(int i=0; i<N_NUMS-1; ++i) calc.add_op('+');
CPPUNIT_ASSERT(calc.num_elements() == 1);
CPPUNIT_ASSERT(calc.get_result() == (double) N_NUMS);
}
static CppUnit::Test *suite(){
CppUnit::TestSuite *ts = new CppUnit::TestSuite("add_*() API test");
ts->addTest(new CppUnit::TestCaller<api_test>("test_api", &api_test::test_api));
return ts;
}
};
| 748ed5ff1bc6d9e5985d738e8f78992a977cbfbc | [
"Markdown",
"CMake",
"C++"
] | 10 | CMake | iibrahimli/se_polish_calc | 133e3b30c6bcd2b86298eba7a71432cff43b31ff | cfa1aeb2c86ba53d21b40477f5aa0412e7c59135 | |
refs/heads/master | <file_sep>/**
******************************************************************************
* File Name : main.c
* Description : Main program body
******************************************************************************
*
*
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of STMicroelectronics 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
#include <string.h>
/* Variables -----------------------------------------------------------------*/
ADC_HandleTypeDef hadc1;
DMA_HandleTypeDef hdma_adc1;
SPI_HandleTypeDef hspi1;
TIM_HandleTypeDef htim1;
TIM_HandleTypeDef htim2;
TIM_HandleTypeDef htim3;
TIM_HandleTypeDef htim4;
UART_HandleTypeDef huart2;
volatile uint32_t sampleReceived;
volatile uint32_t spiSendReady;
static uint32_t adcSample;
uint8_t uartTxBuff[6];
uint8_t spiTxBuff[2] = {0xAA, 0xAA};
/* Function prototypes -------------------------------------------------------*/
void SystemClock_Config(void);
void Error_Handler(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_ADC1_Init(void);
static void MX_SPI1_Init(void);
static void MX_TIM1_Init(void);
static void MX_TIM2_Init(void);
static void MX_TIM3_Init(void);
static void MX_TIM4_Init(void);
void HAL_TIM_MspPostInit(TIM_HandleTypeDef *htim);
/**
* @brief Отправка сообщения по интерфейсу UART.
* @note Используется для вывода значения, снятого с АЦП.
*
* @param huart: указатель на структуру UART_HandleTypeDef, которая
* хранит настройку UART интерфейса.
* @param pData: указатель на переменную, в которой хранится значение,
* снятое с АЦП.
* @retval Функция ничего не возвращает.
*/
void vUARTsendADCSample(UART_HandleTypeDef *huart, uint32_t *pData) {
strcpy((char*)uartTxBuff, (char*)pData);
HAL_UART_Transmit(huart, uartTxBuff, 6, 100);
}
int main(void)
{
/* MCU Configuration----------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Configure the system clock */
SystemClock_Config();
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_USART2_UART_Init();
MX_ADC1_Init();
MX_SPI1_Init();
MX_TIM1_Init();
MX_TIM2_Init();
MX_TIM3_Init();
MX_TIM4_Init();
strcpy((char*)uartTxBuff, "0000\n\r");
// GPIO toggle - 500kHz
HAL_TIM_OC_Start_IT(&htim1, TIM_CHANNEL_1); // Таймер настроен так, чтоб переполняться с частотой в 1МГц
// и при переполнении менять значение на ноге PE9 порта E.
// Таким образом на выходе этой ноги будут идти импульсы
// с частотой 500кГц.
// ADC conversion - 1Hz
HAL_TIM_Base_Start_IT(&htim2); // Период таймера 1 секунда. При переполнении таймера
// происходит прерывание в котором значение на ноге PD12
// инвертируется(на плате STM32F4-Discovery этот пин
// подключен к зеленому светодиоду) с частотой 0,5Гц.
// Так же переполнением этого таймера включается процесс
// захвата значения напряжения на входе 1-го канала 1-го АЦП.
// GPIO toggle - 300Hz
HAL_TIM_OC_Start_IT(&htim3, TIM_CHANNEL_4); // Таймер переполняется с частотой 600Гц и при переполнении
// инвертирует значение на выходе ноги PB1 порта B.
// На выходе получаются имульсы с частотой следования 300Гц.
// GPIO toggle - 100Hz and SPI sending over 100ms
HAL_TIM_Base_Start_IT(&htim4); // Таймер переполняется с частотой 200Гц и при переполнении
// происходит прерывание, в котором инвертируется значение
// ноги PD14 порта D, получаются имульсы с частотой 100Гц.
// Так же в прерывании инкрементируется счетчик, глубиной 20.
// При переполнении счетчика взводится флаг "spiSendReady",
// говорящий о том, что прошло 100мс и можно инициализировать
// пердачу сообщения по SPI.
// ADC first conversion
HAL_ADC_Start_DMA(&hadc1, &adcSample, 1); // Запуск 1-го АЦП в режиме передачи захваченного значения
// через ПДП. Сам захват значения произойдет по триггеру
// переполнения счетчика TIM1.
// После завершения DMA-транзакции будет вызвано прерывание
// "DMA2_Stream0_IRQHandler" в ктором будет взведен флаг
// "sampleReceived", говорящий о том, что данные приняты и
// можно заново запускать АЦП.
/* Infinite loop */
while (1) {
if (sampleReceived) { // Флаг "sampleReceived" взводится гарантированно не
sampleReceived = 0; // чаще раза в 1 секунду, так как захват значения
HAL_ADC_Start_DMA(&hadc1, &adcSample, 1); // происходит только после переполнения счетчика TIM1.
vUARTsendADCSample(&huart2, &adcSample);
}
if (spiSendReady) {
spiSendReady = 0;
HAL_SPI_Transmit(&hspi1, spiTxBuff, 2, 100);
}
}
}
/** System Clock Configuration
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = 16;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 96;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 7;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV4;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK) {
Error_Handler();
}
HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
/* SysTick_IRQn interrupt configuration */
HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}
/* ADC1 init function */
static void MX_ADC1_Init(void)
{
ADC_ChannelConfTypeDef sConfig;
/**Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
*/
hadc1.Instance = ADC1;
hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
hadc1.Init.Resolution = ADC_RESOLUTION_12B;
hadc1.Init.ScanConvMode = DISABLE;
hadc1.Init.ContinuousConvMode = DISABLE;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_RISING;
hadc1.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T2_TRGO;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.NbrOfConversion = 1;
hadc1.Init.DMAContinuousRequests = ENABLE;
hadc1.Init.EOCSelection = ADC_EOC_SEQ_CONV;
if (HAL_ADC_Init(&hadc1) != HAL_OK) {
Error_Handler();
}
/**Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
*/
sConfig.Channel = ADC_CHANNEL_1;
sConfig.Rank = 1;
sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK) {
Error_Handler();
}
}
/* SPI1 init function */
static void MX_SPI1_Init(void)
{
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_MASTER;
hspi1.Init.Direction = SPI_DIRECTION_2LINES;
hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 10;
if (HAL_SPI_Init(&hspi1) != HAL_OK) {
Error_Handler();
}
}
/* TIM1 init function */
static void MX_TIM1_Init(void)
{
TIM_ClockConfigTypeDef sClockSourceConfig;
TIM_MasterConfigTypeDef sMasterConfig;
TIM_BreakDeadTimeConfigTypeDef sBreakDeadTimeConfig;
TIM_OC_InitTypeDef sConfigOC;
htim1.Instance = TIM1;
htim1.Init.Prescaler = 23;
htim1.Init.CounterMode = TIM_COUNTERMODE_UP;
htim1.Init.Period = 1;
htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim1.Init.RepetitionCounter = 0;
if (HAL_TIM_Base_Init(&htim1) != HAL_OK) {
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim1, &sClockSourceConfig) != HAL_OK) {
Error_Handler();
}
if (HAL_TIM_OC_Init(&htim1) != HAL_OK) {
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim1, &sMasterConfig) != HAL_OK) {
Error_Handler();
}
sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE;
sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF;
sBreakDeadTimeConfig.DeadTime = 0;
sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE;
sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_HIGH;
sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
if (HAL_TIMEx_ConfigBreakDeadTime(&htim1, &sBreakDeadTimeConfig) != HAL_OK) {
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_TOGGLE;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
sConfigOC.OCIdleState = TIM_OCIDLESTATE_SET;
sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
if (HAL_TIM_OC_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_1) != HAL_OK) {
Error_Handler();
}
HAL_TIM_MspPostInit(&htim1);
}
/* TIM2 init function */
static void MX_TIM2_Init(void)
{
TIM_ClockConfigTypeDef sClockSourceConfig;
TIM_MasterConfigTypeDef sMasterConfig;
htim2.Instance = TIM2;
htim2.Init.Prescaler = 47999;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 999;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
if (HAL_TIM_Base_Init(&htim2) != HAL_OK) {
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK) {
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK) {
Error_Handler();
}
}
/* TIM3 init function */
static void MX_TIM3_Init(void)
{
TIM_ClockConfigTypeDef sClockSourceConfig;
TIM_MasterConfigTypeDef sMasterConfig;
TIM_OC_InitTypeDef sConfigOC;
htim3.Instance = TIM3;
htim3.Init.Prescaler = 39999;
htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
htim3.Init.Period = 1;
htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
if (HAL_TIM_Base_Init(&htim3) != HAL_OK) {
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig) != HAL_OK) {
Error_Handler();
}
if (HAL_TIM_OC_Init(&htim3) != HAL_OK) {
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK) {
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_TOGGLE;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_OC_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_4) != HAL_OK) {
Error_Handler();
}
HAL_TIM_MspPostInit(&htim3);
}
/* TIM4 init function */
static void MX_TIM4_Init(void)
{
TIM_ClockConfigTypeDef sClockSourceConfig;
TIM_MasterConfigTypeDef sMasterConfig;
htim4.Instance = TIM4;
htim4.Init.Prescaler = 47999;
htim4.Init.CounterMode = TIM_COUNTERMODE_UP;
htim4.Init.Period = 4;
htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
if (HAL_TIM_Base_Init(&htim4) != HAL_OK) {
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim4, &sClockSourceConfig) != HAL_OK) {
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim4, &sMasterConfig) != HAL_OK) {
Error_Handler();
}
}
/* USART2 init function */
static void MX_USART2_UART_Init(void)
{
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart2) != HAL_OK) {
Error_Handler();
}
}
/**
* Enable DMA controller clock
*/
static void MX_DMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMA2_CLK_ENABLE();
/* DMA interrupt init */
/* DMA2_Stream0_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA2_Stream0_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA2_Stream0_IRQn);
}
/** Configure pins as
* Analog
* Input
* Output
* EVENT_OUT
* EXTI
PC3 ------> I2S2_SD
PA4 ------> I2S3_WS
PB10 ------> I2S2_CK
PC7 ------> I2S3_MCK
PA9 ------> USB_OTG_FS_VBUS
PA10 ------> USB_OTG_FS_ID
PA11 ------> USB_OTG_FS_DM
PA12 ------> USB_OTG_FS_DP
PC10 ------> I2S3_CK
PC12 ------> I2S3_SD
PB6 ------> I2C1_SCL
PB9 ------> I2C1_SDA
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOE_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(CS_I2C_SPI_GPIO_Port, CS_I2C_SPI_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(OTG_FS_PowerSwitchOn_GPIO_Port, OTG_FS_PowerSwitchOn_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOD, LD4_Pin|LD3_Pin|LD5_Pin|LD6_Pin
|GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3
|Audio_RST_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin : CS_I2C_SPI_Pin */
GPIO_InitStruct.Pin = CS_I2C_SPI_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(CS_I2C_SPI_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : OTG_FS_PowerSwitchOn_Pin */
GPIO_InitStruct.Pin = OTG_FS_PowerSwitchOn_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(OTG_FS_PowerSwitchOn_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : PDM_OUT_Pin */
GPIO_InitStruct.Pin = PDM_OUT_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF5_SPI2;
HAL_GPIO_Init(PDM_OUT_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : B1_Pin */
GPIO_InitStruct.Pin = B1_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_EVT_RISING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : PA4 */
GPIO_InitStruct.Pin = GPIO_PIN_4;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF6_SPI3;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pin : BOOT1_Pin */
GPIO_InitStruct.Pin = BOOT1_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(BOOT1_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : CLK_IN_Pin */
GPIO_InitStruct.Pin = CLK_IN_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF5_SPI2;
HAL_GPIO_Init(CLK_IN_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pins : LD4_Pin LD3_Pin LD5_Pin LD6_Pin
PD0 PD1 PD2 PD3
Audio_RST_Pin */
GPIO_InitStruct.Pin = LD4_Pin|LD3_Pin|LD5_Pin|LD6_Pin
|GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3
|Audio_RST_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
/*Configure GPIO pins : PC7 I2S3_SCK_Pin PC12 */
GPIO_InitStruct.Pin = GPIO_PIN_7|I2S3_SCK_Pin|GPIO_PIN_12;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF6_SPI3;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/*Configure GPIO pin : VBUS_FS_Pin */
GPIO_InitStruct.Pin = VBUS_FS_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(VBUS_FS_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pins : OTG_FS_ID_Pin OTG_FS_DM_Pin OTG_FS_DP_Pin */
GPIO_InitStruct.Pin = OTG_FS_ID_Pin|OTG_FS_DM_Pin|OTG_FS_DP_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pin : OTG_FS_OverCurrent_Pin */
GPIO_InitStruct.Pin = OTG_FS_OverCurrent_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(OTG_FS_OverCurrent_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pins : Audio_SCL_Pin Audio_SDA_Pin */
GPIO_InitStruct.Pin = Audio_SCL_Pin|Audio_SDA_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF4_I2C1;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin : MEMS_INT2_Pin */
GPIO_InitStruct.Pin = MEMS_INT2_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_EVT_RISING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(MEMS_INT2_GPIO_Port, &GPIO_InitStruct);
}
/**
* @brief This function is executed in case of error occurrence.
* @param None
* @retval None
*/
void Error_Handler(void)
{
while(1)
{
}
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
}
#endif
/**
* @}
*/
/**
* @}
*/
/*****************************END OF FILE****/
<file_sep>/**
******************************************************************************
* @file stm32f4xx_it.c
* @brief Interrupt Service Routines.
******************************************************************************
*
*
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of STMicroelectronics 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
#include "stm32f4xx.h"
#include "stm32f4xx_it.h"
typedef struct Bits_t
{
struct BitSet_t
{
uint8_t Bit0 :1;
uint8_t Bit1 :1;
uint8_t Bit2 :1;
uint8_t Bit3 :1;
uint8_t Bit4 :1;
uint8_t Bit5 :1;
uint8_t Bit6 :1;
uint8_t Bit7 :1;
uint8_t Bit8 :1;
uint8_t Bit9 :1;
uint8_t Bit10 :1;
uint8_t Bit11 :1;
uint8_t Bit12 :1;
uint8_t Bit13 :1;
uint8_t Bit14 :1;
uint8_t Bit15 :1;
} BitSet;
struct BitReset_t
{
uint8_t Bit0 :1;
uint8_t Bit1 :1;
uint8_t Bit2 :1;
uint8_t Bit3 :1;
uint8_t Bit4 :1;
uint8_t Bit5 :1;
uint8_t Bit6 :1;
uint8_t Bit7 :1;
uint8_t Bit8 :1;
uint8_t Bit9 :1;
uint8_t Bit10 :1;
uint8_t Bit11 :1;
uint8_t Bit12 :1;
uint8_t Bit13 :1;
uint8_t Bit14 :1;
uint8_t Bit15 :1;
} BitReset;
}Bits;
#define PortDBits (*((volatile Bits*)&(GPIOD->BSRR)))
/* External variables --------------------------------------------------------*/
extern DMA_HandleTypeDef hdma_adc1;
extern TIM_HandleTypeDef htim2;
extern TIM_HandleTypeDef htim3;
extern TIM_HandleTypeDef htim4;
extern volatile uint32_t sampleReceived;
extern volatile uint32_t spiSendReady;
volatile uint32_t ledToggle;
volatile uint32_t spiCnt;
/******************************************************************************/
/* Cortex-M4 Processor Interruption and Exception Handlers */
/******************************************************************************/
/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
HAL_IncTick();
HAL_SYSTICK_IRQHandler();
}
/******************************************************************************/
/* STM32F4xx Peripheral Interrupt Handlers */
/* Add here the Interrupt Handlers for the used peripherals. */
/* For the available peripheral interrupt handler names, */
/* please refer to the startup file (startup_stm32f4xx.s). */
/******************************************************************************/
/**
* @brief This function handles TIM2 global interrupt.
*/
void TIM2_IRQHandler(void)
{
HAL_TIM_IRQHandler(&htim2);
if (ledToggle) {
PortDBits.BitReset.Bit12 = 1;
ledToggle = 0;
}
else {
PortDBits.BitSet.Bit12 = 1;
ledToggle = 1;
}
}
/**
* @brief This function handles TIM3 global interrupt.
*/
void TIM3_IRQHandler(void)
{
HAL_TIM_IRQHandler(&htim3);
}
/**
* @brief This function handles TIM4 global interrupt.
*/
void TIM4_IRQHandler(void)
{
HAL_TIM_IRQHandler(&htim4);
if (ledToggle) {
PortDBits.BitReset.Bit14 = 1;
ledToggle = 0;
}
else {
PortDBits.BitSet.Bit14 = 1;
ledToggle = 1;
}
if (spiCnt == 19) {
spiSendReady = 1;
spiCnt = 0;
}
else {
spiCnt++;
}
}
/**
* @brief This function handles DMA2 stream0 global interrupt.
*/
void DMA2_Stream0_IRQHandler(void)
{
HAL_DMA_IRQHandler(&hdma_adc1);
sampleReceived = 1;
}
/*****************************END OF FILE****/
<file_sep>Для сборки проекта использовалась IDE: CooCox IDE v1.7.8
с компилятором gcc входящим в тулчейн "gcc-arm-none-eabi-4_7-2013q3" от Texas Instruments,
который автоматом подцепился к IDE
Вместо логов компиляции есть листинг сообщений, которые выводились в консоль в процессе сборки.
Он находится в ./Logs/building.log
Итоговые файлы программы (*.bin и *.hex) находятся в директории ./NAMITestJob/Debug/bin
Сам проект создан и собран для чипа STM32F407VG, а именно для отладочной платы STM32F4-Discovery.
Частота тактирования ядра 96МГц.
Шины периферии APB1 и APB2 тактируются сигналом 24МГц.
Все таймеры запущены от 48МГц.
В силу особенностей архитектуры, не удалось сделать структуру битовых полей,
при записи в которую 1 или 0 изменяло бы значение пина.
Атомарный доступ к пинам портов осуществляется через регистр BSRR соответсвующего порта.
Устройство этого 32-х битного регистра такого, что при записи единицы в младшие 16 разрядов,
на соответствующих пинах порта утанавливается высокий логический уровень. А при записи единицы
в старшие разряды, состояние пина сбрасывается в ноль.
Поэтому структуру атомарного доступа пришлось разбить на поля для установки в "лог. 1" и на
поля для установки в "лог. 0". Соотвественно вложенные структуры "BitSet" и "BitReset". | d6510b07d945e0178e2e0613d34fe0312ce2dfc1 | [
"C",
"Text"
] | 3 | C | saleric/demo | 8913d6e6b5c68806506ba91fd49b95181183b326 | 67d9aaf943e0c4766c6cd2ee31884d9b9695ba47 | |
refs/heads/master | <file_sep># MyProjects
Here are my students works, trey are lousy, don't watch it, please
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace calculator2
{
class RationalNumber
{
public double c = 0;
public double z = 0;
public RationalNumber(int c, int z)
{
this.c = c;
this.z = z;
}
//slozhenie
public static RationalNumber operator +(RationalNumber rat1, RationalNumber rat2)
{
RationalNumber result = new RationalNumber(1, 1);
result.c = (rat1.c * rat2.z + rat1.z * rat2.c);
result.z = rat1.z * rat2.z;
result.socr(result.c, result.z);
return result;
}
//sokrachenie
public void socr(double chis, double znam)
{
int nod = this.Nod(chis,znam);
this.c = c / nod;
this.z = z / nod;
}
//naimenshiy <NAME>
private int Nod(double chis, double znam)
{
while ((chis != 0) && (znam != 0))
{
if (chis > znam)
chis -= znam;
else
znam -= chis;
}
return Math.Max(Convert.ToInt32(chis), (Convert.ToInt32(znam)));
}
public static RationalNumber operator -(RationalNumber rat1, RationalNumber rat2)
{
RationalNumber result = new RationalNumber(1, 1);
result.c = (rat1.c * rat2.z - rat1.z * rat2.c);
result.z = rat1.z * rat2.z;
result.socr(result.c, result.z);
return result;
}
public static RationalNumber operator *(RationalNumber rat1, RationalNumber rat2)
{
RationalNumber result = new RationalNumber(1, 1);
result.c = (rat1.c * rat2.c);
result.z = rat1.z * rat2.z;
result.socr(result.c, result.z);
return result;
}
public static RationalNumber operator /(RationalNumber rat1, RationalNumber rat2)
{
RationalNumber result = new RationalNumber(1, 1);
result.c = (rat1.c / rat2.c);
result.z = rat1.z / rat2.z;
result.socr(result.c, result.z);
return result;
}
}
}
| f04e674ee4395b96f068098423b7275e9f9c1fe2 | [
"Markdown",
"C#"
] | 2 | Markdown | AastAve/MyProjects | fcb09774c9a2d3ce9b4e773dd6ee39b7f18da926 | efd5cfa87d33ce67a96db121228e542055e523e1 | |
refs/heads/master | <file_sep>import time;
# generate random no using time module
def generate_random(c, d):
ticks = int(time.time())
if (d <= 0):
return 0
c = d-1
c = str(c)
length = len(c)
rand=''
# get random value as per the length of value of max range, for ex b=100, then lenght is 2
while(length > 0):
ticks, r = divmod(ticks,10)
rand = rand+ str(r)
length = length - 1
return(int(rand))
#Provide the range, for ex a=0 and b=100
# here a and b is the range of random no
a = int(input('enter the initial range : '))
b = int(input('enter the final range : '))
lowerPercent = (b*27)//100 -1
lower_no = 0
higher_no = 0
low = False
high=False
lowList=[]
highList=[]
while(True):
rand = generate_random(a, b)
# get new value after a timelapse
time.sleep(1.25)
# if both the counter reaches their max value we will break the loop.
if((higher_no > (b - lowerPercent)) and ( lower_no > lowerPercent)):
break
# lower counter reaches its max value first then we will ignore the values lower than 50.
if(lower_no > lowerPercent):
low = True
rand = generate_random(a, b)
# higher counter reaches its max value first then we will ignore the values greater than 50.
if(higher_no > (b - lowerPercent)):
high = True
rand = generate_random(a, b)
# if we get higher value then increment higher_no counter else increment lower_no counter else continue
if(rand >= (b//2) and not high):
higher_no = higher_no + 1
highList.append(rand)
elif(not low):
lower_no = lower_no + 1
lowList.append(rand)
else:
continue
print(rand)
print("Total High Element Printed ", end='')
print(len(highList))
print(sorted(highList))
print("Total Low Element Printed ", end='')
print(len(lowList))
print(sorted(lowList))
<file_sep>I have generated random number using time.
time.time() provides us current time in miiliseconds.
So if we want to get range in [0 100), inclusive of 0 and exclusive of 100,
we can generate milliseconds and get last two digits of milliseconds everytime to generate a new random number.
So use a while loop to call generate_random(), then after calling
generate_random() function, use time.sleep() for generating some new value everytime after a little time lapse.
Now we want to get number greater than mid-value of range 73% of time, so set two counters, one for getting a number greater than mid-value and one for getting a value lower than mid-value.
Increment both the counters until they reach their max values.
For example in range of 0 to 100, 73 % of 100 is 73, so counter for greater values will be incremented until it reaches 73 and increment counter for lower values until it reaches 27.
Lets assume if lower number counter reaches its limit 27 first then we will ignore the values lower than 50, until, the higher counter reaches its limit 73 and we will only consider value which is greater then 73 and vice-versa.
Once both the counter reaches their max value we will break the loop.
| a7730d09ccaf4d7afef9b6ea199a7f5be2fa231a | [
"Python",
"Text"
] | 2 | Python | diljeet1994/random_no_generator | 1b72e36660c70d6ca0074b2e16798697d2269b71 | 67eb483651ec5a963832ba04b90bd7eab265e83b | |
refs/heads/master | <repo_name>antbrothers/LearningNode<file_sep>/Chapter01/02_load_albums.js
var http=require('http'),
fs=require('fs');
function load_albums_list(callback){
debugger;
fs.readdir(
"albums",
function(err,files){
debugger;
if(err){
callback(err,files);
return;
}
callback(null,files);
}
);
}
function handle_incoming_request(req,res){
console.log("INCOMING REQUEST: " + req.method + " " + req.url);
debugger;
load_albums_list(function(err,albums){
debugger;
if(err){
res.writeHead(500,{"Content-Type": "application/json"});
res.end(JSON.stringify(err) + "\n");
return;
}
var out = {error: null, data:{albums:albums}};
res.writeHead(200,{"Content-Type": "application/json"});
res.end(JSON.stringify(out)+ "\n");
});
}
debugger;
var s = http.createServer(handle_incoming_request);
s.listen(8181);<file_sep>/Chapter01/03_test_folder.js
var http = require('http'),
fs=require('fs');
debugger;
function load_album_list(callback){
debugger;
fs.readdir(
"./node_modules/express/node_modules",
function (err,files){
debugger;
if(err){
callback(err,files);
return;
}
var only_dirs=[];
for(var i=0;i < files.length;i++){
/*fs.stat(
"./node_modules/express/node_modules/" + files[i],
function (err, stats){
if(stats.isDirectory()){
only_dirs.push(files[i]);
}
}
);*/
only_dirs.push(files[i]);
}
callback(null,only_dirs);
}
)
}
function handle_incoming_request(req,res){
console.log("INCOMING REQUEST:" + req.method +" " + req.url);
debugger;
load_album_list(function(err,files){
debugger;
if(err){
res.writeHead(500,{"Content-Type":"application/json"});
res.end(JSON.stringify(err)+'\n');
return;
}
var out={err:null,data:{albums:files}};
res.writeHead(200,{"Content-Type":"application/json"});
res.end(JSON.stringify(out)+"\n")
});
}
var s = http.createServer(handle_incoming_request);
s.listen(9999);<file_sep>/Chapter01/04_test_folder.js
var http=require('http'),
fs=require('fs');
function load_album_list(callback){
fs.readdir(
'albums',
function(err,files){
if(err){
callback(err);
return;
}
var only_dirs=[];
(function iterator(index){
if(index == files.length){
callback(null,only_dirs);
return;
}
fs.stat("albums/"+files[index],
function(err,stats){
if(err){
callback(err);
return;
}
if(stats.isDirectory()){
only_dirs.push(files[index]);
}
iterator(index +1)
}
);
})(0);
}
)
}
function handle_incoming_request(req,res){
load_album_list(function(err,albums){
if(err){
res.writeHead(500, {"Content-Type": "application/json"});
res.end(JSON.stringify(err) + "\n");
return;
}
var out = { error: null,
data: { albums: albums }};
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(out) + "\n");
})
}
var s = http.createServer(handle_incoming_request);
s.listen(8080);<file_sep>/Chapter01/port.js
var net = require('net');
//检查端口是个被占用
function portIsOccupid(port){
var server=net.createServer().listen(port);
server.on('listening',function(){
server.close(); // 关闭服务
console.log("The port 【" + port + "】 is available.");
});
server.on('error',function(err){
if(err.code =="EADDRINUSE"){
console.log("The port【" + port + "】is occupied, please change other port.")
}
})
}
portIsOccupid(8585);
| 205315552dbe3a700a3180976288716ac52658b2 | [
"JavaScript"
] | 4 | JavaScript | antbrothers/LearningNode | 9acd33474309d57f07546ffff6adf82a4a9187d5 | e86e833367480f0edabf133b59a79cca560c8181 | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Venturi77CallHijacker.CallHijacker;
namespace Venturi77CallHijacker {
static class Worker {
static Worker() {
for(int i = 0; i<Utils.Configuration.Functions.Methods.Count();i++) {
methods.Add(i, Utils.Configuration.Functions.Methods[i]);
}
for (int i = 0; i < Utils.Configuration.Functions.MDToken.Count(); i++) {
mdtokens.Add(i, Utils.Configuration.Functions.MDToken[i]);
}
}
public static int LookupMethod(string name) {
var shit = methods.Where(q => q.Value.MethodName.ToUpper() == name.ToUpper()).ToArray();
if (shit.Count() > 0) {
return shit[0].Key;
}
return 69420;
}
public static int LookupMDTOken(int mdtok) {
var shit = mdtokens.Where(q => q.Value.MDTokenInt == mdtok).ToArray();
if(shit.Count() >0) {
return shit[0].Key;
}
return 69420;
}
private static readonly Dictionary<int, Method> methods = new Dictionary<int, Method>();
private static readonly Dictionary<int, MDToken> mdtokens = new Dictionary<int, MDToken>();
}
}
| 6bd7555aa9eeafdfa530051daa0ed1fa538ce4b4 | [
"C#"
] | 1 | C# | 2217936322/Venturi77CallHijacker | d3469cef21027e1c9a8aadc749a85635e6757620 | 0f5a56c8342807e47204f1478060d6fe535bde3f | |
refs/heads/master | <file_sep>require './email_reportable.rb'
require './employees.rb'
require './manager'
require './intern.rb'
employee1 = Actualize::Employee.new({:first_name => "Fred", :last_name => "Flintsone", :salary => 80000, :active => true})
employee2 = Actualize::Employee.new(first_name: "Barney", last_name: "Wruble", salary: 70000, active: false)
manager1 = Actualize::Manager.new({:first_name => "Homer", :last_name => "Simpson", :salary => 100000, :active => true, employees:[employee1, employee2]})
intern1 = Actualize::Intern.new({:first_name => "Bart", :last_name => "Simpson", :salary => 0, :active => "true"})
manager1.send_report
manager1.give_all_raises
p manager1
intern1.print_info
intern1.send_report
<file_sep>module EmailReportable
def send_report
p "sending reports"
end
end<file_sep>#array
# employee1 = ["Fred", "Flinstone", 80000, true]
# employee2 = ["Barney", "Wruble", 70000, false]
# p employee1[0] + " " + employee1[1] + " makes $" + employee1[2].to_s + " per year."
# p employee2[0] + " " + employee2[1] + " makes $" + employee2[2].to_s + " per year"
# p "#{employee2[0]} #{employee2[1]} makes $#{employee2[2]} per year."
#hash
employee1 = {
"first_name" => "Fred",
"last_name" => "Flinstone",
"salary" => 80000,
"active" => true
}
employee2 = {
:first_name => "Barney",
:last_name => "Wruble",
:salary => 70000,
:active => false
}
employee3 = {
first_name: "Betty",
last_name: "Wruble",
salary: 70000,
active: false
}
# p "#{employee1['first_name']} #{employee1['last_name']} makes $#{employee1['salary']} per year."
# p "#{employee2[:first_name]} #{employee2[:last_name]} makes $#{employee2[:salary]} per year."
# p "#{employee3[:first_name]} #{employee3[:last_name]} makes $#{employee3[:salary]} per year."
module Actualize
class Employee
attr_reader :first_name, :last_name, :salary
attr_writer :first_name, :active
def initialize(input_options)
@first_name = input_options[:first_name]
@last_name = input_options[:last_name]
@salary = input_options[:salary]
@active = input_options[:active]
end
# def active(input_active)
# @active = input_active
# end
def print_info
p "#{first_name} #{last_name} makes #{salary} per year."
end
def give_annual_raise
@salary = @salary * 1.05
end
end
end
# employee1 = Employee.new({:first_name => "Fred", :last_name => "Flintsone", :salary => 80000, :active => true})
# employee2 = Employee.new(first_name: "Barney", last_name: "Wruble", salary: 70000, active: false)
# class Employee
# attr_reader :first_name, :last_name, :salary
# attr_writer :first_name
# def initialize(input_options)
# @first_name = input_options[:first_name]
# @last_name = input_options[:last_name]
# @salary = input_options[:salary]
# @active = input_options[:active]
# end
# def print_info
# p "#{first_name} #{last_name} makes #{salary} per year."
# end
# def give_annual_raise
# @salary = @salary * 1.05
# end
# end
# employee1 = Employee.new({:first_name => "Fred", :last_name => "Flintsone", :salary => 80000, :active => true})
# employee2 = Employee.new(first_name: "Barney", last_name: "Wruble", salary: 70000, active: false)
# # p employee1.salary
# # p employee1.first_name
# # p employee1.last_name
# employee1.give_annual_raise
# employee2.give_annual_raise
# employee1.print_info
# employee2.print_info
# # employee1.first_name = 'Danny'
# # p employee1.first_name<file_sep>require './employees.rb'
require './email_reportable.rb'
module Actualize
class Manager < Employee
attr_reader :employees
# attr_writer :first_name
include EmailReportable
def initialize(input_options)
super
@employees = input_options[:employees]
end
# def send_report
# p "sending reports"
# end
def give_all_raises
p "giving all a raise"
@employees.each do |employee|
employee.give_annual_raise
end
end
def fire_all_employees
@employees.each do |employee|
employee.active = false
end
end
end
end
# manager1 = Manager.new({:first_name => "Homer", :last_name => "Simpson", :salary => 100000, :active => true, employees:[employee1, employee2]})
# p manager1.
# manager1.give_all_raises
# p manager1
# manager1.fire_all_employees
# p manager1
# class Employee
# attr_reader :first_name, :last_name, :salary
# attr_writer :first_name, :active
# def initialize(input_options)
# @first_name = input_options[:first_name]
# @last_name = input_options[:last_name]
# @salary = input_options[:salary]
# @active = input_options[:active]
# end
# def active(input_active)
# @active = input_active
# end
# def print_info
# p "#{first_name} #{last_name} makes #{salary} per year."
# end
# def give_annual_raise
# @salary = @salary * 1.05
# end
# end
# employee1 = Employee.new({:first_name => "Fred", :last_name => "Flintsone", :salary => 80000, :active => true})
# employee2 = Employee.new(first_name: "Barney", last_name: "Wruble", salary: 70000, active: false)
# p employee1.salary
# p employee1.first_name
# p employee1.last_name
# employee1.give_annual_raise
# employee2.give_annual_raise
# employee1.print_info
# employee2.print_info
# employee1.first_name = 'Danny'
# p employee1.first_name
# class Manager < Employee
# attr_reader :employees
# # attr_writer :first_name
# def initialize(input_options)
# super
# @employees = input_options[:employees]
# end
# def print_info
# p "#{first_name} #{last_name} makes #{salary} per year."
# end
# def give_annual_raise
# @salary = @salary * 1.05
# end
# def send_report
# p "sending reports"
# end
# def give_all_raise
# p "giving all a raise"
# @employees.each do |employee|
# employee.give_annual_raise
# end
# end
# def fire_all_employees
# @employees.each do |employee|
# employee.active = false
# end
# end
# end
# manager1 = Manager.new({:first_name => "Homer", :last_name => "Simpson", :salary => 100000, :active => true, employees:[employee1, employee2]})
# # p manager1
# manager1.give_all_raise
# p manager1
# manager1.fire_all_employees
# p manager1
| 2e69aec7fa7d416025dce3b3f651060f06a2282a | [
"Ruby"
] | 4 | Ruby | BDCoop1972/factory | d8fa9cd52753088d048d6622e0b1f4176df9c908 | e717fece573d522e666c3366689fffe217270a13 | |
refs/heads/master | <file_sep># android-device-resolutions
This is an android project. When run, apk will print android device resource folder name by resolution. You can paste device specific settings there. For example if resolution comes as sw540dp-xhdpi than your device specific values folder can be "values-sw540dp-xhdpi"
<file_sep>include ':app'
rootProject.name='TestResolution'
<file_sep>package com.example.testresolution
import android.content.res.Configuration
import android.os.Bundle
import android.util.DisplayMetrics
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
val density = resources.displayMetrics.density
val config: Configuration = resources.configuration
val densityDPI = config.smallestScreenWidthDp
test_view.text = getString(R.string.format, densityDPI.toString(), getDensity(density))
}
private fun getDensity(density: Float): String {
if(density <= 0.75) {
return "ldpi"
} else if(density > 0.75 && density <= 1.0) {
return "mdpi"
} else if(density > 1.0 && density <= 1.5) {
return "hdpi"
} else if(density > 1.5 && density <= 2.0) {
return "xhdpi"
} else if(density > 2.0 && density <= 3.0) {
return "xxhdpi"
} else if(density > 3.0 && density <= 4.0) {
return "xxxhdpi"
} else {
return density.toString()
}
}
}
| 379f8b790805cd4aa0d84b7f4dbd59acd226c222 | [
"Markdown",
"Kotlin",
"Gradle"
] | 3 | Markdown | colossusmk2/android-device-resolutions | 0a2ee83255638387af5a0198bf5a1f377e655427 | dc2e2510e294c576106082e5294725ffd7268bd7 | |
refs/heads/master | <repo_name>francikjm/project2<file_sep>/testalgos.py
# This file will test all four functions using the same test cases
#import 2nd algorithm
#import 3rd algorithm
# import Juans's 2nd algorithm
from algo2 import changegreedy as getchange2
def main():
#Test Cases
testOne = [1,2,4,8]
testTwo = [1,3,7,12]
testThree = [1,3,7,12]
#3. Suppose
# V1 = [1, 2, 6, 12, 24, 48, 60],
# V2 = [1, 5, 10, 25, 50] and
# V3 = [1, 6, 13, 37, 150],
# for each integer value of A in [1, 2, 3, …, 50]
# determine the number of coins that changeslow.
# changegreedy and changedp requires for each denomination set.
V1 = [1, 2, 6, 12, 24, 48, 60]
V2 = [1, 5, 10, 25, 50]
V3 = [1, 6, 13, 37, 150]
questhree_Testcase = []
questhree_Testcase.append(V1)
questhree_Testcase.append(V2)
questhree_Testcase.append(V3)
testCase = []
testCase.append(testOne)
testCase.append(testTwo)
testCase.append(testThree)
coinAmount = [15, 29, 31]
for x in range(1, 2):
algoID = x
if (algoID == 1):
getchange = getchange2
elif (algoID == 2):
print("algoID",algoID)
getchange = getchange2
else:
print(algoID)
# Loop through test cases
for testinput in range(0, len(testCase)):
cArray, m = getchange(testCase[testinput], coinAmount[testinput])
print("Array", cArray)
print("m", m)
# Loop for each integer value of A in [1, 2, 3, …, 50] in test cases V1, V2 and V3
for amount in range(1, 51):
#Values of V1
cArray, m = getchange(questhree_Testcase[0], amount)
print("AMOUNT of ", amount, "|" "ARRAY = ", cArray)
print("Number of Coins = ", m)
# Values of V2
cArray, m = getchange(questhree_Testcase[1], amount)
print("AMOUNT of ", amount, "|" "ARRAY = ", cArray)
print("Number of Coins = ", m)
# Values of V3
cArray, m = getchange(questhree_Testcase[2], amount)
print("AMOUNT of ", amount, "|" "ARRAY = ", cArray)
print("Number of Coins = ", m)
# For each integer value of A in [2000, 2001, 2002, …, 2200]
# determine the number of coins that
# changegreedy and changedp requires for each denomination set
for amount in range(2000, 2200):
#Values of V1
cArray, m = getchange(questhree_Testcase[0], amount)
print("AMOUNT of ", amount, "|" "ARRAY = ", cArray)
print("Number of Coins = ", m)
# Values of V2
cArray, m = getchange(questhree_Testcase[1], amount)
print("AMOUNT of ", amount, "|" "ARRAY = ", cArray)
print("Number of Coins = ", m)
# Values of V3
cArray, m = getchange(questhree_Testcase[2], amount)
print("AMOUNT of ", amount, "|" "ARRAY = ", cArray)
print("Number of Coins = ", m)
if __name__ == "__main__":
main()
<file_sep>/README.md
# project2
coin change algorithm
| 93febd150e058d545884a09bd08121e786074558 | [
"Markdown",
"Python"
] | 2 | Python | francikjm/project2 | e9b654b411b5e005bee19b3153bd50cc81e920ee | 2250e28372c9146adfef5769c89bb17bc7cdf362 | |
refs/heads/master | <file_sep>Framework7, Dom7, and Template7 type definitions have been adopted into their respective projects! The Framework7-React may still need to live on for full type expression ... to be updated...
<file_sep>declare module "framework7-react" {
import Dom7, { Dom7Static } from 'Dom7'
import Template7 from 'Template7'
import Framework7, { Framework7Plugin, Device, Request, Utils,
Router, Route, CssSelector, View as F7View } from 'framework7'
export const Framework7React : Framework7Plugin;
export default Framework7React;
export interface F7ReactComponentExtensions {
$f7ready: (f7 : Framework7) => void
$f7 : Framework7
$$ : Dom7Static
$Dom7 : Dom7Static
$device : Device
$request : Request
$utils : Utils
$theme : {
ios: boolean,
material: boolean
}
$f7router : Router.Router
$f7route : Route
}
// Not sure
export interface F7Props<Slots = string> {
slot?: string
}
export interface F7AppProps extends F7Props {
params?: { [ routeParameter : string ] : number | string | undefined }
routes?: Route[]
id?: string
}
export class App extends React.Component<F7AppProps, {}> {}
export const F7App : typeof App;
namespace AccordionContent {
export interface Props extends F7Props {
/** Makes accordion item opened */
opened?: boolean
/** Event will be triggered when accordion content starts its opening animation */
onAccordionOpen?: (el : HTMLElement | CssSelector) => void
/** Event will be triggered after accordion content completes its opening animation */
onAccordionOpened?: (el : HTMLElement | CssSelector) => void
/** Event will be triggered when accordion content starts its closing animation */
onAccordionClose?: (el : HTMLElement | CssSelector) => void
/** Event will be triggered after accordion content completes its closing animation */
onAccordionClosed?: (el : HTMLElement | CssSelector) => void
}
}
export class AccordionContent extends React.Component<AccordionContent.Props, {}> {}
export const F7AccordionContent : typeof AccordionContent;
namespace AccordionItem {
export interface Props extends F7Props {
}
}
export class AccordionItem extends React.Component<AccordionItem.Props, {}> {}
export const F7AccordionItem : typeof AccordionItem;
namespace AccordionToggle {
export interface Props extends F7Props {
}
}
export class AccordionToggle extends React.Component<AccordionToggle.Props, {}> {}
export const F7AccordionToggle : typeof AccordionToggle;
namespace Accordion {
export interface Props extends F7Props {
}
}
export class Accordion extends React.Component<Accordion.Props, {}> {}
export const F7Accordion : typeof Accordion;
namespace ActionsButton {
export interface Props extends F7Props {
bold?: boolean
close?: boolean
}
}
export class ActionsButton extends React.Component<ActionsButton.Props, {}> {}
export const F7ActionsButton : typeof ActionsButton;
namespace ActionsGroup {
export interface Props extends F7Props {
}
}
export class ActionsGroup extends React.Component<ActionsGroup.Props, {}> {}
export const F7ActionsGroup : typeof ActionsGroup;
namespace ActionsLabel {
export interface Props extends F7Props {
bold?: boolean
}
}
export class ActionsLabel extends React.Component<ActionsLabel.Props, {}> {}
export const F7ActionsLabel : typeof ActionsLabel;
namespace Actions {
export interface Props extends F7Props {
opened?: boolean
grid?: boolean
convertToPopover?: boolean
forceToPopover?: boolean
target?: HTMLElement | CssSelector
/** Event will be triggered when accordion content starts its opening animation */
onActionsOpen?: (el : HTMLElement | CssSelector) => void
/** Event will be triggered after accordion content completes its opening animation */
onActionsOpened?: (el : HTMLElement | CssSelector) => void
/** Event will be triggered when accordion content starts its closing animation */
onActionsClose?: (el : HTMLElement | CssSelector) => void
/** Event will be triggered after accordion content completes its closing animation */
onActionsClosed?: (el : HTMLElement | CssSelector) => void
}
}
export class Actions extends React.Component<Actions.Props, {}> {
open(animate: true) : void
close(animate: true) : void
}
export const F7Actions : typeof Actions;
namespace Badge {
export interface Props extends F7Props {
color?: string
}
}
export class Badge extends React.Component<Badge.Props, {}> {}
export const F7Badge : typeof Badge;
namespace BlockFooter {
export interface Props extends F7Props {
}
}
export class BlockFooter extends React.Component<BlockFooter.Props, {}> {}
export const F7BlockFooter : typeof BlockFooter;
namespace BlockHeader {
export interface Props extends F7Props {
}
}
export class BlockHeader extends React.Component<BlockHeader.Props, {}> {}
export const F7BlockHeader : typeof BlockHeader;
namespace BlockTitle {
export interface Props extends F7Props {
}
}
export class BlockTitle extends React.Component<BlockTitle.Props, {}> {}
export const F7BlockTitle : typeof BlockTitle;
namespace Block {
export interface Props extends F7Props {
/** Makes block inset. */
inset?: boolean
/** Makes block inset on tablets, but not on phones. */
tabletInset?: boolean
/** Adds extra highlighting and padding block content. */
strong?: boolean
/** Makes block wrapper for accordion items. */
accordionList?: boolean
/** Adds additional "tabs" class to make the block tabs wrapper. */
tabs?: boolean
/** Adds additional "tab" class when block should be used as a Tab. */
tab?: boolean
/** Adds additional "tab-active" class when block used as a Tab and makes it active tab. */
tabActive?: boolean
/** Removes outer hairlines. */
noHairlines?: boolean
/** Removes outer hairlines for MD theme. */
noHairlinesMd?: boolean
/** Removes outer hairlines for iOS theme. */
noHairlinesIos?: boolean
}
}
export class Block extends React.Component<Block.Props, {}> {}
export const F7Block : typeof Block;
namespace Button {
export interface Props extends F7Props {
/** Enables tab link and specify CSS selector of the target tab (if specified as a string). */
tabLink?: boolean | CssSelector
/** Makes this tab link active. (default false) */
tabLinkActive?: boolean
/** Makes this button active state when used in Segmented. Must be used instead of tab-link-active. (default false) */
active?: boolean
/** Button text label. */
text: string
/** Disables fast click. */
noFastClick: boolean
/** Button tooltip text to show on button hover/press. */
tooltip?: string
/** Makes button round. (default false) */
round?: boolean
/** Makes button round for iOS theme only. (default false) */
roundIos?: boolean
/** Makes button round for MD theme only. (default false) */
roundMd?: boolean
/** Makes big button. (default false) */
big?: boolean
/** Makes big button for iOS theme only. (default false) */
bigIos?: boolean
/** Makes big button for MD theme only. (default false) */
bigMd?: boolean
/** Makes small button. (default false) */
small?: boolean
/** Makes small button for iOS theme only. (default false) */
smallIos?: boolean
/** Makes small button for MD theme only. (default false) */
smallMd?: boolean
/** Makes button filled color. (default false) */
fill?: boolean
/** Makes button filled color for iOS theme only. (default false) */
fillIos?: boolean
/** Makes button filled color for MD theme only. (default false) */
fillMd?: boolean
/** Makes button raised. Affects MD theme only. (default false) */
raised?: boolean
/** Makes button outline. Affects MD theme only. (default false) */
outline?: boolean
// <Button> icon related properties
/** Icon size in px. */
iconSize: string | number
/** Icon color. One of the default colors. */
iconColor: string
/** Custom icon class. */
icon: string
/** Name of F7 Icons font icon. */
iconF7: string
/** Name of Material Icons font icon. */
iconMaterial: string
/** Name of Font Awesome font icon. */
iconFa: string
/** Name of Ionicons font icon. */
iconIon: string
/** Icon to be used in case of iOS theme is used. Consists of icon family and icon name divided by colon, e.g. f7:home or ion:home. */
iconIos: string
/** Icon to be used in case of MD theme is used. Consists of icon family and icon name divided by colon, e.g. material:home or fa:home. */
iconMd: string
// <Button> navigation/router related properties
/** URL of the page to load. In case of boolean href="false" it won't add href tag. (default #) */
href?: string | false
/** Value of link target attribute, e.g. _blank, _self, etc.. */
target: string
/** CSS selector of the View to load the page. */
view: string
/** Enable to bypass Framework7's link click handler. */
external: boolean
/** Enables back navigation link. */
back: boolean
/** Force page to load and ignore previous page in history (use together with back prop). */
force: boolean
/** Reloads new page instead of the currently active one. */
reloadCurrent: boolean
/** Replace the previous page in history with the new one from route. */
reloadPrevious: boolean
/** Load new page and remove all previous pages from history and DOM. */
reloadAll: boolean
/** Disables pages animation. */
animate: boolean
/** Ignores caching. */
ignoreCache: boolean
/** Name of the page to load. */
pageName: string
/** Routable Tab id. */
routeTabId: string
// <Button> action related properties
/** Defines panel to open. Can be left or right. */
panelOpen: 'left' | 'right' | boolean
/** Closes panel on click. */
panelClose: boolean
/** CSS selector of the action sheet to open on click. */
actionsOpen: CssSelector | boolean
/** CSS selector of the action sheet to close on click. Or boolean property to close currently opened action sheet. */
actionsClose: CssSelector | boolean
/** CSS selector of the popup to open on click. */
popupOpen: CssSelector | boolean
/** CSS selector of the popup to close on click. Or boolean property to close currently opened popup. */
popupClose: CssSelector | boolean
/** CSS selector of the popover to open on click. */
popoverOpen: CssSelector | boolean
/** CSS selector of the popover to close on click. Or boolean property to close currently opened popover. */
popoverClose: CssSelector | boolean
/** CSS selector of the sheet modal to open on click. */
sheetOpen: CssSelector | boolean
/** CSS selector of the sheet modal to close on click. Or boolean property to close currently opened sheet modal. */
sheetClose: CssSelector | boolean
/** CSS selector of the login screen to open on click. */
loginScreenOpen: CssSelector | boolean
/** CSS selector of the login screen to close on click. Or boolean property to close currently opened login screen. */
loginScreenClose: CssSelector | boolean
/** CSS selector of the Sortable list to open on click. */
sortableEnable: CssSelector | boolean
/** CSS selector of the Sortable list to close on click. Or boolean property to close currently opened Sortable list. */
sortableDisable: CssSelector | boolean
/** CSS selector of the Sortable list to toggle on click. Or boolean property to toggle currently opened/closed Sortable list. */
sortableToggle: CssSelector | boolean
/** CSS selector of the Expandable Searchbar to be enabled on click. Or boolean property to enable the first found Searchbar. */
searchbarEnable: CssSelector | boolean
/** CSS selector of the Expandable Searchbar to be disabled on click. Or boolean property to disable the first found Searchbar. */
searchbarDisable: CssSelector | boolean
/** CSS selector of the Expandable Searchbar to toggle on click. Or boolean property to toggle the first found Searchbar. */
searchbarToggle: CssSelector | boolean
/** CSS selector of the Expandable Searchbar to clear on click. Or boolean property to clear the first found Searchbar. */
searchbarClear: CssSelector | boolean
/** Event will be triggered after click on a button */
onClick : () => void
}
}
export class Button extends React.Component<Button.Props, {}> {}
export const F7Button : typeof Button;
namespace CardContent {
export interface Props extends F7Props {
/** Adds additional inner padding. (default true) */
padding?: boolean
}
}
export class CardContent extends React.Component<CardContent.Props, {}> {}
export const F7CardContent : typeof CardContent;
namespace CardFooter {
export interface Props extends F7Props {
}
}
export class CardFooter extends React.Component<CardFooter.Props, {}> {}
export const F7CardFooter : typeof CardFooter;
namespace CardHeader {
export interface Props extends F7Props {
}
}
export class CardHeader extends React.Component<CardHeader.Props, {}> {}
export const F7CardHeader : typeof CardHeader;
namespace Card {
export interface Props extends F7Props {
/** Card header content. */
title?: string
/** Card content. */
content?: string
/** Card footer content. */
footer?: string
/** Adds additional inner padding on card content. (default true) */
padding?: boolean
/** Makes Card outline. (default false) */
outline?: boolean
}
}
export class Card extends React.Component<Card.Props, {}> {}
export const F7Card : typeof Card;
namespace Checkbox {
export interface Props extends F7Props {
/** Defines whether the checkbox input is checked or not. */
checked: boolean
/** Defines whether the checkbox input is checked or not, for the case if it is uncontrolled component. */
defaultChecked: boolean
/** Checkbox input name. */
name: string | number
/** Checkbox input value. */
value: string | number | boolean
/** Defines whether the checkbox input is disabled. */
disabled: boolean
/** Defines whether the checkbox input is readonly. */
readonly: boolean
/** Event will be triggered when checkbox state changed */
onChange: () => void
}
}
export class Checkbox extends React.Component<Checkbox.Props, {}> {}
export const F7Checkbox : typeof Checkbox;
namespace Chip {
export interface Props extends F7Props {
/** Chip label text. */
text: string
/** Text content of chip media. */
media: string
/** Chip media element background color. One of the default colors. */
mediaBgColor: string
/** Chip media element text color. One of the default colors. */
mediaTextColor: string
/** Defines whether the Chip has additional "delete" button or not. (default false) */
deleteable?: boolean
/** Makes Card outline. (default false) */
outline?: boolean
/** Event will be triggered on Chip click */
onClick: () => void
/** Event will be triggered on Chip delete button click */
onDelete: () => void
}
}
export class Chip extends React.Component<Chip.Props, {}> {}
export const F7Chip : typeof Chip;
namespace Col {
export interface Props extends F7Props {
/** Column width. Check available Column Sizes. (default auto) */
width?: number| string
/** Column width for large screen tablets (when width >= 768px). */
tabletWidth: number | string
/** Column width for larger screen tablets (when width >= 1025px). */
desktopWidth: number | string
}
}
export class Col extends React.Component<Col.Props, {}> {}
export const F7Col : typeof Col;
namespace FabButton {
export interface Props extends F7Props {
/** When enabled then clicking on this button will close the FAB. (default false) */
fabClose?: boolean
/** Value of link target attribute, e.g. _blank, _self, etc.. */
target: string
/** Button text label. */
label: string
/** Button tooltip text to show on button hover/press. */
tooltip: string
/** Event will be triggered after click on FAB Speed Dial button */
onClick: () => void
}
}
export class FabButton extends React.Component<FabButton.Props, {}> {}
export const F7FabButton : typeof FabButton;
namespace FabButtons {
export interface Props extends F7Props {
/** Speed dial buttons position. (default top) */
position?: 'top' | 'right' | 'bottom' | 'left' | 'center'
}
}
export class FabButtons extends React.Component<FabButtons.Props, {}> {}
export const F7FabButtons : typeof FabButtons;
namespace Fab {
export interface Props extends F7Props {
/** URL of the page to load (if set). Will set href attribute on main FAB link. In case of boolean href="false" it won't add href tag. */
href: string | boolean
/** Value of link target attribute, e.g. _blank, _self, etc.. */
target: string
/** FAB position. Can be one of the following:. (default 'right-bottom') */
position?: 'right-bottom' | 'center-bottom' | 'left-bottom' | 'right-center' | 'center-center' | 'left-center' | 'right-top' | 'center-top' | 'left-top'
/** String CSS selector of the FAB morph target. */
morphTo: string
/** FAB Button text. If specified, then it will be displayed as Extended Fab with text label. */
text: string
/** FAB tooltip text to show on button hover/press. */
tooltip: string
/** event will be triggered after click on FAB */
onClick: () => void
}
}
export class Fab extends React.Component<Fab.Props, {}> {}
export const F7Fab : typeof Fab;
namespace Gauge {
export interface Props extends F7Props {
/** Gauge element ID attribute. */
id: string
/** Gauge type. Can be circle or semicircle. (default circle) */
type?: string
/** Gauge value/percentage. Must be a number between 0 and 1. (default 0) */
value?: number
/** Generated SVG image size (in px). (default 200) */
size?: number
/** Gauge background color. Can be any valid color string, e.g. #ff00ff, rgb(0,0,255), etc.. (default transparent) */
bgColor?: string
/** Main border/stroke background color. (default #eeeeee) */
borderBgColor?: string
/** Main border/stroke color. (default #000000) */
borderColor?: string
/** Main border/stroke width. (default 10) */
borderWidth?: string
/** Gauge value text (large text in the center of gauge). (default null) */
valueText?: string
/** Value text color. (default #000000) */
valueTextColor?: string
/** Value text font size. (default 31) */
valueFontSize?: string
/** Value text font weight. (default 500) */
valueFontWeight?: string
/** Gauge additional label text. (default null) */
labelText?: string
/** Label text color. (default #888888) */
labelTextColor?: string
/** Label text font size. (default 14) */
labelFontSize?: string
/** Label text font weight. (default 400) */
labelFontWeight?: string
}
}
export class Gauge extends React.Component<Gauge.Props, {}> {}
export const F7Gauge : typeof Gauge;
namespace Icon {
export interface Props extends F7Props {
/** Icon size in px. */
size?: number | string
/** Custom icon class. */
icon?: string
/** Name of F7 Icons font icon. */
f7?: string
/** Name of Material Icons font icon. */
material?: string
/** Name of Font Awesome font icon. */
fa?: string
/** Name of Ionicons font icon. */
ion?: string
/** Icon to be used in case of iOS theme is used. Consists of icon family and icon name divided by colon, e.g. f7:home or ion:home. */
ios?: string
/** Icon to be used in case of Material theme is used. Consists of icon family and icon name divided by colon, e.g. material:home or fa:home. */
md?: string
/** Icon tooltip text to show on icon hover/press. */
tooltip?: string
}
}
export class Icon extends React.Component<Icon.Props, {}> {}
export const F7Icon : typeof Icon;
namespace Input {
export interface Props extends F7Props {
/** Defines should the input be wraped with "item-input-wrap" element or not. Must be disabled when using outside of List View. (default true) */
wrap?: boolean
/** Input type. All default HTML5 input type, and few special ones:. */
type: string
/** Makes textarea resizable. (default false) */
resizable?: boolean
/** Value if input's "style" attribute, in case you need to pass extra styles. */
inputStyle: string
/** Adds input clear button that will clear input value on click. (default false) */
clearButton?: boolean
/** When enabled then input value will be validated on change based on passed "pattern" or based on input type. If you use custom validation and need more control on where to show/hide error message, then it is better to disable validation and use error-message together with error-message-force props.. (default false) */
validate?: boolean
/** Custom error message to show when input value is invalid. */
errorMessage: string
/** Force error message to force. Useful in case you use custom validation and want to show/hide error message when you need it. (default false) */
errorMessageForce?: boolean
/** Custom additional text with information about input. */
info: string
/** Input name. */
name: string
/** Input placeholder. */
placeholder: string
/** Wrapping element ID attribute. */
id: string
/** Input element ID attribute. */
inputId: string
/** Input value. */
value: string | number
/** Input value, in case of uncontrolled component. */
defaultValue: string | number
/** Value of input's native "size" attribute. */
size: string | number
/** Value of input's native "pattern" attribute. */
pattern: string
/** Value of input's native "accept" attribute. */
accept: string | number
/** Value of input's native "autocomplete" attribute. */
autocomplete: string
/** Value of input's native "autofocus" attribute. (default false) */
autofocus?: boolean
/** Value of input's native "autosave" attribute. */
autosave: string
/** Marks input as checked. (default false) */
checked?: boolean
/** Marks input as disabled. (default false) */
disabled?: boolean
/** Value of input's native "max" attribute. */
max: string | number
/** Value of input's native "min" attribute. */
min: string | number
/** Value of input's native "step" attribute. */
step: string | number
/** Value of input's native "maxlength" attribute. */
maxlength: string | number
/** Value of input's native "minlength" attribute. */
minlength: string | number
/** Value of input's native "multiple" attribute. (default false) */
multiple?: boolean
/** Marks input as readonly. (default false) */
readonly?: boolean
/** Marks input as required. (default false) */
required?: boolean
/** Value of input's native "tabindex" attribute. */
tabindex: string | number
/** Allows to ignore input value to be stored when using with Form Storage. (default false) */
noStoreData?: boolean
/** Same as previous. (default false) */
ignoreStoreData?: boolean
/** Fired when user focused to input. */
onFocus : (event : Event) => void
/** Fired when user lost focus from input. */
onBlur : (event : Event) => void
/** Fired immediately when input value changed. Note: Input event triggers after beforeinput, keypress, keyup, keydown events. */
onInput : (event : Event) => void
/** Fired when blur if value changed. */
onChange : (event : Event) => void
/** Fired when input clear button clicked */
onInputClear : (event : Event) => void
/** Fired if resizable textarea resized. event.detail will contain object with the initialHeight, currentHeight and scrollHeight properties */
onTextareaResize : (event : Event) => void
/** Fired when input value becomes empty */
onInputEmpty : (event : Event) => void
/** Fired when input value becomes not empty */
onInputNotempty : (event : Event) => void
}
}
export class Input extends React.Component<Input.Props, {}> {}
export const F7Input : typeof Input;
namespace Label {
export interface Props extends F7Props {
/** Enables floating label (affects MD theme only). (default false) */
floating?: boolean
/** Makes label inline. (default false) */
inline?: boolean
}
}
export class Label extends React.Component<Label.Props, {}> {}
export const F7Label : typeof Label;
namespace Link {
export interface Props extends F7Props {
/** Removes "link" class. */
noLinkClass: boolean
/** Enables tab link and specify CSS selector of the target tab (if specified as a string). */
tabLink: string | boolean
/** Makes this tab link active. */
tabLinkActive: boolean
/** Link text. */
text: string
/** Disables fast click. */
noFastClick: boolean
/** Badge count. */
badge: string | number
/** Badge color. One of the default colors. */
badgeColor: string
/** Enable when used in navbar/toolbar with icon only inside. */
iconOnly: boolean
/** Link tooltip text to show on link hover/press. */
tooltip: string
// <Link> Smart Select related properties
/** Enables Smart Select behavior. (default false) */
smartSelect?: boolean
/** Object with Smart Select Parameters. */
smartSelectParams: object
// <Link> icon related properties
/** Icon size in px. */
iconSize: string | number
/** Icon color. One of the default colors. */
iconColor: string
/** Custom icon class. */
icon: string
/** Name of F7 Icons font icon. */
iconF7: string
/** Name of Material Icons font icon. */
iconMaterial: string
/** Name of Font Awesome font icon. */
iconFa: string
/** Name of Ionicons font icon. */
iconIon: string
/** Icon to be used in case of iOS theme is used. Consists of icon family and icon name divided by colon, e.g. f7:home or ion:home. */
iconIos: string
/** Icon to be used in case of MD theme is used. Consists of icon family and icon name divided by colon, e.g. material:home or fa:home. */
iconMd: string
/** Adds badge to the icon (intended to be used in Tabbar's icons). */
iconBadge: string | number
//<Link> navigation/router related properties
/** URL of the page to load. In case of boolean href="false" it won't add href tag. (default #) */
href?: string | boolean
/** Value of link target attribute, e.g. _blank, _self, etc.. */
target: string
/** CSS selector of the View to load the page. */
view: string
/** Enable to bypass Framework7's link click handler. */
external: boolean
/** Enables back navigation link. */
back: boolean
/** Force page to load and ignore previous page in history (use together with back prop). */
force: boolean
/** Reloads new page instead of the currently active one. */
reloadCurrent: boolean
/** Replace the previous page in history with the new one from route. */
reloadPrevious: boolean
/** Load new page and remove all previous pages from history and DOM. */
reloadAll: boolean
/** Disables pages animation. */
animate: boolean
/** Ignores caching. */
ignoreCache: boolean
/** Name of the page to load. */
pageName: string
/** Routable Tab id. */
routeTabId: string
// <Link> action related properties
/** Defines panel to open. Can be left or right. */
panelOpen: string | boolean
/** Closes panel on click. */
panelClose: boolean
/** CSS selector of the action sheet to open on click. */
actionsOpen: string | boolean
/** CSS selector of the action sheet to close on click. Or boolean property to close currently opened action sheet. */
actionsClose: string | boolean
/** CSS selector of the popup to open on click. */
popupOpen: string | boolean
/** CSS selector of the popup to close on click. Or boolean property to close currently opened popup. */
popupClose: string | boolean
/** CSS selector of the popover to open on click. */
popoverOpen: string | boolean
/** CSS selector of the popover to close on click. Or boolean property to close currently opened popover. */
popoverClose: string | boolean
/** CSS selector of the sheet modal to open on click. */
sheetOpen: string | boolean
/** CSS selector of the sheet modal to close on click. Or boolean property to close currently opened sheet modal. */
sheetClose: string | boolean
/** CSS selector of the login screen to open on click. */
loginScreenOpen: string | boolean
/** CSS selector of the login screen to close on click. Or boolean property to close currently opened login screen. */
loginScreenClose: string | boolean
/** CSS selector of the Sortable list to open on click. */
sortableEnable: string | boolean
/** CSS selector of the Sortable list to close on click. Or boolean property to close currently opened Sortable list. */
sortableDisable: string | boolean
/** CSS selector of the Sortable list to toggle on click. Or boolean property to toggle currently opened/closed Sortable list. */
sortableToggle: string | boolean
/** CSS selector of the Expandable Searchbar to be enabled on click. Or boolean property to enable the first found Searchbar. */
searchbarEnable: string | boolean
/** CSS selector of the Expandable Searchbar to be disabled on click. Or boolean property to disable the first found Searchbar. */
searchbarDisable: string | boolean
/** CSS selector of the Expandable Searchbar to toggle on click. Or boolean property to toggle the first found Searchbar. */
searchbarToggle: string | boolean
/** CSS selector of the Expandable Searchbar to clear on click. Or boolean property to clear the first found Searchbar. */
searchbarClear: string | boolean
/** Event will be triggered after click on a link */
onClick: () => void
}
}
export class Link extends React.Component<Link.Props, {}> {}
export const F7Link : typeof Link;
namespace ListButton {
export interface Props extends F7Props {
/** Button inner text. */
title: string
/** Button inner text, same as title. */
text: string
/** Enables tab link and specify CSS selector of the target tab (if specified as a string). */
tabLink: string | boolean
/** Disables fast click. */
noFastClick: boolean
// <ListButton> navigation/router related properties
/** URL of the page to load. In case of boolean href="false" it won't add href tag. (default #) */
href?: string | boolean
/** Value of link target attribute, e.g. _blank, _self, etc.. */
target: string
/** CSS selector of the View to load the page. */
view: string
/** Enable to bypass Framework7's link click handler. */
external: boolean
/** Enables back navigation link. */
back: boolean
/** Force page to load and ignore previous page in history (use together with back prop). */
force: boolean
/** Reloads new page instead of the currently active one. */
reloadCurrent: boolean
/** Replace the previous page in history with the new one from route. */
reloadPrevious: boolean
/** Load new page and remove all previous pages from history and DOM. */
reloadAll: boolean
/** Disables pages animation. */
animate: boolean
/** Ignores caching. */
ignoreCache: boolean
/** Name of the page to load. */
pageName: string
/** Routable Tab id. */
routeTabId: string
// <ListButton> action related properties
/** Defines panel to open. Can be left or right. */
panelOpen: CssSelector | boolean
/** Closes panel on click. */
panelClose: boolean
/** CSS selector of the action sheet to open on click. */
actionsOpen: CssSelector | boolean
/** CSS selector of the action sheet to close on click. Or boolean property to close currently opened action sheet. */
actionsClose: CssSelector | boolean
/** CSS selector of the popup to open on click. */
popupOpen: CssSelector | boolean
/** CSS selector of the popup to close on click. Or boolean property to close currently opened popup. */
popupClose: CssSelector | boolean
/** CSS selector of the popover to open on click. */
popoverOpen: CssSelector | boolean
/** CSS selector of the popover to close on click. Or boolean property to close currently opened popover. */
popoverClose: CssSelector | boolean
/** CSS selector of the sheet modal to open on click. */
sheetOpen: CssSelector | boolean
/** CSS selector of the sheet modal to close on click. Or boolean property to close currently opened sheet modal. */
sheetClose: CssSelector | boolean
/** CSS selector of the login screen to open on click. */
loginScreenOpen: CssSelector | boolean
/** CSS selector of the login screen to close on click. Or boolean property to close currently opened login screen. */
loginScreenClose: CssSelector | boolean
/** CSS selector of the Sortable list to open on click. */
sortableEnable: CssSelector | boolean
/** CSS selector of the Sortable list to close on click. Or boolean property to close currently opened Sortable list. */
sortableDisable: CssSelector | boolean
/** CSS selector of the Sortable list to toggle on click. Or boolean property to toggle currently opened/closed Sortable list. */
sortableToggle: CssSelector | boolean
/** CSS selector of the Expandable Searchbar to be enabled on click. Or boolean property to enable the first found Searchbar. */
searchbarEnable: CssSelector | boolean
/** CSS selector of the Expandable Searchbar to be disabled on click. Or boolean property to disable the first found Searchbar. */
searchbarDisable: CssSelector | boolean
/** CSS selector of the Expandable Searchbar to toggle on click. Or boolean property to toggle the first found Searchbar. */
searchbarToggle: CssSelector | boolean
/** CSS selector of the Expandable Searchbar to clear on click. Or boolean property to clear the first found Searchbar. */
searchbarClear: CssSelector | boolean
/** Event will be triggered after click on a button */
onClick: () => void
}
}
export class ListButton extends React.Component<ListButton.Props, {}> {}
export const F7ListButton : typeof ListButton;
namespace ListGroup {
export interface Props extends F7Props {
/** Enables Media List for this group. (default false) */
mediaList?: boolean
/** Enables Sortable List for this group. (default false) */
sortable?: boolean
/** Enables simplified Simple List for this group. (default false) */
simpleList?: boolean
}
}
export class ListGroup extends React.Component<ListGroup.Props, {}> {}
export const F7ListGroup : typeof ListGroup;
namespace ListIndex {
export interface Props extends F7Props {
/** Initializes List Index. (default true) */
init?: boolean
/** Related List View element. HTMLElement or string with CSS selector of List View element. */
listEl: HTMLElement | CssSelector
/** Array with indexes. If not passed then it will automatically generate it based on item-divider and list-group-title elements inside of passed List View element in listEl parameter. (default auto) */
indexes?: number[] | string
/** Will automatically scroll related List View to the selected index. (default true) */
scrollList?: boolean
/** Enables label bubble with selected index when you swipe over list index. (default false) */
label?: boolean
/** Single index item height. It is required to calculate dynamic index and how many indexes fit on the screen. For iOS theme. (default 14) */
iosItemHeight?: number
/** Single index item height. It is required to calculate dynamic index and how many indexes fit on the screen. For MD theme. (default 14) */
mdItemHeight?: number
onListIndexSelect: (itemContent : any) => void
}
}
export class ListIndex extends React.Component<ListIndex.Props, {}> {
/** Recalculates indexes, sizes and rerenders list index */
update() : void
/** Scrolls related list to specified index content */
scrollToList(itemContent : any) : void
}
export const F7ListIndex : typeof ListIndex;
namespace ListItemCell {
export interface Props extends F7Props {
}
}
export class ListItemCell extends React.Component<ListItemCell.Props, {}> {}
export const F7ListItemCell : typeof ListItemCell;
namespace ListItemContent {
export interface Props extends F7Props {
}
}
export class ListItemContent extends React.Component<ListItemContent.Props, {}> {}
export const F7ListItemContent : typeof ListItemContent;
namespace ListItemRow {
export interface Props extends F7Props {
}
}
export class ListItemRow extends React.Component<ListItemRow.Props, {}> {}
export const F7ListItemRow : typeof ListItemRow;
namespace ListItem {
export interface Props extends F7Props {
// <ListItem> properties
/** List item title. */
title: string
/** List item subtitle (only for Media List). */
subtitle: string
/** List item text (only for Media List). */
text: string
/** List item header text. */
header: string
/** List item footer text. */
footer: string
/** List item media image URL. */
media: string
/** List item label. */
after: string
/** List item Badge. */
badge: string | number
/** List item Badge color. One of the default colors. */
badgeColor: string
/** Enables Media list item for the current list item. */
mediaItem: boolean
/** Converts list item to list item divider. */
divider: boolean
/** Converts list item to list group title. */
groupTitle: boolean
/** Disables fast click. */
noFastClick: boolean
/** List item link target attribute. */
target: boolean
// <ListItem> Form inputs specific properties:
/** Enables inline-styled labels for Form Inputs. By default inherirt inlineLabels prop on parent <List>. (default false) */
inlineLabel?: boolean
/** Enables additional styling for Form Inputs inside. By default will try to detect based on content. (default false) */
itemInput?: boolean
/** Enables additional styling for Form Inputs with additional info. By default will try to detect based on content. (default false) */
itemInputWithInfo?: boolean
// <ListItem> Swipeout specific properties:
/** Converts list item to swipeout list item. */
swipeout: boolean
/** Defines whether swipe actions should be opened or not. Note, only one swipeout item can be opened at same time. */
swipeoutOpened: boolean
// <ListItem> Accordion specific properties:
/** Converts list item to accordion list item. (default false) */
accordionItem?: boolean
/** Makes accordion item opened. (default false) */
accordionItemOpened?: boolean
// <ListItem> Smart Select specific properties:
/** Enables Smart Select behavior. (default false) */
smartSelect?: boolean
/** Object with Smart Select Parameters. */
smartSelectParams: object
// <ListItem> Checkboxes & Radios specific properties:
/** Enables checkbox-item. (default false) */
checkbox?: boolean
/** Enables radio-item. (default false) */
radio?: boolean
/** Whether the checkbox/radio input is checked. (default false) */
checked?: boolean
/** Defines whether the checkbox input is checked or not, for the case if it is uncontrolled component. */
defaultChecked: boolean
/** Checkbox/radio input name. */
name: string
/** Checkbox/radio input value. */
value: string | number
/** Whether the checkbox/radio input is readonly. (default false) */
readonly?: boolean
/** Whether the checkbox/radio input is disabled. (default false) */
disabled?: boolean
/** Whether the checkbox/radio input is required. (default false) */
required?: boolean
// <ListItem> navigation/router related properties:
/** Enables link and link URL if specified as string. Same as href prop. */
link: boolean | string
/** URL of the page to load. In case of boolean href="false" it won't add href tag. (default #) */
href?: string | boolean
/** CSS selector of the View to load the page. */
view: string
/** Enable to bypass Framework7's link click handler. */
external: boolean
/** Enables back navigation link. */
back: boolean
/** Force page to load and ignore previous page in history (use together with back prop). */
force: boolean
/** Reloads new page instead of the currently active one. */
reloadCurrent: boolean
/** Replace the previous page in history with the new one from route. */
reloadPrevious: boolean
/** Load new page and remove all previous pages from history and DOM. */
reloadAll: boolean
/** Disables pages animation. */
animate: boolean
/** Ignores caching. */
ignoreCache: boolean
/** Name of the page to load. */
pageName: string
/** Routable Tab id. */
routeTabId: string
// <ListItem> action related properties:
/** Defines panel to open. Can be left or right. */
panelOpen: string | boolean
/** Closes panel on click. */
panelClose: boolean
/** CSS selector of the action sheet to open on click. */
actionsOpen: string | boolean
/** CSS selector of the action sheet to close on click. Or boolean property to close currently opened action sheet. */
actionsClose: string | boolean
/** CSS selector of the popup to open on click. */
popupOpen: string | boolean
/** CSS selector of the popup to close on click. Or boolean property to close currently opened popup. */
popupClose: string | boolean
/** CSS selector of the popover to open on click. */
popoverOpen: string | boolean
/** CSS selector of the popover to close on click. Or boolean property to close currently opened popover. */
popoverClose: string | boolean
/** CSS selector of the sheet modal to open on click. */
sheetOpen: string | boolean
/** CSS selector of the sheet modal to close on click. Or boolean property to close currently opened sheet modal. */
sheetClose: string | boolean
/** CSS selector of the login screen to open on click. */
loginScreenOpen: string | boolean
/** CSS selector of the login screen to close on click. Or boolean property to close currently opened login screen. */
loginScreenClose: string | boolean
/** CSS selector of the Sortable list to open on click. */
sortableEnable: string | boolean
/** CSS selector of the Sortable list to close on click. Or boolean property to close currently opened Sortable list. */
sortableDisable: string | boolean
/** CSS selector of the Sortable list to toggle on click. Or boolean property to toggle currently opened/closed Sortable list. */
sortableToggle: string | boolean
/** CSS selector of the Expandable Searchbar to be enabled on click. Or boolean property to enable the first found Searchbar. */
searchbarEnable: string | boolean
/** CSS selector of the Expandable Searchbar to be disabled on click. Or boolean property to disable the first found Searchbar. */
searchbarDisable: string | boolean
/** CSS selector of the Expandable Searchbar to toggle on click. Or boolean property to toggle the first found Searchbar. */
searchbarToggle: string | boolean
/** CSS selector of the Expandable Searchbar to clear on click. Or boolean property to clear the first found Searchbar. */
searchbarClear: string | boolean
// event
/** Event will be triggeres when user clicks on list item */
onClick: () => void
/** Event will be triggeres when "change" event occurs on list item input (radio or checkbox) */
onChange: () => void
/** Event will be triggered while you move swipeout element. event.detail.progress contains current opened progress percentage */
onSwipeout: () => void
/** Event will be triggered when swipeout element starts its opening animation */
onSwipeoutOpen: () => void
/** Event will be triggered after swipeout element completes its opening animation */
onSwipeoutOpened: () => void
/** Event will be triggered when swipeout element starts its closing animation */
onSwipeoutClose: () => void
/** Event will be triggered after swipeout element completes its closing animation */
onSwipeoutClosed: () => void
/** Event will be triggered after swipeout element starts its delete animation */
onSwipeoutDelete: () => void
/** Event will be triggered after swipeout element completes its delete animation right before it will be removed from DOM */
onSwipeoutDeleted: () => void
/** Event will be triggered when accordion content starts its opening animation. */
onAccordionOpen: () => void
/** Event will be triggered after accordion content completes its opening animation. */
onAccordionOpened: () => void
/** Event will be triggered when accordion content starts its closing animation. */
onAccordionClose: () => void
/** Event will be triggered after accordion content completes its closing animation. */
onAccordionClosed: () => void
}
}
export class ListItem extends React.Component<ListItem.Props, {}> {}
export const F7ListItem : typeof ListItem;
namespace List {
export interface Props extends F7Props {
/** Makes list block inset. (default false) */
inset?: boolean
/** Makes block inset on tablets, but not on phones. (default false) */
tabletInset?: boolean
/** Enables Media List. (default false) */
mediaList?: boolean
/** Enables simplified Links List. (default false) */
linksList?: boolean
/** Enables simplified Simple List. (default false) */
simpleList?: boolean
/** Enables Sortable List. (default false) */
sortable?: boolean
/** Enables sorting on sortable list. (default false) */
sortableEnabled?: boolean
/** Enables Accordion List. (default false) */
accordion?: boolean
/** Enables Contacts List by adding required addional classes for styling. (default false) */
contactsList?: boolean
/** Enables <form> tag on list block instead of <div>. (default false) */
form?: boolean
/** Enables form storage for the current form. (default false) */
formStoreData?: boolean
/** Enables inline-styled labels for Form Inputs. (default false) */
inlineLabels?: boolean
/** Removes outer hairlines. (default false) */
noHairlines?: boolean
/** Removes outer hairlines for MD theme. (default false) */
noHairlinesMd?: boolean
/** Removes outer hairlines for iOS theme. (default false) */
noHairlinesIos?: boolean
/** Removes inner hairlines between items. (default false) */
noHairlinesBetween?: boolean
/** Removes inner hairlines between items for MD theme. (default false) */
noHairlinesBetweenMd?: boolean
/** Removes inner hairlines between items for iOS theme. (default false) */
noHairlinesBetweenIos?: boolean
/** Adds additional "tab" class when block should be used as a Tab. (default false) */
tab?: boolean
/** Adds additional "tab-active" class when block used as a Tab and makes it active tab. (default false) */
tabActive?: boolean
/** Enables Virtual List. (default false) */
virtualList?: boolean
/** Object with Virtual List Parameters. */
virtualListParams: object
// <List> events
/** Event will be triggered when List Block-Tab becomes visible/active */
onTabShow() : void
/** Event will be triggered when List Block-Tab becomes invisible/inactive */
onTabHide() : void
/** Event will be triggered on list-form submit when list used as form (with enabled form prop) */
onSubmit() : void
// <List> Sortable specific events
/** Event will be triggered when sortable mode is enabled */
sortableEnable() : void
/** Event will be triggered when sortable mode is disabled */
sortableDisable() : void
/** Event will be triggered after user release currently sorting element in new position. event.detail will contain object with from and to properties with start/new index numbers of sorted list item */
sortableSort() : void
// <List> Virtual List specific events
/** Event will be triggered before item will be added to virtual document fragment */
virtualItemBeforeInsert() : void
/** Event will be triggered after current DOM list will be removed and before new document will be inserted */
virtualItemsBeforeInsert() : void
/** Event will be triggered after new document fragment with items inserted */
virtualItemsAfterInsert() : void
/** Event will be triggered before current DOM list will be removed and replaced with new document fragment */
virtualBeforeClear() : void
}
}
export class List extends React.Component<List.Props, {}> {}
export const F7List : typeof List;
namespace LoginScreenTitle {
export interface Props extends F7Props {
}
}
export class LoginScreenTitle extends React.Component<LoginScreenTitle.Props, {}> {}
export const F7LoginScreenTitle : typeof LoginScreenTitle;
namespace LoginScreen {
export interface Props extends F7Props {
/** Allows to open/close Login Screen and set its initial state. (default false) */
opened?: boolean
/** Event will be triggered when Login Screen starts its opening animation */
onLoginScreenOpen : () => void
/** Event will be triggered after Login Screen completes its opening animation */
onLoginScreenOpened : () => void
/** Event will be triggered when Login Screen starts its closing animation */
onLoginScreenClose : () => void
/** Event will be triggered after Login Screen completes its closing animation */
onLoginScreenClosed : () => void
}
}
export class LoginScreen extends React.Component<LoginScreen.Props, {}> {
/** Open login screen */
open(animate : boolean) : void
/** Close login screen */
close(animate : boolean) : void
}
export const F7LoginScreen : typeof LoginScreen;
namespace Message {
export interface Props extends F7Props {
/** Message type: sent (default) or received. (default sent) */
type?: string
/** Message text. */
text: string
/** Message user's avatar URL. */
avatar: string
/** Message user's name. */
name: string
/** Message image URL. */
image: string
/** Message header. */
header: string
/** Message footer. */
footer: string
/** Message text header. */
textHeader: string
/** Message text footer. */
textFooter: string
/** Defines that the message is first in the conversation. (default false) */
first?: boolean
/** Defines that the message is last in the conversation. (default false) */
last?: boolean
/** Defines that the message has visual "tail". Usually last message in conversation. (default false) */
tail?: boolean
/** Defines that this message sender name is the same as on previous message. (default false) */
sameName?: boolean
/** Defines that this message header text is the same as on previous message. (default false) */
sameHeader?: boolean
/** Defines that this message footer text is the same as on previous message. (default false) */
sameFooter?: boolean
/** Defines that this message user's avatar URL is the same as on previous message. (default false) */
sameAvatar?: boolean
/** Event will be triggered when user clicks on message bubble */
onClick : () => void
/** Event will be triggered when user clicks on message user's name */
onClickName : () => void
/** Event will be triggered when user clicks on message text */
onClickText : () => void
/** Event will be triggered when user clicks on message user's avatar */
onClickAvatar : () => void
/** Event will be triggered when user clicks on message header */
onClickHeader : () => void
/** Event will be triggered when user clicks on message footer */
onClickFooter : () => void
/** Event will be triggered when user clicks on message bubble */
onClickBubble : () => void
}
}
export class Message extends React.Component<Message.Props, {}> {}
export const F7Message : typeof Message;
namespace MessagebarAttachment {
export interface Props extends F7Props {
/** Attachment image URL. */
image: string
/** Defines whether the attachment is deletable or not. In case of deletable the additional delete button will be rendered. (default true) */
deletable?: boolean
/** Event will be triggered on attachment click */
onAttachmentClick : (event : Event) => void
/** Event will be triggered on attachment delete button click */
onAttachmentDelete : (event : Event) => void
}
}
export class MessagebarAttachment extends React.Component<MessagebarAttachment.Props, {}> {}
export const F7MessagebarAttachment : typeof MessagebarAttachment;
namespace MessagebarAttachments {
export interface Props extends F7Props {
}
}
export class MessagebarAttachments extends React.Component<MessagebarAttachments.Props, {}> {}
export const F7MessagebarAttachments : typeof MessagebarAttachments;
namespace MessagebarSheetImage {
export interface Props extends F7Props {
/** Sheet image URL. */
image: string
/** Indicates whether this sheet image-item is checked or not. (default false) */
checked?: boolean
/** Event will be triggered on sheet item checkbox change */
change?: (event : Event) => void
}
}
export class MessagebarSheetImage extends React.Component<MessagebarSheetImage.Props, {}> {}
export const F7MessagebarSheetImage : typeof MessagebarSheetImage;
namespace MessagebarSheetItem {
export interface Props extends F7Props {
}
}
export class MessagebarSheetItem extends React.Component<MessagebarSheetItem.Props, {}> {}
export const F7MessagebarSheetItem : typeof MessagebarSheetItem;
namespace MessagebarSheet {
export interface Props extends F7Props {
}
}
export class MessagebarSheet extends React.Component<MessagebarSheet.Props, {}> {}
export const F7MessagebarSheet : typeof MessagebarSheet;
namespace Messagebar {
export interface Props extends F7Props {
/** Initializes Messagebar. (default true) */
init?: boolean
/** Textarea "name" attribute. */
name: string
/** Textarea placeholder text. (default Message) */
placeholder?: string
/** Textarea value. */
value: string | number
/** Sets "readonly" textarea attribute. (default false) */
readonly?: boolean
/** Sets "disbled" textarea attribute. (default false) */
disabled?: boolean
/** Enables Send link and specifies its text. This property will be ignored in case you use send-link slot. */
sendLink: string
/** Defines resizeable textarea max height. */
maxHeight: number
/** Enables resizeable textarea. (default true) */
resizable?: boolean
/** Makes messagebar sheet visible/active. (default false) */
sheetVisible?: boolean
/** Makes messagebar attachments visible/active. (default false) */
attachmentsVisible?: boolean
/** When enabled, it will resize messages page when messagebar textarea size changed. (default true) */
resizePage?: boolean
}
}
export class Messagebar extends React.Component<Messagebar.Props, {}> {
/** Clear textarea and update/reset its size */
clear() : void
/** Set messagebar textarea value/text */
setValue(newValue : string | number) : void
/** Return messagebar textarea value */
getValue() : void
/** Force Messagebar to resize messages page depending on messagebar height/size */
resize() : void
/** Focus messagebar textarea */
focus() : void
/** Remove focus from messagebar textarea */
blur() : void
/** Event will be triggered when "change" event occurs on messagebar textarea element */
onChange : (event : Event) => void
/** Event will be triggered when "input" event occurs on messagebar textarea element */
onInput : (event : Event) => void
/** Event will be triggered when "focus" event occurs on messagebar textarea element */
onFocus : (event : Event) => void
/** Event will be triggered when "blur" event occurs on messagebar textarea element */
onBlur : (event : Event) => void
/** Event will be triggered when user clicks on messagebar "send link" */
onSubmit : (value : string | number, clear : boolean) => void
/** Event will be triggered when user clicks on messagebar "send link" */
onSend : (value : string | number, clear : boolean) => void
}
export const F7Messagebar : typeof Messagebar;
namespace MessagesTitle {
export interface Props extends F7Props {
}
}
export class MessagesTitle extends React.Component<MessagesTitle.Props, {}> {}
export const F7MessagesTitle : typeof MessagesTitle;
namespace Messages {
export interface Props extends F7Props {
/** Initializes Messages component. (default true) */
init?: boolean
/** Enable if you want to use new messages on top, instead of having them on bottom. (default false) */
newMessagesFirst?: boolean
/** Enable/disable messages autoscrolling when adding new message. (default true) */
scrollMessages?: boolean
/** If enabled then messages autoscrolling will happen only when user is on top/bottom of the messages view. (default true) */
scrollMessagesOnEdge?: boolean
}
}
export class Messages extends React.Component<Messages.Props, {}> {
/** Scroll messages to top/bottom depending on newMessagesFirst parameter */
scroll(durationMS : number, positionPX : number) : void
/** Show typing message indicator */
showTyping(message : Message) : void
/** Hide typing message indicator */
hideTyping() : void
}
export const F7Messages : typeof Messages;
namespace NavLeft {
export interface Props extends F7Props {
/** Adds back-link with text (if string value is specified). */
backLink: boolean | string
/** Custom back link URL. */
backLinkUrl: string
/** Enables "sliding" effect. By default inhertis sliding prop of parent Navbar. */
sliding: boolean
/** Event will be triggered after click on navbar back link */
onBackClick : () => void
/** Event will be triggered after click on navbar back link */
onClickBack : () => void
}
}
export class NavLeft extends React.Component<NavLeft.Props, {}> {}
export const F7NavLeft : typeof NavLeft;
namespace NavRight {
export interface Props extends F7Props {
/** Enables "sliding" effect. By default inhertis sliding prop of parent Navbar. */
sliding: boolean
}
}
export class NavRight extends React.Component<NavRight.Props, {}> {}
export const F7NavRight : typeof NavRight;
namespace NavTitle {
export interface Props extends F7Props {
/** Specifies element inner title text (affects if there is no child elements). */
title: string
/** Sub title text. */
subtitle: string
/** Enables "sliding" effect. By default inhertis sliding prop of parent Navbar. */
sliding: boolean
}
}
export class NavTitle extends React.Component<NavTitle.Props, {}> {}
export const F7NavTitle : typeof NavTitle;
namespace Navbar {
export interface Props extends F7Props {
/** When enabled (by default), it will put all the content within internal `navbar-inner` element. Disable it only in case you want to put totally custom layout inside. (default true) */
inner?: boolean
/** Navbar title. */
title: string
/** Navbar sub title. */
subtitle: string
/** Adds back-link with text (if string value is specified). */
backLink: boolean | string
/** Custom back link URL. */
backLinkUrl: string
/** Enables "sliding" effect for nav elements. (default true) */
sliding?: boolean
/** Disable shadow rendering for Material theme. (default false) */
noShadow?: boolean
/** Disable navbar bottom thin border (hairline) for iOS theme. (default false) */
noHairline?: boolean
/** Makes navbar hidden. (default false) */
hidden?: boolean
/** Event will be triggered after click on navbar back link */
onBackClick : () => void
/** Event will be triggered after click on navbar back link */
onClickBack : () => void
}
}
export class Navbar extends React.Component<Navbar.Props, {}> {
/** Hide navbar */
hide(animate : boolean) : void
/** Show navbar */
show(animate : boolean) : void
/** Size navbar */
size() : void
}
export const F7Navbar : typeof Navbar;
namespace PageContent {
export interface Props extends F7Props {
ptr?:boolean
ptrDistance?:number
ptrPreloader?:boolean
infinite?:boolean
infiniteTop?:boolean
infiniteDistance?:boolean
infinitePreloader?:boolean
hideBarsOnScroll?:boolean
hideNavbarOnScroll?:boolean
hideToolbarOnScroll?:boolean
messagesContent?:boolean
loginScreen?:boolean
tabShow?: () => void
tabHide?: () => void
onPtrPullStart?: () => void
onPtrPullMove?: () => void
onPtrPullEnd?: () => void
onPtrRefresh?: () => void
onPtrDone?: () => void
onInfinite?: () => void
}
}
export class PageContent extends React.Component<PageContent.Props, {}> {}
export const F7PageContent : typeof PageContent;
namespace Page {
export interface Props extends F7Props {
name?:string
stacked?:boolean
messagesContent?:boolean
pageContent?:boolean
tabs?:boolean
loginScreen?:boolean
noSwipeback?:boolean
withSubnavbar?:boolean
noNavbar?:boolean
noToolbar?:boolean
hideBarsOnScroll?:boolean
hideNavbarOnScroll?:boolean
hideToolbarOnScroll?:boolean
ptr?:boolean
ptrDistance?:number
ptrPreloader?:boolean
infinite?:boolean
infiniteTop?:boolean
infiniteDistance?:boolean
infinitePreloader?:boolean
onPageMounted? : () => void
onPageInit? : () => void
onPageReinit? : () => void
onPageBeforeIn? : () => void
onPageAfterIn? : () => void
onPageBeforeOut? : () => void
onPageAfterOut? : () => void
onPageBeforeRemove? : () => void
onPtrPullStart? : () => void
onPtrPullMove? : () => void
onPtrPullEnd? : () => void
onPtrRefresh? : () => void
onPtrDone? : () => void
onInfinite? : () => void
}
}
export class Page extends React.Component<Page.Props, {}> {}
export const F7Page : typeof Page;
namespace Panel {
export interface Props extends F7Props {
/** Panel side. Could be left or right. */
side: string
/** Shortcut prop for side="left". */
left: boolean
/** Shortcut prop for side="right". */
right: boolean
/** Panel effect. Could be cover or reveal. */
effect: string
/** Shortcut prop for effect="cover". */
cover: boolean
/** Shortcut prop for effect="reveal". */
reveal: boolean
/** Allows to open/close panel and set its initial state. */
opened: boolean
/** Event will be triggered when Panel starts its opening animation */
onPanelOpen : () => void
/** Event will be triggered after Panel completes its opening animation */
onPanelOpened : () => void
/** Event will be triggered when Panel starts its closing animation */
onPanelClose : () => void
/** Event will be triggered after Panel completes its closing animation */
onPanelClosed : () => void
/** Event will be triggered when the panel backdrop is clicked */
onPanelBackdropClick : () => void
/** Event will be triggered for swipe panels during touch swipe action */
onPanelSwipe : () => void
/** Event will be triggered in the very beginning of opening it with swipe */
onPanelSwipeOpen : () => void
/** Event will be triggered when it becomes visible/hidden when app width matches its breakpoint */
onPanelBreakpoint : () => void
}
}
export class Panel extends React.Component<Panel.Props, {}> {
/** Open panel */
open(animate : boolean) : void
/** Close panel */
close(animate : boolean) : void
}
export const F7Panel : typeof Panel;
namespace PhotoBrowser {
export interface Props extends F7Props {
}
}
export class PhotoBrowser extends React.Component<PhotoBrowser.Props, {}> {}
export const F7PhotoBrowser : typeof PhotoBrowser;
namespace Popover {
export interface Props extends F7Props {
}
}
export class Popover extends React.Component<Popover.Props, {}> {}
export const F7Popover : typeof Popover;
namespace Popup {
export interface Props extends F7Props {
/** Defines whether the popup should be displayed fullscreen on tablets or not */
tabletFullscreen : boolean
/** Allows to open/close Popup and set its initial state */
opened : boolean
/** Enables Popup backdrop (dark semi transparent layer behind). By default inherits same app parameter value (true) */
backdrop : boolean
/** When enabled, popup will be closed on backdrop click. By default inherits same app parameter value (true) */
closeByBackdropClick : boolean
/** Whether the Popup should be opened/closed with animation or not. Can be overwritten in .open() and .close() methods. By default inherits same app parameter value (true) */
animate : boolean
/** Event will be triggered when Popup starts its opening animation */
onPopupOpen : () => void
/** Event will be triggered after Popup completes its opening animation */
onPopupOpened : () => void
/** Event will be triggered when Popup starts its closing animation */
onPopupClose : () => void
/** Event will be triggered after Popup completes its closing animation */
onPopupClosed : () => void
}
}
export class Popup extends React.Component<Popup.Props, {}> {
/** Open popup */
open(animate : boolean) : void
/** Close popup */
close(animate : boolean) : void
}
export const F7Popup : typeof Popup;
namespace Preloader {
export interface Props extends F7Props {
}
}
export class Preloader extends React.Component<Preloader.Props, {}> {}
export const F7Preloader : typeof Preloader;
namespace Progressbar {
export interface Props extends F7Props {
/** Determinate progress (from 0 to 100) */
progress : number
/** Whether progressbar is infinite or not (determinate) */
infinite : boolean
}
}
export class Progressbar extends React.Component<Progressbar.Props, {}> {
/** Set progressbar progress */
set(progress : number, durationMS : number) : void
}
export const F7Progressbar : typeof Progressbar;
namespace Radio {
export interface Props extends F7Props {
/** Defines whether the radio input is checked or not. */
checked: boolean
/** Defines whether the checkbox input is checked or not, for the case if it is uncontrolled component. */
defaultChecked: boolean
/** Radio input name. */
name: string | number
/** Radio input value. */
value: string | number | boolean
/** Defines whether the radio input is disabled. */
disabled: boolean
/** Defines whether the radio input is readonly. */
readonly: boolean
/** Event will be triggered when radio input state changed */
onChange : () => void
}
}
export class Radio extends React.Component<Radio.Props, {}> {}
export const F7Radio : typeof Radio;
namespace Range {
export interface Props extends F7Props {
}
}
export class Range extends React.Component<Range.Props, {}> {}
export const F7Range : typeof Range;
namespace RoutableModals {
export interface Props extends F7Props {
}
}
export class RoutableModals extends React.Component<RoutableModals.Props, {}> {}
export const F7RoutableModals : typeof RoutableModals;
namespace Row {
export interface Props extends F7Props {
/** Removes spacing between columns. (default false) */
noGap?: boolean
/** Defines which tag must be used to render row element. (default div) */
tag?: string
}
}
export class Row extends React.Component<Row.Props, {}> {}
export const F7Row : typeof Row;
namespace Searchbar {
export interface Props extends F7Props {
}
}
export class Searchbar extends React.Component<Searchbar.Props, {}> {}
export const F7Searchbar : typeof Searchbar;
namespace Segmented {
export interface Props extends F7Props {
/** Makes segmented raised. Affects MD theme only. (default false) */
raised?: boolean
/** Makes segmented round. (default false) */
round?: boolean
/** Tag used to render Segmented element. (default div) */
tag?: string
}
}
export class Segmented extends React.Component<Segmented.Props, {}> {}
export const F7Segmented : typeof Segmented;
namespace Sheet {
export interface Props extends F7Props {
/** Enable to render additional sheet modal backdrop when required. (default false) */
backdrop?: boolean
/** Allows to open/close Sheet Modal and set its initial state. (default false) */
opened?: boolean
/** When enabled, sheet will be closed on backdrop click. By default inherits same app parameter value. (default true) */
closeByBackdropClick?: boolean
/** When enabled, sheet will be closed on when click outside of it. By default inherits same app parameter value. (default false) */
closeByOutsideClick?: boolean
/** Event will be triggered when Sheet starts its opening animation */
onSheetOpen : () => void
/** Event will be triggered after Sheet completes its opening animation */
onSheetOpened : () => void
/** Event will be triggered when Sheet starts its closing animation */
onSheetClose : () => void
/** Event will be triggered after Sheet completes its closing animation */
onSheetClosed : () => void
}
}
export class Sheet extends React.Component<Sheet.Props, {}> {
/** Open Sheet modal */
open(animate : boolean) : void
/** Close Sheet modal */
close(animate : boolean) : void
}
export const F7Sheet : typeof Sheet;
namespace Statusbar {
export interface Props extends F7Props {
}
}
export class Statusbar extends React.Component<Statusbar.Props, {}> {}
export const F7Statusbar : typeof Statusbar;
namespace Stepper {
export interface Props extends F7Props {
}
}
export class Stepper extends React.Component<Stepper.Props, {}> {}
export const F7Stepper : typeof Stepper;
namespace Subnavbar {
export interface Props extends F7Props {
}
}
export class Subnavbar extends React.Component<Subnavbar.Props, {}> {}
export const F7Subnavbar : typeof Subnavbar;
namespace SwipeoutActions {
export interface Props extends F7Props {
}
}
export class SwipeoutActions extends React.Component<SwipeoutActions.Props, {}> {}
export const F7SwipeoutActions : typeof SwipeoutActions;
namespace SwipeoutButton {
export interface Props extends F7Props {
}
}
export class SwipeoutButton extends React.Component<SwipeoutButton.Props, {}> {}
export const F7SwipeoutButton : typeof SwipeoutButton;
namespace SwiperSlide {
export interface Props extends F7Props {
}
}
export class SwiperSlide extends React.Component<SwiperSlide.Props, {}> {}
export const F7SwiperSlide : typeof SwiperSlide;
namespace Swiper {
export interface Props extends F7Props {
}
}
export class Swiper extends React.Component<Swiper.Props, {}> {}
export const F7Swiper : typeof Swiper;
namespace Tab {
export interface Props extends F7Props {
/** Defines currently active/visible tab */
tabActive : boolean
/** Tab ID */
id : string
}
}
export class Tab extends React.Component<Tab.Props, {}> {}
export const F7Tab : typeof Tab;
namespace Tabs {
export interface Props extends F7Props {
/** Enables animated tabs */
animated : boolean
/** Enables swipeable tabs */
swipeable : boolean
/** Enables routable tabs */
routable : boolean
/** Event will be triggered when Tab becomes visible/active */
onTabShow : () => void
/** Event will be triggered when Tab becomes invisible/inactive */
onTabHide : () => void
}
}
export class Tabs extends React.Component<Tabs.Props, {}> {
/** Show this tab */
show(animate : boolean) : void
}
export const F7Tabs : typeof Tabs;
namespace Toggle {
export interface Props extends F7Props {
}
}
export class Toggle extends React.Component<Toggle.Props, {}> {}
export const F7Toggle : typeof Toggle;
namespace Toolbar {
export interface Props extends F7Props {
}
}
export class Toolbar extends React.Component<Toolbar.Props, {}> {}
export const F7Toolbar : typeof Toolbar;
namespace View {
export interface Props extends F7Props, Partial<F7View.Parameters> {
init?: boolean
tab?: boolean
tabActive?: boolean
/** Event will be triggered during swipe back move */
swipebackMove? : () => void
/** Event will be triggered right before swipe back animation to previous page when you release it */
swipeBackBeforeChange? : () => void
/** Event will be triggered after swipe back animation to previous page when you release it */
swipeBackAfterChange? : () => void
/** Event will be triggered right before swipe back animation to current page when you release it */
swipeBackBeforeReset? : () => void
/** Event will be triggered after swipe back animation to current page when you release it */
swipeBackAfterReset? : () => void
/** Event will be triggered when View-Tab becomes visible/active */
tabShow? : () => void
/** Event will be triggered when View-Tab becomes invisible/inactive */
tabHide? : () => void
}
}
export class View extends React.Component<View.Props, {}> {}
export const F7View : typeof View;
namespace Views {
export interface Props extends F7Props {
tabs?: boolean
}
}
export class Views extends React.Component<Views.Props, {}> {}
export const F7Views : typeof Views;
}<file_sep>import * as clipboardy from 'clipboardy'
const rows = clipboardy.readSync();
const transformed = rows.split('\n')
.map(row => {
const cells = row.split('\t').map(cell => (cell || '').replace(/\n/g, ' ').trim());
return ` /** ${cells[3]}.${ cells[2].length ? ` (default ${cells[2]})` : ''} */\n ${cells[0]}${cells[2].length ? '?' : ''}: ${cells[1]}`;
})
.join('\n');
clipboardy.writeSync(transformed);
console.log(transformed);<file_sep>/// <reference path="./dom7.d.ts" />
/// <reference path="./template7.d.ts" />
/// <reference path="./framework7.d.ts" />
/// <reference path="./framework7-react.d.ts" /> | df87e1c218470a7d6f65531044b9c6696a1383a0 | [
"Markdown",
"TypeScript"
] | 4 | Markdown | JasonKleban/Framework7.d.ts | 5103b75bccdf78f1d7a339cc71b8c86f152b9691 | c4cdf6f1ae47cef3d66d3a70710648bffddb73d1 | |
refs/heads/master | <file_sep># TheMovieDatabase
List of tasks completed
1. Catalog of most popular movies -> Done
2. Detail page of selected movie -> Done
3. Fullscreen plyback of trailer on click of "Watch Trailer" -> Done
4. Offile mode handling -> Done
5. iPad and iPhone, Portrait and Landscape support -> Done
<file_sep>//
// PopularMovieCollectionViewCell.swift
// TheMovieDatabase
//
// Created by <NAME> on 03/08/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import Kingfisher
class PopularMovieCollectionViewCell: UICollectionViewCell {
@IBOutlet private weak var posterView: UIImageView!
@IBOutlet private weak var movieTitle: UILabel!
@IBOutlet private weak var ratings: UILabel!
var movie: Results! {
didSet {
let url = URL(string: Constants.API.URLS.ImageDownloadURL + (movie.poster_path ?? ""))
posterView.kf.setImage(with: url)
movieTitle.text = movie.title
ratings.text = "Rating: \(movie.vote_average ?? 0.0)"
}
}
}
<file_sep>//
// Constants.swift
// TheMovieDatabase
//
// Created by <NAME> on 03/08/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
//Constants file contains all constants used in the application
struct Constants {
struct API {
//Base URL String
static let BaseURL = "https://api.themoviedb.org/3"
//The Movie Database Key
static let APIKey = "e7d3538e958b374dc44ab98a864965a0"
struct URLS {
//Popularity movie URL String
static let PopularMoviesURL = Constants.API.BaseURL + "/movie/popular?api_key=" + Constants.API.APIKey
//Image download URL
static let ImageDownloadURL = "https://image.tmdb.org/t/p/w500"
//Detail Page API
static let MovieDetailURL = Constants.API.BaseURL + "/movie/"
}
}
}
<file_sep>//
// BaseNavigationViewController.swift
// TheMovieDatabase
//
// Created by <NAME> on 04/08/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class BaseNavigationViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//Overrriding trait collection to have portrait view on iPad
override func overrideTraitCollection(forChild childViewController: UIViewController) -> UITraitCollection? {
if view.bounds.width < view.bounds.height {
let traitCollections = [UITraitCollection(horizontalSizeClass: .compact), UITraitCollection(verticalSizeClass: .regular)]
return UITraitCollection(traitsFrom: traitCollections)
} else {
let traitCollections = [UITraitCollection(horizontalSizeClass: .unspecified), UITraitCollection(verticalSizeClass: .unspecified)]
return UITraitCollection(traitsFrom: traitCollections)
}
}
}
<file_sep>//
// DetailHeaderTableViewCell.swift
// TheMovieDatabase
//
// Created by <NAME> on 04/08/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class DetailHeaderTableViewCell: UITableViewCell {
@IBOutlet private weak var posterImage: UIImageView!
@IBOutlet private weak var movieTitle: UILabel!
var movie: Movie! {
didSet {
let url = URL(string: Constants.API.URLS.ImageDownloadURL + (movie.backdrop_path ?? ""))
posterImage.kf.setImage(with: url) { result in
self.setNeedsLayout()
}
movieTitle.text = movie.title
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep># Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'TheMovieDatabase' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for TheMovieDatabase
pod 'Alamofire'
pod 'Kingfisher'
pod 'Toast-Swift'
pod 'YoutubeDirectLinkExtractor'
target 'TheMovieDatabaseTests' do
inherit! :search_paths
# Pods for testing
end
end
<file_sep>//
// ArrayExtensions.swift
// TheMovieDatabase
//
// Created by <NAME> on 03/08/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
extension Array {
//Create genre string from IDs
func genre() -> String? {
if self.count == 0 { return "" }
let genreIDs = [28: "Action",
12: "Adventure",
16: "Animation",
35: "Comedy",
80: "Crime",
99: "Documentary",
18: "Drama",
10751: "Family",
14: "Fantasy",
36: "History",
27: "Horror",
10402: "Music",
9648: "Mystery",
10749: "Romance",
878: "Science Fiction",
10770: "TV Movie",
53: "Thriller",
10752: "War",
37: "Western"]
var txt = ""
for itm in (self as! [Genres]) {
let value = genreIDs[itm.id!]
txt += value!
if itm.id! != (self.last! as! Genres).id! {
txt += ", "
}
}
return txt
}
}
<file_sep>//
// HomeDataTableViewCell.swift
// TheMovieDatabase
//
// Created by <NAME> on 04/08/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class HomeDataTableViewCell: UITableViewCell {
@IBOutlet weak var titleTxt: UILabel!
@IBOutlet weak var subTxt: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// HomeViewController.swift
// TheMovieDatabase
//
// Created by <NAME> on 03/08/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import Toast_Swift
class HomeViewController: UIViewController {
private var currentIdx: Int = 1
private var moviesList: MoviesBase!
@IBOutlet private weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
getPopularMovies()
}
override func refreshView() {
if AlamofireManager.isConnectedToInternet {
getPopularMovies()
}
}
//API call to get popular movies
func getPopularMovies() {
let url = URL(string: Constants.API.URLS.PopularMoviesURL + "&page=\(currentIdx)")
AlamofireManager.getRequest(url: url!) { [weak self] (data, error) in
if let err = error {
self?.view.makeToast(err)
return
}
let jsonDecoder = JSONDecoder()
if let model = try? jsonDecoder.decode(MoviesBase.self, from: data!) {
if self?.moviesList == nil { self?.moviesList = model }
else if (self?.moviesList.page)! < model.page! { self?.moviesList.update(data: model) }
self?.collectionView.reloadData()
}
}
}
}
extension HomeViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return moviesList?.results?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Movie", for: indexPath) as! PopularMovieCollectionViewCell
cell.movie = moviesList.results![indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.item == (moviesList.results?.count ?? 0) - 1 {
if currentIdx < (moviesList.total_pages ?? 0) {
currentIdx += 1
getPopularMovies()
}
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = MovieDetailViewController.create()
vc.movieID = moviesList.results![indexPath.item].id
navigationController?.pushViewController(vc, animated: true)
}
}
<file_sep>//
// AlamofireManager.swift
// TheMovieDatabase
//
// Created by <NAME> on 03/08/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Alamofire
class AlamofireManager: NSObject {
//Check connectivity
class var isConnectedToInternet:Bool {
return NetworkReachabilityManager()!.isReachable
}
//API Get Method calls
//@url: url to fetch data
//@completion: Return Data received from API response and error message
static func getRequest(url: URL, completion: ((Data?, String?) -> ())?) {
if !isConnectedToInternet { completion?(nil, "You are not connected to the internet."); return }
Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default)
.responseData { (response) in
if let error = response.error {
completion?(nil, error.localizedDescription)
return
}
if let data = response.result.value {
completion?(data, nil)
}
}
}
static let shared = AlamofireManager()
//Reachability Manager
let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.apple.com")
//Observing changes in reachability
func startNetworkReachabilityObserver() {
reachabilityManager?.listener = { status in
switch status {
case .notReachable:
break
case .unknown, .reachable(.ethernetOrWiFi), .reachable(.wwan) :
UIApplication.getTopViewController()?.refreshView()
break
}
}
reachabilityManager?.startListening()
}
}
<file_sep>//
// UIViewControllerExtension.swift
// TheMovieDatabase
//
// Created by <NAME> on 05/08/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
extension UIViewController {
@objc func refreshView() {
//Overrides for reachability update
}
}
<file_sep>//
// MovieDetailViewController.swift
// TheMovieDatabase
//
// Created by <NAME> on 03/08/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import AVKit
import Toast_Swift
import YoutubeDirectLinkExtractor
class MovieDetailViewController: UIViewController {
private var movie: Movie!
var movieID: Int!
@IBOutlet weak var tableView: UITableView!
//Creating new instance of view controller
static func create() -> MovieDetailViewController {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MovieDetailViewController") as! MovieDetailViewController
return vc
}
override func viewDidLoad() {
super.viewDidLoad()
getMovieDetails()
}
override func refreshView() {
if AlamofireManager.isConnectedToInternet {
getMovieDetails()
}
}
//API call to fetch movie details
func getMovieDetails() {
let url = URL(string: Constants.API.URLS.MovieDetailURL + "\(movieID ?? 0)?api_key=" + Constants.API.APIKey + "&append_to_response=videos")
AlamofireManager.getRequest(url: url!) { [weak self] (data, error) in
if let err = error {
self?.view.makeToast(err)
return
}
let jsonDecoder = JSONDecoder()
if let model = try? jsonDecoder.decode(Movie.self, from: data!) {
self?.movie = model
self?.tableView.reloadData()
}
}
}
//Play video
//@str : youtube url
func playVideo(str: String) {
let url = URL(string: str)
let player = AVPlayer(url: url!)
let vc = AVPlayerViewController()
vc.player = player
if #available(iOS 11.0, *) {
vc.entersFullScreenWhenPlaybackBegins = true
} else {
// Fallback on earlier versions
}
present(vc, animated: true) {
vc.player?.play()
}
}
//Action to watch trailer button
@IBAction func watchTrailer() {
if movie == nil {
self.view.makeToast("Please reselect the movie")
return
}
if !AlamofireManager.isConnectedToInternet {
self.view.makeToast("You are not connected to the internet.")
return
}
//Used YouTubeDirectLinkExtractor Library to fetch youtube url
if let videos = movie.videos?.results, videos.count > 0, let key = videos[0].key {
YoutubeDirectLinkExtractor().extractInfo(for: .id(key), success: { [weak self] (info) in
self?.playVideo(str: info.highestQualityPlayableLink!)
}) { (error) in
DispatchQueue.main.async {
self.view.makeToast(error.localizedDescription)
}
}
} else {
self.view.makeToast("No video links available")
}
}
}
extension MovieDetailViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movie == nil ? 0 : 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "Movie") as! DetailHeaderTableViewCell
cell.movie = movie
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "Data") as! HomeDataTableViewCell
cell.titleTxt?.text = "Genres"
cell.subTxt?.text = movie.genres?.genre()
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "Data") as! HomeDataTableViewCell
cell.titleTxt?.text = "Date"
cell.subTxt?.text = movie.release_date
return cell
case 3:
let cell = tableView.dequeueReusableCell(withIdentifier: "Data") as! HomeDataTableViewCell
cell.titleTxt?.text = "Overview"
cell.subTxt?.text = movie.overview
return cell
default:
return UITableViewCell()
}
}
}
<file_sep>//
// Helper.swift
// TheMovieDatabase
//
// Created by <NAME> on 03/08/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class Helper: NSObject {
}
| 54279195d8605c071d1e6d5746a3e278387341af | [
"Markdown",
"Ruby",
"Swift"
] | 13 | Markdown | rahulbelekar/TheMovieDatabase | 91e26cfa510872dcf37a2cab92b49e66a0a6dfe6 | 2b53d90a2686bbdebf7923a3cf3a2e22baadac1f | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InlämningAdressList
{
/*CLASS:Person
*PURPOSE: The person entry in the adress list
*/
class Person
{
public string name, address, telephone, email;
public Person(string N, string A, string T, string E)
{
name = N; address = A; telephone = T; email = E;
}
/*METHOD:PERSON
*PURPOSE:asks user ent for input if the classes is initiliazed with no parameters
* PARAMETERS:None
*/
public Person()
{
Console.WriteLine("Adds new person");
Console.Write(" 1. enter name: ");
name = Console.ReadLine();
Console.Write(" 2. enter address: ");
address = Console.ReadLine();
Console.Write(" 3. enter telphone: ");
telephone = Console.ReadLine();
Console.Write(" 4. enter email: ");
email = Console.ReadLine();
}
/* METHOD: Person.Print
* PURPOSE: write a person entry to the address list file
* PARAMETERS: None
* RETURN VALUE: void
*/
public string PrintPerson()
{
return $"{name},{address},{telephone},{email}";
}
}
class Program
{
static void Main(string[] args)
{
List<Person> Dict = new List<Person>();
string fileStream = @"C:\Users\husse\address.lis";
Console.Write("Loading address list ... ");
Load(Dict);
Console.WriteLine("Hello and welcome to the address list");
Console.WriteLine("Type 'quit' to quit!");
string command;
do
{
Console.Write("> ");
command = Console.ReadLine();
if (command == "quit")
{
Console.WriteLine("Bye!");
}
else if (command == "new")
{
Dict.Add(new Person());
}
else if (command == "delete")
{
Console.Write("Who do you want to delete (enter name): ");
string wantsToDelete = Console.ReadLine();
int found = -1;
for (int i = 0; i < Dict.Count(); i++)
{
if (Dict[i].name == wantsToDelete) found = i;
}
if (found == -1)
{
Console.WriteLine("Unfortunately: {0} was not in telephone list", wantsToDelete);
}
else
{
Dict.RemoveAt(found);
}
}
else if (command == "view")
{
for (int i = 0; i < Dict.Count(); i++)
{
Dict[1].PrintPerson();
//Person P = Dict[i]
//Console.WriteLine("{0}, {1}, {2}, {3}", P.name, P.address, P.telephone, P.email);
}
}
else if (command == "change")
{
Console.Write("Who do you want to change (enter name): ");
string wantChange = Console.ReadLine();
int found = -1;
for (int i = 0; i < Dict.Count(); i++)
{
if (Dict[i].name == wantChange) found = i;
}
if (found == -1)
{
Console.WriteLine("Unfortunately: {0} was not in telephone list", wantChange);
}
else
{
Console.Write("What do you want to change (name, address, telephone or email): ");
string fieldToChange = Console.ReadLine();
Console.Write("What do you want to change {0} on {1} to: ", fieldToChange, wantChange);
string newValue = Console.ReadLine();
switch (fieldToChange)
{
case "name": Dict[found].name = newValue; break;
case "address": Dict[found].address = newValue; break;
case "telephone": Dict[found].telephone = newValue; break;
case "email": Dict[found].email = newValue; break;
default: break;
}
}
}
else
{
Console.WriteLine("Unknown command: {0}", command);
}
} while (command != "quit");
}
/* METHOD: LoadList (static)
* PURPOSE: Reads the/a file and initializes objects into list
* PARAMETERS: List<Person>
* RETURN VALUE: void
*/
private static void Load(List<Person> Dict)
{
using (StreamReader fileStream = new StreamReader(@"C:\Users\husse\address.lis"))
{
while (fileStream.Peek() >= 0)
{
string line = fileStream.ReadLine();
// Console.WriteLine(line);
string[] word = line.Split('#');
// Console.WriteLine("{0}, {1}, {2}, {3}", word[0], word[1], word[2], word[3]);
Person P = new Person(word[0], word[1], word[2], word[3]);
Dict.Add(P);
}
}
Console.WriteLine("Done!"); //List<Person> Dict = new List<Person>();
}
}
} | 67a0a00bae195b71b6874f34f16726896cdc6353 | [
"C#"
] | 1 | C# | Husseinnoori/-Inlamning_2_ra | 672630a09a58a103e47fc716087657a53d8e3173 | 4c9b57b51b3cf4cbad531666c177fdcd10465a1e | |
refs/heads/master | <repo_name>maildebjyoti/jazzytrip<file_sep>/References.md
#Angular2
https://angular.io/docs/ts/latest/tutorial
https://angular.io/docs/ts/latest/guide/cheatsheet.html
https://angular.io/docs/ts/latest/guide/style-guide.html
#ng2 + Express
https://universal.angular.io/quickstart/
#Others
Debugging:
https://juristr.com/blog/2016/02/debugging-angular2-console/
https://www.pluralsight.com/guides/front-end-javascript/debugging-angular-2-applications
<file_sep>/client/app/Shared/search.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import { User } from './user';
@Injectable()
export class SearchService {
constructor(private http: Http) { }
search(term: string): Observable<User[]> {
return this.http
.get(`api/search?name=${term}`)
.map((data: Response): User[] => {
console.log(data);
return data.json();
});
}
}
<file_sep>/server/routes.js
var router = require('express').Router();
var four0four = require('./utils/404')();
var data = require('./data');
router.get('/users', getUsers);
router.get('/user/:id', getUser);
router.get('/search', search);
router.get('/searchuser/:user', searchUser);
router.post('/setuser', setUserData);
router.get('/*', four0four.notFoundMiddleware);
module.exports = router;
//////////////
function getUsers(req, res) {
var token = req.body.token || req.query.token || req.headers['x-access-token'];
//res.setHeader('x-access-token', token);
res.status(200).send(data.users);
}
function getUser(req, res, next) {
var id = req.params.id;
var person = data.users.filter(function (p) {
return p.id.toString() === id;
})[0];
if (person) {
res.status(200).send(person);
} else {
four0four.send404(req, res, 'person ' + id + ' not found');
}
}
function search(req, res, next) {
var name = req.query.name;
var persons = [];
data.users.filter(function (p) {
var firstname = p.firstName.toString().toLowerCase();
var searchUser = name.toString().toLowerCase();
if (firstname.indexOf(searchUser) !== -1) {
persons.push(p);
}
});
res.status(200).send(persons);
}
function searchUser(req, res, next) {
var user = req.params.user;
var name = req.query.token;
var persons = [];
data.users.filter(function (p) {
var firstname = p.firstName.toString().toLowerCase();
var searchUser = user.toString().toLowerCase();
//console.log(firstname.indexOf(searchUser) !== -1 ? p : []);
if (firstname.indexOf(searchUser) !== -1) {
persons.push(p);
}
});
if (persons.length > 0) {
res.status(200).send(persons);
} else {
four0four.send404(req, res, 'Error: ' + user + ' not found');
}
}
function setUserData(req, res) {
var data = req.body;
var token = req.headers['x-access-token'];
var respObj = {
status: 'Success',
token: token,
data: data,
query: req.query
}
res.status(200).send(respObj);
}<file_sep>/client/app/Dashboard/dashboard.component.ts
import { Component, OnInit } from '@angular/core';
import { Hero } from '../Shared/hero';
import { User } from '../Shared/user';
import { HeroService } from '../Shared/hero.service';
//import { SearchComponent } from './../Shared/search.service';
@Component({
moduleId: module.id,
selector: 'my-dashboard',
templateUrl: 'dashboard.component.html',
styleUrls: ['dashboard.component.css']
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
users: User[] = [];
test = 'TEST';
constructor(private heroService: HeroService) { }
ngOnInit(): void {
console.log('Dashboard - ngOnInit');
// this.heroService.getHeroes()
// .then(heroes => this.heroes = heroes.slice(1, 5));
this.heroService.getHeroes().then(users => this.users = users);
}
}
<file_sep>/client/app/Shared/hero.service.ts
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Hero } from './hero';
import { User } from './user';
import { Injectable } from '@angular/core';
@Injectable()
export class HeroService {
private usersUrl = 'api/users'; // URL to web api
private userUrl = 'api/user'; // URL to web api
constructor(private http: Http) { }
getHeroes(): Promise<User[]> {
return this.http.get(this.usersUrl)
.toPromise()
.then(response => response.json() as User[])
.catch(this.handleError);
}
// getHeroes(): Promise<Hero[]> {
// return Promise.resolve(HEROES);
// }
// getHeroesSlowly(): Promise<Hero[]> {
// return new Promise(resolve => {
// // Simulate server latency with 2 second delay
// setTimeout(() => resolve(this.getHeroes()), 2000);
// });
// }
getHero(id: number): Promise<User> {
return this.http.get(this.userUrl + '/' + id)
.toPromise()
// .then(response => response.json() as User)
.then((response): User => {
// console.log(response);
return response.json();
})
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
| 7276e2415011687ffae1fae0e83d56a9222655f3 | [
"Markdown",
"TypeScript",
"JavaScript"
] | 5 | Markdown | maildebjyoti/jazzytrip | 2b15b0102e38ecb50367b32dd000a30e684f9fa1 | b8005d97f1c4843c55607aa12b81c0a1c9c43fbf | |
refs/heads/master | <repo_name>tanya1oberemok/ProductList<file_sep>/src/app/components/log-in/log-in.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/services/auth.service';
@Component({
selector: 'app-log-in',
templateUrl: './log-in.component.html',
styleUrls: ['./log-in.component.css']
})
export class LogInComponent implements OnInit {
form:FormGroup;
constructor(
private formBuilder:FormBuilder,
private authService: AuthService,
private router: Router
) {
this.form = this.formBuilder.group({
userName: ['',Validators.required],
password: ['',Validators.required]
});
}
ngOnInit() {
}
}
<file_sep>/src/app/components/product/product.component.ts
import { Component, OnInit } from '@angular/core';
import { ListsService } from 'src/app/services/lists.service';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
constructor(
private listsService: ListsService,
private route: ActivatedRoute
) { }
ngOnInit() {
this.getId();
}
getId(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.listsService.getId(id)
.subscribe(list => list.id === id);
}
}
<file_sep>/src/app/services/lists.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { of } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ListsService {
constructor(private http: HttpClient) { }
getProducts() {
return this.http.get('/assets/list.json')
}
getId(id: number) {
return of( this.getProducts().find(list => list.id === id));
}
}
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { ListComponent } from './components/list/list.component';
import { LogInComponent } from './components/log-in/log-in.component';
import { NavigationComponent } from './components/navigation/navigation.component';
import { RegisterComponent } from './components/register/register.component';
import { ProductComponent } from './components/product/product.component';
const itemRoutes: Routes = [
{
path: 'products', component: ListComponent, children:
[
{
path: 'products/:id', component: ProductComponent
}
]
},
{
path: 'login', component: LogInComponent
},
{
path: 'register', component: RegisterComponent
}
]
const routes: Routes = [
{
path: 'api', component: NavigationComponent, children: itemRoutes
},
{
path: '', component: HomeComponent
},
{
path: 'login', component: LogInComponent, children:
[
{
path: 'register', component: RegisterComponent
}
]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
| e212f4fff4054830ce6fa0d9e849ad07a875c0ca | [
"TypeScript"
] | 4 | TypeScript | tanya1oberemok/ProductList | 67d06916013601ebfc7d37005370c82bc118b268 | 9c266750556ce828d962cc82d5e48aa650fa6ba0 | |
refs/heads/master | <repo_name>MahmoudReyad/Yallaa_Fix<file_sep>/index.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
if (!empty($_POST['choosing-submit'])) {
$iphoneType = filter_var($_POST['select_iphone'] , FILTER_SANITIZE_STRING);
$iphone_color = filter_var($_POST['color'] , FILTER_SANITIZE_STRING);
$name =filter_var( $_POST['name'] , FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'] , FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST['phone'] , FILTER_SANITIZE_NUMBER_INT);
$problem = filter_var($_POST['problem'] , FILTER_SANITIZE_STRING);
$address = filter_var($_POST['address'] , FILTER_SANITIZE_STRING);
$name_ed = True;
$email_ed = True;
$phone_ed =True;
$problem_ed = True;
$address_ed = True;
if(strlen($name) == 0){
$name_error = "Your Field Can't be empty";
$name_ed = True;
}
elseif(strlen($name) <= 3){
$name_error = "Your Name should be more than 3 Characters";
$name_ed = True;
}
else {
$name_ed = false;
}
if(strlen($email) == 0){
$email_error = "Your Field Can't be empty";
$email_ed = True;
}
else if(strlen($email) <= 4){
$email_error = "Your email should be more than 5 Characters and contain @ symbol";
$email_ed = True;
}
else {
$email_ed = false;
}
if(strlen($phone) == 0){
$phone_error = "Your Field Can't be empty";
$phone_ed = True;
}
else if(strlen($phone) < 11 || strlen($phone) > 11){
$phone_error = "Your Phone number should equal 11 numbers";
$phone_ed = True;
}
else {
$phone_ed = false;
}
if(strlen($problem) == 0){
$problem_error = "Your Field Can't be empty";
$problem_ed = True;
}
else if(strlen($problem) <= 10){
$problem_error = "Your Phone number should equal 10 Characters";
$problem_ed = True;
}
else {
$problem_ed = false;
}
if(strlen($address) == 0){
$address_error = "Your Field Can't be empty";
$address_ed = True;
}
else if(strlen($address) <= 15){
$address_error = "Your Address should equal 15 Characters";
$address_ed = True;
}
else {
$address_ed = false;
}
if($name_ed || $email_ed || $phone_ed || $address_ed || $problem_ed){
$faild = "<div class='alert alert-danger success'><p>Thers is Some Thing Wrong</p></div>";
}
else {
$success = "<div class='alert alert-success success'><p>Successful request</p></div>";
$company_mail = "<EMAIL>";
$subject = "New Order";
$msg = "Mr ".$name." want to fix his ".$iphone_color." ".$iphoneType." with a problem in".$problem."\n"."and his phone number is ".$phone." and his address is \n".$address;
mail($company_mail , $subject ,$msg , "Requesting Order");
$name = "";
$phone = "";
$email = "";
$problem = "";
$address = "";
}
}
elseif (!empty($_POST['subscribe'])) {
$mail = $_POST['email'];
$company_mail = "<EMAIL>";
$subject = "News subbscribtion";
$msg = "this email ".$mail." want to keep updated with your news";
mail($company_mail , $subject , $msg , "news subscribe");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mobile Fixing Company</title>
<link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">
<!-- Font Awesome Library -->
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/style.css">
<link href="https://fonts.googleapis.com/css?family=Dhurjati" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=BioRhyme+Expanded" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Raleway:400,700,900i" rel="stylesheet">
</head>
<body>
<!-- <div class="loading-page">
<i class="fas fa-cog fa-4x fa-spin"></i>
<h3>Loading...</h3>
</div> -->
<!-- Start NavBar -->
<nav class="navbar navbar-default navbar-fixed-top ">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#mynavbar" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><p>Yallaa <span>Fix</span></p></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="mynavbar">
<ul class="nav navbar-nav navbar-right">
<li class="active" ><a href="index.php">Home <span class="sr-only">(current)</span></a></li>
<li><a href="contact.php" data-value="footer" class="contact">Contact us</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container -->
</nav>
<!-- End NavBar -->
<!--Start Main Header -->
<header class="main-header text-center">
<div class="container">
<div class="row">
<div id="content" class="col-xs-12">
<div class="row">
<img src="images/logo.png" alt="brand" class="img-responsive">
<div class="col-xs-12"><h1>fix your phone at Your home</h1></div>
</div>
<div class="row">
<div class="col-xs-12"><button class="btn btn-success order" data-value=".choose-your-phone">Order Now</button></div>
</div>
</div>
</div>
</div>
</header>
<!--End Main Header -->
<!-- Start How it works -->
<section class="how-it-works">
<div class="container">
<div class="row">
<div class="col-lg-3">
<h1><span>H</span/>ow <br> it <span>W</span>orks ? </h1>
</div>
<div class="col-lg-3">
<i class="fas fa-laptop fa-3x"></i>
<strong>Book Us </strong>
<p>You can book an iFixer through our website or by calling us on 01067818181.</p>
</div>
<div class="col-lg-3">
<i class="fas fa-car fa-3x"></i>
<strong>We come to you </strong>
<p>There's no need to stop what you're doing to have your iPhone repaired - we'll meet you at your house, office or a nearby café.</p>
</div>
<div class="col-lg-3">
<i class="fas fa-thumbs-up fa-3x"></i>
<strong>Lifetime Warranty</strong>
<p>It's a risk-free experience; your repair is backed by the iFix Lifetime Warranty system.</p>
</div>
</div>
</div>
</section>
<!--End How it works -->
<!-- Start Choose Your Phone -->
<section class="choose-your-phone text-center">
<div class="container">
<div class="row">
<div class="col-xs-12">
<h1>Choose Your Device</h1>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="col-xs-6">
<img class="img-responsive" src="images/iphone-choice.png" alt="Iphone">
<button type="button" class="btn btn-primary iphone" data-value="#form">IPhone</button>
</div>
<div class="col-xs-6 text-center">
<img class="img-responsive" src= "images/other-choice.png" alt="Other">
<button type="button" class="btn btn-primary other" data-toggle="modal" data-target=".bs-example-modal-sm">Other</button>
<div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<h2>Coming Soon</h2>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!--End Chhose Your Phone -->
<section class="if_success text-center">
<div class="container">
<div class="row">
<?php if(isset($success)){ ?>
<div class="modal fade" id="global-modal" role="dialog">
<div class="modal-dialog modal-lg">
<!--Modal Content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" style="margin-top: -16px; font-size: 28px;" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" style="padding: 0;">
<?php
echo $success;
} ?>
</div>
</div>
</div>
</div>
<?php if(isset($faild)){ ?>
<div class="modal fade" id="global-modal" role="dialog">
<div class="modal-dialog modal-lg">
<!--Modal Content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" style="margin-top: -16px; font-size: 28px;" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" style="padding: 0;">
<?php
echo $faild;
echo "<br> <button class='btn btn-danger class btn_faild'>Check Your Errors</button>";
} ?>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="request-order text-center" id="form">
<div class="container">
<div class="row">
<div class="col-xs-12">
<h1> Request Your Order</h1>
</div>
<div class="col-xs-12">
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST" id="choosing_form">
<label>IPhone Type </label>
<select name="select_iphone" class = "form-control">
<option value="iphone5">IPHONE5</option>
<option value="iphone5s">IPHONE5S</option>
<option value="iphon5ce">IPHONE5C</option>
<option value="iphone6">IPHONE6</option>
<option value="iphone6plus">IPHONE6PLUS</option>
<option value="iphone6s">IPHONE6S</option>
<option value="iphone6splus">IPHONE6SPLUS</option>
<option value="iphone7">IPHONE7</option>
<option value="iphone7s">IPHONE7S</option>
<option value="iphone7splus">IPHONE7SPLUS</option>
<option value="iphone8">IPHONE8</option>
<option value="iphone8s">IPHONE8S</option>
<option value="iphonex">IPHONEX</option>
</select>
<label>IPhone Color</label>
<select name="color" class = "form-control">
<option value="white">White</option>
<option value="black">Black</option>
<option value="gold">Gold</option>
</select>
<div class="fomr-group">
<textarea class="form-control" required name="problem" placeholder="What is your problem"></textarea>
<div class="custom-alert alert alert-danger"></div>
<?php if(isset($problem_error )){ ?>
<div class="alert alert-warning"><p><?php echo $problem_error; ?></div>
<?php }?>
</div>
<div class="fomr-group">
<input class="form-control" type="name" name="name" required placeholder="Your Name" maxlength="15" value = "<?php if(isset($name)) echo $_POST['name'] ?>">
<div class="custom-alert alert alert-danger"></div>
<?php if(isset($name_error )){ ?>
<div class="alert alert-warning"><p><?php echo $name_error; ?></div>
<?php }?>
</div>
<div class="fomr-group">
<input class="form-control" type="tel" name="phone" required placeholder="Your Mobile Phone" maxlength="11" pattern="\d*" value = "<?php if(isset($phone)) echo $_POST['phone'] ?>">
<div class="custom-alert alert alert-danger"></div>
<?php if(isset($phone_error )){ ?>
<div class="alert alert-warning"><p><?php echo $phone_error; ?></div>
<?php }?>
</div>
<div class="fomr-group">
<input type="email" class="form-control" name="email" value = "<?php if(isset($email)) echo $_POST['email'] ?>" required placeholder="Enter Valid Email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$">
<div class="custom-alert alert alert-danger"></div>
<?php if(isset($email_error)){ ?>
<div class="alert alert-warning"><p><?php echo $email_error; ?></div>
<?php }?>
</div>
<div class="fomr-group">
<input type="text" class="form-control" name="address" required placeholder="Enter Your Address" value = "<?php if(isset($address)) echo $_POST['address'] ?>">
<div class="custom-alert alert alert-danger"></div>
<?php if(isset($address_error)){ ?>
<div class="alert alert-warning"><p><?php echo $address_error; ?></div>
<?php }?>
</div>
<input type="submit" class="form-control btn btn-success btn-block" name="choosing-submit" value="Submit">
</form>
</div>
</div>
</div>
</section>
<!--Start Mother board fixing -->
<section class="mother_board text-center">
<div class="container">
<div class="row">
<div class="col-xs-12">
<p>We also fix MotherBoards</p>
</div>
</div>
</div>
</section>
<!--End Mother Board fixing -->
<!--Start issues -->
<!-- <section class="issues ">
<div class="container">
<div class="row">
<div class="col-md-6 col-xs-12">
<h1>You're a couple of steps away from a fully-repaired iPhone.</h1>
<p>We'll fix any of these issues.</p>
</div>
<div class="col-md-6 col-xs-12">
<img src="images/iphone-issues.png" class="img-responsive" alt="iphone_issues">
</div>
</div>
</div>
</section> -->
<!-- End issues -->
<!--Start ultimate footer -->
<footer class="ultimate-footer">
<div class="container">
<div class="row">
<div class="col-md-3 col-xs-12">
<img src="images/logo.png" alt="Brand Logo" class="img-responsive">
</div>
<div class="col-md-4 col-xs-12">
<h3>About</h3>
<p>iFix is a new mobile repair concept brought to you by a team of Egyptian mobile experts and technology enthusiasts. We understand how precious your mobile device is to you, which is why we're here to the rescue! Our team of professional and highly-qualified technicians promises to have your problems
fixed wherever you are, in no more than 30 minutes.</p>
</div>
<div class="col-md-2 col-xs-12">
<h3>Contact</h3>
<p>Working Hours Everyday (except Fridays & National Holidays)10.00 am to 8.00 pm</p>
<p>Headquarters Ground Floor, Villa 519, A Zone-South of Police AcademyNew Cairo, Egypt</p>
<p>Call us on 010 67 81 81 81</p>
<p>Don't Want to talk? Email us! <EMAIL></p>
</div>
<div class="col-md-3 col-xs-12">
<h3>Follow us</h3>
<i class="fab fa-facebook fa-3x"></i>
<i class="fab fa-instagram fa-3x"></i>
</div>
</div>
</div>
</footer>
<!--End ultimate footer -->
<!-- Jquery CDN -->
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/custom.js"></script>
</body>
</html>
<file_sep>/README.md
# Yallaa_Fix
Yallaafix.com website
<file_sep>/contact.php
<?php
// Check if the user come from POST Request
if($_SERVER['REQUEST_METHOD'] == "POST"){
$user_name = filter_var( $_POST['user'] , FILTER_SANITIZE_STRING);
$email = filter_var($_POST['Email'] , FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST['Phone'] ,FILTER_SANITIZE_NUMBER_INT );
$message = filter_var($_POST['message'] ,FILTER_SANITIZE_STRING);
$un_error = true;
$e_erorr = true;
$p_error = true;
$m_error = true;
$FormErrors = array();
if(strlen($user_name) < 4){
$user_error = "Your user name should be more than or equal 4";
$un_error = true;
$user_name = " ";
}
else {
$un_error = false;
}
if(strlen($email) < 7){
$mail_error = "Please Enter Valid Mail";
$email = " ";
$m_error = true;
}
else {
$m_error = false;
}
if(strlen($phone) < 11){
$phone_error = "Your Phone number should be at least 11 numbers";
$phone = " ";
$p_error = true;
}
else {
$p_error = false;
}
if(strlen($message) < 20){
$message_error = "Your Message Should Contain More Than 20 Characters";
$message = " ";
$m_error = true;
}
else {
$m_error = false;
}
if( $un_error || $m_error || $p_error || $m_error){
}
else {
$success= "<div class='alert alert-success custom-success text-center'><p>We Have Recieved Your Email</p></div>";
$msg = "tset";
mail("<EMAIL>" , "Inquire" ,$msg , "Issues");
$user_name = "";
$email = "";
$phone = "";
$message = "";
}
if (!empty($_POST['subscribe'])) {
$mail = $_POST['email'];
$company_mail = "<EMAIL>";
$subject = "News subbscribtion";
$msg = "this email ".$mail." want to keep updated with your news";
mail($company_mail , $subject , $msg , "news subscribe");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mobile Fixing Company</title>
<link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">
<!-- Font Awesome Library -->
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/contact.css">
<link href="https://fonts.googleapis.com/css?family=Dhurjati" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=BioRhyme+Expanded" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Raleway:400,700,900i" rel="stylesheet">
</head>
<body>
<!-- Start NavBar -->
<nav class="navbar navbar-default navbar-fixed-top ">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#mynavbar" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><p>Yallaa <span>Fix</span></p></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="mynavbar">
<ul class="nav navbar-nav navbar-right">
<li ><a href="index.php">Home <span class="sr-only">(current)</span></a></li>
<li class="active"><a href="#" data-value="footer" class="contact">Contact us</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container -->
</nav>
<!-- End NavBar -->
<!--Start Main Header -->
<!-- <header class="main-header text-center">
<div class="container">
<div class="row">
<div id="content" class="col-xs-12">
<div class="row">
<div class="col-xs-12"><h1>fix your phone in under 30 minutes anywhere <wbr>backed by a Lifetime Warranty</h1></div>
</div>
<div class="row">
<div class="col-xs-12"><button class="btn btn-success order" data-value=".choose-your-phone">Order Now</button></div>
</div>
</div>
</div>
</div>
</header> -->
<!--End Main Header -->
<section class="contact_us text-center">
<div class="container">
<h1 class="text-center"> Contact US</h1>
<?php if(isset($success)){
echo $success;
} ?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST" class="my_form">
<div class="form-group">
<input class="form-control" type="name" name="user" placeholder= "Enter Your Name"
value="<?php if(isset($user_name))echo $user_name ?>" required>
<?php if(isset($user_error)){ ?>
<div class="error alert alert-warning">
<?php echo "<p>" . $user_error ."</p>"; ?>
</div>
<?php } ?>
<div class="alert alert-warning custom-alert"></div>
</div>
<div class="form-group">
<input class="form-control" type="email" name="Email" placeholder="Enter Valid Mail"
required value="<?php if(isset($email))echo $email ?>">
<?php if(isset($mail_error)){ ?>
<div class="error alert alert-warning">
<?php echo "<p>" . $mail_error ."</p>"; ?>
</div>
<?php } ?>
<div class="alert alert-warning custom-alert"><p>Your user name should be more than or equal 4</p></div>
</div>
<div class="form-group">
<input class="form-control" type="tel" name="Phone" value="<?php if(isset($phone))echo $phone ?>"
placeholder="Enter Your Phone" required>
<?php if(isset($phone_error)){ ?>
<div class="error alert alert-warning">
<?php echo "<p>" . $phone_error ."</p>"; ?>
</div>
<?php } ?>
<div class="alert alert-warning custom-alert"><p>Your user name should be more than or equal 4</p></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" value="<?php if(isset($message))echo $message ?>"
placeholder="Enter Your Holder"></textarea>
<?php if(isset($message_error)){ ?>
<div class="error alert alert-warning">
<?php echo "<p>" . $message_error ."</p>"; ?>
</div>
<?php } ?>
<div class="custom-alert alert alert-warning"></div>
</div>
<input class="btn btn-success btn-block" type="submit" value="Send Message">
</form>
</div>
</section>
<!--Start ultimate footer -->
<footer class="ultimate-footer">
<div class="container">
<div class="row">
<div class="col-md-4 col-xs-12">
<img src="images/logo.png" alt="Brand Logo" class="img-responsive">
</div>
<div class="col-md-3 col-xs-12">
<h3>About</h3>
<p>iFix is a new mobile repair concept brought to you by a team of Egyptian mobile experts and technology enthusiasts. We understand how precious your mobile device is to you, which is why we're here to the rescue! Our team of professional and highly-qualified technicians promises to have your problems
fixed wherever you are, in no more than 30 minutes.</p>
</div>
<div class="col-md-2 col-xs-12">
<h3>Contact</h3>
<p>Working Hours Everyday (except Fridays & National Holidays)10.00 am to 8.00 pm</p>
<p>Headquarters Ground Floor, Villa 519, A Zone-South of Police AcademyNew Cairo, Egypt</p>
<p>Call us on 010 67 81 81 81</p>
<p>Don't Want to talk? Email us! <EMAIL></p>
</div>
<div class="col-md-3 col-xs-12">
<h3>Follow us</h3>
<i class="fab fa-facebook fa-3x"></i>
<i class="fab fa-instagram fa-3x"></i>
</div>
</div>
</div>
</footer>
<!--End ultimate footer -->
<!-- Jquery CDN -->
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/custom.js"></script>
<script src="js/contact.js"></script>
</body>
</html>
| 50761e05ffddc0e1dfb3a60ef626fbaea497cf36 | [
"Markdown",
"PHP"
] | 3 | PHP | MahmoudReyad/Yallaa_Fix | b7523b5dd4a777fcef80d48426b2b13063d3c53d | a284b6ba97bccc931f0c6950660c062a4dd58eb1 | |
refs/heads/master | <repo_name>MyCryptoHQ/eth-exists<file_sep>/src/utils/make-request.spec.ts
import { makeHttpRequest } from '@src/utils/make-request';
import moxios from 'moxios';
describe('makeHttpRequest tests', () => {
beforeEach(() => moxios.install());
afterEach(() => moxios.uninstall());
it('should return with a successful request', done => {
makeHttpRequest({
addr: '',
port: 100000,
timeout: 5000,
type: 'http',
}).then(() => {
done();
});
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({ status: 200 });
});
});
it('should return with a failed request', done => {
makeHttpRequest({
addr: '',
port: 100000,
timeout: 5000,
type: 'http',
}).catch(_ => {
done();
});
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWithTimeout();
});
});
});
<file_sep>/src/utils/node-exists.ts
/**
*
* @description Checks if the current engine is nodejs
* @returns {boolean}
*/
function nodeExists(): boolean {
return process.toString() === '[object process]';
}
<file_sep>/src/utils/make-request.ts
import axios, { AxiosResponse } from 'axios';
import WebSocket from 'isomorphic-ws';
export interface IHttpConfig {
type: 'http';
addr: string;
port: number;
timeout: number;
}
export function makeHttpRequest(
config: IHttpConfig,
): Promise<AxiosResponse<any>> {
return axios
.post(
`${config.addr}:${config.port}`,
'{"jsonrpc":"2.0","method":"net_version","params":[],"id":67}',
{
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': '*',
},
timeout: config.timeout,
},
)
.then(r => {
if (r.status !== 200) {
throw Error('Request failed');
}
return r;
});
}
export interface IWSConfig {
type: 'ws';
addr: string;
port: number;
timeout: number;
}
export function makeWsRequest(config: IWSConfig) {
const url = `${config.addr}:${config.port}`;
console.log(url);
const socket = new WebSocket(url, {
handshakeTimeout: config.timeout,
});
return new Promise((resolve, reject) => {
let timeout: NodeJS.Timer;
socket.onopen = () => {
clearTimeout(timeout);
resolve('worked');
};
socket.onerror = e => {
clearTimeout(timeout);
reject(e);
};
timeout = setTimeout(() => {
reject(Error('timeout'));
}, config.timeout);
});
}
export type RequestConfig = IWSConfig | IHttpConfig;
export function makeRequest(config: RequestConfig) {
switch (config.type) {
case 'http':
return makeHttpRequest(config);
case 'ws':
return makeWsRequest(config);
}
}
<file_sep>/readme.md
# eth-exists
A library that helps check for available nodes / providers.
Useful for when you want to check a list of providers and see which ones
are online.
## Usage
```ts
import { exists } from 'mycrypto-eth-exists';
// a provider to see if they're online or not by sending a
// getNetVersion JSON-RPC request to them and checking for a response
const httpProviderToCheck: IHttpConfig = {
type: 'http',
addr: 'http://localhost',
port: 8545,
timeout: 5000,
};
// a provider to see if they're online or not by
// attempting to open a ws connection to that address
const wsProviderToCheck: IWSConfig = {
type: 'ws',
addr: 'ws://localhost',
port: 8546,
timeout: 5000,
};
// array of providers to check
const providersToCheck = [httpProviderToCheck, wsProviderToCheck];
// whether to include the default provider checks
const includeDefaults = false;
async function example() {
// results will contain an array of providers with the same data as the initially declared
// objects above, except they will now have a success parameter included to see if
// they were succesfully connected to or not
// and an error parameter of the error if it failed to connect
const results = await exists(providersToCheck, includeDefaults);
}
```
## Provider Check Defaults
```ts
const DEFAULT_WS: IWSConfig = {
type: 'ws',
addr: 'ws://localhost',
port: 8546,
timeout: 5000,
};
const DEFAULT_HTTP: IHttpConfig = {
type: 'http',
addr: 'http://localhost',
port: 8545,
timeout: 5000,
};
```
<file_sep>/src/index.ts
import {
IHttpConfig,
IWSConfig,
makeRequest,
RequestConfig,
} from './utils/make-request';
const DEFAULT_WS: IWSConfig = {
type: 'ws',
addr: 'ws://localhost',
port: 8546,
timeout: 5000,
};
const DEFAULT_HTTP: IHttpConfig = {
type: 'http',
addr: 'http://localhost',
port: 8545,
timeout: 5000,
};
const DEFAULT_CONFIGS = [DEFAULT_HTTP, DEFAULT_WS];
export type SuccessConfig = RequestConfig & {
success: true;
};
export type FailConfig = RequestConfig & {
success: false;
error: Error;
};
export interface IOptions {
includeDefaults: boolean;
}
export function exists(
configs: RequestConfig[] = [],
opts: IOptions = { includeDefaults: true },
) {
const configsToCheck = [
...configs,
...(opts.includeDefaults ? DEFAULT_CONFIGS : []),
];
const result: Promise<(SuccessConfig | FailConfig)[]> = Promise.all(
configsToCheck.map(c =>
makeRequest(c)
.then(() => ({ ...c, success: true as true }))
.catch(e => ({ ...c, success: false as false, error: e as Error })),
),
);
return result;
}
| 75b646b89d5034aa1e17f55a3faa8dd967964603 | [
"Markdown",
"TypeScript"
] | 5 | TypeScript | MyCryptoHQ/eth-exists | 387310531e77fe95e90ffe042aaf9d17b391a088 | c27db80a012618d73b1cdac779fce3bac4bd9935 | |
refs/heads/main | <repo_name>lmontem/news-explorer-api<file_sep>/constants/constants.js
const userNotFoundMessage = 'User not found';
const articleNotFoundMessage = 'Article not found';
const invalidDataMessage = 'Invalid data';
const duplicateMessage = 'Duplicate Email';
const authMessage = 'Authorization required';
const incorrectMessage = 'Incorrect email or password';
const permissionMessage = 'You do not have permissions';
const deleteMessage = 'Article deleted';
module.exports = {
userNotFoundMessage,
articleNotFoundMessage,
invalidDataMessage,
duplicateMessage,
authMessage,
incorrectMessage,
permissionMessage,
deleteMessage,
};
<file_sep>/README.md
# news-explorer-api
final project backend
API for creating users, signing it, saving and deleting articles
# website
http://api.lmontem-news-explorer.students.nomoreparties.site/
| 2df0ead3a2ac7421890e13f0e8eab37ba03b87f6 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | lmontem/news-explorer-api | b38a8bb67f785e1b8a0d5d5c68b3848f6c9cf4f5 | 16ff76dd4ab2c07c1127ba6cb953a7c5d0d37f71 | |
refs/heads/master | <file_sep>import sys
#I mADE A CHANGE
lower = 1
print "User supplied {} arguments at run time".format(len(sys.argv))
if len(sys.argv) == 1: #array
my_input = raw_input("Enter something, yo!")
else:
my_input = sys.argv[1]
n = int(my_input)
for i in xrange(lower,n):
try:
if i % 15 == 0:
print "fizz buzz"
elif i % 3 == 0:
print "fizz"
elif i % 5 == 0:
print "buzz"
else:
print i
except ValueError:
print ("Need to supply numeric inputs")
| af8465dc990571bcb6ac7b5a9aa305b98af5aefd | [
"Python"
] | 1 | Python | mlitman/FizzBuzzPython | acb19af57bd30f7540f968bf8d57aa6695906095 | c7866dae27f1fea42a97106253198fbbd2225c94 | |
refs/heads/master | <repo_name>casteem/insteem<file_sep>/src/components/StoryList/components/StoryListItem/components/StoryListItemExtra.js
import moment from "moment/moment";
import React from "react";
import steem from "steem";
import styled from "styled-components";
import { Link } from "react-router-dom";
import { Icon, Label } from "semantic-ui-react";
const Container = styled.div`
color: gray;
`;
const StoryListItemExtra = ({ story }) => {
return (
<Container>
{moment.utc(story.created).fromNow()} in{" "}
<Label color="blue" size="small" basic>
{story.category}
</Label>
by <Link to={`/@${story.author}`}>{story.author}</Link>{" "}
<Label circular>
{steem.formatter.reputation(story.author_reputation)}
</Label>
<Icon name="chevron up" /> {story.net_votes}
</Container>
);
};
export default StoryListItemExtra;
<file_sep>/src/services/helpers/filter.js
import _ from "lodash";
import { calculateReputationScore } from "./format";
import { parseMetadata } from "services/helpers/format";
import { contains, reject } from "ramda";
export const containsTag = (json, tag = "") => {
const activeTags = parseMetadata(json).tags;
const bool = contains(tag, activeTags);
return bool;
};
export const rejectByTag = (stories, tags = []) => {
stories = reject(story => containsTag(story.json_metadata, tags))(stories);
return stories;
};
export const filterReputation = (postList = [], maxRep = 75, minRep = 25) => {
return _.reject(postList, post => {
const score = calculateReputationScore(post.author_reputation);
if (score <= maxRep && score >= minRep) return false;
return true;
});
};
// Use all filter options at once.
export const filterAll = (
postList = [],
maxRep,
minRep,
maxChars,
minChars
) => {
return _.reject(postList, post => {
const score = calculateReputationScore(post.author_reputation);
const chars = _.get(post, "body_length");
if (
score <= maxRep &&
score >= minRep &&
chars >= minChars &&
chars <= maxChars
)
return false;
return true;
});
};
<file_sep>/src/scenes/CategoryScene/index.js
export * from "./CategoryScene";
export { default } from "./CategoryScene";
<file_sep>/src/scenes/Mentions/MentionsScene/index.js
export { default } from "./MentionsScene";
<file_sep>/src/components/StoryList/components/StoryListItem/components/StoryListItemMeta.js
import React from "react";
import styled from "styled-components";
import moment from "moment";
import { Link } from "react-router-dom";
import { Label } from "semantic-ui-react";
import steem from "steem";
const Container = styled.div`
color: gray;
font-size: 0.9em;
padding-top: 5px;
`;
const StoryListItemMeta = ({ story }) => {
return (
<Container>
{moment.utc(story.created).fromNow()} in{" "}
<Label color="blue" size="small" basic>
{story.category}
</Label>
by <Link to={`/@${story.author}`}>{story.author}</Link>{" "}
<Label circular>
{steem.formatter.reputation(story.author_reputation)}
</Label>
</Container>
);
};
export default StoryListItemMeta;
<file_sep>/src/scenes/Auth/SigninScene/Signin.scene.js
import React from "react";
import steem from "steem";
import { connect } from "react-redux";
import { signin } from "services/state/auth/actions";
import { Grid, Form, Input, Button, Message } from "semantic-ui-react";
// SignIn Form.
class SignIn extends React.Component {
constructor(props) {
super(props);
this.state = {
username: "",
password: "",
wif: ""
};
}
signin(e) {
e.preventDefault();
const wif = this.state.password;
// const wif = steem.auth.toWif(this.state.username, this.state.password, [
// "posting"
// ]);
const isWif = steem.auth.isWif(wif);
if (!isWif) {
alert("Please use a private posting key!");
return;
}
this.props.onSignin(this.state.username, this.state.password, wif);
}
render() {
return (
<Grid centered>
<Grid.Column width="6">
<Form
style={{ padding: 20, textAlign: "center" }}
onSubmit={e => this.signin(e)}
>
<Form.Field required>
<Input
onChange={event =>
this.setState({ username: event.target.value })
}
value={this.state.username}
placeholder="Username"
required
/>
</Form.Field>
<Form.Field>
<Input
onChange={event =>
this.setState({ password: event.target.value })
}
value={this.state.password}
placeholder="Private Posting Key"
type="password"
required
/>
</Form.Field>
<Button type="submit">Signin</Button>
{/*<Button onClick={e => this.signin(e)}>Signin</Button>*/}
</Form>
</Grid.Column>
<Message>
Insteem uses your private posting key to interact with steem. This key
is stored unencrypted in your browser and can only be used for posting
and voting. Make sure you are only using your posting key. Keep your
active/owner keys safe.
</Message>
</Grid>
);
}
}
const mapStateToProps = (state, ownProps) => {
return {
isSignedIn: state.auth.isSignedIn
};
};
const mapDispatchToProps = dispatch => {
return {
onSignin: (username, password, wif) => {
dispatch(signin(username, password, wif));
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(SignIn);
<file_sep>/src/scenes/StoryScene/components/StoryMetaBox.js
import React from "react";
import { Link } from "react-router-dom";
import { Segment, Label, Icon } from "semantic-ui-react";
import styled from "styled-components";
import moment from "moment";
import { parseMetadata } from "services/helpers/format";
const Author = styled.div`
margin-bottom: 1rem;
`;
const Date = styled.div`
margin-bottom: 1rem;
`;
// Wrap semantic Label Group in styled component.
const Tags = styled(Label.Group)`
margin-bottom: 1rem;
`;
const renderTags = json => {
return parseMetadata(json).tags.map(tag => (
<Label key={tag} basic>
{tag}
</Label>
));
};
const StoryMetaBox = props => {
const { story } = props;
return (
<Segment>
<Author>
<Link to={`/@${story.author}`}>{story.author}</Link>
</Author>
<Date>
{moment(story.created)
.utc()
.format("LLL")}
</Date>
<Tags>{renderTags(story.json_metadata)}</Tags>
<Icon name="chevron circle up" color="green" size="large" />{" "}
{story.net_votes}
</Segment>
);
};
export default StoryMetaBox;
<file_sep>/src/scenes/Layout/Layout.js
import React from "react";
import styled from "styled-components";
const Container = styled.div`
min-height: 100%;
background-color: #f9f9f9;
`;
const Layout = props => {
return <Container>{props.children}</Container>;
};
export default Layout;
<file_sep>/src/dsteem.client.js
import { Client } from "dsteem";
const client = new Client("https://api.steemit.com");
export default client;
<file_sep>/src/scenes/CategoryScene/CategoryScene.js
import React from "react";
import StoryList from "components/StoryList/StoryList";
import { rejectByTag } from "services/helpers/filter";
import { graphql } from "react-apollo";
import gql from "graphql-tag";
import { Loader, Grid } from "semantic-ui-react";
import Meta from "components/Meta";
import HowToBox from "components/Layout/HowToBox";
import FeaturedBox from "scenes/Index/components/FeaturedBox";
import AboutBox from "components/Layout/AboutBox";
const CategoryScene = props => {
let { data: { loading, getDiscussions: stories }, match } = props;
if (loading) return <Loader active />;
// Hide `nsfw` stories.
stories = rejectByTag(stories, "nsfw");
return (
<Grid stackable>
<Meta
data={{
title:
match.params.category[0].toUpperCase() +
match.params.category.slice(1)
}}
/>
<Grid.Column width={10}>
{<StoryList stories={stories || []} />}
</Grid.Column>
<Grid.Column width={6}>
<HowToBox />
<br />
<FeaturedBox />
<br />
<AboutBox />
</Grid.Column>
</Grid>
);
};
const QUERY = gql`
query discussions($category: String = "news") {
getDiscussions(by: "hot", query: { tag: $category }) {
id
title
body
author
author_reputation
net_votes
category
permlink
json_metadata
created
}
}
`;
export default graphql(QUERY, {
options: ({ match }) => ({
variables: { category: match.params.category },
pollInterval: 1000 * 60 * 5 // 5 min
})
})(CategoryScene);
<file_sep>/src/scenes/Index/index.js
export {default} from './IndexScene'
<file_sep>/src/components/Profile/components/ProfileDetails.js
import React from "react";
import _ from "lodash";
import { userData } from "services/helpers/format";
import { Segment, List } from "semantic-ui-react";
// import ExternalLink from "components/Elements/ExternalLink";
const renderVotingPower = vp => {
return vp / 100;
};
const ProfileDetails = ({ user }) => {
return (
<Segment>
<List horizontal>
<List.Item>{_.get(userData(user), "name")}</List.Item>
<List.Item>{_.get(userData(user), "location")}</List.Item>
<List.Item>{_.get(userData(user), "about")}</List.Item>
<List.Item>
{/*<ExternalLink url={_.get(userData(user), "website")} value="test" />*/}
Voting Power: {renderVotingPower(user.voting_power)}
</List.Item>
</List>
</Segment>
);
};
export default ProfileDetails;
<file_sep>/src/scenes/Profile/ProfileScene.js
import React from "react";
import { isNil } from "ramda";
import { userImage } from "services/helpers/format";
import { graphql } from "react-apollo";
import gql from "graphql-tag";
import steem from "steem";
import Loader from "../../components/Loader";
import ProfileDetails from "components/Profile/components/ProfileDetails";
import StoryList from "components/StoryList/StoryList";
import { Image, Label } from "semantic-ui-react";
// import ExternalLink from "components/Elements/ExternalLink";
class ProfileScene extends React.Component {
render() {
const {
data: {
loading,
account: user,
getDiscussionsByAuthorBeforeDate: stories
}
} = this.props;
if (loading) return <Loader />;
if (isNil(user)) return null;
return (
<div>
<h1>
<Image src={userImage(user)} avatar />
{user.name}{" "}
<Label circular size="big">
{steem.formatter.reputation(user.reputation)}
</Label>
{/*<FavoriteButton username={user.name} />{" "}*/}
{/*<ExternalLink url={`https://steemit.com/@${user.name}`}>*/}
{/*<Icon name="share" />*/}
{/*</ExternalLink>{" "}*/}
</h1>
<ProfileDetails user={user} />
<StoryList stories={stories} />
</div>
);
}
}
const QUERY = gql`
query user($username: String!) {
account(username: $username) {
id
name
json_metadata
created
reputation
voting_power
}
getDiscussionsByAuthorBeforeDate(author: $username) {
id
title
body
author
author_reputation
net_votes
category
permlink
json_metadata
created
}
}
`;
export default graphql(QUERY, {
options: ({ match }) => ({
variables: { username: match.params.username },
// Polling: 1min
pollInterval: 60 * 1000
})
})(ProfileScene);
<file_sep>/src/components/StoryList/components/StoryListItem/components/StoryListItemBody.js
import React from "react";
import PropTypes from "prop-types";
import ellipsis from "text-ellipsis";
import striptags from "striptags";
import Remarkable from "remarkable";
const remarkable = new Remarkable({ html: true });
function decodeEntities(body) {
return body.replace(/</g, "<").replace(/>/g, ">");
}
const BodyShort = props => {
let body = striptags(
remarkable.render(striptags(decodeEntities(props.body)))
);
body = body.replace(/(?:https?|ftp):\/\/[\S]+/g, "");
// If body consists of whitespace characters only skip it.
if (!body.replace(/\s/g, "").length) {
return null;
}
return (
<div
dangerouslySetInnerHTML={{
__html: ellipsis(body, props.length, { ellipsis: "…" })
}}
/>
);
};
BodyShort.propTypes = {
body: PropTypes.string,
length: PropTypes.number
};
BodyShort.defaultProps = {
body: "",
length: 200
};
export default BodyShort;
<file_sep>/src/components/User/ReputationLabel.js
import React from "react";
import steem from "steem";
import { Label as UnstyledLabel } from "unstyled";
const Label = UnstyledLabel.extend`
background-color: #e8e8e8;
font-size: 0.85rem;
min-width: 2em;
min-height: 2em;
padding: 0.5em !important;
line-height: 1em;
text-align: center;
border-radius: 500rem;
`;
const ReputationLabel = ({ reputation }) => {
return (
<Label title="Reputation">{steem.formatter.reputation(reputation)}</Label>
);
};
export default ReputationLabel;
<file_sep>/src/scenes/Mentions/MentionsScene/MentionsScene.js
import React from "react";
import { graphql } from "react-apollo";
import gql from "graphql-tag";
import Loader from "components/Loader";
import MentionItem from "./components/MentionItem";
import MentionPagination from "./components/MentionPagination";
const MentionsScene = props => {
const { data: { loading, mentions }, match } = props;
if (loading) return <Loader />;
return (
<div>
<h3>Total Mentions: {mentions.hits}</h3>
<MentionPagination mentions={mentions} username={match.params.username} />
{mentions.results.map(mention => (
<MentionItem
key={mention.permlink + mention.created}
mention={mention}
/>
))}
</div>
);
};
const Query = gql`
query getMentions($username: String!, $page: Int = 1) {
mentions(username: $username, page: $page) {
hits
results {
author
created
permlink
summary
title
type
}
}
}
`;
export default graphql(Query, {
options: ({ match }) => ({
variables: {
username: match.params.username,
page: match.params.page
}
})
})(MentionsScene);
<file_sep>/src/components/StoryList/StoryList.js
import React from "react";
import { map } from "ramda";
import { Item } from "semantic-ui-react";
import StoryListItem from "./components/StoryListItem";
const StoryList = props => {
const { stories } = props;
return (
<Item.Group relaxed divided>
{map(story => <StoryListItem key={story.id} story={story} />)(stories)}
</Item.Group>
);
};
export default StoryList;
<file_sep>/src/scenes/Static/AboutScene.js
import React from "react";
import Remarkable from "remarkable";
import styled from "styled-components";
const md = new Remarkable({
html: true, // remarkable renders first then sanitize runs...
breaks: false,
linkify: false, // linkify is done locally
typographer: false, // https://github.com/jonschlinkert/remarkable/issues/142#issuecomment-221546793
quotes: "“”‘’"
});
const markdown = `
# About Insteem
Insteem will become a decentralised, rewarding news platform for
independent journalism and create an international network of
journalists, away from MSM.
Our goal is to spread high quality, uncensored, undeletable news from all over the world,
by independent journalists and writers.
## How will it work?
* Journalists/Writers post their stories via Insteem
* Insteem will check new stories for plagiarism and show that next to a story (it won’t prevent publishing though, unless it's considered spam)
* Insteem will automatically vote on stories depending on an internal rating system (score) of journalists (multiple factors like e.g. reputation, length of story, unique content, spam level etc.)
* The voting will happen (near) instant, to bring news from quality writers to the top immediately
* This will be combined with manual upvoting through our Editors
* There will be different kind of templates for articles to post, like daily (short) news,
extensive stories or opinionated articles
`;
const Text = styled.div`
font-size: 16px;
color: rgba(0, 0, 0, 0.7);
`;
const AboutScene = props => {
return (
<Text>
<div dangerouslySetInnerHTML={{ __html: md.render(markdown) }} />
</Text>
);
};
export default AboutScene;
<file_sep>/src/components/Menu/CategoryMenu.js
import React from "react";
import { Link } from "react-router-dom";
import { Container, Menu, Dropdown } from "semantic-ui-react";
const CategoryMenu = () => {
return (
<Menu widths={11} stackable style={styles.menu}>
<Container>
<Menu.Item as={Link} to={"/categories/world"}>
World
</Menu.Item>
<Menu.Item as={Link} to={"/categories/politics"}>
Politics
</Menu.Item>
<Menu.Item as={Link} to={"/categories/business"}>
Business
</Menu.Item>
<Menu.Item as={Link} to={"/categories/technology"}>
Tech
</Menu.Item>
<Menu.Item as={Link} to={"/categories/science"}>
Science
</Menu.Item>
<Menu.Item as={Link} to={"/categories/health"}>
Health
</Menu.Item>
<Menu.Item as={Link} to={"/categories/sports"}>
Sports
</Menu.Item>
<Menu.Item as={Link} to={"/categories/art"}>
Arts
</Menu.Item>
<Menu.Item as={Link} to={"/categories/travel"}>
Travel
</Menu.Item>
<Menu.Item as={Link} to={"/categories/cryptocurrency"}>
Crypto
</Menu.Item>
<Dropdown item text="more">
<Dropdown.Menu>
<Dropdown.Item as={Link} to={"/categories/style"}>
Style
</Dropdown.Item>
<Dropdown.Item as={Link} to={"/categories/food"}>
Food
</Dropdown.Item>
<Dropdown.Item as={Link} to={"/categories/opinion"}>
Opinion
</Dropdown.Item>
<Dropdown.Item as={Link} to={"/categories/photography"}>
Photography
</Dropdown.Item>
<Dropdown.Item as={Link} to={"/categories/philosopy"}>
Philosophy
</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</Container>
</Menu>
);
};
export default CategoryMenu;
const styles = {
menu: {
marginBottom: 20
}
};
<file_sep>/src/services/helpers/format.js
import steem from "steem";
import _ from "lodash";
import { isNil } from "ramda";
/**
* Take the author_score from steem and convert it in a human readable score.
* @param reputation
* @return {number}
*/
export const calculateReputationScore = reputation => {
return steem.formatter.reputation(reputation);
};
/**
* Parse the `json_metadata` property from steem.
* @param json - string to parse into JSON format.
*/
export const parseMetadata = json => {
// Check if JSON string is not empty otherwise `parse` will fail.
if (json.length > 0) {
return JSON.parse(json);
}
return "";
};
// Get profile picture for user.
export const userImage = user => {
if (isNil(user)) return;
const image = _.get(JSON.parse(user.json_metadata), "profile.profile_image");
if (_.isEmpty(image)) return null;
return image;
};
// Get JSON formatted profile data for user.
export const userData = user => {
return _.get(parseMetadata(user.json_metadata), "profile");
};
<file_sep>/src/scenes/Journalists/JournalistsScene/index.js
export { default } from "./JournalistsScene";
<file_sep>/README.md
# Insteem - The News on Steem
Insteem rewards independant journalists on steem.
## Insteem Web/App
This is the web frontend for the Insteem project.
For the mobile app see: [insteem-app](https://github.com/Insteem/insteem-app)
## Mission
Insteem will become the platform and community for independent journalismn on steem.
## Ideas
Ideas:
* Dedicated Web and Mobile Apps (Insteem and Insteem Mobile, something similar to utopian-ui)
* Curation Trails
* BidBot for news stories
* Resteem service for high quality news
* Feature posts of great veteran or upcoming journalists
* SP Delegation for Voting
* Writing/Audio/Video competitions
* Post promotion
* Coaching for upcoming or promising journalists(edited)
<file_sep>/src/scenes/StoryScene/index.js
export * from "./StoryScene";
export { default } from "./StoryScene";
<file_sep>/src/scenes/Journalists/JournalistsScene/JournalistsScene.js
import React from "react";
import { Grid, Header, Label, Card, Button, Icon } from "semantic-ui-react";
import { map } from "ramda";
import { Link } from "react-router-dom";
const journalists = [
{
name: "adamcarter",
desc: "Writes about technical stuff at Disobedient Media.",
tags: ["technology"],
location: "USA"
},
{
name: "ameliabartlett",
desc:
"Writer and Photographer from East Tennessee" +
" covering all aspects of life and supports women via" +
" @ladiesofsteemit.",
tags: ["photography", "womanpower", " ladiesofsteemit"],
location: "Knoxville, TN, US"
},
{
name: "cyberwarrior",
desc:
"Blogger and crypto expert. Covers a wide" +
" spectrum from politics, technology up to food.",
tags: ["politics", "technology", "life"]
},
{
name: "didic",
desc:
"Recovering journalist from Israel, currently writing" +
" about" +
" geeky books, nerdy entertainment, and social justice.",
tags: ["books", "tv", "film", "culture"],
location: "Israel"
},
{
name: "eleanorgoldfield",
desc:
"Socio-political engaged activist," +
" journalist and poet from Washington. Hosts the daily show `Act out.`",
tags: ["politics", "science"],
location: "Washington, D.C., US"
},
{
name: "elizbethleavos",
desc:
"Independent journalists" +
" from Disobedient Media. Covers" +
" politics and freedom of speech.",
tags: ["politics", "wikileaks"],
location: "USA"
},
{
name: "fedescholari",
desc:
"Italian (?) writer covering business, crypto" +
" and money related topics ",
tags: ["cryptocurrency", "money", "china"]
},
{
name: "greenmask9",
desc:
" New author from the Czech Republic. Covers health," +
" psychology, sports and politics.",
tags: ["health", "politics", "sports", " psychology"],
location: "Czech" + " Republic"
},
{
name: "johnvibes",
desc:
"Author and researcher who writes for numerous" +
" alternative" +
" media websites, including The Free Thought Project and The Mind" +
" Unleashed, covering topics relating to government and police" +
" corruption, the drug war and consciousness. In addition to his" +
" activist work, he also hosts various live events, including the Free" +
" Your Mind Conference.",
tags: ["politics", "society", "corruption"],
location: "USA"
},
{
name: "joshsigurdson",
desc:
'Journalist at World Alternative Media. Does video" +\n' +
' " interviews on DTube, talks about money, crypto and business.',
tags: ["business", "politics", "cryptocurrency"],
location: "Winnipeg, Canada"
},
{
name: "leecamp",
desc:
'Journalist from Washington. Host of "Redacted' +
' Tonight", a comedy show on Youtube (so far).',
tags: ["comedy", "politics", "life"],
location: "Washington,D.C., US"
},
{
name: "lilyraabe",
desc:
"Working artist, business consultant, and entrepeneur" +
" currently developing business strategy and content for 6 nonprofit" +
" clients, and 5 independent artists. Her goal is to help artists thrive" +
" on and off the Blockchain. Arts Editor of Insteem",
tags: ["arts", "society", "politics"],
location: "Seattle, US"
},
{
name: "news2share",
desc:
"An online media team from Washington. Range from" +
" local, national to international politics",
tags: ["politics", "technology"],
location: "Washington,D.C., US"
},
{
name: "ocupation",
desc:
"Writes about everything that comes to his mind," +
" gaming, conspiracy, photography, health and so on.",
tags: ["politics", "geoengineering", "conspiracy"]
},
{
name: "patricklancaster",
desc:
"Video and photo journalists. Reports exclusively about the war in" +
" Ukrain",
tags: ["politics", "war", "ukraine"],
location: "Ukraine"
},
{
name: "travelwithus",
desc:
"Young family traveling the world and reporting their adventures" +
" while conquering new countries.|",
tags: ["travel", "life", "photography"],
location: "Everywhere"
},
{
name: "yahialababidi",
desc:
"Author of 7 books & published in international" +
" magazines and newspapers. As an Egyptian-American, he touches on" +
" immigration, Islamophobia & other cultural issues, in addition to covering" +
" literature & philosophical/spiritual matters.",
tags: ["society", "politics", "culture", "philosophy"]
}
];
const blockedJournalists = [
{
name: "sarahlouise",
desc:
"Posts daily news about anything. The level of english in the" +
" articles doesn't fit with the one in the comments and e.g. the" +
" `introduceyourself` post. No plagiarism detected so far.",
tags: []
}
];
const renderTags = map(label => (
<Label key={label} color="green">
{label}
</Label>
));
const renderJournalists = map(user => (
<Card key={user.name}>
<Card.Content>
<Card.Header as={Link} to={`/@${user.name}`}>
{user.name}
</Card.Header>
<Card.Meta>{user.location}</Card.Meta>
<Card.Description>{user.desc}</Card.Description>
</Card.Content>
<Card.Content extra>
<Button
icon
floated="right"
size="tiny"
color="blue"
as="a"
href={`https://steemit.com/@${user.name}`}
target="_blank"
>
<Icon name="external share" />
</Button>
<Label.Group size="small">{renderTags(user.tags)}</Label.Group>
</Card.Content>
</Card>
));
const JournalistsScene = () => {
return (
<Grid centered columns={1}>
<Grid.Column>
<Header>Journalists and Writers (Approved)</Header>
<Card.Group itemsPerRow={3}>
{renderJournalists(journalists)}
</Card.Group>
<Header>Unapproved Journalists </Header>
<Card.Group>{renderJournalists(blockedJournalists)}</Card.Group>
</Grid.Column>
</Grid>
);
};
export default JournalistsScene;
<file_sep>/src/services/state/reducers.js
/*
This file controls the shape of the default state.
It imports all the various reducers and combines them using the
`combineReducers()` API from redux.
*/
import { combineReducers } from "redux";
import auth from "./auth/reducer";
// import post from "./posts/reducer";
// import tags from "./tags/reducer";
// import rehydrated from "./rehydrated/reducer";
const reducer = combineReducers({
auth
// post,
// tags,
// rehydrated
});
export default reducer;
<file_sep>/src/scenes/StoryScene/StoryScene.js
import React from "react";
import client from "dsteem.client";
import { lifecycle } from "recompose";
import { head, propOr } from "ramda";
import { Grid, Header, Image } from "semantic-ui-react";
import Markdown from "react-markdown";
import { parseMetadata } from "services/helpers/format";
import styled from "styled-components";
import Meta from "components/Meta";
import StoryBody from "./components/StoryBody";
import StoryMeta from "./components/StoryMeta";
import StoryMetaBox from "./components/StoryMetaBox";
const Container = styled.div`
overflow: hidden;
margin-bottom: 10rem;
`;
const CoverImage = styled.div`
margin-bottom: 1rem;
`;
const Content = styled.div`
font-size: 1.3rem;
font-weight: 300;
color: hsla(0, 0%, 0%, 0.6);
`;
const StoryScene = props => {
const { story } = props;
if (!story) return <div />;
// Get images from story object
const images = propOr([], "image")(parseMetadata(story.json_metadata));
const image = head(images);
return (
<Container>
<Meta data={story} />
<Grid>
<Grid.Column width={11}>
<Header>{story.title}</Header>
<StoryMeta story={story} />
{/*<CoverImage>{image ? <Image src={image} /> : <div />}</CoverImage>*/}
<Content>
<StoryBody body={story.body} />
{/*<Markdown*/}
{/*source={story.body}*/}
{/*skipHtml={false}*/}
{/*escapeHtml={false}*/}
{/*disallowedTypes={["image"]}*/}
{/*/>*/}
</Content>
</Grid.Column>
<Grid.Column width={5}>
<StoryMetaBox story={story} />
</Grid.Column>
</Grid>
</Container>
);
};
export default lifecycle({
componentWillMount() {
const { author, permlink } = this.props.match.params;
console.log(author, permlink);
client.database
.getDiscussions("blog", {
tag: author,
limit: 1,
start_author: author,
start_permlink: permlink
})
.then(stories => {
this.setState({ story: head(stories) });
});
}
})(StoryScene);
<file_sep>/src/components/User/UserLink.js
import React from "react";
import { Link as ReactLink } from "react-router-dom";
import styled from "styled-components";
const Link = styled(ReactLink)`
display: block;
margin-bottom: 0.5rem;
`;
const UserImage = styled.div`
display: inline-block;
height: 2rem;
width: 2rem;
border-radius: 50%;
background-image: url(${props => props.image});
background-size: cover;
margin-right: 0.75rem;
vertical-align: middle;
`;
const UserLink = ({ user }) => {
return (
<Link to={`/@${user.name}`}>
<UserImage image={user.profile.profile_image} />
{user.name}
{/*<ReputationLabel reputation={user.reputation} />*/}
</Link>
);
};
export default UserLink;
<file_sep>/src/scenes/Static/RulesScene.js
import React from "react";
import Remarkable from "remarkable";
import styled from "styled-components";
const md = new Remarkable({
html: true, // remarkable renders first then sanitize runs...
breaks: false,
linkify: false, // linkify is done locally
typographer: false, // https://github.com/jonschlinkert/remarkable/issues/142#issuecomment-221546793
quotes: "“”‘’"
});
const markdown = `
# Rules
* To be considered for an upvote/resteem of @insteem and members,
add the tag 'insteem' to your story.
* Optional: Add 'Powered by [Insteem](https://www.insteem.com)',
the News on Steem at the end of your story,
it will improve your chances for upvotes/resteem
* If your story doesn't fit our standards, we'll ask you to remove it
* Only articles with full source of the information will be considered
* Only articles which are your own IP will be considered
`;
const Text = styled.div`
font-size: 16px;
color: rgba(0, 0, 0, 0.7);
`;
const RulesScene = props => {
return (
<Text>
<div dangerouslySetInnerHTML={{ __html: md.render(markdown) }} />
</Text>
);
};
export default RulesScene;
<file_sep>/src/components/Layout/AboutBox.js
import React from "react";
import { Segment, Header } from "semantic-ui-react";
import { Link } from "react-router-dom";
const AboutBox = () => {
return (
<div>
<Header attached="top">
<Link to="/about">About </Link>
</Header>
<Segment attached="bottom">
Insteem will become a decentralised, rewarding news platform for
independent journalism and create an international network of
journalists, away from MSM.
<br />
<Link to="/rules">Rules</Link>
</Segment>
</div>
);
};
export default AboutBox;
<file_sep>/src/components/Menu/MainMenu.js
import React from "react";
import { connect } from "react-redux";
import { signout } from "services/state/auth/actions";
import { Link } from "react-router-dom";
import { Container, Menu, Image } from "semantic-ui-react";
import styled from "styled-components";
import AccountMenu from "components/Menu/AccountMenu";
import SigninModal from "scenes/Auth/SigninModal";
const Title = styled.span`
padding-left: 100px;
color: darkgray;
text-align: right;
`;
const MainMenu = props => {
const { isSignedIn } = props;
return (
<Menu borderless stackable fixed="top" style={styles.menu} size="large">
<Container>
<Menu.Item as={Link} to={"/"}>
<Image
inline
style={{ height: 30, width: 30 }}
shape="rounded"
src="/insteem.png"
/>
{" "}
<span style={styles.brand}>
INSTEEM <span style={styles.brand.beta}>beta</span>
</span>
<Title>Decentralized News by Independent Journalists</Title>
</Menu.Item>
{/*<Menu.Item as={Link} to="/comments">*/}
{/*Comments*/}
{/*</Menu.Item>*/}
{/*<Menu.Item as={Link} to="/messages">*/}
{/*Messages*/}
{/*</Menu.Item>*/}
{/*<Menu.Item as={Link} to="/mentions">*/}
{/*Mentions*/}
{/*</Menu.Item>*/}
<Menu.Menu position="right" />
<Menu.Menu position="right">
{isSignedIn ? (
<AccountMenu />
) : (
<Menu.Item link>
<SigninModal />
</Menu.Item>
)}
</Menu.Menu>
</Container>
</Menu>
);
};
const mapStateToProps = state => {
return {
isSignedIn: state.auth.isSignedIn
};
};
const mapDispatchToProps = dispatch => {
return {
onSignout: () => {
dispatch(signout());
}
};
};
// export default connect(null, mapDispatchToProps)(MainMenu);
export default connect(mapStateToProps, mapDispatchToProps)(MainMenu);
const styles = {
menu: {
marginBottom: 20
},
brand: {
fontWeight: "bold",
fontSize: 26,
beta: { fontSize: 11 }
}
};
<file_sep>/src/scenes/Auth/SigninScene/index.js
export { default } from "./Signin.scene";
<file_sep>/src/services/helpers/image.js
const IMG_PROXY = "https://steemitimages.com/0x0/";
const IMG_PROXY_PREVIEW = "https://steemitimages.com/600x800/";
export const getProxyImageURL = (url, type) => {
if (type === "preview") {
return `${IMG_PROXY_PREVIEW}${url}`;
}
return `${IMG_PROXY}${url}`;
};
export default null;
<file_sep>/src/components/Meta.js
import React from "react";
import { Helmet } from "react-helmet";
import logo from "components/Layout/insteem.png";
const Meta = props => {
const { data = {} } = props;
const { title } = data || "Insteem";
const {
body: description = "Decentralized News by Independent Journalists"
} = data;
const path =
"/" + data.category + "/@" + data.author + "/" + data.permlink || "";
return (
<Helmet titleTemplate="%s | Insteem" defaultTitle="Insteem">
<title>{title}</title>
<meta name="description" content={description} />
<meta name="keywords" content={title} />
<meta name="author" content={data.author} />
<meta name="og:title" content={title} />
<meta name="og:description" content={data.description} />
<meta name="og:image" content={logo} />
{data.image ? <meta name="og:image" content={data.image.url} /> : null}
<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="@GatsbyCentral" />
<meta name="twitter:image" content={logo} />
<link rel="canonical" href={`https://www.steemit.com${path}`} />
<link rel="image_src" href={logo} />
</Helmet>
);
};
export default Meta;
<file_sep>/src/components/Layout/HowToBox.js
import React from "react";
import styled from "styled-components";
import { Header, Segment, Label } from "semantic-ui-react";
const LI = styled.li`
margin: 0.4rem;
`;
const HowToBox = props => {
return (
<div>
<Header attached="top">How to</Header>
<Segment attached="bottom">
<ul>
<LI>
Write your story on the steem frontend of your choice. Posting will
be coming soon.
</LI>
<LI>
Use{" "}
<Label color="blue" basic>
news
</Label>{" "}
as the first tag
</LI>
<LI>
Use{" "}
<Label color="blue" basic>
insteem
</Label>{" "}
to qualify for an upvote of @insteem.{" "}
</LI>
<LI>Use at least one of the tags from the main menu</LI>
</ul>
</Segment>
</div>
);
};
export default HowToBox;
| 5ad4b5fb54f3b51a056f0953b321ad476182d87a | [
"JavaScript",
"Markdown"
] | 34 | JavaScript | casteem/insteem | 9572b49c15ca2590de3083a572930db44817adc6 | a2e60f6bcdaba50786dd5b3cd53d58868b464b31 | |
refs/heads/master | <repo_name>jcap49/clipit<file_sep>/db/migrate/20130415200037_add_photo_attachment_to_clips_table.rb
class AddPhotoAttachmentToClipsTable < ActiveRecord::Migration
def self.up
add_attachment :clips, :photo
end
def self.down
remove_attachment :clips, :photo
end
end
<file_sep>/spec-week4-14.md
ClipIt Spec - 4/14-4/20
To-do:
-fix menu js errors
-finish clip partial css styling
-create a flash error for false password login attempt
Done (as of 4/21):
Miscellaneous:
-registered for YouTube application API (via google code)
-implemenet user authentication via devise
-wrote home copy
-wrote about copy
-fix delete clip bug
-figure out how to constrain photo size
-fix mailer to send forgot password message
-fix create clip bug with "unless rendering" thing
-refactor clips/show & /examples into a partial
-error messages
-error chrome is ugly as hell
-better formatting for clips/show
-home:
-needs formatting
-about:
-needs formatting
-create:
-"Create photo" button needs to be hidden
-fix footer (change from fixed to absolute and position properly)
Views:
-implement mock ups (use some previous work as well)
-home
-create
-edit/view
-finish implementing clip/example
-how to extract "random" clips from database
-adjust appropriate views to accomodate music syncing portion
Models:
-create a clip model
-has title, body, (other attributes)
-has_many photos
Controllers:
-static pages
-handles home page (and any other future static pages)
-clip controller
-handles creation of clip
-photo upload
-body (text) of clip submission
-finish implementing user auth
-fix "your clips page" (css tweaks)
-check to make sure login/logout scenarios ok
-test login/logout/recover password
-think about building an admin page
-need a 404 error for /clips when not signed in
-implement music syncing feature (see youtube api hack)
-finish implementing jquery dropdown with api
-clip controller
-music sync
-use iframe api to load player (& hide controls - see docs for more info)
-use youtube data api to search for youtube videos
(youtube video id on the backend - which then gets passed to iframe api to load/play video)
<file_sep>/spec/requests/clips_pages_spec.rb
require 'spec_helper'
describe "ClipsPages" do
subject { page }
let(:user) { FactoryGirl.create(:user) }
before { sign_in user }
describe "clip creation" do
before { visit new_clip_path }
describe "with invalid information" do
it "should not create a clip" do
expect { click_button "Create" }.not_to change(Clip, :content)
end
describe "error messages" do
before { click_button "Post" }
it { should have_content('error') }
end
end
describe "with valid information" do
before { fill_in 'clip_content', with: "lorem ipsum" }
it "should create a clip" do
expect { click_button "Post" }.to change(Clip, :count).by(1)
end
end
end
describe "micropost destruction" do
before { FactoryGirl.create(:clip, user: user) }
describe "as correct user" do
before { visit clips_path }
it "should delete a micropost" do
expect { click_link "delete" }.to change(Clip, :count).by(-1)
end
end
end
end
<file_sep>/spec/models/clip_spec.rb
require 'spec helper'
describe clip do
let(:user) { FactoryGirl.create(:user) }
before { @clip = user.clips.build(content: "Lorem ipsum") }
subject { @clip }
it { should respond_to(:user_id) }
it { should respond_to(:user) }
it { should respond_to(:unique_url) }
it { should respond_to(:slug) }
it { should respond_to(:photo) }
it { should respond_to(:body) }
it { should respond_to(:user_id) }r
it { should respond_to(:song) }
its(:user) { should == user }
it { should be_valid }
describe "accessible attributes" do
it "should not allow access to user_id" do
expect do
Clip.new(user_id: user.id)
end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
end
end
describe "when user_id is not present" do
before { @clip.user_id = nil }
it { should_not be_valid }
end
describe "with blank content" do
before { @clip.content = " " }
it { should_not be_valid }
end
describe "with content that is too long" do
before { @clip.content = "a" * 141 }
it { should_not be_valid }
end
end
<file_sep>/spec/requests/static_pages_spec.rb
require 'spec_helper'
describe "Static pages" do
let(:base_title) {"Clip.It - the easiest way to share the soundtrack of your memories"}
subject { page }
describe "Home page" do
before { visit root_path }
it_should_behave_like "all static pages"
it { should have_selector 'title' }
end
describe "Why page" do
before { visit why_path }
it_should_behave_like "all static pages"
it { should have_selector 'title' }
end
describe "Examples" do
before { visit example_path }
it_should_behave_like "all static pages"
it { should have_selector 'title'}
end
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :yt_client
private
def yt_client
@yt_client ||= YouTubeIt::Client.new(:dev_key => "<KEY>")
end
end
<file_sep>/app/models/admin.rb
class Admin < ActiveRecord::Base
devise :database_authenticatable, :rememberable
attr_accessible :email, :password, :password_confirmation, :god_mode, :reports_only
end
<file_sep>/app/models/clip.rb
class Clip < ActiveRecord::Base
extend FriendlyId
friendly_id :title , :use => :slugged
belongs_to :user
# Attrs
attr_accessible :user_id, :title, :body, :photo, :slug, :unique_url, :song, :song_id
has_attached_file :photo, :styles => {
:small => "160x160>",
:large => "525x525>"}
# Validations
validates :title, presence: true, length: {maximum: 250}
validates :body, presence: true, length: {maximum: 1000}
#TO-DO: add presence validator back to photo before pushing live
validates :slug, presence: true
validates :song, presence: true
# TO-DO: add a song attr & migration
end
<file_sep>/db/migrate/20130415185243_add_body_to_clips_table.rb
class AddBodyToClipsTable < ActiveRecord::Migration
def change
add_column :clips, :body, :string
end
end
<file_sep>/app/controllers/clips_controller.rb
class ClipsController < ApplicationController
before_filter :authenticate_user!, only: [:edit, :index, :destroy]
def index
@clips = current_user.clips
@users = User.all
end
def show
@clip = Clip.find(params[:id])
@video = yt_client.videos_by(:query => @clip.song, :max_results => "1", :format => "5", :autoplay => "1", :controls => "2")
@html_for_video = @video.videos
@e_video = @html_for_video.collect {|video| video.embed_html5(:url_params => {:autoplay => "1"})}
respond_to do |format|
format.html
format.json { render json: @clip }
end
end
def new
@clip = Clip.new
respond_to do |format|
format.html
format.json { render json: @clip }
end
end
def edit
@clip = Clip.find(params[:id])
end
def create
if user_signed_in?
@clip = current_user.clips.build(params[:clip])
if @clip.save
redirect_to @clip, notice: 'Clip was successfully created.'
else
render new_clip_path
end
else
@clip = Clip.new(params[:clip])
if @clip.save
redirect_to @clip, notice: 'Clip was successfully created.'
else
render new_clip_path
end
end
end
def update
@clip = Clip.find(params[:id])
respond_to do |format|
if @clip.update_attributes(params[:clip])
format.html { redirect_to @clip, notice: 'Clip was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @clip.errors, status: :unprocessable_entity }
end
end
end
def destroy
@clip = Clip.find(params[:id])
@clip.destroy
respond_to do |format|
format.html { redirect_to clips_url }
format.json { head :no_content }
end
end
def example
@clip = Clip.limit(1).offset(rand(Clip.count)).first
@video = yt_client.videos_by(:query => @clip.song, :max_results => "1", :format => "5", :autoplay => "1")
@html_for_video = @video.videos
@e_video = @html_for_video.collect {|video| video.embed_html5(:url_params => {:autoplay => "1"})}
end
def video_results
@videos = yt_client.videos_by(:query => params[:term], :max_results => "1", :format => "5")
display_video_results
end
#TO-DO add save feature for song
#implement appropriate embed view for clips/show
def display_video_results
@results = @videos.videos
@results.collect! {|video| video.title}
render :json => @results
end
end
<file_sep>/config/routes.rb
ClipIt::Application.routes.draw do
devise_for :users
resources :clips, only: [:new, :create, :show, :edit, :index, :destroy, :update] do
collection do
get :video_results
end
end
match '/admins/dashboard', to: 'admins#dashboard'
match '/example', to: 'clips#example'
match '/why', to: 'static_pages#why'
root to: 'static_pages#home'
end
<file_sep>/app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController
def home
@clip = Clip.limit(1).offset(rand(Clip.count)).first
@video = yt_client.videos_by(:query => @clip.song, :max_results => "1", :format => "5", :autoplay => "1")
@html_for_video = @video.videos
@e_video = @html_for_video.collect {|video| video.embed_html5(:url_params => {:autoplay => "1"})}
end
def why
end
end
<file_sep>/Gemfile
source 'https://rubygems.org'
gem 'rails', '3.2.12'
gem 'pg'
gem 'paperclip', '3.4.1'
gem 'friendly_id', "~> 4.0.9"
gem 'youtube_it'
gem 'devise'
gem 'cocaine', '0.5.1'
gem "zurb-foundation"
gem "compass"
gem 'aws-sdk'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
group :development, :test do
gem 'rspec-rails', '2.11.0'
end
group :test do
gem 'capybara', '1.1.2'
gem 'factory_girl_rails', '4.1.0'
gem 'cucumber-rails', '1.2.1', :require => false
gem 'database_cleaner', '0.7.0'
end
gem 'jquery-rails'
<file_sep>/config/initializers/load_youtube_it.rb
require 'ostruct'
raw_config = File.read(::Rails.root.to_s + "/config/youtube_it.yml")
YouTubeItConfig = OpenStruct.new(YAML.load(raw_config)[Rails.env])
<file_sep>/app/controllers/admins_controller.rb
class AdminsController < ApplicationController
include Devise::Controllers::Helpers
def dashboard
@users = User.all
@clips = Clip.all
end
end
| 1790a4a944ea0e79c5a442fdf21d530cd1e812f9 | [
"Markdown",
"Ruby"
] | 15 | Ruby | jcap49/clipit | f6387133c243cc1044e6bade4eadf105875284f9 | 7d4163fbf9ab53b2cce0b7e3d21f4564f9819fdd | |
refs/heads/master | <file_sep>/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* time : 12ms
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head){
return head;
}
auto getLenAndLink = [](ListNode* head)->int{
ListNode* backup = head;
int ret = 0;
while(head->next){
++ret;
head = head->next;
}
head->next = backup;
return ret + 1;
};
//获取链表长度并连接链表为单循环链表
int len = getLenAndLink(head);
//获取右移次数
int rightRotateNum = k%len;
//右移n次等与左移len-n次
//减1是为了找到新的头指针的前一个
//找到头指针的前一个后,要将它的next置为nullptr
for(int i=0;i<((len-1)-rightRotateNum);++i){
head = head->next;
}
ListNode* ret = head->next;
head->next = nullptr;
return ret;
}
};<file_sep>/**
* time : 12ms
*/
//https://leetcode-cn.com/problems/container-with-most-water/solution/container-with-most-water-shuang-zhi-zhen-fa-yi-do/
/**
* 双指针 一头一尾同时向中间靠拢,减小解空间
* 两个指针指向两块板,每次一个指针向内收缩
* 收缩的条件为小的那块板收缩
* 因为容量取决于短板
* 只有当短板收缩时,容量才可能增大
* 长板收缩时,容量只会不变或减小
*/
class Solution {
public:
#define getArea(i,j) (((j)-(i))*(min(height[i],height[j])))
int maxArea(vector<int>& height) {
int head = 0;
int tail = height.size() - 1;
int maxx = 0;
while(head < tail){
maxx = max(maxx,getArea(head,tail));
if(height[head] < height[tail]){
++head;
}
else{
--tail;
}
}
return maxx;
}
};<file_sep>/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* time : 8ms
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head || !(head->next)){
return head;
}
ListNode v(0);
ListNode* vhead = &v;
vhead->next = head;
//pre 已经排序好的链表的最后一个元素
ListNode* pre = vhead;
//beg 元素相同的链表的第一个元素
//end 元素相同的链表的最后一个元素
ListNode* beg = head;
ListNode* end = head;
while(end){
//找到最后一个与beg指向的元素相同的元素
//beg到end为一个链表,里面所有的元素值都相同,链表长度可能为一
while(end->next && end->val == end->next->val){
end = end->next;
}
//当链表长度为一
if(beg == end){
//才将pre指针后移
pre->next = beg;
beg = beg->next;
end = beg;
pre = pre->next;
}
//链表长度不为一
else{
//不移动pre指针
pre->next = end->next;
beg = end->next;
end = beg;
}
}
return vhead->next;
}
};
<file_sep>/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* time : 8ms
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if(!head || !(head->next)){
return head;
}
ListNode* before = new ListNode(0);
ListNode* after = new ListNode(0);
//备份指针
ListNode* ret = before;
ListNode* afterBackup = after;
while(head){
if(head->val < x){
//小于x的节点链接到before链表
before->next = head;
before = head;
}
else{
//大于x的节点链接到after链表
after->next = head;
after = head;
}
//后移head
head = head->next;
//并将上一个节点脱离原链表
before->next = nullptr;
after->next = nullptr;
}
//首尾链表相连
before->next = afterBackup->next;
return ret->next;
}
};<file_sep>/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* time : 16ms
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode tt(0);
ListNode* vhead = &tt;
ListNode* ret = head;
ListNode* t = nullptr;
ListNode* last = nullptr;
bool once = true;
bool finish = false;
vhead->next = head;
ListNode* tail = head;
ListNode* tailbackup = tail;
while (tailbackup) {
//找到k个元素成为链表
//不足k个会函数返回
for (int i = 1; i<k; ++i) {
tail = tail->next ? tail->next : tail;
if(tail == last){
finish = true;
break;
}
else{
last = tail;
}
}
if(finish){
break;
}
//备份tail
//当局部反转后,tail会被破坏
tailbackup = tail->next;
if (once) {
ret = tail;
once = false;
}
t = vhead->next;
reverseList(vhead, tail, tail->next, k);
vhead = t;
tail = tailbackup;
}
return ret;
}
//将vhead->next 到 tail的元素反转 局部反转
//不足k个不会进入函数
//反转后将nextListHead拼接到反转后的链表
void reverseList(ListNode* vhead, ListNode* tail, ListNode* nextListHead,int k) {
//没有元素 一个元素
if (vhead->next == nullptr || vhead->next == tail) {
return;
}
ListNode* leftListHead = vhead->next;
int i = 0;
while (i++ < k && leftListHead != tail->next && leftListHead != nullptr) {
ListNode* t = vhead->next;
vhead->next = leftListHead;
leftListHead = leftListHead->next;
vhead->next->next = t;
if (vhead->next->next == vhead->next) {
vhead->next->next = nextListHead;
}
}
}
}; | 7058096061e6a1f672646bbf819c104f8bbc9272 | [
"C++"
] | 5 | C++ | AmazingFrog/leetcodePractice | 4763ae23080e3ad91861d57a223be32d71dd2518 | 03cc707f5afc1c1fec44540a33e876c0ccb3717f | |
refs/heads/master | <file_sep>//
// ViewController.swift
// MapViewDemo
//
// Created by <NAME> on 2016/12/05.
// Copyright © 2016年 ARTE Co., Ltd. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
@IBOutlet weak var mapView: MKMapView! {
didSet {
mapView.delegate = self
}
}
/// 位置情報の更新に成功した時の処理
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = manager.location {
mapView.setCenter(location.coordinate, animated: true)
}
}
/// 位置情報の更新に失敗した時の処理
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
/// 領域の観測開始時の処理
func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) {
let alert = UIAlertController(title: "Notice", message: "監視開始", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(defaultAction)
present(alert, animated: true, completion: nil)
}
/// 領域に入った時の処理
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
let alert = UIAlertController(title: "Notice", message: "\(region.identifier)です", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(defaultAction)
present(alert, animated: true, completion: nil)
}
/// 領域から出た時の処理
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
let alert = UIAlertController(title: "Notice", message: "\(region.identifier)からでました", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(defaultAction)
present(alert, animated: true, completion: nil)
}
/// overlayの描画
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKCircleRenderer(overlay: overlay)
renderer.lineWidth = 1.0
renderer.fillColor = UIColor.lightGray
renderer.strokeColor = UIColor.blue
renderer.alpha = 0.5
return renderer
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.allowsBackgroundLocationUpdates = true
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.requestLocation()
}
// 初期位置の設定
let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
mapView.region.span = span
stopMonitoring()
// 監視する領域
let shinbanbaRegion = CLCircularRegion(
center: CLLocationCoordinate2DMake(35.616494, 139.741501),
radius: 200.0,
identifier: "新馬場駅"
)
let seisekiRegion = CLCircularRegion(
center: CLLocationCoordinate2DMake(35.618927, 139.744431),
radius: 50.0,
identifier: "聖蹟公園"
)
let kitashinagawaRegion = CLCircularRegion(
center: CLLocationCoordinate2DMake(35.622281, 139.739302),
radius: 450.0,
identifier: "北品川駅"
)
locationManager.startMonitoring(for: shinbanbaRegion)
locationManager.startMonitoring(for: seisekiRegion)
locationManager.startMonitoring(for: kitashinagawaRegion)
addCircleToMapView(region: shinbanbaRegion)
addCircleToMapView(region: seisekiRegion)
addCircleToMapView(region: kitashinagawaRegion)
let keikyuStations = [
"青物横丁駅" : CLLocationCoordinate2DMake(35.609328, 139.742937),
"鮫洲駅" : CLLocationCoordinate2DMake(35.605069, 139.742339),
"立会川駅" : CLLocationCoordinate2DMake(35.598559, 139.738929),
"大森海岸駅" : CLLocationCoordinate2DMake(35.587684, 139.735390),
"平和島駅" : CLLocationCoordinate2DMake(35.578757, 139.734968),
"大森町駅" : CLLocationCoordinate2DMake(35.572419, 139.732003),
"梅屋敷駅" : CLLocationCoordinate2DMake(35.566939, 139.728344),
"京急蒲田駅" : CLLocationCoordinate2DMake(35.560809, 139.723817)
]
for station in keikyuStations {
let region = CLCircularRegion(center: station.value, radius: 200.0, identifier: station.key)
locationManager.startMonitoring(for: region)
addCircleToMapView(region: region)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// すべての監視を停止
private func stopMonitoring() {
for region in locationManager.monitoredRegions {
locationManager.stopMonitoring(for: region)
}
}
private func addCircleToMapView(region: CLCircularRegion) {
let circle = MKCircle(center: region.center, radius: region.radius)
mapView.add(circle)
}
}
| 816c46f28ee4f67abc86b4f5a545946075722d24 | [
"Swift"
] | 1 | Swift | sf-arte/MapViewDemo | a6b8a4ed5dd4fe54fcbc117e197c4405214d3d31 | a05d4c98905d0d8be9732670e63667bb364bfc5d | |
refs/heads/master | <repo_name>bioShaun/MultiQC-oms<file_sep>/multiqc_oms/modules/expCorr/expCorr.py
#!/usr/bin/env python
""" MultiQC module to parse output from HISAT2 """
from __future__ import print_function
from collections import OrderedDict
import os
import logging
import pandas as pd
from multiqc import config
from multiqc.plots import heatmap
from multiqc.modules.base_module import BaseMultiqcModule
# Initialise the logger
log = logging.getLogger(__name__)
class MultiqcModule(BaseMultiqcModule):
""" dupradar module. """
def __init__(self):
# Initialise the parent object
super(MultiqcModule, self).__init__(name="Sample Correlation", anchor="expCorr",
info=" is generated from normalised gene counts through "
"<a href='https://bioconductor.org/packages/release/bioc/html/edgeR.html' target='_blank'>edgeR</a>.")
# Find and load correlation matrix
self.cor_data = dict()
for n, f in enumerate(self.find_log_files('expCorr', filehandles=False, filecontents=False)):
if n > 0:
raise ValueError('more than one correlation matrix found.')
self.cor_data['correlation'] = f
if len(self.cor_data) == 0:
raise UserWarning
log.info("Found {} reports".format(len(self.cor_data)))
# Write parsed report data to a file
self.write_data_file(self.cor_data, 'multiqc_expCorr')
heatmap_name, heatmap_val = self.parse_corr_matrix()
# correlation heatmap
self.cor_heatmap_plot(heatmap_name, heatmap_val)
def parse_corr_matrix(self):
"""
"""
f = self.cor_data['correlation']
cor_file = os.path.join(f['root'], f['fn'])
cor_df = pd.read_csv(cor_file, index_col=0)
heatmap_name = list(cor_df.columns)
heatmap_val = [list(cor_df.loc[i]) for i in cor_df.index]
return heatmap_name, heatmap_val
def cor_heatmap_plot(self, heatmap_name, heatmap_val):
""" Make the HighCharts HTML to plot sample correlation heatmap. """
# Split the data into SE and PE
pconfig = {
'title': 'Pearson correlation',
'xlab': True,
}
self.add_section(
description='Pearson correlation between log<sub>2</sub> normalised CPM values are calculated and clustered.',
plot=heatmap.plot(heatmap_val, heatmap_name, pconfig=pconfig)
)
<file_sep>/multiqc_oms/modules/expCorr/__init__.py
from __future__ import absolute_import
from .expCorr import MultiqcModule
<file_sep>/multiqc_oms/modules/diffNum/diff_bar.py
#!/usr/bin/env python
""" MultiQC submodule to parse output from diff number table"""
import os
from collections import OrderedDict
import logging
import pandas as pd
from multiqc.plots import bargraph
# Initialise the logger
log = logging.getLogger(__name__)
def parse_reports(self):
""" Find diff number table and parse their data """
# Set up vars
self.diff_num = dict()
# Go through files and parse data using regexes
for n, f in enumerate(
self.find_log_files(
'diffNum/diff_bar', filehandles=False, filecontents=False)):
if n > 0:
raise ValueError('more than one diff number table found.')
self.diff_num['table'] = f
if len(self.diff_num) == 0:
raise UserWarning
self.write_data_file(self.diff_num, 'multiqc_diffNum_bar')
diff_num_file = os.path.join(
self.diff_num['table']['root'], self.diff_num['table']['fn'])
diff_num_df = pd.read_csv(diff_num_file, index_col=0)
plot_data = OrderedDict()
for idx_i in diff_num_df.index:
plot_data[idx_i] = {'up-regulated': diff_num_df.loc[idx_i].up,
'down-regulated': diff_num_df.loc[idx_i].down}
pconfig = {
'title': 'Differential Expressed Genes',
'cpswitch_counts_label': 'Number of Genes',
}
self.add_section(
description=('This plot shows the Differential expressed gene number'
' for each compare.'),
plot=bargraph.plot(plot_data, pconfig=pconfig)
)
# Return number of compares found
return len(plot_data)
<file_sep>/multiqc_oms/modules/diffNum/diffNum.py
#!/usr/bin/env python
""" MultiQC module to parse output from HISAT2 """
from __future__ import print_function
from collections import OrderedDict
import os
import logging
import pandas as pd
from multiqc import config
from multiqc.plots import heatmap
from multiqc.modules.base_module import BaseMultiqcModule
# Initialise the logger
log = logging.getLogger(__name__)
class MultiqcModule(BaseMultiqcModule):
""" Show Number of diff genes. """
def __init__(self):
# Initialise the parent object
super(MultiqcModule, self).__init__(name="Differential analysis", anchor="diffNum",
info=" is generated from normalised gene counts through "
"<a href='https://bioconductor.org/packages/release/bioc/html/edgeR.html' target='_blank'>edgeR</a>.")
n = dict()
diff_num_sections = [
'diff_bar',
'diff_matrix',
]
for sm in diff_num_sections:
try:
module = __import__(
'multiqc_oms.modules.diffNum.{}'.format(sm), fromlist=[''])
n[sm] = getattr(module, 'parse_reports')(self)
if n[sm] > 0:
log.info("Found {} {} reports".format(n[sm], sm))
except (ImportError, AttributeError, UserWarning):
log.warn("Could not find diffNum Section '{}'".format(sm))
# Exit if we didn't find anything
if sum(n.values()) == 0:
raise UserWarning
<file_sep>/setup.py
#!/usr/bin/env python
"""
MultiQC-oms is a plugin for MultiQC, providing additional tools which are
specific to OMS.
"""
from setuptools import setup, find_packages
version = '0.6'
setup(
name='multiqc_oms',
version=version,
author='<NAME>',
author_email='<EMAIL>',
description="MultiQC plugin for the OMS",
long_description=__doc__,
keywords='bioinformatics',
license='MIT',
packages=find_packages(),
include_package_data=True,
install_requires=[
'couchdb',
'simplejson',
'pyyaml',
'requests',
'multiqc'
],
entry_points={
'multiqc.modules.v1': [
'dupradar = multiqc_oms.modules.dupradar:MultiqcModule',
'expCorr = multiqc_oms.modules.expCorr:MultiqcModule',
'stringtie = multiqc_oms.modules.stringtie:MultiqcModule',
'diffNum = multiqc_oms.modules.diffNum:MultiqcModule',
'enrichNum = multiqc_oms.modules.enrichNum:MultiqcModule',
],
'multiqc.templates.v1': [
'oms = multiqc_oms.templates.oms',
],
'multiqc.hooks.v1': [
'before_config = multiqc_oms.multiqc_oms:load_config',
],
},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Operating System :: Unix',
'Programming Language :: Python',
'Programming Language :: JavaScript',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Bio-Informatics',
'Topic :: Scientific/Engineering :: Visualization',
],
)
<file_sep>/multiqc_oms/modules/stringtie/__init__.py
from __future__ import absolute_import
from .stringtie import MultiqcModule
<file_sep>/multiqc_oms/templates/oms/__init__.py
#!/usr/bin/env python
"""
=============
oms
=============
This theme is a stand-alone report themed for use by the OMS
"""
import os
template_parent = 'default'
template_dir = os.path.dirname(__file__)
base_fn = 'base.html'
<file_sep>/multiqc_oms/modules/diffNum/__init__.py
from __future__ import absolute_import
from .diffNum import MultiqcModule
<file_sep>/multiqc_oms/modules/dupradar/dupradar.py
#!/usr/bin/env python
""" MultiQC module to parse output from HISAT2 """
from __future__ import print_function
from collections import OrderedDict
import logging
import re
import json
from multiqc import config
from multiqc.plots import linegraph
from multiqc.modules.base_module import BaseMultiqcModule
# Initialise the logger
log = logging.getLogger(__name__)
class MultiqcModule(BaseMultiqcModule):
""" dupradar module. """
def __init__(self):
# Initialise the parent object
super(MultiqcModule, self).__init__(name="DupRadar", anchor="dupradar",
href='https://bioconductor.org/packages/release/bioc/html/dupRadar.html',
info=" provides duplication rate quality control for RNA-Seq datasets. "
"Highly expressed genes can be expected to have a lot of duplicate reads, "
"but high numbers of duplicates at low read counts can indicate low library "
"complexity with technical duplication. ")
# Find and load any HISAT2 reports
self.dupradar_data = dict()
for f in self.find_log_files('dupradar', filehandles=True):
self.parse_dupradar_logs(f)
# Filter to strip out ignored sample names
self.dupradar_data = self.ignore_samples(self.dupradar_data)
if len(self.dupradar_data) == 0:
raise UserWarning
log.info("Found {} reports".format(len(self.dupradar_data)))
# Write parsed report data to a file
self.write_data_file(self.dupradar_data, 'multiqc_dupradar')
# Basic Stats Table
# Report table is immutable, so just updating it works
# self.hisat2_general_stats_table()
# Alignment Rate Plot
self.dupradar_plot()
def parse_dupradar_logs(self, f):
"""
"""
s_name = f['s_name']
parsed_data = OrderedDict()
for l in f['f']:
if l[0] != '#':
reads_kbp, dup_rate = l.strip().split()
parsed_data[float(reads_kbp)] = float(dup_rate)
self.add_data_source(f, s_name)
self.dupradar_data[s_name] = parsed_data
def dupradar_plot(self):
""" Make the HighCharts HTML to plot gene duplication distributions. """
# Split the data into SE and PE
pconfig = {
'title': 'DupRadar General Linear Model',
'xLog': True,
'xlab': 'expression (reads/kbp)',
'ylab': '% duplicate reads',
'ymax': 100,
'ymin': 0,
'tt_label': '<b>{point.x:.1f} reads/kbp</b>: {point.y:,.2f}% duplicates',
'xPlotLines': [
{
'color': 'green',
'dashStyle': 'LongDash',
'value': 0.5,
'width': 1,
'label': {
'style': {'color': 'green'},
'text': '0.5 RPKM',
'verticalAlign': 'bottom',
'y': -65,
}
},
{
'color': 'red',
'dashStyle': 'LongDash',
'value': 1000,
'width': 1,
'label': {
'style': {'color': 'green'},
'text': '1 read/bp',
'verticalAlign': 'bottom',
'y': -65,
}
},
],
}
self.add_section(
description='This plot shows the general linear models - a summary of the gene duplication distributions.',
plot=linegraph.plot(self.dupradar_data, pconfig)
)
<file_sep>/multiqc_oms/modules/dupradar/__init__.py
from __future__ import absolute_import
from .dupradar import MultiqcModule
<file_sep>/multiqc_oms/modules/enrichNum/enrichNum.py
#!/usr/bin/env python
""" MultiQC module to parse output from HISAT2 """
from __future__ import print_function
import os
import json
import logging
from multiqc.modules.base_module import BaseMultiqcModule
from multiqc.plots import bargraph, linegraph
# Initialise the logger
log = logging.getLogger(__name__)
class MultiqcModule(BaseMultiqcModule):
""" Show Number of diff genes. """
def __init__(self):
# Initialise the parent object
super(MultiqcModule, self).__init__(name="Enrichment analysis", anchor="enrichNum",
info=" is applied to differential expressed genes using "
"<a href='https://bioconductor.org/packages/release/bioc/html/goseq.html' target='_blank'>goseq</a> "
"and <a href='http://kobas.cbi.pku.edu.cn/' target='_blank'>KOBAS</a>."
"Top 20 Enriched KEGG Pathways and GO terms were selected to show in the report.")
self.kegg_dict = dict()
for n, f in enumerate(
self.find_log_files(
'enrichNum/kegg',
filecontents=False,
filehandles=False)):
if n > 0:
raise ValueError('more than one kegg summary found.')
kegg_file = os.path.join(f['root'], f['fn'])
self.kegg_dict = json.load(open(kegg_file))
self.write_data_file({'kegg': f}, 'multiqc_enrichNum_kegg')
if len(self.kegg_dict) == 0:
raise UserWarning
else:
self.add_section(
name='KEGG Pathway',
anchor='enrichNum-kegg',
plot=self.enrich_num_chart('enrichNum_kegg_plot',
'Top Enriched KEGG Pathways',
self.kegg_dict))
self.go_dict = dict()
for n, f in enumerate(
self.find_log_files(
'enrichNum/go',
filecontents=False,
filehandles=False)):
if n > 0:
raise ValueError('more than one go summary found.')
go_file = os.path.join(f['root'], f['fn'])
self.go_dict = json.load(open(go_file))
self.write_data_file({'go': f}, 'multiqc_enrichNum_go')
if len(self.go_dict) == 0:
raise UserWarning
else:
self.add_section(
name='GO',
anchor='enrichNum-go',
plot=self.enrich_num_chart('enrichNum_go_plot',
'Top Enriched GO Terms',
self.go_dict))
def enrich_num_chart(self, plot_id, plot_title, plot_data):
# Config for the plot
pconfig = {
'id': plot_id,
'title': plot_title,
'ylab': '-log10(Corrected P-value)',
'stacking': None,
'cpswitch': False,
'tt_percentages': False,
'tt_decimals': 2,
}
return bargraph.plot(plot_data, pconfig=pconfig)
<file_sep>/multiqc_oms/modules/diffNum/diff_matrix.py
#!/usr/bin/env python
""" MultiQC submodule to parse output from diff number table"""
import os
from collections import OrderedDict
import logging
import pandas as pd
from multiqc.plots import heatmap
# Initialise the logger
log = logging.getLogger(__name__)
def parse_reports(self):
""" Find diff number table and parse their data """
# Set up vars
self.diff_num = dict()
# Go through files and parse data using regexes
for n, f in enumerate(
self.find_log_files(
'diffNum/diff_matrix', filehandles=False, filecontents=False)):
if n > 0:
raise ValueError('more than one diff number table found.')
self.diff_num['table'] = f
if len(self.diff_num) == 0:
raise UserWarning
self.write_data_file(self.diff_num, 'multiqc_diffNum_matrix')
diff_num_file = os.path.join(
self.diff_num['table']['root'], self.diff_num['table']['fn'])
diff_num_df = pd.read_csv(diff_num_file, index_col=0)
heatmap_name = list(diff_num_df.columns)
heatmap_val = [list(diff_num_df.loc[i]) for i in diff_num_df.index]
pconfig = {
'title': 'Differential Expressed Genes',
'xlab': True,
}
self.add_section(
description=('This plot shows the Differential expressed gene number'
' for each compare.'),
plot=heatmap.plot(heatmap_val, heatmap_name, pconfig=pconfig)
)
# Return number of compares found
return len(heatmap_val)
<file_sep>/multiqc_oms/multiqc_oms.py
from multiqc.utils import config
def load_config():
my_search_patterns = {
'dupradar': {'fn': '*.markDups_duprateExpDensCurve.txt'},
'expCorr': {'fn': 'log2CPM_sample_cor.csv'},
'stringtie': {'fn': '*.tmap'},
'diffNum/diff_bar': {'fn': 'diff.genes.compare.csv'},
'diffNum/diff_matrix': {'fn': 'diff.genes.matrix.csv'},
'enrichNum/kegg': {'fn': 'top.kegg.enrich.json'},
'enrichNum/go': {'fn': 'top.go.enrich.json'},
}
config.update_dict(config.sp, my_search_patterns)
<file_sep>/multiqc_oms/modules/stringtie/stringtie.py
#!/usr/bin/env python
""" MultiQC module to parse output from HISAT2 """
from __future__ import print_function
from collections import OrderedDict
import os
import logging
import pandas as pd
from multiqc import config
from collections import Counter
from multiqc.plots import bargraph
from multiqc.modules.base_module import BaseMultiqcModule
# Initialise the logger
log = logging.getLogger(__name__)
class MultiqcModule(BaseMultiqcModule):
""" stringtie assembly module. """
def __init__(self):
# Initialise the parent object
super(MultiqcModule, self).__init__(name="StringTie", anchor="stringtie",
href='https://ccb.jhu.edu/software/stringtie/',
info=" is a fast and highly efficient assembler of RNA-Seq alignments into potential transcripts. ")
# Find and load any HISAT2 reports
self.stringtie_data = dict()
for f in self.find_log_files('stringtie', filehandles=False, filecontents=False):
self.parse_stringtie_logs(f)
# Filter to strip out ignored sample names
self.stringtie_data = self.ignore_samples(self.stringtie_data)
if len(self.stringtie_data) == 0:
raise UserWarning
log.info("Found {} reports".format(len(self.stringtie_data)))
# Write parsed report data to a file
self.write_data_file(self.stringtie_data, 'multiqc_dupradar')
# assembly Plot
self.stringtie_plot()
def parse_stringtie_logs(self, f):
"""
"""
s_name = f['s_name']
f_file = os.path.join(f['root'], f['fn'])
f_df = pd.read_csv(f_file, sep='\t')
self.add_data_source(f, s_name)
self.stringtie_data[s_name] = dict(Counter(f_df.class_code))
def stringtie_plot(self):
""" Make the HighCharts HTML to plot stringtie assembly. """
# Split the data into SE and PE
pconfig = {
'title': 'StringTie assemblies',
'ylab': 'Transcripts number',
'cpswitch_counts_label': 'Number of Transcripts',
}
self.add_section(
description='This plot shows the different type of transcripts assembled for each sample.',
plot=bargraph.plot(self.stringtie_data, pconfig=pconfig)
)
<file_sep>/multiqc_oms/modules/enrichNum/__init__.py
from __future__ import absolute_import
from .enrichNum import MultiqcModule
| 21e47e6f48c1bb58916e528c1bb1dacf79659fa0 | [
"Python"
] | 15 | Python | bioShaun/MultiQC-oms | 5e6368380d2a95bbf2916846689697a39b0c582f | f3c6585d84c3806515d71c3d5d224955323c654a | |
refs/heads/master | <file_sep>package nl.han.dare2date.matchservice;
import facebook4j.User;
import nl.han.dare2date.matchservice.model.MatchResponse;
import nl.han.dare2date.matchservice.model.MatchResult;
import org.apache.camel.Exchange;
import org.apache.camel.processor.aggregate.AggregationStrategy;
import twitter4j.Status;
import java.math.BigInteger;
import java.util.ArrayList;
public class SocialMediaMatchAggregrate implements AggregationStrategy {
private int match = 0;
/**
* This method is called every time a to(...) returns a response. This response (whether it's from
* twitter or facebook) is sent in the body of the newExchange.
*
* @param oldExchange
* @param newExchange
* @return
*/
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
}
/**
* Build a Response using the results of twitter & facebook. This is no useful
* matchalgorithm but you can do better don't you?
*/
increateMatchValueForFacebookUser(oldExchange, newExchange);
increaseMatchForTwitterStatus(oldExchange, newExchange);
return oldExchange;
}
private void increaseMatchForTwitterStatus(Exchange oldExchange, Exchange newExchange) {
ArrayList<Status> statuses = newExchange.getIn().getBody(ArrayList.class);
if (statuses != null) {
for (Status status : statuses) {
// A match is bigger when a user has a lots of tweets favoured
match += status.getFavoriteCount();
}
MatchResult matchResult = new MatchResult();
matchResult.setNumber(BigInteger.valueOf(match));
MatchResponse matchResponse = new MatchResponse();
matchResponse.setMatchResult(matchResult);
oldExchange.getIn().setBody(matchResponse);
}
}
private void increateMatchValueForFacebookUser(Exchange oldExchange, Exchange newExchange) {
User user = newExchange.getIn().getBody(User.class);
if (user != null) {
match += user.getName().length();
MatchResult matchResult = new MatchResult();
// A match is bigger when a user has a long name
matchResult.setNumber(BigInteger.valueOf(match));
MatchResponse matchResponse = new MatchResponse();
matchResponse.setMatchResult(matchResult);
oldExchange.getIn().setBody(matchResponse);
}
}
}
<file_sep>Visit the WSDL at http://localhost:8080/ws/calculatorservice/calculator.wsdl
<file_sep>package nl.ase.calculator.gateway;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.springframework.stereotype.Service;
@Service
public class MoviePrinter implements IMoviePrinter {
public void printMovieDetails(String searchTerm) {try {
HttpResponse<JsonNode> jsonResponse = Unirest.post("http://www.moviemeter.nl/api/film/")
.header("accept", "application/json")
.queryString("api_key", "<KEY>")
.queryString("q", searchTerm)
.asJson();
System.out.println(jsonResponse.getBody().toString());
} catch (UnirestException e) {
e.printStackTrace();
}
}
}<file_sep>spring.datasource.url=jdbc:mysql://localhost:3306/dare2date
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect<file_sep>How to run this route
---------------------
1. Run Maven: ```mvn clean package```
2. Create a run-configuration for Tomcat 7 or 8 (you can also use Jetty, see the alternative)
3. Deploy the war (Dare2DateCamel.war) to the Tomcat instance
4. Run Tomcat. If only the Tomcat homepage shows up you have to fall back to the alternative
5. Visit http://localhost:8080/Dare2DateCamel/applyregistration.wsdl or drop a SOAP message in the inbox folder
6. This project does not contain a JAXB-plugin so you have to generate (right click XSD->WebServices->Generate Java Code...) Java classes yourself based on your own XSD.
Alternative
-----------
For steps 2-4 you can also Run Maven with Jetty ```mvn jetty:run```.
Implementation
--------------
When you run the ApplyRegistrationRoute, messages can be obtained from two sources:
* inbox-folder (located in the bin-directory of your Tomcat/Jetty instance (don't run this example with mvn tomcat:run, instead use a separate Tomcat server. In src/main/webapp/WEB-INF/applyregistrationservice an example messages is included which
you can copy to your inbox folder in case your webservice is not available.
* a webservice with its wsdl served at http://localhost:8080/Dare2DateCamel/applyregistration.wsdl
(otherwise: http://localhost:8080/applyregistration.wsdl)
| 781e4057a1a153b8fd969027e89abe6152d43d96 | [
"Markdown",
"Java",
"INI"
] | 5 | Java | toru2220/icaase | f937e885b7c02a752303ae874542df33cc3bf547 | f67f1b9e27aac7da3c3adb1fbb18dd958dc8c07b | |
refs/heads/master | <file_sep>Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'application#search_steam'
get 'search/:busqueda', to: 'search_steam#scrape_steam'
get 'prices/:id/:title', to: 'search_steam#obtener_mejor_precio'
end
<file_sep>class SearchSteamController < ApplicationController
def scrape_steam
require 'open-uri'
@busqueda = params[:busqueda]
doc = Nokogiri::HTML(open("https://store.steampowered.com/search/?term="+@busqueda))
entries = doc.css('a.search_result_row')
@entriesArray = []
entries.each do |entry|
title = entry.css('span.title').text
id = entry.xpath('@data-ds-appid').text
linkImage = entry.css("img").attr('src').text
element = {title:title, id:id, Image:linkImage}
@entriesArray << element
end
render json: @entriesArray
end
def obtener_mejor_precio
title = (params[:title].to_s).gsub(/[^[:ascii:]]/, "")
id = params[:id].to_s
monedas=divisas()
@resultado = []
@nuevoScrap=scrap_steam_product(id,title)
@resultado<<@nuevoScrap
@nuevoScrap=scrap_nuuvem(title,monedas[:Real])
if @nuevoScrap != 0
@resultado<<@nuevoScrap
end
@nuevoScrap=scrap_gate(title,monedas[:Dolar])
if @nuevoScrap != 0
@resultado<<@nuevoScrap
end
return render json: @resultado
end
def scrap_steam_product(id, title)
require 'open-uri'
url_product = "https://store.steampowered.com/app/"+ id
doc = Nokogiri::HTML(open(url_product))
if doc.css('div.discount_pct')[0] != nil
scrap_precio = doc.css('div.discount_final_price')[0]
else
scrap_precio = doc.css('div.game_purchase_price')[0]
end
linkImage = doc.css("img.game_header_image_full").attr('src').text
if scrap_precio !=nil
string_precio = scrap_precio.text
precio= (string_precio.gsub(/\D+/, '')).to_i
return {Title:title, Cost:precio, CostoConvertido:precio ,Url:url_product, Currency:'Peso', Store:'Steam', Enable:'OK',Image: linkImage }
else
return {Title:title, Store:'Steam', Enable:'UNAVAILABLE', Image: linkImage}
end
end
def divisas
require 'open-uri'
doc = Nokogiri::HTML(open("https://www.portal.brou.com.uy/home"))
string_dolar = (doc.css('p.valor')[1].text).gsub(',', '.')
dolar=string_dolar.to_f
string_real = (doc.css('p.valor')[9].text).gsub(',', '.')
real=string_real.to_f
return {Dolar:dolar, Real:real}
end
def scrap_nuuvem(title, real)
require 'open-uri'
encoded_url = URI.encode("https://www.nuuvem.com/catalog/search/"+ title)
doc = Nokogiri::HTML(open(encoded_url))
entries = doc.css('div.product-card--grid')
entries.each do |entry|
title_temp = entry.css('a.product-card--wrapper').attr('title').text
if (title_match(title,title_temp)==true)
string_precio = entry.css('span.integer').text + ((entry.css('span.decimal').text).gsub(',', '.'))
url_product= entry.css('a.product-card--wrapper').attr('href').text
precio = string_precio.to_f
costo_convertido = (string_precio.to_f * real.to_f).round
if (revisar_region (url_product))
return {Title:title, Cost:precio, CostoConvertido:costo_convertido , Url:url_product, Currency:'Real', Store:'Nuuvem', Enable:'OK'}
else
return {Title:title, Cost:precio, CostoConvertido:costo_convertido , Url:url_product, Currency:'Real', Store:'Nuuvem', Enable:'NO'}
end
end
end
return 0
end
def scrap_gate(title, dolar)
require 'open-uri'
encoded_url = URI.encode("https://latam.gamersgate.com/games?prio=relevance&q="+ title)
doc = Nokogiri::HTML(open(encoded_url))
entries = doc.css('li.odd')
entries.each do |entry|
title_temp = entry.css('a.ttl').attr('title').text
if (title_match(title,title_temp)==true)
string_precio = (entry.css('span.bold.red.big').text).gsub('$', '')
if string_precio == ""
string_precio = (entry.css('span.textstyle1').text).gsub('$', '')
end
url_product= entry.css('a.ttl').attr('href').text
precio = string_precio.to_f
costo_convertido = (string_precio.to_f * dolar.to_f).round
return {Title:title, Cost:precio, CostoConvertido:costo_convertido , Url:url_product, Currency:'Dolar', Store:'Gamers Gate', Enable:'OK'}
end
end
return 0
end
########################################################## Metodos Auxiliares ##########################################################################3
def revisar_region(url)
require 'open-uri'
doc = Nokogiri::HTML(open(url))
region = doc.css('div.product-widget--content').text
if ((region.include? "Latin") || (region.include? "Uruguay")|| (region.include? "South"))
return true
else
return false
end
end
def title_match(title1,title2)
title1Limpio = (title1.gsub(/[^[:ascii:]]/, "")).downcase
title2Limpio = (title2.gsub(/[^[:ascii:]]/, "")).downcase
if (levenshtein_distance(title1Limpio, title2Limpio) == 0)
return true
else
return false
end
end
def is_number? (string)
true if Integer(string) rescue false
end
def levenshtein_distance(str1, str2)
n = str1.length
m = str2.length
max = n/2
return m if 0 == n
return n if 0 == m
return n if (n - m).abs > max
d = (0..m).to_a
x = nil
str1.each_char.with_index do |char1,i|
e = i+1
str2.each_char.with_index do |char2,j|
cost = (char1 == char2) ? 0 : 1
x = [ d[j+1] + 1, # insertion
e + 1, # deletion
d[j] + cost # substitution
].min
d[j] = e
e = x
end
d[m] = x
end
x
end
end<file_sep>class ApplicationController < ActionController::Base
def search_steam
require 'open-uri'
doc = Nokogiri::HTML(open("https://www.portal.brou.com.uy/home"))
string_dolar = (doc.css('p.valor')[1].text).gsub(',', '.')
dolar=string_dolar.to_f
string_real = (doc.css('p.valor')[9].text).gsub(',', '.')
real=string_real.to_f
divisas = {Dolar:dolar, Real:real}
render json: divisas
end
end
| 473202ab5a7f1c83f84f1bbe1cf394d599da71b5 | [
"Ruby"
] | 3 | Ruby | DiktatorShadaloo/GunstigeSpiele | 0b22500c3307588ce9e2b70026c19295b37a4226 | 6b42c5526eea126a4f11fbc4b66b41d2c1ed364f | |
refs/heads/master | <file_sep>
var Discord = require('discord.js');
var bot = new Discord.Client();
var fs = require('fs');
var rbx = require('roblox-js');
var commandsList = fs.readFileSync('Storage/commands.txt', 'utf8');
var config = require('./Storage/client.json')
const prefix = '::';
bot.on('message', message => {
var sender = message.author; // The person who sent the Message
var msg = message.content.toUpperCase(); // Takes the message and makes it all uppercase
var args = message.content.slice(prefix.length).split(" ");
var cmd = args.shift().toLowerCase();
if (sender.bot) return;
try{
let commandFile = require(`./commands/${cmd}.js`);
commandFile.run(bot, message, args);
} catch(e) {
} finally {
console.log(`${message.author.username} ran the command: ${cmd}`);
}
});
bot.on('ready', () => {
console.log('EXECUTIVE_SCPF Launched!') // Runs when the bot is Launched
bot.user.setStatus('Online')
bot.user.setActivity('Do ::help for a list of commands!')
});
// Login
bot.login(process.env.BOT_TOKEN);
| 0377ea3ab692ddade4dfb27eea328ed75fca0250 | [
"JavaScript"
] | 1 | JavaScript | ArmedGaming/mtfbot2 | dda23dc726e8c32906251312ccae6c1d7095fce8 | d05ccb991a99d75498c7c398ac679f6cf6cc25c4 | |
refs/heads/master | <file_sep># Gesture Detection and Recognition in TV News Videos
Communication using body language is an ancient art form, currently evolving in many fascinating ways. And automatic detection of human body language is becoming an active subject of research due to its application in various vision-based articulated body pose estimation systems such as Markerless motion capture for human-computer interfaces, Robot control, visual surveillance, Human image synthesis. A specific part of this field, gesture recognition, has gained great attention in recent years. Current focuses in the field include emotion recognition from face and hand gesture recognition. Users can use simple gestures to control or interact with devices without physically touching them. Gesture recognition has also benefited in the field of Defence, Home Automation, Automated sign language translation.
*This is my [Google Summer of Code 2019](https://summerofcode.withgoogle.com/projects/#4821012401618944) Project with [the Distributed Little Red Hen Lab](http://www.redhenlab.org).*
The aim of this project is to develop an automated system for hand gesture detection and recognition in TV news videos. Given a news video of certain time duration, the automated system should not only detect the hand gestures in the video but also provide a label from among the set of hand-gesture classes. Finally, the system should be incorporated into singularity container for deployment on high-performance clusters (HPC) clusters.
### Tools and Libraries
- openCV
- Tensorflow
- Keras
- Singularity Container
### Project Update
The progress made in the project is updated in the blog posts. The blog posts with the updates on the work done are:
- [Setting up OpenPose in CWRU HPC](https://medium.com/@abhinavpatel2912/setting-up-openpose-in-cwru-hpc-8955f510f6ac)
- [Week 1 & Week 2 (GSoC 2019)](https://medium.com/@abhinavpatel2912/week-1-week-2-gsoc-2019-85448409dd0f)
- [Week 3 & Week 4 (GSoC 2019)](https://medium.com/@abhinavpatel2912/week-3-week-4-gsoc-2019-12d572b2cd5c)
- [Week 5 (GSoC 2019)](https://medium.com/@abhinavpatel2912/week-5-gsoc-2019-6b07acc91eb6)
- [Weeks 6-8 (GSoC 2019)](https://medium.com/@abhinavpatel2912/weeks-6-8-gsoc-2019-1b3d7df33e0c)
<file_sep># Importing Libraries
import sys
import json
import os
import numpy as np
# Default video frame dimensions
img_height = 240
img_width = 320
offset = 25 # amount of shift in extreme points (in pixels)
def getExtrmCoords(points_list, img_height, img_width):
'''
:param points_list: list of x and y coordinates of joints along with their confidence scores
:return: extreme coordinates in x and y directions
'''
x_coord = []
y_coord = []
# print("points_list: ", points_list)
for ptr in range(0, len(points_list), 3):
curr_x = points_list[ptr]
curr_y = points_list[ptr + 1]
prob = points_list[ptr + 2]
if curr_x > 0 and curr_x < img_width and prob > 0.2:
x_coord.append(curr_x)
if curr_y > 0 and curr_y < img_height and prob > 0.2:
y_coord.append(curr_y)
# print("x_coord: ", x_coord)
# print("y_coord: ", y_coord)
points_min_x = 1000
points_max_x = 0
points_min_y = 1000
if len(x_coord) > 0 and len(y_coord) > 0:
points_min_x = min(i for i in x_coord if i > 0)
points_max_x = max(i for i in x_coord if i > 0)
points_min_y = min(i for i in y_coord if i > 0)
return points_min_x, points_max_x, points_min_y
def getBoundingBox(json_path, global_val, img_height, img_width):
'''
:param json_path: path of directory containing all the json files of the respective video
:param global_val: list of variables storing extreme coordinates
:return: bounding box around the person in the given video
'''
global_min_x, global_max_x, global_min_y, global_max_y = global_val
skipped = 0
file_list = os.listdir(json_path)
for json_file in file_list:
arr = json_file.split('.')
if arr[-1] != "json":
continue
# print("{} json started!".format(json_file))
json_file_path = os.path.join(json_path, json_file)
with open(json_file_path, 'r') as myfile:
data = myfile.read()
try:
obj = json.loads(data)
main_dict = obj['people'][0]
except:
continue
# print("main_dict.keys() is {}".format(main_dict.keys()))
pose = main_dict['pose_keypoints']
hand_left = main_dict['hand_left_keypoints']
hand_right = main_dict['hand_right_keypoints']
# face = main_dict['face_keypoints']
pose_min_x, pose_max_x, pose_min_y = getExtrmCoords(pose, img_height, img_width)
hand_left_min_x, hand_left_max_x, hand_left_min_y = getExtrmCoords(hand_left, img_height, img_width)
hand_right_min_x, hand_right_max_x, hand_right_min_y = getExtrmCoords(hand_right, img_height, img_width)
# face_min_x, face_max_x, face_min_y = getExtrmCoords(face)
global_min_x = min(global_min_x, pose_min_x, hand_left_min_x, hand_right_min_x)
global_max_x = max(global_max_x, pose_max_x, hand_left_max_x, hand_right_max_x)
global_min_y = min(global_min_y, pose_min_y, hand_left_min_y, hand_right_min_y)
# print("global_min_x is {} and global_max_x is {}".format(global_min_x, global_max_x))
if global_min_x - offset <= 0:
global_min_x = 0
else:
global_min_x -= offset
if global_max_x + offset > img_width:
global_max_x = img_width
else:
global_max_x += offset
if global_min_y - offset <= 0:
global_min_y = 0
else:
global_min_y -= offset
bounding_box = [
global_min_x,
global_max_x,
global_min_y,
global_max_y
]
return bounding_box
def main(global_val):
'''
:param global_val: list of variables storing extreme coordinates
:return: bounding box for each of the video of ChaLearn Dataset
'''
store_json = "/home/axp798/axp798gallinahome/store/json/"
dir_list = os.listdir(store_json)
for dir_name in dir_list:
video_list = os.listdir(os.path.join(store_json, dir_name))
for video_name in video_list:
json_path = os.path.join(store_json, "{}/{}/".format(dir_name, video_name))
bounding_box = getBoundingBox(json_path, global_val)
return bounding_box
if __name__ == '__main__':
global_min_x = 100000
global_max_x = 0
global_min_y = 0
global_max_y = img_height
global_val = [global_min_x, global_max_x, global_min_y, global_max_y]
main(global_val)
<file_sep>import tensorflow as tf
import numpy as np
import os
def getKernel(name, shape):
kernel = tf.get_variable(name, shape, tf.float32, tf.contrib.layers.xavier_initializer(uniform=True,
seed=None,
dtype=tf.float32))
return kernel
def _bias_variable(name, shape):
return tf.get_variable(name, shape, tf.float32, tf.constant_initializer(0.0, dtype=tf.float32))
# block 1
def conv3DBlock(prev_layer, layer_name, in_filters, out_filters):
with tf.variable_scope(layer_name):
kernel_shape = 3
kernel_name = "weights"
conv_stride = [1, 1, 1, 1, 1]
kernel = getKernel(kernel_name, [kernel_shape, kernel_shape, kernel_shape, in_filters, out_filters])
prev_layer = tf.nn.conv3d(prev_layer, kernel, strides=conv_stride, padding="SAME")
prev_layer = tf.layers.batch_normalization(prev_layer, training=True)
biases = _bias_variable('biases', [out_filters])
prev_layer = tf.nn.bias_add(prev_layer, biases)
prev_layer = tf.nn.relu(prev_layer)
return prev_layer
def maxPool3DBlock(prev_layer, ksize, pool_stride):
prev_layer = tf.nn.max_pool3d(prev_layer, ksize, pool_stride, padding="VALID")
return prev_layer
def inference(video):
shapes_list = []
num_classes = 249
prev_layer = video
in_filters = 3
# block 1
out_filters = 32
layer_name = "conv1a"
prev_layer = conv3DBlock(prev_layer, layer_name, in_filters, out_filters)
prev_layer = maxPool3DBlock(prev_layer, [1, 1, 2, 2, 1], [1, 1, 2, 2, 1])
in_filters = out_filters
print(prev_layer.get_shape())
shapes_list.append(prev_layer.get_shape())
# block 2
out_filters = 64
layer_name = "conv2a"
prev_layer = conv3DBlock(prev_layer, layer_name, in_filters, out_filters)
prev_layer = maxPool3DBlock(prev_layer, [1, 2, 2, 2, 1], [1, 2, 2, 2, 1])
in_filters = out_filters
print(prev_layer.get_shape())
shapes_list.append(prev_layer.get_shape())
# block 3
out_filters = 128
layer_name = "conv3a"
prev_layer = conv3DBlock(prev_layer, layer_name, in_filters, out_filters)
in_filters = out_filters
print(prev_layer.get_shape())
shapes_list.append(prev_layer.get_shape())
out_filters = 128
layer_name = "conv3b"
prev_layer = conv3DBlock(prev_layer, layer_name, in_filters, out_filters)
in_filters = out_filters
print(prev_layer.get_shape())
shapes_list.append(prev_layer.get_shape())
prev_layer = maxPool3DBlock(prev_layer, [1, 2, 2, 2, 1], [1, 2, 2, 2, 1])
shapes_list.append(prev_layer.get_shape())
# block 4
out_filters = 256
layer_name = "conv4a"
prev_layer = conv3DBlock(prev_layer, layer_name, in_filters, out_filters)
in_filters = out_filters
print(prev_layer.get_shape())
shapes_list.append(prev_layer.get_shape())
out_filters = 256
layer_name = "conv4b"
prev_layer = conv3DBlock(prev_layer, layer_name, in_filters, out_filters)
in_filters = out_filters
print(prev_layer.get_shape())
shapes_list.append(prev_layer.get_shape())
prev_layer = maxPool3DBlock(prev_layer, [1, 2, 2, 2, 1], [1, 2, 2, 2, 1])
shapes_list.append(prev_layer.get_shape())
# block 5
out_filters = 256
layer_name = "conv5a"
prev_layer = conv3DBlock(prev_layer, layer_name, in_filters, out_filters)
in_filters = out_filters
print(prev_layer.get_shape())
shapes_list.append(prev_layer.get_shape())
out_filters = 256
layer_name = "conv5b"
prev_layer = conv3DBlock(prev_layer, layer_name, in_filters, out_filters)
in_filters = out_filters
print(prev_layer.get_shape())
shapes_list.append(prev_layer.get_shape())
prev_layer = maxPool3DBlock(prev_layer, [1, 2, 2, 2, 1], [1, 2, 2, 2, 1])
shapes_list.append(prev_layer.get_shape())
with tf.variable_scope('fc1'):
dim = np.prod(prev_layer.get_shape().as_list()[1:])
prev_layer_flat = tf.reshape(prev_layer, [-1, dim])
weights = getKernel('weights', [dim, 512])
biases = _bias_variable('biases', [512])
prev_layer = tf.nn.relu(tf.matmul(prev_layer_flat, weights) + biases)
print(prev_layer.get_shape())
shapes_list.append(prev_layer.get_shape())
with tf.variable_scope('dropout1'):
prev_layer = tf.nn.dropout(prev_layer, 0.4)
with tf.variable_scope('fc2'):
dim = np.prod(prev_layer.get_shape().as_list()[1:])
prev_layer_flat = tf.reshape(prev_layer, [-1, dim])
weights = getKernel('weights', [dim, 512])
biases = _bias_variable('biases', [512])
prev_layer = tf.nn.relu(tf.matmul(prev_layer_flat, weights) + biases)
print(prev_layer.get_shape())
shapes_list.append(prev_layer.get_shape())
with tf.variable_scope('dropout2'):
prev_layer = tf.nn.dropout(prev_layer, 0.4)
with tf.variable_scope('Softmax_Layer'):
dim = np.prod(prev_layer.get_shape().as_list()[1:])
prev_layer_flat = tf.reshape(prev_layer, [-1, dim])
weights = getKernel('weights', [dim, num_classes])
biases = _bias_variable('biases', [num_classes])
softmax_linear = tf.add(tf.matmul(prev_layer_flat, weights), biases)
print(softmax_linear.get_shape())
shapes_list.append(prev_layer.get_shape())
return softmax_linear, shapes_list
<file_sep>import os
import numpy as np
import tensorflow as tf
from tensorflow.python.client import device_lib
import time
# import scipy.misc as smisc
import pickle
import random
def getKernel(name, shape):
kernel = tf.get_variable(name, shape, tf.float32, tf.contrib.layers.xavier_initializer(uniform=True,
seed=None,
dtype=tf.float32))
return kernel
def _bias_variable(name, shape):
return tf.get_variable(name, shape, tf.float32, tf.constant_initializer(0.0, dtype=tf.float32))
def maxPool3DBlock(prev_layer, ksize, pool_stride):
prev_layer = tf.nn.max_pool3d(prev_layer, ksize, pool_stride, padding="VALID")
return prev_layer
def conv3DBlock(prev_layer, layer_name, in_filters, out_filters):
kernel_shape = 3
kernel_name = "weights"
conv_stride = [1, 1, 1, 1, 1]
with tf.variable_scope(layer_name):
kernel = getKernel(kernel_name, [kernel_shape, kernel_shape, kernel_shape, in_filters, out_filters])
prev_layer = tf.nn.conv3d(prev_layer, kernel, strides=conv_stride, padding="SAME")
# print(layer_name, prev_layer.get_shape())
return prev_layer
def inpuT_block(inpuT, inpuT_filter_shape, inpuT_stride):
with tf.variable_scope("inpuT_layer"):
out_filters = 3
kernel_name = "weights"
kernel = getKernel(kernel_name, inpuT_filter_shape)
curr_layer = tf.nn.conv3d(inpuT, kernel, strides=inpuT_stride, padding="SAME")
curr_layer = tf.layers.batch_normalization(curr_layer, training=True)
biases = _bias_variable('biases', [out_filters])
curr_layer = tf.nn.bias_add(curr_layer, biases)
curr_layer = tf.nn.relu(curr_layer)
return curr_layer
def basic_block(inpuT, in_filters, out_filters, layer_num, add_kernel_name):
layer_name = "conv{}a".format(layer_num)
prev_layer = conv3DBlock(inpuT, layer_name, in_filters, out_filters)
prev_layer = tf.layers.batch_normalization(prev_layer, training=True)
prev_layer = tf.nn.relu(prev_layer)
in_filters = out_filters
layer_name = "conv{}b".format(layer_num)
prev_layer = conv3DBlock(prev_layer, layer_name, in_filters, out_filters)
prev_layer = tf.layers.batch_normalization(prev_layer, training=True)
residual = prev_layer
prev_layer = _shortcut3d(inpuT, residual, add_kernel_name)
prev_layer = tf.nn.relu(prev_layer)
return prev_layer
def _shortcut3d(inpuT, residual, add_kernel_name):
"""3D shortcut to match inpuT and residual and sum them."""
conv_stride = [1, 1, 1, 1, 1]
inpuT_shape = inpuT.get_shape().as_list()
residual_shape = residual.get_shape().as_list()
equal_channels = inpuT_shape[-1] == residual_shape[-1]
shortcut = inpuT
if not equal_channels:
kernel = getKernel(add_kernel_name, [1, 1, 1, inpuT_shape[-1], residual_shape[-1]])
shortcut = tf.nn.conv3d(shortcut, kernel, strides=conv_stride, padding="SAME")
return (shortcut + residual)
def inference(inpuT):
num_filters_list = [16, 32, 64, 128] # as per the paper
num_classes = 27
num_channels = 3
inpuT_filter_shape = [3, 7, 7, num_channels, num_channels]
inpuT_stride = [1, 1, 2, 2, 1]
print (inpuT.get_shape())
prev_layer = inpuT_block(inpuT, inpuT_filter_shape, inpuT_stride)
print(prev_layer.get_shape())
in_filters = 3
for index, out_filters in enumerate(num_filters_list):
add_kernel_name = "add{}".format(index + 1)
prev_layer = basic_block(prev_layer, in_filters, out_filters, index + 2, add_kernel_name)
print(prev_layer.get_shape())
if index > 0:
ksize = [1, 2, 1, 1, 1]
pool_stride = [1, 2, 1, 1, 1]
prev_layer = maxPool3DBlock(prev_layer, ksize, pool_stride)
print(prev_layer.get_shape())
in_filters = out_filters
shape_list = prev_layer.get_shape().as_list()
num_frames = shape_list[1]
height = shape_list[2]
width = shape_list[3]
prev_layer = tf.nn.avg_pool3d(prev_layer, [1, num_frames, height, width, 1], [1, 1, 1, 1, 1], padding="VALID")
print(prev_layer.get_shape())
with tf.variable_scope('fc1') as scope:
dim = np.prod(prev_layer.get_shape().as_list()[1:])
prev_layer_flat = tf.reshape(prev_layer, [-1, dim])
weights = getKernel('weights', [dim, 64])
biases = _bias_variable('biases', [64])
prev_layer = tf.nn.relu(tf.matmul(prev_layer_flat, weights) + biases, name=scope.name)
print(prev_layer.get_shape())
#
# with tf.variable_scope('dropout1'):
# prev_layer = tf.nn.dropout(prev_layer, 0.4)
with tf.variable_scope('fc2') as scope:
dim = np.prod(prev_layer.get_shape().as_list()[1:])
prev_layer_flat = tf.reshape(prev_layer, [-1, dim])
weights = getKernel('weights', [dim, 64])
biases = _bias_variable('biases', [64])
prev_layer = tf.nn.relu(tf.matmul(prev_layer_flat, weights) + biases, name=scope.name)
print(prev_layer.get_shape())
# with tf.variable_scope('dropout2'):
# prev_layer = tf.nn.dropout(prev_layer, 0.4)
with tf.variable_scope('softmax_linear') as scope:
dim = np.prod(prev_layer.get_shape().as_list()[1:])
prev_layer_flat = tf.reshape(prev_layer, [-1, dim])
weights = getKernel('weights', [dim, num_classes])
biases = _bias_variable('biases', [num_classes])
softmax_linear = tf.add(tf.matmul(prev_layer_flat, weights), biases, name=scope.name)
print(softmax_linear.get_shape())
return softmax_linear
<file_sep>import os
openpose_simg = "/home/axp798/axp798gallinahome/openpose_1_0_5.simg" # Path to openpose singularity image being used
store_path = "/home/axp798/axp798gallinahome/" # Path to directory for storing rendered videos and json files from train videos
json_store = os.path.join(store_path, "JD_JSON/") # directory to store json files containing hand, face and body coordinates from the videos
jd_videos_dir = "/home/axp798/axp798gallinahome/jester_datase/" # Path to list of directories containing training videos
lib_dir = "/home/axp798/axp798gallinahome/" # Path to directory to be accessible from within the singularity container
def main():
video_ptr = 0
videos_list = os.listdir(jd_videos_dir)
for video_name in videos_list:
print("Video {}-{} started!".format(video_ptr + 1, video_name))
images_dir = os.path.join(jd_videos_dir, video_name)
modified_video_name = ('0' * (6 - len(video_name))) + video_name ## 2 --> 000002
print(modified_video_name)
if not os.path.exists(os.path.join(json_store, "{}/".format(modified_video_name))):
os.mkdir(os.path.join(json_store, "{}/".format(modified_video_name)))
video_path = images_dir
write_json_path = os.path.join(json_store, "{}/".format(modified_video_name))
command = "singularity run --nv --bind {} {} --image_dir {} --write_keypoint_json {} --no_display --render_pose 0 --hand".format(
lib_dir,
openpose_simg,
video_path,
write_json_path)
os.system(command) # run the command on terminal
video_ptr += 1
print("Video {} completed!".format(video_ptr))
if __name__ == '__main__':
main()
<file_sep>import os
import random
import numpy as np
import tensorflow as tf
from tensorflow.contrib.framework import arg_scope
from tensorflow.contrib.layers import batch_norm, flatten
from tensorflow.python.client import device_lib
weight_decay = 0.0005
momentum = 0.9
init_learning_rate = 0.001
cardinality = 8 # how many split ?
blocks = 3 # res_block ! (split + transition)
"""
So, the total number of layers is (3*blokcs)*residual_layer_num + 2
because, blocks = split(conv 2) + transition(conv 1) = 3 layer
and, first conv layer 1, last dense layer 1
thus, total number of layers = (3*blocks)*residual_layer_num + 2
"""
depth = 64 # out channel
image_size = 112
image_depth = 16
num_channels = 3
num_classes = 249
def conv_layer(input, filter, kernel, stride, padding='SAME', layer_name="conv"):
with tf.name_scope(layer_name):
network = tf.layers.conv3d(inputs=input, use_bias=False, filters=filter, kernel_size=kernel, strides=stride,
padding=padding)
return network
def Global_Average_Pooling(x):
x_shape = x.get_shape().as_list()
depth = x_shape[1]
height = x_shape[2]
width = x_shape[3]
return tf.layers.average_pooling3d(inputs=x, pool_size=[depth, height, width], strides=[1, 1, 1], padding='valid')
def Max_pooling(x, pool_size=[2, 2, 2], stride=2, padding='SAME'):
return tf.layers.max_pooling3d(inputs=x, pool_size=pool_size, strides=stride, padding=padding)
def Batch_Normalization(x, training, scope):
with arg_scope([batch_norm],
scope=scope,
updates_collections=None,
decay=0.9,
center=True,
scale=True,
zero_debias_moving_mean=True):
return tf.cond(training,
lambda: batch_norm(inputs=x, is_training=training, reuse=None),
lambda: batch_norm(inputs=x, is_training=training, reuse=True))
def Relu(x):
return tf.nn.relu(x)
def Concatenation(layers):
return tf.concat(layers, axis=4)
def Linear(x):
return tf.layers.dense(inputs=x, use_bias=False, units=num_classes, name='linear' + str(random.random()))
def Evaluate(sess):
test_acc = 0.0
test_loss = 0.0
test_pre_index = 0
add = 1000
for it in range(test_iteration):
test_batch_x = test_x[test_pre_index: test_pre_index + add]
test_batch_y = test_y[test_pre_index: test_pre_index + add]
test_pre_index = test_pre_index + add
test_feed_dict = {
x: test_batch_x,
label: test_batch_y,
learning_rate: epoch_learning_rate,
training_flag: False
}
loss_, acc_ = sess.run([cost, accuracy], feed_dict=test_feed_dict)
test_loss += loss_
test_acc += acc_
test_loss /= test_iteration # average loss
test_acc /= test_iteration # average accuracy
summary = tf.Summary(value=[tf.Summary.Value(tag='test_loss', simple_value=test_loss),
tf.Summary.Value(tag='test_accuracy', simple_value=test_acc)])
return test_acc, test_loss, summary
class ResNeXt(object):
def __init__(self, x, training):
self.training = training
self.model = self.Build_ResNext(x)
def first_layer(self, x, scope):
with tf.name_scope(scope):
x = conv_layer(x, filter=64, kernel=[7, 7, 7], stride=[1, 2, 2], padding='SAME',
layer_name=scope + '_conv1' + str(random.random()))
x = Batch_Normalization(x, training=self.training,
scope=scope + '_batch1{}'.format(random.randint(10, 100)))
x = Max_pooling(x, pool_size=[3, 3, 3], stride=2, padding='SAME')
x = Relu(x)
return x
def transform_layer(self, x, stride, scope):
with tf.name_scope(scope):
x = conv_layer(x, filter=depth, kernel=[1, 1, 1], stride=stride,
layer_name=scope + '_conv1' + str(random.random()))
x = Batch_Normalization(x, training=self.training, scope=scope + '_batch1'.format(random.randint(20, 200)))
x = Relu(x)
x = conv_layer(x, filter=depth, kernel=[3, 3, 3], stride=1,
layer_name=scope + '_conv2' + str(random.random()))
x = Batch_Normalization(x, training=self.training, scope=scope + '_batch2'.format(random.randint(30, 300)))
x = Relu(x)
return x
def transition_layer(self, x, out_dim, scope):
with tf.name_scope(scope):
x = conv_layer(x, filter=out_dim, kernel=[1, 1, 1], stride=1,
layer_name=scope + '_conv1' + str(random.random()))
x = Batch_Normalization(x, training=self.training, scope=scope + '_batch1'.format(random.randint(40, 400)))
# x = Relu(x)
return x
def split_layer(self, input_x, stride, layer_name):
with tf.name_scope(layer_name):
layers_split = list()
for i in range(cardinality):
splits = self.transform_layer(input_x, stride=stride,
scope=layer_name + '_splitN_' + str(i) + str(random.random()))
layers_split.append(splits)
return Concatenation(layers_split)
def residual_layer(self, input_x, out_dim, layer_num, res_block=blocks):
# split + transform(bottleneck) + transition + merge
for i in range(res_block):
# input_dim = input_x.get_shape().as_list()[-1]
input_dim = int(np.shape(input_x)[-1])
channel = None
if input_dim * 2 == out_dim:
flag = True
stride = 2
channel = int(input_dim / 2)
else:
flag = False
stride = 1
x = self.split_layer(input_x, stride=stride,
layer_name='split_layer_' + layer_num + '_' + str(i) + str(random.random()))
x = self.transition_layer(x, out_dim=out_dim,
scope='trans_layer_' + layer_num + '_' + str(i) + str(random.random()))
if flag is True:
pad_input_x = Max_pooling(input_x)
pad_input_x = tf.pad(pad_input_x, [[0, 0], [0, 0], [0, 0], [0, 0], [channel, channel]])
else:
x = conv_layer(input_x, filter=out_dim, kernel=[1, 1, 1], stride=[2, 2, 2],
layer_name='conv_residual' + str(random.random()))
x = Batch_Normalization(x, training=self.training, scope='batch_residual{}'.format(random.random()))
pad_input_x = x
input_x = Relu(x + pad_input_x)
print(input_x.get_shape())
return input_x
def Build_ResNext(self, input_x):
# only cifar10 architecture
input_x = self.first_layer(input_x, scope='first_layer')
print(input_x.get_shape())
x = self.residual_layer(input_x, out_dim=256, layer_num='1', res_block=3)
x = self.residual_layer(x, out_dim=512, layer_num='2', res_block=4)
x = self.residual_layer(x, out_dim=1024, layer_num='3', res_block=6)
x = self.residual_layer(x, out_dim=2048, layer_num='4', res_block=3)
x = Global_Average_Pooling(x)
x = flatten(x)
x = Linear(x)
# x = tf.reshape(x, [-1,10])
return x
# train_x, train_y, test_x, test_y = prepare_data()
# train_x, test_x = color_preprocessing(train_x, test_x)
# image_size = 32, img_channels = 3, class_num = 10 in cifar10
# os.environ['CUDA_VISIBLE_DEVICES'] = "1"
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = "2"
# print(device_lib.list_local_devices())
#
# choose_device = "/device:GPU:0"
# with tf.device(choose_device):
#
# x = tf.placeholder(tf.float32, shape=[None, image_depth, image_size, image_size, num_channels])
# label = tf.placeholder(tf.float32, shape=[None, num_classes])
#
# training_flag = tf.placeholder(tf.bool)
#
# learning_rate = tf.placeholder(tf.float32, name='learning_rate')
#
# with tf.name_scope("cross_entropy"):
# logits = ResNeXt(x, training=training_flag).model
# cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=label, logits=logits))
# l2_loss = tf.add_n([tf.nn.l2_loss(var) for var in tf.trainable_variables()])
#
# update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
# with tf.control_dependencies(update_ops):
# optimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=momentum, use_nesterov=True)
# train = optimizer.minimize(cost + l2_loss * weight_decay)
#
# with tf.name_scope("accuracy"):
# correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(label, 1))
# accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#
# # saver = tf.train.Saver(tf.global_variables())
#
# gpu_options = tf.GPUOptions(allow_growth=True)
# with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:
# # ckpt = tf.train.get_checkpoint_state('./model')
# ckpt = 0
# if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):
# saver.restore(sess, ckpt.model_checkpoint_path)
# else:
# sess.run(tf.global_variables_initializer())
#
# summary_writer = tf.summary.FileWriter('./../graphs', sess.graph)
#
# epoch_learning_rate = init_learning_rate
# print("Session started.")
# for epoch in range(1, total_epochs + 1):
# if epoch == (total_epochs * 0.5) or epoch == (total_epochs * 0.75):
# epoch_learning_rate = epoch_learning_rate / 10
#
# pre_index = 0
# train_acc = 0.0
# train_loss = 0.0
# iteration = 10
# for step in range(1, iteration + 1):
# # if pre_index + batch_size < 50000:
# # batch_x = train_x[pre_index: pre_index + batch_size]
# # batch_y = train_y[pre_index: pre_index + batch_size]
# # else:
# # batch_x = train_x[pre_index:]
# # batch_y = train_y[pre_index:]
# print("{} iter started.".format(step))
# batch_x = np.ones((batch_size, image_depth, image_size, image_size, num_channels))
# batch_y = np.zeros((batch_size, num_classes))
# # batch_x = data_augmentation(batch_x)
#
# train_feed_dict = {
# x: batch_x,
# label: batch_y,
# learning_rate: epoch_learning_rate,
# training_flag: True
# }
#
# _, batch_loss = sess.run([train, cost], feed_dict=train_feed_dict)
# batch_acc = accuracy.eval(feed_dict=train_feed_dict)
#
# train_loss += batch_loss
# train_acc += batch_acc
# pre_index += batch_size
#
# print("{}-{}, epoch: {}, iter: {} done.".format(batch_loss, batch_acc, epoch, iteration))
#
#
# train_loss /= iteration # average loss
# train_acc /= iteration # average accuracy
#
# train_summary = tf.Summary(value=[tf.Summary.Value(tag='train_loss', simple_value=train_loss),
# tf.Summary.Value(tag='train_accuracy', simple_value=train_acc)])
#
# # test_acc, test_loss, test_summary = Evaluate(sess)
#
# summary_writer.add_summary(summary=train_summary, global_step=epoch)
# # summary_writer.add_summary(summary=test_summary, global_step=epoch)
# summary_writer.flush()
#
# line = "epoch: %d/%d, train_loss: %.4f, train_acc: %.4f \n" % (epoch, total_epochs, train_loss, train_acc)
# print(line)
#
# # with open('logs.txt', 'a') as f:
# # f.write(line)
#
# # saver.save(sess=sess, save_path='./model/ResNeXt.ckpt')
<file_sep>import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, "/home/axp798/axp798gallinahome/Gesture-Detection/")
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cv2
import os
import pickle
from image_acquisition import getBoundingBox
import time
video_store = "/home/axp798/axp798gallinahome/jester_datase/20bn-jester-v1/"
json_store = "/home/axp798/axp798gallinahome/JD_JSON"
train_lables_path = '/home/axp798/axp798gallinahome/Gesture-Detection/jester-v1-train.csv'
labels_path = '/home/axp798/axp798gallinahome/Gesture-Detection/jester-v1-labels.csv'
def video_labels(train_lables_path, labels_path):
'''
:@param train_lables_path: path of file containing video names with their labels
:@param labels_path: path of file containing index of each gesture
:return: sorted list of video names along with their label (from 0 to 26)
'''
tpd = pd.read_csv(train_lables_path, sep=';', header=None)
lab = pd.read_csv(labels_path, sep=';', header=None)
arr_train = np.array(tpd)
lst_train = list(arr_train)
lst_train = [list(arr) for arr in lst_train]
lst_train = sorted(lst_train, key=lambda x: x[0])
lst_labels = np.array(lab)
lst_labels = list(lst_labels)
lst_labels = [list(arr)[0] for arr in lst_labels]
ref_dict = {label: ind for ind, label in enumerate(lst_labels)}
for ind, row in enumerate(lst_train):
lst_train[ind][1] = ref_dict[row[1]]
ind += 1
return lst_train
def getFrameCut(frame, bounding_box):
'''
:param frame: numpy array of image
:param bounding_box: list of bounds of the box
:return: bounding box of the numpy array
'''
left_most = int(bounding_box[0])
right_most = int(bounding_box[1])
top_most = int(bounding_box[2])
bottom_most = int(bounding_box[3])
return frame[top_most: bottom_most, left_most: right_most]
def returnBoundingBox(json_path, img_height, img_width):
'''
:param json_path: path of folder containing json files of the current video
:param img_height: height of image frame
:param img_width: width of image frame
:return: left, right top and bottom bounds
'''
global_val = [100000, 0, 100000, img_height]
return getBoundingBox(json_path, global_val, img_height, img_width)
def getVideoDimension(video_path):
'''
:param video_name: name of the video for which dimension is asked
:return: shape of the video frame
'''
frame_list = os.listdir(video_path)
sample_image_path = os.path.join(video_path, frame_list[0])
curr_image = plt.imread(sample_image_path)
return curr_image.shape
def saveFramesWithLabels(video_store, json_store, train_lables_path, labels_path):
'''
:param video_store: path of folder containing all the videos
:param json_store: path of the folder containing json files of all the videos
:param train_lables_path: path of file containing video names with their labels
:param labels_path: path of file containing index of each gesture
:return: stores a dictionary with key as a list of numpy array of video frame and value as video label
'''
list_train_videos_name = video_labels(train_lables_path, labels_path)
num_videos = 0
net_start_time = time.time()
log_file_path = "/home/axp798/axp798gallinahome/Gesture-Detection/assets/jes_dat/log1.txt"
file1 = open(log_file_path, "w")
file1.write("Logs: \n")
file1.close()
bounding_box_list = []
incorrect_box = []
save_video_path = '/home/axp798/axp798gallinahome/data/jester/train_64/'
save_bounding_box_path = "/home/axp798/axp798gallinahome/data/jester/boxes/"
for videoName_and_label in list_train_videos_name[start: end]:
num_videos += 1
video_start_time = time.time()
video_name = videoName_and_label[0]
label = videoName_and_label[1]
video_name = str(video_name)
modified_video_name = video_name.zfill(6) # to get json files
json_path = os.path.join(json_store, modified_video_name)
video_path = os.path.join(video_store, video_name)
print("{}-{}-{} started!".format(num_videos, video_name, modified_video_name))
img_shape = getVideoDimension(video_path)
img_height = img_shape[0]
img_width = img_shape[1]
bounding_box = returnBoundingBox(json_path, img_height, img_width)
frame_list = os.listdir(os.path.join(video_store, video_name))
cut_frame_list = []
check = 0
for ind in range(len(frame_list)):
frame_name = str(ind + 1).zfill(5) + ".jpg"
frame_path = os.path.join(video_store + video_name, frame_name)
frame = plt.imread(frame_path)
frame_cut = getFrameCut(frame, bounding_box)
if frame_cut.size == 0:
incorrect_box.append(modified_video_name)
check = 1
break
res = cv2.resize(frame_cut, dsize=(64, 64), interpolation=cv2.INTER_CUBIC)
cut_frame_list.append(res)
if check:
log1 = "{}-{}-{} ; incorrect boxes: {}-{}! \n".format(num_videos, video_name, modified_video_name,
len(incorrect_box), incorrect_box)
file1 = open(log_file_path, "a")
file1.write(log1)
file1.close()
print(log1)
continue
cut_frame_array = np.array(cut_frame_list)
video_shape = cut_frame_array.shape
bounding_box_list.append(["{}".format(modified_video_name), bounding_box])
pkl_vid_name = "{}_{}.pkl".format(num_videos, modified_video_name)
with open(save_video_path + pkl_vid_name, 'wb') as f:
pickle.dump([cut_frame_array, label], f)
with open(save_bounding_box_path + "train_boxes.pkl", 'wb') as f:
pickle.dump(bounding_box_list, f)
video_end_time = time.time()
log = "{}-{}-{} done in {}! ----- bounding box: {}, video shape: {} \n".format(num_videos, video_name,
modified_video_name,
video_end_time - video_start_time,
bounding_box, video_shape)
file1 = open(log_file_path, "a")
file1.write(log)
file1.close()
print(log)
net_end_time = time.time()
print("Done in {}s".format(net_end_time - net_start_time))
if __name__ == '__main__':
saveFramesWithLabels(video_store, json_store, train_lables_path, labels_path)
<file_sep># -*- coding:utf-8 -*-
import os
import pickle
import random
import sys
import time
import cv2
import numpy as np
import scipy.ndimage
class MultiScaleCornerCrop(object):
"""Crop the given PIL.Image to randomly selected size.
A crop of size is selected from scales of the original size.
A position of cropping is randomly selected from 4 corners and 1 center.
This crop is finally resized to given size.
Args:
scales: cropping scales of the original size
size: size of the smaller edge
interpolation: Default: PIL.Image.BILINEAR
"""
def __init__(self,
scales,
shape,
interpolation=cv2.INTER_AREA,
crop_positions=('c', 'tl', 'tr', 'bl', 'br')):
self.scales = scales
self.shape = shape
self.interpolation = interpolation
self.scale = None
self.crop_position = None
self.crop_positions = crop_positions
def __call__(self, img):
min_length = min(img.shape[0], img.shape[1])
crop_shape = int(min_length * self.scale)
image_width = img.shape[0]
image_height = img.shape[1]
x1, x2, y1, y2 = 0, 0, 0, 0
if self.crop_position == 'c':
center_x = image_width // 2
center_y = image_height // 2
box_half = crop_shape // 2
x1 = center_x - box_half
y1 = center_y - box_half
x2 = center_x + box_half
y2 = center_y + box_half
elif self.crop_position == 'tl':
x1 = 0
y1 = 0
x2 = crop_shape
y2 = crop_shape
elif self.crop_position == 'tr':
x1 = image_width - crop_shape
y1 = 0
x2 = image_width
y2 = crop_shape
elif self.crop_position == 'bl':
x1 = 0
y1 = image_height - crop_shape
x2 = crop_shape
y2 = image_height
elif self.crop_position == 'br':
x1 = image_width - crop_shape
y1 = image_height - crop_shape
x2 = image_width
y2 = image_height
img = img[y1: y2, x1: x2, :]
return cv2.resize(img, dsize=(self.shape[0], self.shape[1]), interpolation=self.interpolation)
def randomize_parameters(self):
self.scale = self.scales[random.randint(0, len(self.scales) - 1)]
self.crop_position = self.crop_positions[random.randint(0, len(self.scales) - 1)]
class SpatialElasticDisplacement(object):
def __init__(self, sigma=2.0, alpha=1.0, order=0, cval=0, mode="constant"):
self.alpha = alpha
self.sigma = sigma
self.order = order
self.cval = cval
self.mode = mode
def __call__(self, img):
if self.p < 0.50:
image = img
image_first_channel = image[:, :, 0]
indices_x, indices_y = self._generate_indices(image_first_channel.shape, alpha=self.alpha, sigma=self.sigma)
ret_image = (self._map_coordinates(
image,
indices_x,
indices_y,
order=self.order,
cval=self.cval,
mode=self.mode))
return ret_image
else:
return img
def _generate_indices(self, shape, alpha, sigma):
assert (len(shape) == 2), "shape: Should be of size 2!"
dx = scipy.ndimage.gaussian_filter((np.random.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha
dy = scipy.ndimage.gaussian_filter((np.random.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha
x, y = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing='ij')
return np.reshape(x + dx, (-1, 1)), np.reshape(y + dy, (-1, 1))
def _map_coordinates(self, image, indices_x, indices_y, order=1, cval=0, mode="constant"):
assert (len(image.shape) == 3), "image.shape: Should be of size 3!"
result = np.copy(image)
height, width = image.shape[0:2]
for c in range(image.shape[2]):
remapped_flat = scipy.ndimage.interpolation.map_coordinates(
image[..., c],
(indices_x, indices_y),
order=order,
cval=cval,
mode=mode
)
remapped = remapped_flat.reshape((height, width))
result[..., c] = remapped
return result
def randomize_parameters(self):
self.p = random.random()
self.alpha = 1 if random.random() > 0.5 else 2
def data_augmentation(batch, shape):
mean = [119.65972197, 100.70736938, 107.86672802]
std = [55.12904017, 52.20730189, 52.71543496]
mscc = MultiScaleCornerCrop(scales=[1, 0.93, 0.87, 0.80], shape=shape)
sed = SpatialElasticDisplacement()
ans_batch = np.zeros((batch.shape[0], batch.shape[1], shape[0], shape[1], 3))
for video_index in range(batch.shape[0]):
curr_video = batch[video_index]
mscc.randomize_parameters()
sed.randomize_parameters()
for frame_index in range(curr_video.shape[0]):
curr_image = curr_video[frame_index]
normalized_image = (curr_image - mean) / std
normalized_image = normalized_image / 255.0
cropped_and_scaled = mscc.__call__(normalized_image)
ans_batch[video_index, frame_index, :, :, :] = sed.__call__(cropped_and_scaled)
return ans_batch
<file_sep>import sys
sys.path.insert(1, "/home/axp798/axp798gallinahome/Gesture-Detection/")
import numpy as np
import matplotlib.pyplot as plt
import cv2
import os
import time
video_store = "/mnt/ConGD_phase_1/valid/"
labels_path = '/mnt/ConGD_labels/valid.txt'
store_frames_path = "/shared/valid/frames/"
with open(labels_path, 'r') as f:
lines = f.readlines()
num_sample = 0
prev_mean = 0
prev_squared_mean = 0
prev_samples = -1
global_squared_mean = 0
global_mean = 0
for curr_line in lines:
net_start_time = time.time()
line_ele = curr_line.split(' ')
dir_info = line_ele[0]
par_name, vid_name = dir_info.split('/')[0], dir_info.split('/')[1]
label_info = line_ele[1:]
for j, curr_label in enumerate(label_info):
video_start_time = time.time()
curr_label_info = curr_label.split(':')
rang = curr_label_info[0]
label = curr_label_info[1]
start_frame = rang.split(',')[0]
end_frame = rang.split(',')[1]
start_frame, end_frame = int(start_frame), int(end_frame)
img_height = 240
img_width = 320
num_sample += 1
print("{} video started.".format(num_sample))
frame_list = []
for ind in range(start_frame - 1, end_frame):
frame_name = "frame{}.jpg".format(ind + 1)
video_frame_dir = os.path.join(store_frames_path, "{}/{}".format(par_name, vid_name))
frame_path = os.path.join(video_frame_dir, frame_name)
frame = plt.imread(frame_path)
frame_list.append(frame)
frame_array = np.array(frame_list)
curr_mean = np.mean(frame_array, axis=(0, 1, 2))
curr_samples = len(frame_list) * img_height * img_width
if prev_samples != -1:
multiply_factor = (curr_samples / (curr_samples + prev_samples), prev_samples / (curr_samples + prev_samples))
global_mean = curr_mean * multiply_factor[0] + prev_mean * multiply_factor[1]
prev_samples += curr_samples
else:
global_mean = curr_mean
prev_samples = curr_samples
prev_mean = global_mean
print(prev_mean)
global_channel_mean = global_mean
num_sample = 0
for curr_line in lines:
net_start_time = time.time()
line_ele = curr_line.split(' ')
dir_info = line_ele[0]
par_name, vid_name = dir_info.split('/')[0], dir_info.split('/')[1]
label_info = line_ele[1:]
for j, curr_label in enumerate(label_info):
# TODO:
# get bounding box
# convert to frames
# get cut frames
video_start_time = time.time()
curr_label_info = curr_label.split(':')
rang = curr_label_info[0]
label = curr_label_info[1]
start_frame = rang.split(',')[0]
end_frame = rang.split(',')[1]
start_frame, end_frame = int(start_frame), int(end_frame)
img_height = 240
img_width = 320
num_sample += 1
print("{} video started.".format(num_sample))
frame_list = []
for ind in range(start_frame - 1, end_frame):
frame_name = "frame{}.jpg".format(ind + 1)
video_frame_dir = os.path.join(store_frames_path, "{}/{}".format(par_name, vid_name))
frame_path = os.path.join(video_frame_dir, frame_name)
frame = plt.imread(frame_path)
frame_list.append(frame - global_channel_mean)
frame_array = np.array(frame_list)
curr_squared_mean = np.mean(np.square(frame_array), axis=(0, 1, 2))
curr_samples = len(frame_list) * img_height * img_width
if prev_samples != -1:
multiply_factor = (curr_samples / (curr_samples + prev_samples), prev_samples / (curr_samples + prev_samples))
global_squared_mean = curr_squared_mean * multiply_factor[0] + prev_squared_mean * multiply_factor[1]
prev_samples += curr_samples
else:
global_squared_mean = curr_squared_mean
prev_samples = curr_samples
prev_squared_mean = global_squared_mean
print(prev_squared_mean)
global_channel_std = np.sqrt(prev_squared_mean)
print(global_channel_mean)
print(global_channel_std)
<file_sep>import sys
sys.path.insert(1, "/home/axp798/axp798gallinahome/Gesture-Detection/")
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cv2
import os
import pickle
import image_acquisition2 as img_ac
import time
video_store = "/home/axp798/axp798gallinahome/ConGD/ConGD_phase_1/train/"
json_store = "/home/axp798/axp798gallinahome/store/train/json/"
labels_path = '/home/axp798/axp798gallinahome/ConGD/ConGD_labels/train.txt'
store_frames_path = "/home/axp798/axp798gallinahome/store/train/frames/"
def store_frames(dir_name, vid_name):
vid_path = os.path.join(video_store, "{}/{}.M.avi".format(dir_name, vid_name))
video_par_dir = os.path.join(store_frames_path, dir_name)
video_frame_dir = os.path.join(store_frames_path, "{}/{}".format(dir_name, vid_name))
if not os.path.exists(video_par_dir):
os.mkdir(video_par_dir)
if not os.path.exists(video_frame_dir):
os.mkdir(video_frame_dir)
vidcap = cv2.VideoCapture(vid_path)
success, image = vidcap.read()
count = 1
while success:
cv2.imwrite(os.path.join(video_frame_dir, "frame{}.jpg".format(count)), image) # save frame as JPEG file
success, image = vidcap.read()
count += 1
def getFrameCut(frame, bounding_box):
'''
:param frame: numpy array of image
:param bounding_box: list of bounds of the box
:return: bounding box of the numpy array
'''
left_most = int(bounding_box[0])
right_most = int(bounding_box[1])
top_most = int(bounding_box[2])
bottom_most = int(bounding_box[3])
return frame[top_most: bottom_most, left_most: right_most]
def returnBoundingBox(json_path, img_height, img_width):
'''
:param json_path: path of folder containing json files of the current video
:param img_height: height of image frame
:param img_width: width of image frame
:return: left, right top and bottom bounds
'''
global_val = [100000, 0, 100000, img_height]
return getBoundingBox(json_path, global_val, img_height, img_width)
def getVideoDimension(video_path):
'''
:param video_name: name of the video for which dimension is asked
:return: shape of the video frame
'''
frame_list = os.listdir(video_path)
sample_image_path = os.path.join(video_path, frame_list[0])
curr_image = plt.imread(sample_image_path)
return curr_image.shape
def saveFramesWithLabels(video_store, json_store, labels_path):
'''
:param video_store: path of folder containing all the videos
:param json_store: path of the folder containing json files of all the videos
:param train_lables_path: path of file containing video names with their labels
:param labels_path: path of file containing index of each gesture
:return: stores a dictionary with key as a list of numpy array of video frame and value as video label
'''
num_videos = 0
start_time = time.time()
save_video_path = '/home/axp798/axp798gallinahome/data/chalearn/train_112/'
save_bounding_box_path = "/home/axp798/axp798gallinahome/data/chalearn/train_boxes/"
log_file_path = "/home/axp798/axp798gallinahome/Gesture-Detection/assets/chalearn_dataset/log1.txt"
file1 = open(log_file_path, "w")
file1.write("Logs: \n")
file1.close()
bounding_box_list = []
incorrect_box = []
with open(labels_path, 'r') as f:
lines = f.readlines()
for curr_line in lines:
net_start_time = time.time()
line_ele = curr_line.split(' ')
dir_info = line_ele[0]
par_name, vid_name = dir_info.split('/')[0], dir_info.split('/')[1]
label_info = line_ele[1:]
for j, curr_label in enumerate(label_info):
# TODO:
# get bounding box
# convert to frames
# get cut frames
num_videos += 1
video_start_time = time.time()
curr_label_info = curr_label.split(':')
rang = curr_label_info[0]
label = curr_label_info[1]
start_frame = rang.split(',')[0]
end_frame = rang.split(',')[1]
start_frame, end_frame = int(start_frame), int(end_frame)
# Get bounding box
dir_path = os.path.join(json_store, par_name)
vid_path = os.path.join(dir_path, vid_name)
img_height = 240
img_width = 320
json_path = vid_path
global_val = [100000, 0, 100000, img_height]
bounding_box = img_ac.getBoundingBox(json_path, vid_name, global_val, img_height, img_width, start_frame,
end_frame)
# store frames
if j == 0:
store_frames(par_name, vid_name)
# get cut frames
cut_frame_list = []
check = 0
for ind in range(start_frame - 1, end_frame):
frame_name = "frame{}.jpg".format(ind + 1)
video_frame_dir = os.path.join(store_frames_path, "{}/{}".format(par_name, vid_name))
frame_path = os.path.join(video_frame_dir, frame_name)
frame = plt.imread(frame_path)
frame_cut = getFrameCut(frame, bounding_box)
if frame_cut.size == 0:
incorrect_box.append([dir_info, start_frame, end_frame])
check = 1
break
res = cv2.resize(frame_cut, dsize=(112, 112), interpolation=cv2.INTER_CUBIC)
cut_frame_list.append(res)
if check:
log1 = "{}-{} ; incorrect boxes: {}-{}! \n".format(num_videos, dir_info,
len(incorrect_box), incorrect_box)
file1 = open(log_file_path, "a")
file1.write(log1)
file1.close()
print(log1)
continue
cut_frame_array = np.array(cut_frame_list)
video_shape = cut_frame_array.shape
bounding_box_list.append(["{}_{}-{}".format(dir_info, start_frame, end_frame), bounding_box, label])
pkl_vid_name = "{}-{}-{}_{}-{}.pkl".format(num_videos, par_name, vid_name, start_frame, end_frame)
with open(save_video_path + pkl_vid_name, 'wb') as f:
pickle.dump([cut_frame_array, label], f)
with open(save_bounding_box_path + "boxes.pkl", 'wb') as f:
pickle.dump(bounding_box_list, f)
video_end_time = time.time()
log = "{}-{}-{} done in {}s ----- bounding box: {}, video shape: {} \n".format(num_videos, dir_info,
"{}_{}".format(start_frame,
end_frame),
video_end_time - video_start_time,
bounding_box, video_shape)
file1 = open(log_file_path, "a")
file1.write(log)
file1.close()
print(log)
net_end_time = time.time()
print("########### Line {} done in {}s ###############".format(dir_info, net_end_time - net_start_time))
end_time = time.time()
print("Done in {}s".format(end_time - start_time))
if __name__ == '__main__':
saveFramesWithLabels(video_store, json_store, labels_path)
<file_sep># Importing Libraries
import os
import cv2
# Path to openpose singularity image being used
openpose_simg = "/home/axp798/axp798gallinahome/openpose_1_0_5.simg"
# Path to directory for storing rendered videos and json files from train videos
store_path = "/home/axp798/axp798gallinahome/store/train/"
# directory to store rendered videos in the same format as train videos are stored
videos_store = os.path.join(store_path, "videos/")
# directory to store json files containing hand, face and body coordinates from the videos
json_store = os.path.join(store_path, "json/")
# Path to list of directories containing training videos
train_dir = "/home/axp798/axp798gallinahome/ConGD/ConGD_phase_1/train/"
video_bind = ""
lib_dir = "/home/axp798/axp798gallinahome/" # Path to directory to be accessible from within the singularity container
def create_frames(video_path, dir_name, video_name, parts):
# Creates and stores video frames from the given video
vidcap = cv2.VideoCapture(video_path)
done, frame = vidcap.read()
num = 0
if not os.path.exists(os.path.join(store_path, "frames/{}/{}/".format(dir_name, parts[0]))):
# create directory to store frames
os.mkdir(os.path.join(store_path, "frames/{}/{}/".format(dir_name, parts[0])))
while done:
frame_store = os.path.join(store_path, "frames/{}/{}/frames{}.jpg".format(dir_name, parts[0], num))
cv2.imwrite(frame_store, frame) # save frame as JPEG file
done, frame = vidcap.read()
print('Read a new frame: ', done)
num += 1
return
def delete_video(write_video_path):
os.system("rm {}".format(write_video_path)) # execute the delete video command
return
def main():
# Uses the videos in the train_dir to extract json files from them using openpose,
# stores videos having coordinates in them, creates frames from them and deletes the videos finally
dir_ptr = 15
for dir_name in os.listdir(train_dir)[14: 100]:
print("Directory {} started!".format(dir_ptr))
# dir_name = 001, 002, ..... , 027, 028, ..... , 128, 129, ....
print("{} directory started ".format(dir_name))
# video_dir = "/home/axp798/axp798gallinahome/ConGD/ConGD_phase_1/train/001/"
video_dir = os.path.join(train_dir, dir_name)
if not os.path.exists(os.path.join(store_path, "frames/{}/".format(dir_name))):
os.mkdir(os.path.join(store_path, "frames/{}/".format(dir_name)))
if not os.path.exists(os.path.join(videos_store, "{}/".format(dir_name))):
# creating the directory to store videos
# os.path.join(videos_store, "{}/".format(dir_name)) = "/home/axp798/axp798gallinahome/store/train/videos/001/"
os.mkdir(os.path.join(videos_store, "{}/".format(dir_name)))
if not os.path.exists(os.path.join(json_store, "{}/".format(dir_name))):
os.mkdir(os.path.join(json_store, "{}/".format(dir_name)))
video_ptr = 1
for video_name in os.listdir(video_dir):
# video_name = 00001.K.avi, 00001.M.avi etc.
# .k extension is for depth frames videos
# .M extension videos is for 3D RGB videos
parts = video_name.split('.') # parts = [00001, k, avi] or parts = [00001, M, avi]
if (parts[1] == 'K'):
# excluding the depth frames videos
continue
else:
# prcessing the RGB videos
print("Directory {} and video {} started!".format(dir_ptr, video_ptr))
print("{} video directory started ".format(video_name))
add = "{}/{}".format(dir_name, video_name) # add = "001/00001.M.avi"
video_path = os.path.join(train_dir, add)
# video_path = "/home/axp798/axp798gallinahome/ConGD/ConGD_phase_1/train/001/00001.M.avi"
print(video_path)
# write_video_path = "/home/axp798/axp798gallinahome/store/train/videos/001/result_00001.avi"
write_video_path = os.path.join(videos_store, "{}/result_{}.avi".format(dir_name, parts[0]))
# write_json_path = "/home/axp798/axp798gallinahome/store/train/json/001/00001"
write_json_path = os.path.join(json_store, "{}/{}/".format(dir_name, parts[0]))
video_bind = video_path
print("command started!")
command = "singularity run --nv --bind {},{} {} --video {} --write_keypoint_json {} --no_display " \
"--render_pose 0 " \
"--hand"\
.format(
video_path,
lib_dir,
openpose_simg,
video_path,
write_json_path)
os.system(command) # run the command on terminal
# convert the rendered videos with openpose coordinates to frames
create_frames(write_video_path, dir_name, video_name, parts)
# delete the rendered videos to save disk space
delete_video(write_video_path)
video_ptr += 1
print("Directory {} and video {} completed!".format(dir_ptr, video_ptr))
dir_ptr += 1
print("Directory {} completed!".format(dir_ptr))
if __name__ == '__main__':
main()
<file_sep>import argparse
import os
import pickle
import random
import sys
import time
from resnext import ResNeXt
import c3D as conv3d4
import c3D2 as conv3d2
import c3D3 as conv3d3
import c3D_main as conv3d1
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from chalearn_utils import data_augmentation
from tensorflow.python.client import device_lib
# from AdamWOptimizer import create_optimizer
# from tensorflow.keras import *
# from tensorflow.keras.layers import *
# from tensorflow.keras.models import *
def append_frames(cut_frame_array, required_num_frames):
appended_list_of_frames = list(cut_frame_array)
num_curr_frames = cut_frame_array.shape[0]
num_more_frames = required_num_frames - num_curr_frames
for i in range(num_more_frames):
appended_list_of_frames.append(cut_frame_array[i % num_curr_frames])
return np.array(appended_list_of_frames)
def get_video_reduced_fps(appended_video, factor):
num_total_frames = appended_video.shape[0]
final_video = []
for index in range(0, num_total_frames, factor):
final_video.append(appended_video[index])
return np.array(final_video)
def get_final_video(par_name, vid_name, label_info, num_video_in_curr_line, window_size, set='train'):
curr_label = label_info[num_video_in_curr_line]
curr_label_info = curr_label.split(':')
rang = curr_label_info[0]
label = curr_label_info[1]
start_frame = rang.split(',')[0]
end_frame = rang.split(',')[1]
start_frame, end_frame = int(start_frame), int(end_frame)
frame_list = []
for ind in range(start_frame - 1, end_frame):
frame_name = "frame{}.jpg".format(ind + 1)
if set == 'train':
video_frame_dir = os.path.join(train_frames_path, "{}/{}".format(par_name, vid_name))
else:
video_frame_dir = os.path.join(valid_frames_path, "{}/{}".format(par_name, vid_name))
frame_path = os.path.join(video_frame_dir, frame_name)
frame = plt.imread(frame_path)
frame_list.append(frame)
frame_array = np.array(frame_list)
num_frames = frame_array.shape[0]
required_num_frames = (int(num_frames / window_size) + 1) * window_size
appended_video = append_frames(frame_array, required_num_frames) # returns numpy array
factor = int(appended_video.shape[0] / window_size)
final_video = get_video_reduced_fps(appended_video, factor) # returns numpy array
return final_video, label
def extract_line_info(curr_line):
line_ele = curr_line.split(' ')
dir_info = line_ele[0]
par_name, vid_name = dir_info.split('/')[0], dir_info.split('/')[1]
label_info = line_ele[1:]
# total_video_in_curr_line = len(label_info)
return par_name, vid_name, label_info
def train_neural_network(x_inpuT,
y_inpuT,
labels_path,
val_labels_path,
save_loss_path,
save_model_path,
batch_size,
val_batch_size,
image_height,
image_width,
learning_rate,
weight_decay,
num_iter,
epochs,
which_model,
num_train_videos,
num_val_videos,
win_size):
with tf.name_scope("cross_entropy"):
prediction = 0
shapes_list = None
if which_model == 1:
prediction, shapes_list = conv3d1.inference(x_inpuT)
elif which_model == 2:
resnext_model = ResNeXt(x_inpuT, tf.constant(True, dtype=tf.bool))
prediction = resnext_model.Build_ResNext(x_inpuT)
elif which_model == 3:
prediction = conv3d2.inference(x_inpuT)
elif which_model == 4:
prediction = conv3d3.inference(x_inpuT)
elif which_model == 5:
prediction, shapes_list = conv3d4.inference(x_inpuT)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y_inpuT))
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
# optimizer = 0
if weight_decay is not None:
print("weight decay applied.")
optimizer = create_optimizer(cost, learning_rate, weight_decay)
else:
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)
with tf.name_scope("accuracy"):
correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y_inpuT, 1))
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
# saver = tf.train.Saver(save_relative_paths=True)
print("Calculating total parameters in the model")
total_parameters = 0
for variable in tf.trainable_variables():
# shape is an array of tf.Dimension
shape = variable.get_shape()
print(shape)
# print(len(shape))
variable_parameters = 1
for dim in shape:
# print(dim)
variable_parameters *= dim.value
# print(variable_parameters)
total_parameters += variable_parameters
print(total_parameters)
if shapes_list is not None:
print(shapes_list)
gpu_options = tf.GPUOptions(allow_growth=True)
with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:
print("session starts!")
sess.run(tf.global_variables_initializer())
start_time = time.time()
epoch_loss_list = []
val_loss_list = []
ori_height = 240
ori_width = 320
with open(labels_path, 'r') as f:
lines = f.readlines()
with open(val_labels_path, 'r') as f:
val_lines = f.readlines()
for epoch in range(epochs):
print("Epoch {} started!".format(epoch + 1))
epoch_start_time = time.time()
epoch_loss = 0
train_acc = 0
window_size = win_size
random.seed(7)
print("Random seed fixed for training.")
num_videos = num_train_videos
num_batches = int(num_videos / batch_size)
num_iter_total_data_per_epoch = num_iter
for iter_index in range(num_iter_total_data_per_epoch):
prev_line = -1
num_line = 0
num_video_in_curr_line = 0
# for batch_num in range(num_batches):
batch_x = np.zeros((batch_size, depth, ori_height, ori_width, 3))
batch_y = np.zeros((batch_size, num_classes))
batch_index = 0
num_batch_completed = 0
while True:
if prev_line != num_line:
curr_line = lines[num_line]
par_name, vid_name, label_info = extract_line_info(curr_line)
total_video_in_curr_line = len(label_info)
final_video, label = get_final_video(par_name, vid_name, label_info, num_video_in_curr_line, window_size, set='train')
# print(final_video.shape)
batch_x[batch_index, :, :, :, :] = final_video
basic_line = [0] * num_classes
basic_line[int(label) - 1] = 1
basic_label = basic_line
batch_y[batch_index, :] = np.array(basic_label)
batch_index += 1
if batch_index == batch_size:
# train_batch
batch_start_time = time.time()
mini_batch_x = data_augmentation(batch_x, (image_height, image_width))
# mini_batch_x = mini_batch_x / 255.0
mini_batch_y = batch_y
perm = np.random.permutation(batch_size)
mini_batch_x = mini_batch_x[perm]
mini_batch_y = mini_batch_y[perm]
_optimizer, _cost, _prediction, _accuracy = sess.run([optimizer, cost, prediction, accuracy],
feed_dict={x_inpuT: mini_batch_x,
y_inpuT: mini_batch_y})
epoch_loss += _cost
train_acc += _accuracy
num_batch_completed += 1
batch_end_time = time.time()
total_train_batch_completed = iter_index * num_batches + num_batch_completed
log1 = "\rEpoch: {}, " \
"iter: {}, " \
"batches completed: {}, " \
"time taken: {:.5f}, " \
"loss: {:.6f}, " \
"accuracy: {:.4f} \n". \
format(
epoch + 1,
iter_index + 1,
total_train_batch_completed,
batch_end_time - batch_start_time,
epoch_loss / (batch_size * total_train_batch_completed),
_accuracy)
print(log1)
sys.stdout.flush()
if num_batch_completed == num_batches:
break
batch_index = 0
batch_x = np.zeros((batch_size, depth, ori_height, ori_width, 3))
batch_y = np.zeros((batch_size, num_classes))
prev_line = num_line
num_video_in_curr_line += 1
if num_video_in_curr_line == total_video_in_curr_line:
num_video_in_curr_line = 0
num_line += 1
# validation loss
print("<---------------- Validation Set started ---------------->")
val_loss = 0
val_acc = 0
val_num_videos = num_val_videos
val_num_batches = int(val_num_videos / val_batch_size)
random.seed(23)
print("Random seed fixed for validation.")
for __ in range(num_iter_total_data_per_epoch):
prev_line = -1
num_line = 0
num_video_in_curr_line = 0
# for batch_num in range(val_num_batches):
#
val_batch_x = np.zeros((val_batch_size, depth, ori_height, ori_width, 3))
val_batch_y = np.zeros((val_batch_size, num_classes))
batch_index = 0
val_num_batch_completed = 0
while True:
if prev_line != num_line:
curr_line = val_lines[num_line]
par_name, vid_name, label_info = extract_line_info(curr_line)
total_video_in_curr_line = len(label_info)
# process video
final_video, label = get_final_video(par_name, vid_name, label_info, num_video_in_curr_line, window_size, set='valid')
# print(final_video.shape)
val_batch_x[batch_index, :, :, :, :] = final_video
basic_line = [0] * num_classes
basic_line[int(label) - 1] = 1
basic_label = basic_line
val_batch_y[batch_index, :] = np.array(basic_label)
batch_index += 1
if batch_index == val_batch_size:
val_batch_x = data_augmentation(val_batch_x, (image_height, image_width))
# val_batch_x = val_batch_x / 255.0
perm = np.random.permutation(batch_size)
val_batch_x = val_batch_x[perm]
val_batch_y = val_batch_y[perm]
val_cost, val_batch_accuracy = sess.run([cost, accuracy],
feed_dict={x_inpuT: val_batch_x, y_inpuT: val_batch_y})
val_acc += val_batch_accuracy
val_loss += val_cost
val_num_batch_completed += 1
if val_num_batch_completed == val_num_batches:
break
val_batch_x = np.zeros((val_batch_size, depth, ori_height, ori_width, 3))
val_batch_y = np.zeros((val_batch_size, num_classes))
batch_index = 0
prev_line = num_line
num_video_in_curr_line += 1
if num_video_in_curr_line == total_video_in_curr_line:
num_video_in_curr_line = 0
num_line += 1
epoch_end_time = time.time()
total_train_batch_completed = num_iter_total_data_per_epoch * num_batch_completed
total_val_num_batch_completed = num_iter_total_data_per_epoch * val_num_batch_completed
epoch_loss = epoch_loss / (batch_size * total_train_batch_completed)
train_acc = train_acc / total_train_batch_completed
val_loss /= (val_batch_size * total_val_num_batch_completed)
val_acc = val_acc / total_val_num_batch_completed
log3 = "Epoch {} done; " \
"Time Taken: {:.4f}s; " \
"Train_loss: {:.6f}; " \
"Val_loss: {:.6f}; " \
"Train_acc: {:.4f}; " \
"Val_acc: {:.4f}; " \
"Train batches: {}; " \
"Val batches: {};\n". \
format(epoch + 1, epoch_end_time - epoch_start_time, epoch_loss, val_loss, train_acc, val_acc,
num_iter_total_data_per_epoch * num_batch_completed,
num_iter_total_data_per_epoch * val_num_batch_completed)
print(log3)
if save_loss_path is not None:
file1 = open(save_loss_path, "a")
file1.write(log3)
file1.close()
epoch_loss_list.append(epoch_loss)
val_loss_list.append(val_loss)
if save_model_path is not None:
saver.save(sess, save_model_path)
end_time = time.time()
print('Time elapse: ', str(end_time - start_time))
print(epoch_loss_list)
if save_loss_path is not None:
file1 = open(save_loss_path, "a")
file1.write("Train Loss List: {} \n".format(str(epoch_loss_list)))
file1.write("Val Loss List: {} \n".format(str(val_loss_list)))
file1.close()
if __name__ == '__main__':
np.random.seed(0)
parser = argparse.ArgumentParser()
parser.add_argument('-cs', action='store', dest='check_singularity', type=int)
parser.add_argument('-ih', action='store', dest='height', type=int)
parser.add_argument('-iw', action='store', dest='width', type=int)
parser.add_argument('-bs', action='store', dest='batch_size', type=int)
parser.add_argument('-vbs', action='store', dest='val_batch_size', type=int)
parser.add_argument('-lr', action='store', dest='learning_rate', type=float)
parser.add_argument('-wd', action='store', dest='weight_decay', type=float, const=None)
parser.add_argument('-ni', action='store', dest='num_iter', type=int)
parser.add_argument('-e', action='store', dest='epochs', type=int)
parser.add_argument('-ntv', action='store', dest='num_train_videos', type=int)
parser.add_argument('-nvv', action='store', dest='num_val_videos', type=int)
parser.add_argument('-ws', action='store', dest='win_size', type=int)
parser.add_argument('-slp', action='store', dest='save_loss_path', const=None)
parser.add_argument('-smp', action='store', dest='save_model_path', const=None)
parser.add_argument('-mn', action='store', dest='model_num', type=int)
parser.add_argument('-vd', action='store', dest='visible_devices')
parser.add_argument('-nd', action='store', dest='num_device', type=int)
results = parser.parse_args()
arg_check_singularity = results.check_singularity
arg_height = results.height
arg_width = results.width
arg_batch_size = results.batch_size
arg_val_batch_size = results.val_batch_size
arg_lr = results.learning_rate
arg_wd = results.weight_decay
arg_num_iter = results.num_iter
arg_epochs = results.epochs
arg_num_val_videos = results.num_val_videos
arg_num_train_videos = results.num_train_videos
arg_win_size = results.win_size
arg_save_loss_path = results.save_loss_path
arg_save_model_path = results.save_model_path
arg_model_num = results.model_num
arg_visible_devices = results.visible_devices
arg_num_device = results.num_device
labels_path = '/home/axp798/axp798gallinahome/ConGD/ConGD_labels/train.txt'
val_labels_path = '/home/axp798/axp798gallinahome/ConGD/ConGD_labels/valid.txt'
train_frames_path = "/home/axp798/axp798gallinahome/store/train/frames/"
valid_frames_path = "/home/axp798/axp798gallinahome/store/valid/frames/"
save_loss = "/home/axp798/axp798gallinahome/Gesture-Detection/models/loss_chalearn/"
save_model = "/home/axp798/axp798gallinahome/Gesture-Detection/models/saved_models_chalearn/"
if arg_check_singularity:
labels_path = '/mnt/ConGD_labels/train.txt'
val_labels_path = '/mnt/ConGD_labels/valid.txt'
train_frames_path = "/shared/train/frames/"
valid_frames_path = "/shared/valid/frames/"
save_loss = "/home/models/loss_chalearn/"
save_model = "/home/models/saved_models_chalearn/"
ar_save_loss_path = None
if arg_save_loss_path is not None:
ar_save_loss_path = save_loss + "{}".format(arg_save_loss_path)
ar_save_model_path = None
if arg_save_model_path is not None:
path = save_model + "{}/".format(arg_save_model_path)
if not os.path.exists(path):
os.mkdir(path)
ar_save_model_path = path + "model"
if ar_save_loss_path is not None:
file1 = open(ar_save_loss_path, "w")
file1.write("Params: {} \n".format(results))
file1.write("Losses: \n")
file1.close()
depth = arg_win_size
num_classes = 249
os.environ['CUDA_VISIBLE_DEVICES'] = "{}".format(arg_visible_devices)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = "2"
print(device_lib.list_local_devices())
choose_device = "/device:GPU:{}".format(arg_num_device)
tf.reset_default_graph()
with tf.device(choose_device):
x_inpuT = tf.placeholder(tf.float32, shape=[arg_batch_size, depth, arg_height, arg_width, 3])
y_inpuT = tf.placeholder(tf.float32, shape=[arg_batch_size, num_classes])
train_neural_network(x_inpuT, y_inpuT, labels_path, val_labels_path,
save_loss_path=ar_save_loss_path,
save_model_path=ar_save_model_path,
batch_size=arg_batch_size,
val_batch_size=arg_val_batch_size,
image_height=arg_height,
image_width=arg_width,
learning_rate=arg_lr,
weight_decay=arg_wd,
num_iter=arg_num_iter,
epochs=arg_epochs,
which_model=arg_model_num,
num_train_videos=arg_num_train_videos,
num_val_videos=arg_num_val_videos,
win_size=arg_win_size)
<file_sep>import os
import cv2
import matplotlib.pyplot as plt
import numpy as np
def getFrameCut(frame, bounding_box):
'''
:param frame: numpy array of image
:param bounding_box: list of bounds of the box
:return: bounding box of the numpy array
'''
left_most = int(bounding_box[0])
right_most = int(bounding_box[1])
top_most = int(bounding_box[2])
bottom_most = int(bounding_box[3])
return frame[top_most: bottom_most, left_most: right_most]
def get_frame_array(lst_item, video_store, image_height, image_width):
'''
:param lst_item: [video_name, bounding_box, label]
:param video_store: path to jester videos
:param image_height: required height of each frame
:param image_width: required width of each frame
:return: frame array with given bounding box and image dimensions
'''
mod_video_name = lst_item[0]
video_name = mod_video_name.lstrip("0")
bounding_box = lst_item[1]
frame_list = os.listdir(os.path.join(video_store, video_name))
cut_frame_list = []
for ind in range(len(frame_list)):
frame_name = str(ind + 1).zfill(5) + ".jpg"
frame_path = os.path.join(video_store + video_name, frame_name)
frame = plt.imread(frame_path)
frame_cut = getFrameCut(frame, bounding_box)
res = cv2.resize(frame_cut, dsize=(image_height, image_width), interpolation=cv2.INTER_CUBIC)
cut_frame_list.append(res)
cut_frame_array = np.array(cut_frame_list)
return cut_frame_array
<file_sep>import argparse
import os
import pickle
import random
import sys
import time
import numpy as np
import resnet_10 as resnet
import tensorflow as tf
from AdamWOptimizer import create_optimizer
from tensorflow.python.client import device_lib
def append_frames(cut_frame_array, required_num_frames):
appended_list_of_frames = list(cut_frame_array)
num_curr_frames = cut_frame_array.shape[0]
num_more_frames = required_num_frames - num_curr_frames
for i in range(num_more_frames):
appended_list_of_frames.append(cut_frame_array[i % num_curr_frames])
return np.array(appended_list_of_frames)
def train_neural_network(x_inpuT,
y_inpuT,
data_path,
val_data_path,
save_loss_path,
save_model_path,
batch_size,
val_batch_size,
learning_rate,
weight_decay,
epochs,
which_model,
num_val_videos,
random_clips,
win_size,
ignore_factor):
with tf.name_scope("cross_entropy"):
prediction = 0
if which_model == 1:
prediction = resnet.inference(x_inpuT)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y_inpuT))
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
# optimizer = 0
if weight_decay is not None:
print("weight decay applied.")
optimizer = create_optimizer(cost, learning_rate, weight_decay)
else:
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)
with tf.name_scope("accuracy"):
correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y_inpuT, 1))
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
saver = tf.train.Saver()
gpu_options = tf.GPUOptions(allow_growth=True)
with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:
print("session starts!")
sess.run(tf.global_variables_initializer())
start_time = time.time()
epoch_loss_list = []
val_loss_list = []
pkl_files_list = os.listdir(data_path)
val_pkl_files_list = os.listdir(val_data_path)
for epoch in range(epochs):
print("Epoch {} started!".format(epoch + 1))
epoch_start_time = time.time()
epoch_loss = 0
train_acc = 0
num_batch_completed = 0
window_size = win_size
num_clips_per_video = random_clips
random.seed(7)
print("Random seed fixed for training.")
# pkl_files_list = pkl_files_list[ : 64]
num_videos = len(pkl_files_list) - (len(pkl_files_list) % batch_size)
num_blocks = int(num_videos / batch_size)
block_x = np.zeros((num_clips_per_video, batch_size, depth, height, width, 3))
block_y = np.zeros((num_clips_per_video, batch_size, num_classes))
for block_index in range(num_blocks):
for index_in_batch, pkl_file in enumerate(
pkl_files_list[block_index * batch_size: (block_index + 1) * batch_size]):
with open(os.path.join(data_path, pkl_file), 'rb') as f:
frames_and_label = pickle.load(f)
cut_frame_array = frames_and_label[0]
label = frames_and_label[1]
num_frames = cut_frame_array.shape[0]
required_num_frames = int(window_size * ignore_factor)
if num_frames <= required_num_frames:
# print(num_frames, required_num_frames)
cut_frame_array = append_frames(cut_frame_array, required_num_frames)
num_frames = cut_frame_array.shape[0]
# print(num_frames)
for batch_index in range(num_clips_per_video):
start_frame = random.randint(0, num_frames - window_size)
end_frame = start_frame + window_size
block_x[batch_index, index_in_batch, :, :, :, :] = np.array(
cut_frame_array[start_frame: end_frame, :, :, :])
basic_line = [0] * num_classes
basic_line[int(label) - 1] = 1
basic_label = basic_line
block_y[batch_index, index_in_batch, :] = np.array(basic_label)
for batch_index in range(num_clips_per_video):
batch_start_time = time.time()
mini_batch_x = block_x[batch_index, :, :, :, :, :]
mini_batch_x = mini_batch_x / 255.0
mini_batch_y = block_y[batch_index, :, :]
perm = np.random.permutation(batch_size)
mini_batch_x = mini_batch_x[perm]
mini_batch_y = mini_batch_y[perm]
_optimizer, _cost, _prediction, _accuracy = sess.run([optimizer, cost, prediction, accuracy],
feed_dict={x_inpuT: mini_batch_x,
y_inpuT: mini_batch_y})
epoch_loss += _cost
train_acc += _accuracy
num_batch_completed += 1
batch_end_time = time.time()
log1 = "\rEpoch: {}, " \
"batches completed: {}, " \
"time taken: {:.5f}, " \
"loss: {:.6f}, " \
"accuracy: {:.4f} \n". \
format(
epoch + 1,
num_batch_completed,
batch_end_time - batch_start_time,
epoch_loss / (batch_size * num_batch_completed),
_accuracy)
print(log1)
sys.stdout.flush()
del block_x, block_y
# validation loss
val_loss = 0
val_acc = 0
val_num_batch_completed = 0
num_clips_per_video = 1
val_num_videos = num_val_videos
val_num_blocks = int(val_num_videos / val_batch_size)
val_block_x = np.zeros((num_clips_per_video, val_batch_size, depth, height, width, 3))
val_block_y = np.zeros((num_clips_per_video, val_batch_size, num_classes))
random.seed(23)
print("Random seed fixed for validation.")
for block_index in range(val_num_blocks):
for index_in_batch, val_pkl_file in enumerate(
val_pkl_files_list[block_index * val_batch_size: (block_index + 1) * val_batch_size]):
with open(os.path.join(val_data_path, val_pkl_file), 'rb') as f:
frames_and_label = pickle.load(f)
cut_frame_array = frames_and_label[0]
label = frames_and_label[1]
num_frames = cut_frame_array.shape[0]
required_num_frames = int(window_size * ignore_factor)
if num_frames <= window_size:
cut_frame_array = append_frames(cut_frame_array, required_num_frames)
num_frames = cut_frame_array.shape[0]
for batch_index in range(num_clips_per_video):
start_frame = random.randint(0, num_frames - window_size)
end_frame = start_frame + window_size
val_block_x[batch_index, index_in_batch, :, :, :, :] = np.array(
cut_frame_array[start_frame: end_frame, :, :, :])
basic_line = [0] * num_classes
basic_line[int(label) - 1] = 1
basic_label = basic_line
val_block_y[batch_index, index_in_batch, :] = np.array(basic_label)
for batch_index in range(num_clips_per_video):
val_batch_x = val_block_x[batch_index, :, :, :, :, :]
val_batch_x = val_batch_x / 255.0
val_batch_y = val_block_y[batch_index, :, :]
val_cost, val_batch_accuracy = sess.run([cost, accuracy],
feed_dict={x_inpuT: val_batch_x, y_inpuT: val_batch_y})
val_acc += val_batch_accuracy
val_loss += val_cost
val_num_batch_completed += 1
del val_block_x, val_block_y
epoch_loss = epoch_loss / (batch_size * num_batch_completed)
train_acc = train_acc / num_batch_completed
val_loss /= (val_batch_size * val_num_batch_completed)
val_acc = val_acc / val_num_batch_completed
epoch_end_time = time.time()
log3 = "Epoch {} done; " \
"Time Taken: {:.4f}s; " \
"Train_loss: {:.6f}; " \
"Val_loss: {:.6f}; " \
"Train_acc: {:.4f}; " \
"Val_acc: {:.4f}; " \
"Train batches: {}; " \
"Val batches: {};\n". \
format(epoch + 1, epoch_end_time - epoch_start_time, epoch_loss, val_loss, train_acc, val_acc,
num_batch_completed, val_num_batch_completed)
print(log3)
if save_loss_path is not None:
file1 = open(save_loss_path, "a")
file1.write(log3)
file1.close()
epoch_loss_list.append(epoch_loss)
val_loss_list.append(val_loss)
if save_model_path is not None:
saver.save(sess, save_model_path)
end_time = time.time()
print('Time elapse: ', str(end_time - start_time))
print(epoch_loss_list)
if save_loss_path is not None:
file1 = open(save_loss_path, "a")
file1.write("Train Loss List: {} \n".format(str(epoch_loss_list)))
file1.write("Val Loss List: {} \n".format(str(val_loss_list)))
file1.close()
if __name__ == '__main__':
np.random.seed(0)
parser = argparse.ArgumentParser()
parser.add_argument('-bs', action='store', dest='batch_size', type=int)
parser.add_argument('-vbs', action='store', dest='val_batch_size', type=int)
parser.add_argument('-lr', action='store', dest='learning_rate', type=float)
parser.add_argument('-wd', action='store', dest='weight_decay', type=float, const=None)
parser.add_argument('-e', action='store', dest='epochs', type=int)
parser.add_argument('-nvv', action='store', dest='num_val_videos', type=int)
parser.add_argument('-rc', action='store', dest='random_clips', type=int)
parser.add_argument('-ws', action='store', dest='win_size', type=int)
parser.add_argument('-slp', action='store', dest='save_loss_path', const=None)
parser.add_argument('-smp', action='store', dest='save_model_path', const=None)
parser.add_argument('-mn', action='store', dest='model_num', type=int)
parser.add_argument('-vd', action='store', dest='visible_devices')
parser.add_argument('-nd', action='store', dest='num_device', type=int)
parser.add_argument('-if', action='store', dest='ign_fact', type=float, const=None)
results = parser.parse_args()
arg_batch_size = results.batch_size
arg_val_batch_size = results.val_batch_size
arg_lr = results.learning_rate
arg_wd = results.weight_decay
arg_epochs = results.epochs
arg_num_val_videos = results.num_val_videos
arg_random_clips = results.random_clips
arg_win_size = results.win_size
arg_save_loss_path = results.save_loss_path
arg_save_model_path = results.save_model_path
arg_model_num = results.model_num
arg_visible_devices = results.visible_devices
arg_num_device = results.num_device
arg_ign_fact = results.ign_fact
data_path = "/home/axp798/axp798gallinahome/data/jester/train_64/"
val_data_path = "/home/axp798/axp798gallinahome/data/jester/valid_64/"
ar_save_loss_path = None
if arg_save_loss_path is not None:
ar_save_loss_path = "/home/axp798/axp798gallinahome/Gesture-Detection/models/loss_jester/{}".format(
arg_save_loss_path)
ar_save_model_path = None
if arg_save_model_path is not None:
path = '/home/axp798/axp798gallinahome/Gesture-Detection/models/saved_models_jester/{}/'.format(
arg_save_model_path)
if not os.path.exists(path):
os.mkdir(path)
ar_save_model_path = path + "model"
if ar_save_loss_path is not None:
file1 = open(ar_save_loss_path, "w")
file1.write("Params: {} \n".format(results))
file1.write("Losses: \n")
file1.close()
depth = arg_win_size
height = 64
width = 64
num_classes = 27
os.environ['CUDA_VISIBLE_DEVICES'] = "{}".format(arg_visible_devices)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = "2"
print(device_lib.list_local_devices())
choose_device = "/device:GPU:{}".format(arg_num_device)
with tf.device(choose_device):
x_inpuT = tf.placeholder(tf.float32, shape=[arg_batch_size, depth, height, width, 3])
y_inpuT = tf.placeholder(tf.float32, shape=[arg_batch_size, num_classes])
train_neural_network(x_inpuT, y_inpuT, data_path, val_data_path,
save_loss_path=ar_save_loss_path,
save_model_path=ar_save_model_path,
batch_size=arg_batch_size,
learning_rate=arg_lr,
weight_decay=arg_wd,
epochs=arg_epochs,
val_batch_size=arg_val_batch_size,
which_model=arg_model_num,
num_val_videos=arg_num_val_videos,
random_clips=arg_random_clips,
win_size=arg_win_size,
ignore_factor=arg_ign_fact)
<file_sep>import os
import cv2
import time
videos_path = "/home/axp798/axp798gallinahome/ConGD/ConGD_phase_1/train"
store_frames = "/home/axp798/axp798gallinahome/store/train/frames"
script_start_time = time.time()
# print(os.listdir(videos_path)[270])
# dir = "246"
# curr_dir_path = os.path.join(videos_path, dir)
# print(curr_dir_path)
# print(os.listdir(curr_dir_path))
dir_count = 271
for dir in os.listdir(videos_path)[270:]:
print("{}) {} started!".format(dir_count, dir))
curr_dir_path = os.path.join(videos_path, dir)
par_dir = os.path.join(store_frames, dir)
if not os.path.exists(par_dir):
os.mkdir(par_dir)
dir_start_time = time.time()
video_count = 1
for video in os.listdir(curr_dir_path):
if video[-5] == 'K':
continue
video_start_time = time.time()
print("{}) {}-{} started!".format(video_count, dir, video))
vidcap = cv2.VideoCapture(os.path.join(curr_dir_path, video))
success, image = vidcap.read()
count = 1
# make directory // video = 00001.K.avi therefore video[:-6]
video_frame_dir = os.path.join(store_frames, "{}/{}".format(dir, video[ : -6]))
if not os.path.exists(video_frame_dir):
os.mkdir(video_frame_dir)
while success:
# print("frames started!")
cv2.imwrite(os.path.join(video_frame_dir, "frame{}.jpg".format(count)), image) # save frame as JPEG file
success, image = vidcap.read()
# print('Read a new frame: ', success)
count += 1
video_end_time = time.time()
print("{}) {}-{} is done in {} sec".format(video_count, dir, video, video_end_time - video_start_time))
video_count += 1
dir_end_time = time.time()
print("{}) {} is done in {} sec".format(dir_count, dir, dir_end_time - dir_start_time))
dir_count += 1
script_end_time = time.time()
print("Done in {} sec".format(script_end_time - script_start_time))
| 295122a8120b1dd930c4a0d2d3ba0d0e11fef23c | [
"Markdown",
"Python"
] | 15 | Markdown | abhinavpatel2912/Gesture-Detection | 9c460c063fa4f68dad1be4a62bfba3c36d81db21 | a6427edd36a56564e314117d25b174b7e8097d57 | |
refs/heads/master | <repo_name>mellauyellow/Music-App<file_sep>/app/models/album.rb
class Album < ActiveRecord::Base
ALBUM_STATUS = %w(live studio)
validates :band_id, :name, :status, presence: true
validates :status, inclusion: ALBUM_STATUS
belongs_to :band,
class_name: :Band,
primary_key: :id,
foreign_key: :band_id
has_many :tracks,
class_name: :Track,
primary_key: :id,
foreign_key: :album_id,
dependent: :destroy
end
<file_sep>/app/controllers/albums_controller.rb
class AlbumsController < ApplicationController
before_action :require_login
def create
@album = Album.new(album_params)
if @album.save
redirect_to band_url(@album.band_id)
else
flash.now[:errors] = @album.errors.full_messages
render :new
end
end
def new
@album = Album.new
@bands = Band.all
@current_band = Band.find_by_id(params[:band_id])
render :new
end
def update
@album = current_album
if @album.update_attributes(album_params)
redirect_to band_url(@album.band_id)
else
flash.now[:errors] = @album.errors.full_messages
render :edit
end
end
def destroy
@album = current_album
band_id = @album.band_id
@album.destroy
redirect_to band_url(band_id)
end
def edit
@album = current_album
@current_band = Band.find_by_id(@album.band_id)
@bands = Band.all
render :edit
end
def show
@album = current_album
@current_band = Band.find_by_id(@album.band_id)
end
private
def album_params
params.require(:album).permit(:band_id, :status, :name)
end
end
<file_sep>/app/models/track.rb
class Track < ActiveRecord::Base
TRACK_STATUS = %w(bonus regular)
validates :album_id, :name, :status, presence: true
validates :status, inclusion: TRACK_STATUS
belongs_to :album,
class_name: :Album,
primary_key: :id,
foreign_key: :album_id
has_one :band,
through: :album,
source: :band
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
helper_method :current_user, :logged_in?
def current_user
return nil unless session[:session_token]
@current_user ||= User.find_by(session_token: session[:session_token])
end
def log_in_user!(user)
session[:session_token] = user.reset_session_token!
end
def logout(user)
user.reset_session_token!
session[:session_token] = nil
end
def logged_in?
!current_user.nil?
end
def current_band
@current_band ||= Band.find_by_id(params[:id])
end
def current_album
@current_album ||= Album.find_by_id(params[:id])
end
def current_track
@current_track ||= Track.find_by_id(params[:id])
end
def require_login
redirect_to new_session_url if current_user.nil?
end
end
| cc9d9118142965c2692e7936323875fefa6ec2c4 | [
"Ruby"
] | 4 | Ruby | mellauyellow/Music-App | f9754c61f04daafa32c86ca4fc4e69b11acfc82b | cc6aec4132154f69340c026693a00c3313bc8173 | |
refs/heads/main | <file_sep># laravel-with-react
ReactJS CRUD with Laravel REST API from Scratch
<file_sep>import axios from "axios";
import { useState,useEffect } from "react";
import { Link } from "react-router-dom";
import React from 'react';
import swal from "sweetalert";
export default function EditStudent(props) {
const id = props.match.params.id;
const [studentData, setStudentData] = useState({
id:'',
name: "",
course: "",
email: "",
phone: "",
});
useEffect(()=>{
async function fetchStudent(){
const res = await axios.get(`http://localhost:8000/api/edit-student/${id}`);
if(res.data.status === 200)
{
setStudentData({
id: res.data.student.id,
name: res.data.student.name,
course: res.data.student.course,
email: res.data.student.email,
phone: res.data.student.phone,
});
}
}
fetchStudent();
},[id]);
let name, value;
const handleChange = (e) => {
name = e.target.name;
value = e.target.value;
setStudentData({ ...studentData, [name]: value });
};
const updateStudent = async (e) => {
e.preventDefault();
try {
const res = await axios.post("http://localhost:8000/api/update-student", studentData);
if(res.data.status===200) {
swal({
title: "Updated!",
text: res.data.message,
icon: "success",
button: "OK!",
});
setStudentData({
id:'',
name: "",
course: "",
email: "",
phone: "",
})
}
} catch (err) {
console.log(err);
}
};
return (
<div className="container">
<div className="row">
<div className="col-md-12">
<div className="card">
<div className="card-header">
<h4>
Edit Student
<Link to="/" className="btn btn-primary btn-sm float-end">
Back
</Link>
</h4>
</div>
<div className="col-md-6 offset-md-3 mt-3">
<div className="card-body">
<form onSubmit={updateStudent}>
<div className="form-group mb-3">
<label>Student Name</label>
<input
type="text"
name="name"
value={studentData.name}
onChange={handleChange}
required
className="form-control"
/>
</div>
<div className="form-group mb-3">
<label>Student Course</label>
<input
type="text"
name="course"
value={studentData.course}
onChange={handleChange}
required
className="form-control"
/>
</div>
<div className="form-group mb-3">
<label>Student Email</label>
<input
type="email"
name="email"
value={studentData.email}
onChange={handleChange}
required
className="form-control"
/>
</div>
<div className="form-group mb-3">
<label>Student Phone No.</label>
<input
type="text"
name="phone"
value={studentData.phone}
onChange={handleChange}
required
className="form-control"
/>
</div>
<button type="submit" className="btn btn-info btn-block">
Update Student
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
<file_sep>import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import "./App.css";
import AddStudent from "./components/pages/AddStudent";
import Student from "./components/pages/Student";
import EditStudent from "./components/pages/EditStudent";
import React from 'react';
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={Student} />
<Route exact path="/addStudent" component={AddStudent} />
<Route exact path="/edit-student/:id" component={EditStudent} />
</Switch>
</Router>
);
}
export default App;
| 72033662b757dc5f1ac25253073c3d9033c7d2d4 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | FC91thunderbird/react-crud-with-laravel | 396d3afea335e3a28eda20593bb485df7f012dcc | 39d71fda8bb82fd0633e014b742af5fc9b491ee8 | |
refs/heads/master | <file_sep><?php
error_reporting(E_ALL);
header('HTTP/1.1 404 Not Found');<file_sep><?php
/**
* YAF引导类,
*
*
*
*
*
*
*/
class Bootstrap extends Yaf_Bootstrap_Abstract
{
// public function _initPlugin(Yaf_Dispatcher $dispatcher) {
// $user = new UserPlugin();
// $dispatcher->registerPlugin($user);
// }
public function _initConfig()
{
}
}<file_sep><?php
class LoginController extends core_Commonents
{
public function init()
{
parent::init(FALSE);
}
public function indexAction()
{
$this->getView()->display('login/index.tpl');
}
}<file_sep><?php
function bootstrap_add_route($dispatcher)
{
$router = $dispatcher->getRouter();
$articles_detail_ = new Yaf_Route_Regex(
'%details/([a-zA-Z0-9\/]+)%',
array(
'controller' => 'Articles',
'action' => 'detail'
),
array(
1 => 'id'
)
);
$router->addRoute('articles_detail_', $articles_detail_);
$category_router = new Yaf_Route_Regex(
'%category/([a-zA-Z0-9\/]+)%',
array(
'controller' => 'Classify',
'action' => 'groups'
),
array(
1 => 'category',
)
);
$router->addRoute('category_router', $category_router);
}<file_sep><?php
class core_Base extends Yaf_Controller_Abstract
{
private $smarty;
public function init()
{
$this->_initSmarty();
}
private function _initSmarty()
{
$smarty = new Helper_Smarty();
$this->smarty = $smarty;
}
//重写YAF getView方法, 使其使用smarty引擎
public function getView()
{
return $this->smarty;
}
public function set_assign($name, $value)
{
$this->smarty->assign($name, $value);
}
public function set_display($path)
{
//$this->smarty->default_modifiers = array('$' => 'escape:"html"');
$this->smarty->display($path);
}
}<file_sep>[product]
application.directory = APP_PATH;
application.view.ext = tpl;
application.bootstrap = BASE_PATH "/conf/bootstrap.php";
application.modules = "Index, V1"
;application.ext String php PHP脚本的扩展名
;application.bootstrap String Bootstrapplication.php Bootstrap路径(绝对路径)
;application.library String application.directory + "/library" 本地(自身)类库的绝对目录地址
;application.baseUri String NULL 在路由中, 需要忽略的路径前缀, 一般不需要设置, Yaf会自动判断.
;application.dispatcher.defaultModule String index 默认的模块
;application.dispatcher.throwException Bool True 在出错的时候, 是否抛出异常
;application.dispatcher.catchException Bool False 是否使用默认的异常捕获Controller, 如果开启, 在有未捕获的异常的时候, 控制权会交给ErrorController的errorAction方法, 可以通过$request->getException()获得此异常对象
;application.dispatcher.defaultController String index 默认的控制器
;application.dispatcher.defaultAction String index 默认的动作
;application.view.ext String phtml 视图模板扩展名
;application.modules String Index 声明存在的模块名, 请注意, 如果你要定义这个值, 一定要定义Index Module
;application.system.* String * 通过这个属性, 可以修改yaf的runtime configure, 比如application.system.lowcase_path, 但是请注意只有PHP_INI_ALL的配置项才可以在这里被修改, 此选项从2.2.0开始引入<file_sep><?php
class Config
{
private static $_data = NULL;
/**
*
*
* @param [type] $key [description]
* @param [type] $value [description]
*/
public static function set($key, $value = NULL)
{
if (is_array($key)) {
foreach ($key as $key_item => $value_item) {
if (empty($key_item)) continue;
self::$_data[$key_item] = $value_item;
}
} else {
self::$_data[$key] = $value;
}
}
public static function get($key)
{
if(empty($key) || !isset(self::$_data[$key])) return FALSE;
return self::$_data[$key];
}
}
$all = [
'BaseURL' => 'http://www.yaftest1.com',
];
Config::set($all);
Config::set($dbconfig);
$all = NULL;
$dbconfig = NULL;
<file_sep><?php
class MysqldbModel extends DBModel
{
public function __construct($tableName)
{
parent::__construct($tableName, 'Mysql');
}
/**
*
* example 1.
* where(array(
* 'key1' => 'value1',
* 'key2' => NULL,
* 'key3' => array('!=' => 'value3'),
* 'key4' => array('value4_1', 'value4_2')
* ));
*
* output : WHERE `key1`='value1' AND `key2` is NULL AND `key3` != 'value3' AND (`key4` = 'value4_1' OR `key4` = 'value4_2')
*
* example 2.
* where(array(
* array('key1' => array('like' => '%value1%')),
* array(
* 'key2' => 3,
* 'key3' => 4,
* )
* ), array(
* 'order_by' => 'id DESC',
* 'offset' => 10,
* 'limit' => 20,
* ));
*
* output: WHERE (`key1` like '%value1%') OR (`key2`='3' AND `key3`='4') ORDER BY id DESC LIMIT 10, 20
*
* select(
* ['id' => 1],
* [
* 'fields' => 'name,age,okok,xxxxxxxx'//可以 count_num AS `total` 取别名
* 'order_by' => 'id DESC',
* 'offset' => 10,
* 'limit' => 20,
* ]
* )
*
* output select name,age,okok,xxxxxxxx,haha form 表名 where id = 1 order by id desc limit 10,20
*
*
*/
public function select($where, $attrs = [])
{
$pdo = $this->initPDO(TRUE);//read
$sql = $this->_sql_makeer->where($where, $attrs);
$table = $this->_table_name;
$select_fields = isset($attrs['fields']) ? $attrs['fields'] : '*';
$sql = "select {$select_fields} from {$table}" . $sql;
return $this->selectBySql($sql);
}
/**
* 插入数据
*
* 单行数据
* insert(array(
* 'key1' => 'val1',
* 'key2' => '&/CURRENT_TIMESTAMP',
* ));
*
* output : (`key1`,`key2`) VALUES ('val1',CURRENT_TIMESTAMP)
*
* 多行数据
* insert(array(
* 'key1', 'key2',
* ), array(
* array('val11', 'val12'),
* array('val21', 'val22')
* ));
* output: (`key1`,`key2`) VALUES ('val11','val12'),('val21','val22')
*
*
* @param array $data [description]
* @param [type] $rowsData 不为空是可批量插入
* @param boolean $return_last_id 是否返回lastID,
* @return boolean|int
*
* @todo 返回lastid总是0, 。。。。。。
*
*/
public function insert($data = [], $rowsData = NULL, $return_last_id = TRUE)
{
$pdo = $this->initPDO(FALSE);//wrrite
$sql = $this->_sql_makeer->insert($data, $rowsData);
$table = $this->_table_name;
$sql = "insert into {$table}" . $sql;
//insert into sss (`key1`,`key2`) VALUES ('xxx1','xxx1'),('xxx2','xxx2')
//这里可以加入日志配置
$sth = $pdo->prepare($sql);
$ret = $sth->execute();
$this->_errors['errorCode'] = $sth->errorCode();
$this->_errors['errorInfo'] = $sth->errorInfo();
if ($ret === FALSE) {
//数据库出错, 这里可以加入日志配置
return FALSE;
}
if ($return_last_id) {
return $this->getLastId();
}
return TRUE;
}
/**
* @example
* update(array(
* 'key1' => 'value1',
* 'key2' => '&/CURRENT_TIMESTAMP',
* ));
* output: " (`key1`,`key2`) VALUES ('value1',CURRENT_TIMESTAMP)"
*
* @param array $data
* @return string
*/
public function update($where, $data = [])
{
if (empty($data)) return FALSE;
$pdo = $this->initPDO(FALSE);//wrrite
$sql_update = $this->_sql_makeer->update($data);
$sql_where = $this->_sql_makeer->where($where);
$table = $this->_table_name;
$sql = "UPDATE {$table} " . $sql_update . $sql_where;
$res = $this->selectBySql($sql);
return $res === FALSE ? FALSE : TRUE;
}
}<file_sep><?php
public class core_Auth extends core_AbcBase
{
private $base = null;
public function __construct(core_Base $base)
{
$this->base = $base;
}
public function init()
{
$this->base->init();
echo "<h1>core_Auth init</h1>";
}
}<file_sep><?php
error_reporting(E_ALL);
//定义项目跟路径
define('BASE_PATH', realpath( dirname(__FILE__).'/../'));
//定义应用路径
define('APP_PATH', realpath( BASE_PATH . '/application/'));
//应用入口路径
defined('PUBLIC_PATH') or define('PUBLIC_PATH', realpath(BASE_PATH . '/public/'));
//引入全局引导配置,
require PUBLIC_PATH . '/bootstrap.php';
//yaf 加载应用配置文件
//$yaf = new Yaf_Application(BASE_PATH . '/conf/application.ini');
$yaf = new Yaf_Application(
[
'application' => [
'directory' => APP_PATH,
'modules' => "Index,Demo",
'view' => [
'ext' => 'tpl',
],
// 'dispatcher' => [
// 'defaultController' => 'index',
// 'defaultAction' => 'index',
// 'catchException' => false,
// 'defaultModule' => 'V1',
// 'throwException' => true,
// ],
// 'bootstrap' => BASE_PATH . "/conf/bootstrap.php",
]
]
);
$dispatcher = $yaf->getDispatcher();
$dispatcher->autoRender(FALSE);//关闭默认视图输出FALSE, 开启为默认TRUE
bootstrap_add_route($dispatcher);
//运行yaf
$yaf->run();
//->bootstrap()//可选的调用, 起用时, 要指定bootstrap文件所在地址
<file_sep>$(function() {
var testEditormdView;
var id = article_id;
$.get("/articles/getContent", {id:id}, function(markdown) {
if (markdown.code == 0) {
testEditormdView = editormd.markdownToHTML("test-editormd-view2", {
markdown : markdown.result ,//+ "\r\n" + $("#append-test").text(),
//htmlDecode : true, // 开启 HTML 标签解析,为了安全性,默认不开启
htmlDecode : "style,script,iframe", // you can filter tags decode
//toc : false,
tocm : true, // Using [TOCM]
//tocContainer : "#custom-toc-container", // 自定义 ToC 容器层
//gfm : false,
//tocDropdown : true,
// markdownSourceCode : true, // 是否保留 Markdown 源码,即是否删除保存源码的 Textarea 标签
emoji : true,
taskList : true,
tex : true, // 默认不解析
flowChart : true, // 默认不解析
sequenceDiagram : true, // 默认不解析
});
} else {
layer.alert('获取文章内容失败,请尝试重新加载!');
}
}, 'JSON');
});<file_sep><?php
class TopsModel extends MysqldbModel
{
public function __construct()
{
parent::__construct('tops');
}
}<file_sep><?php
class Helper_Test
{
private $name = 'helper_test';
public function getName()
{
return $this->name;
}
public function guid() {
$charid = strtoupper(md5(uniqid(mt_rand(), true)));
$uuid =
substr($charid, 0, 8).
substr($charid, 8, 4).
substr($charid,12, 4).
substr($charid,16, 4).
substr($charid,20,12);
return $uuid;
}
}<file_sep><?php
interface service_DB extends service_BaseDB
{
public function select($where, $attrs = []);
public function insert($data = [], $rowsData = NULL, $return_last_id = TRUE);
public function update($where, $data = []);
public function delete($where);
}<file_sep><?php
/**
*
* 核心模型类
*
*
*
*
*/
abstract class DBModel implements service_DB
{
protected $_default_sql_makeer = 'Mysql';
protected $_table_name = '';
protected $_table_prefix = '';
protected $_errors = [];
protected $_pdo = NULL;
protected $_sql_makeer = NULL;
protected $_dbconfig = NULL;
protected $_isread = TRUE; //默认是读, 从从库读取数据, 主库插入数据
const DB_SLAVE = 'read'; //常量,从数据库配置数组键名
const DB_MASTER = 'write';
public function __construct($tableName, $sqlMakeer = '')
{
if (empty($tableName)) {
throw new exception_Exception('The tabme name non\'t allow null!!!');
}
if (!empty($sqlMakeer))
$this->_default_sql_makeer = $sqlMakeer;
$sql = 'sql_' . $this->_default_sql_makeer;
try {
$this->_sql_makeer = $sql::getInstance();
} catch (exception_Exception $e) {
throw new exception_Exception('sqlMakeer is nont extise, on ' . $e->getLine(), 1);
}
$configs = Config::get('DBConfig');
if (empty($configs)) throw new exception_Exception('db propertince is error, ' . $e->getLine(), 1);
if($isread) {
$index = rand(1, count($configs[self::DB_SLAVE]));
$this->_dbconfig = $configs[self::DB_SLAVE][$index-1];
} else {
$this->_dbconfig = $configs[self::DB_MASTER];
}
$this->_table_prefix = $this->_dbconfig['prefix'];
$this->_table_name = $this->_dbconfig['prefix'].$tableName;
}
/**
*
* 初始化pdo链接, 在crud操作前请先初始化pdo操作, 因为该操作会读取数据库配置、
*
* @param boolean $isread 主从配置关键, true代表从从机上获取数据,false代表从master获取,
* 一般insert,delete用主机, 其余用从机
* @return PDO PDO object
*/
protected function initPDO($isread = TRUE)
{
static $instance = NULL;
$kk = $isread ? 'read' : 'write';
if (isset($instance[$kk]) && is_object($instance[$kk])) {
return $instance[$kk];
}
$dns = $this->_dbconfig['dns'];
$driver_options = NULL;
try {
$pdo = new PDO($dns, $this->_dbconfig['user'], $this->_dbconfig['password'], $driver_options);
$this->_pdo = $pdo;
$instance[$kk] = $pdo;
} catch (exception_Exception $e) {
throw new exception_Exception('sqlMakeer is nont extise, on ' . $e->getLine(), 1);
}
return $this->_pdo;
}
/**
* 外部调用数据库操作失败接口
*
* @return array
*/
public function getErrors()
{
return $this->_errors;
}
public function getTableName()
{
return $this->_table_name;
}
public function getTabblePrefix()
{
return $this->_table_prefix;
}
private function join($tag = 'INNER')
{
$table_master = $this->_table_name;
$sql = 'select * from table_master inner join ';
}
/**
* $obj->join('left, inner, reight')
* ->table('tablename', 'bieming')
* ->where('id = id')
* ->order()
* ->limit()
*
*
*
*
*/
/**
* 查询一个
*
* @param array $where 查询条件 参考Mysqldb select方法,
* @param array $attrs 字段、分页等
* @return
*/
public function selectOne($where, $attrs = [])
{
$attrs['limit'] = 1;
$attrs['offset'] = 0;
$res = $this->select($where, $attrs);
if ($res === FALSE) {
return FALSE;
}
if (empty($res)) {
return NULL;
}
return array_pop($res);
}
/**
* 计数
*
* @param array $where 查询条件 参考Mysqldb select方法,
* @return
*/
public function selectCount($where)
{
$attrs['fields'] = 'count(*) AS `total`';
$res = $this->selectOne($where, $attrs);
if ( !empty($res)){
return intval(['total']);
}
return 0;
}
/**
*
* 获取最好一条ID, 可能不同数据库获取不同, (mysql)是可以这样获取的
* 若其他数据库获取方式不同, 子类可覆盖该方法
*
*
* @return [type] [description]
*/
protected function getLastId()
{
$pdo = $this->initPDO(FALSE);
return $pdo->lastInsertId();
}
/**
*
* 根据sql查询数据
*
* @param string $sql sql语句
* @return boolean|array 返回结果, FALSE表示数据库操作失败,
*/
protected function selectBySql($sql)
{
$sth = $this->_pdo->prepare($sql);
$ret = $sth->execute();
$this->_errors['errorCode'] = $sth->errorCode();
$this->_errors['errorInfo'] = $sth->errorInfo();
if ($ret === FALSE) {
//数据库出错, 这里可以加入日志配置
return FALSE;
}
return $sth->fetchAll(PDO::FETCH_ASSOC);
}
/**
*
* 根据条件删除
*
* @param array $where
* @return int 返回删除受影响的行数
*/
public function delete($where)
{
$pdo = $this->initPDO();
$table = $this->_table_name;
$sql = $this->_sql_makeer->where($where);
$sql = "DELETE FROM {$table}" . $sql;
return $this->selectBySql($sql);
}
/**
* 直接执行sql
* @param [type] $sql [description]
* @param boolean $isread [description]
* @return [type] [description]
*/
public function execute($sql, $isread = TRUE)
{
$pdo = $this->initPDO($isread, $isread);
return $this->selectBySql($sql);
}
//由于不同数据库sqlmaker返回可能不一样, 所有具体的crud也不一样,
//所yi数据库的crud应该根据具体数据库来配置
public abstract function select($where, $attrs = []);
public abstract function insert($data = [], $rowsData = NULL, $return_last_id = TRUE);
public abstract function update($where, $data = []);
}<file_sep><?php
session_start();
var_dump($_SESSION);
$_SESSION['xxxx'] = 222;
<file_sep>
<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\FirePHPHandler;
class IndexController extends core_Commonents
{
private $logger = NULL;
public function init()
{
parent::init(FALSE);
// Create the logger
$logger = new Logger('my_logger');
// Now add some handlers
$logger->pushHandler(new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG));
$logger->pushHandler(new FirePHPHandler());
$this->logger = $logger;
}
public function indexAction()
{
echo "Hello world";
//$this->getView()->assign('content', '你好, 世界!22');
// You can now use your logger
$this->logger->addInfo('My logger is now ready');
//$this->getView()->display('index/index.tpl');
}
public function actionPostAction()
{
$url = 'www.yaftest1.com/Demo/index/Require_post';
$data = array(
'name' => 'ethan',
'gender' => 'male',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
//特别注意, 请求头设置为这样, $_POST是接收不到数据的,详情看下文链接
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
}
public function Require_postAction()
{
$post = $_POST;
print_r($post);
}
}<file_sep><?php /* Smarty version Smarty-3.1.19, created on 2016-03-23 16:01:06
compiled from "static\common\inc\js_lib.tpl" */ ?>
<?php /*%%SmartyHeaderCode:2308956f22e67abb040-05286353%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'41137f215a8b7cf8312adadfcf93f1482853d4a5' =>
array (
0 => 'static\\common\\inc\\js_lib.tpl',
1 => 1458720017,
2 => 'file',
),
),
'nocache_hash' => '2308956f22e67abb040-05286353',
'function' =>
array (
),
'version' => 'Smarty-3.1.19',
'unifunc' => 'content_56f22e67abeec6_98928943',
'has_nocache_code' => false,
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_56f22e67abeec6_98928943')) {function content_56f22e67abeec6_98928943($_smarty_tpl) {?><script src="//lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="/static/plugins/layer/layer.js"></script>
<script src="/static/plugins/layer/extend/layer.ext.js"></script><?php }} ?>
<file_sep><?php
class RegisterController extends core_Commonents
{
public function init()
{
parent::init(FALSE);
}
public function indexAction()
{
$this->getView()->display('register/index.tpl');
}
}<file_sep><?php
class service_Wocao
{
public function __construct()
{
echo "----";
}
public function fanshe($moduleName, $controllerName, $acctionName)
{
$class = new \ReflectionClass($controllerName);
}
public function __destruct()
{
echo "end------------";
}
}<file_sep><?php
class TestController extends core_Commonents
{
public function init($check = true)
{
parent::init(FALSE);
}
public function indexAction()
{
$sip = 'ssttp://sss.ss.ss';
$sip = stripos($sip, 'http://');
var_dump($sip);
$name = gettext('你好世界!');
$this->getView()->assign('name', $name);
$this->getView()->display('test/index.tpl');
}
public function xxx1Action()
{
$this->getView()->display('test/t.tpl');
}
public function xxx2Action()
{
$imageStrs = $_POST['IMGSTR'];
$image = explode('__', $imageStrs, -1);
foreach($image as $key => $v) {
unset($image[$key]);
$image[$key]['image_src'] = $v;
$v=substr($v,-4);//去除前面
$image[$key]['image_name'] = mt_rand(1, 1111) .$v;
}
print_r($image);
}
public function ajaxFileAction()
{
var_dump($_GET);
var_dump($_POST);
var_dump($_FILES);
echo json_encode(['error' => 'success']);
}
public function ajaxFileShowAction()
{
$this->getView()->display('test/ajax.tpl');
}
public function wocaocaoAction()
{
$this->getView()->display('test/wwwww.tpl');
}
public function wocaocao2Action()
{
var_dump($_POST);
}
}<file_sep><?php
class Helper_Http
{
/**
* 获得请求URL,不含协议
* @return string
*/
public static function getFormUrl()
{
return $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
/**
* 获得请求URL,含协议
* @return string
*/
public static function getFullUrl()
{
return 'http://' . static::getFormUrl();
}
}<file_sep><?php
class core_Commonents extends core_Base
{
protected $user = NULL;
protected $_id = 1;//当前用户ID
protected $islogin = FALSE;
protected $_is_ajax = FALSE;
protected $_is_post = FALSE;
/**
* INIT
* @param boolean $check 是否需要登录
* @return [type] [description]
*/
public function init($check = TRUE)
{
parent::init();
if ($check)
$this->_checkLogging();
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
$this->_is_ajax = TRUE;
}
if ( !empty($_POST)) {
$this->_is_post = TRUE;
}
}
public function wocao()
{
echo "core_Commonents wocao";
}
protected function _checkLogging()
{
if (empty($this->user)) $this->redirect();
}
/**
* 重定向
*
* @param string $url 重定向URL
* @param integer $code 状态码
* @return exit script
*/
public function redirect($url = '' , $code = 302)
{
if ( empty($url)) $url = Config::get('BaseURL') . '/login';
$call = Helper_Http::getFullUrl();
$url .= '?form='.urlencode($call);
header('Location:'.$url, TRUE, $code);
exit;
}
/**
* ajax return success
*
* @param string $message [description]
* @param array $data [description]
* @param integer $code [description]
* @return json
*/
protected function _ajax_return_success($message = 'SUCCESS', $data = [], $code = 0)
{
$json_data = [
'msg' => $message,
'code' => $code,
'result' => $data,
];
$this->_print_json($json_data);
}
/**
* ajax return failed
*
* @param string $message [description]
* @param integer $code [description]
* @return json
*/
protected function _ajax_return_failed($message = 'service exception, plase try again!!', $data = [], $code = 500)
{
$json_data = [
'msg' => $message,
'code' => $code,
'result' => $data,
];
$this->_print_json($json_data);
}
/**
* print json to page
*
* @param array $data [description]
* @return
*/
protected function _print_json($data = [])
{
$json = json_encode($data);
echo $json;
exit;
}
public function show_404()
{
$this->getView()->display('common/404.tpl');
exit;
}
}<file_sep>
<?php
class IndexController extends core_Commonents
{
use trait_Session;
public function init($c = TRUE)
{
parent::init(FALSE);
}
// public function wocao()
// {
// echo "IndexController wocao";
// }
/**
*
*
* @return [type] [description]
*/
public function indexAction()
{
$this->wocao();
echo "Hello world";
// $x = new service_Wocao();
// list($m, $c, $a) = $this->getRequestURI();
// $x->fanshe($m, $c, $a);
// $x = null;
// $this->getView()->assign('content', '你好, 世界!22');
// //$this->set_assign('content', '你好, 世界!');
// //$this->disableView(); //关闭视图输出
// $this->getView()->display('index/index.tpl');
}
public function aaaAction()
{
$aa = new UserPlugin();
var_dump($aa);
}
public function testAction()
{
// $db = new MysqldbModel('onetable');
// $ok = $db->delete(['id' => 2]);
// var_dump($ok);
// var_dump($db->getErrors());
$this->getView()->display('test/test_upload.tpl');
}
public function uploadAction()
{
echo "<h1>--------------------get--------------------</h1>";
var_dump($_GET);
echo "<h1>--------------------post--------------------</h1>";
var_dump($_POST);
echo "<h1>--------------------file--------------------</h1>";
var_dump($_FILES);
}
//http://www.yaftest1.com/index/pic
public function picAction()
{
var_dump($_GET);
foreach ($pics as $key => $value) {
$data[] = [
'image_src' =>$value,
'image_name' => mt_rand(1, 1111) . '.jpg'
];
}
}
public function httptestAction()
{
// var_dump($_POST);
// echo "----------\r\n";
// var_dump($http_raw_post_data);
$raw_post_data = file_get_contents('php://input', 'r');
var_dump($raw_post_data);
}
/**
* 获得当前请求的 m + c + a
* @return [type] [description]
*/
protected function getRequestURI()
{
$module_name = $this->getRequest()->getModuleName();
$controller_name = $this->getRequest()->getControllerName();
$action_name = $this->getRequest()->getActionName();
return [$module_name, $controller_name, $action_name];
}
}<file_sep>## YAF
> yaf自身有自己的加载机制, 只要满足特定的文件夹格式, 无需再自己配置`autoload`,
<file_sep><?php
interface service_BaseDB
{
}<file_sep><?php
/**
*
*
1 routerStartup
在路由之前触发 这个是7个事件中, 最早的一个.
但是一些全局自定的工作, 还是应该放在Bootstrap中去完成
2 routerShutdown 路由结束之后触发
此时路由一定正确完成, 否则这个事件不会触发
3 dispatchLoopStartup 分发循环开始之前被触发
4 preDispatch 分发之前触发 如果在一个请求处理过程中,
发生了forward, 则这个事件会被触发多次
5 postDispatch 分发结束之后触发 此时动作已经执行结束,
视图也已经渲染完成. 和preDispatch类似, 此事件也可能触发多次
6 dispatchLoopShutdown 分发循环结束之后触发
此时表示所有的业务逻辑都已经运行完成, 但是响应还没有发送
*
*
*/
class UserPlugin extends Yaf_Plugin_Abstract
{
/*public function routerStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
echo "routerStartup";
}
public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
echo "routerShutdown";
}*/
}<file_sep><?php
class ClassifyController extends core_Commonents
{
public function init()
{
parent::init(FALSE);
}
public function groupsAction()
{
$group = $this->getRequest()->getParam('category');
$class = new ArticleModel();
$table1 = $class->getTableName();
$table2 = $class->getTabblePrefix() . 'classify';
$sql = "select * from {$table1} as table1 inner join {$table2} as table2 where table1.`c_id` = table2.`c_id`";
$ssss = $class->execute($sql);
var_dump($sss);
}
}<file_sep><?php /* Smarty version Smarty-3.1.19, created on 2016-03-23 13:49:27
compiled from "F:\Zend\git\yaf\application\views\index\index.tpl" */ ?>
<?php /*%%SmartyHeaderCode:2729556f22e679539f0-79062059%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'c8caa57bbcf579e95d47ece8ce4bba65ece45467' =>
array (
0 => 'F:\\Zend\\git\\yaf\\application\\views\\index\\index.tpl',
1 => 1457686243,
2 => 'file',
),
'b7aba38bca2edd88e759555da3d41a3d050d194e' =>
array (
0 => 'F:\\Zend\\git\\yaf\\application\\views\\common\\base.tpl',
1 => 1458622089,
2 => 'file',
),
'00bb99ef4a9bc68c1e51c7d435e33d9abfa8f392' =>
array (
0 => 'F:\\Zend\\git\\yaf\\application\\views\\common\\header.tpl',
1 => 1458623402,
2 => 'file',
),
'25d0cfc6ae6a2d07f03e53021daf49c4789747eb' =>
array (
0 => 'F:\\Zend\\git\\yaf\\application\\views\\common\\footer.tpl',
1 => 1457685727,
2 => 'file',
),
),
'nocache_hash' => '2729556f22e679539f0-79062059',
'function' =>
array (
),
'has_nocache_code' => false,
'version' => 'Smarty-3.1.19',
'unifunc' => 'content_56f22e67a883b3_84155262',
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_56f22e67a883b3_84155262')) {function content_56f22e67a883b3_84155262($_smarty_tpl) {?>
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1" />
<meta name="renderer" content="webkit" />
<meta charset="utf-8" />
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<title>社区---Godruoyi</title>
<meta name="description" content="This is description , you can input everthing.">
<meta name="keywords" content="KEY WORDS">
<!-- setting icon -->
<!-- <link rel="shortcut icon" href="resource/common/favicon.ico" type="image/x-icon"/>-->
<?php echo $_smarty_tpl->getSubTemplate ("static/common/inc/css_common.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0);?>
<?php echo $_smarty_tpl->getSubTemplate ("static/common/inc/js_lib.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0);?>
</head>
<body>
<?php /* Call merged included template "../common/header.tpl" */
$_tpl_stack[] = $_smarty_tpl;
$_smarty_tpl = $_smarty_tpl->setupInlineSubTemplate("../common/header.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0, '2729556f22e679539f0-79062059');
content_56f22e67a16f22_06825672($_smarty_tpl);
$_smarty_tpl = array_pop($_tpl_stack);
/* End of included template "../common/header.tpl" */?>
<div class="aw-container-wrap">
<div class="container category">
<div class="row">
<div class="col-sm-12">
<ul class="list">
<li class="active"><a href="#">全部</a></li>
<li><a href="#">PHP</a></li>
<li><a href="#">Laravel</a></li>
<li><a href="#">ThinnkPHP</a></li>
<li><a href="#">YAF</a></li>
</ul>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="aw-content-wrap clearfix">
<div class="col-sm-12 col-md-9 aw-main-content">
<!-- 新消息通知 -->
<div class="aw-mod aw-notification-box hide" id="index_notification">
<div class="mod-head common-head">
<h2>
<span class="pull-right">
<a href="" class="text-color-999"><i class="icon icon-setting"></i> 通知设置</a>
</span>
<i class="icon icon-bell"></i>新通知<em class="badge badge-important" name="notification_unread_num"></em>
</h2>
</div>
<div class="mod-body">
<ul id="notification_list"></ul>
</div>
<div class="mod-footer clearfix">
<a href="javascript:;" onclick="AWS.Message.read_notification(false, 0, false);" class="pull-left btn btn-mini btn-gray">我知道了</a>
<a href="#notifications/" class="pull-right btn btn-mini btn-success">查看所有</a>
</div>
</div>
<!-- end 新消息通知 -->
<!-- tab切换 -->
<ul class="nav nav-tabs aw-nav-tabs active hidden-xs">
<li><a href="#sort_type-unresponsive">等待回复</a></li>
<li><a href="#sort_type-hot__day-7" id="sort_control_hot">热门</a></li>
<li><a href="#is_recommend-1">推荐</a></li>
<li class="active"><a href="#">最新</a></li>
<h2 class="hidden-xs"><i class="icon icon-list"></i> 发现</h2>
</ul>
<!-- end tab切换 -->
<div class="aw-mod aw-explore-list">
<div class="mod-body">
<div class="aw-common-list">
<div class="aw-item active" data-topic-id="251,6,">
<a class="aw-user-name hidden-xs" data-id="792" href="#people/Jellybean" rel="nofollow">
<img src="#static/common/avatar-max-img.png" alt="" />
</a>
<div class="aw-question-content">
<h4>
<a href="#question/363">size的大小,对es search性能的影响</a>
</h4>
<a href="#question/363#!answer_form" class="pull-right text-color-999">回复</a>
<p>
<a class="aw-question-tags" href="#explore/category-2">Elasticsearch</a>
• <a href="#people/Jellybean" class="aw-user-name">Jellybean</a>
<span class="text-color-999">发起了问题 • 1 人关注 • 0 个回复 • 14 次浏览 • 3 小时前 </span>
<span class="text-color-999 related-topic hide"> • 来自相关话题</span>
</p>
</div>
</div>
</div>
</div>
<div class="mod-footer">
<div class="page-control">
<ul class="pagination pull-right">
<li class="active"><a href="javascript:;">1</a></li>
<li><a href="#sort_type-new__day-0__is_recommend-0__page-2">2</a></li>
<li><a href="#sort_type-new__day-0__is_recommend-0__page-3">3</a></li>
<li><a href="#sort_type-new__day-0__is_recommend-0__page-4">4</a></li>
<li><a href="#sort_type-new__day-0__is_recommend-0__page-2">></a></li>
<li><a href="#sort_type-new__day-0__is_recommend-0__page-42">>></a></li>
</ul>
</div>
</div>
</div>
</div>
<!-- 侧边栏 -->
<div class="col-sm-12 col-md-3 aw-side-bar hidden-xs hidden-sm">
<div class="aw-mod aw-text-align-justify">
<div class="mod-head">
<a href="#topic/channel-hot" class="pull-right">更多 ></a>
<h3>热门话题</h3>
</div>
<div class="mod-body">
<dl>
<dt class="pull-left aw-border-radius-5">
<a href="#topic/elasticsearch">
<img alt="" src="#uploads/topic/20151101/61458e7771b84fd8f6551a51051dc112_50_50.png" />
</a>
</dt>
<dd class="pull-left">
<p class="clearfix">
<span class="topic-tag">
<a href="#topic/elasticsearch" class="text" data-id="38">elasticsearch</a>
</span>
</p>
<p><b>41</b> 个问题, <b>37</b> 人关注</p>
</dd>
</dl>
<dl>
<dt class="pull-left aw-border-radius-5">
<a href="#topic/elastic"><img alt="" src="#static/common/topic-mid-img.png" /></a>
</dt>
<dd class="pull-left">
<p class="clearfix">
<span class="topic-tag">
<a href="#topic/elastic" class="text" data-id="165">elastic</a>
</span>
</p>
<p><b>3</b> 个问题, <b>7</b> 人关注</p>
</dd>
</dl>
</div>
</div>
<div class="aw-mod aw-text-align-justify">
<div class="mod-head">
<a href="#people/" class="pull-right">更多 ></a>
<h3>热门用户</h3>
</div>
<div class="mod-body">
<dl>
<dt class="pull-left aw-border-radius-5">
<a href="#people/rayshen"><img alt="" src="#static/common/avatar-mid-img.png" /></a>
</dt>
<dd class="pull-left">
<a href="#people/rayshen" data-id="503" class="aw-user-name">rayshen </a>
<p class="signature"></p>
<p><b>2</b> 个问题, <b>0</b> 次赞同</p>
</dd>
</dl>
<dl>
<dt class="pull-left aw-border-radius-5">
<a href="#people/dreams"><img alt="" src="#static/common/avatar-mid-img.png" /></a>
</dt>
<dd class="pull-left">
<a href="#people/dreams" data-id="806" class="aw-user-name">dreams </a>
<p class="signature"></p>
<p><b>3</b> 个问题, <b>0</b> 次赞同</p>
</dd>
</dl>
</div>
</div>
</div>
<!-- end 侧边栏 -->
</div>
</div>
</div>
</div>
<?php /* Call merged included template "../common/footer.tpl" */
$_tpl_stack[] = $_smarty_tpl;
$_smarty_tpl = $_smarty_tpl->setupInlineSubTemplate("../common/footer.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0, '2729556f22e679539f0-79062059');
content_56f22e67a789b7_29803353($_smarty_tpl);
$_smarty_tpl = array_pop($_tpl_stack);
/* End of included template "../common/footer.tpl" */?>
<!-- 百度统计 -->
<script type="text/javascript">
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3F777acfdc44fd57af7be29408af76bcba' type='text/javascript'%3E%3C/script%3E"));
</script>
<a class="aw-back-top hidden-xs" href="javascript:;" onclick="$.scrollTo(1, 600, {queue:true});"><i class="icon icon-up"></i></a>
<!-- DO NOT REMOVE -->
<div id="aw-ajax-box" class="aw-ajax-box"></div>
<div style="display:none;" id="__crond">
<script type="text/javascript">
/*$(document).ready(function () {
$('#__crond').html(unescape('%3Cimg%20src%3D%22' + G_BASE_URL + '/crond/run/1456901234%22%20width%3D%221%22%20height%3D%221%22%20/%3E'));
});*/
</script>
</div>
</body>
</html><?php }} ?>
<?php /* Smarty version Smarty-3.1.19, created on 2016-03-23 13:49:27
compiled from "F:\Zend\git\yaf\application\views\common\header.tpl" */ ?>
<?php if ($_valid && !is_callable('content_56f22e67a16f22_06825672')) {function content_56f22e67a16f22_06825672($_smarty_tpl) {?>
<div class="aw-top-menu-wrap">
<div class="container">
<!-- logo -->
<div class="aw-logo hidden-xs">
<a href="http://www.godruoyi.com"></a>
</div>
<!-- end logo -->
<!-- 搜索框 -->
<div class="aw-search-box hidden-xs hidden-sm">
<form class="navbar-search" action="#" id="global_search_form" method="post">
<input class="form-control search-query" type="text" placeholder="搜索问题、话题或人" autocomplete="off" name="q" id="aw-search-query" />
<span title="搜索" id="global_search_btns" onClick="$('#global_search_form').submit();"><i class="icon icon-search"></i></span>
<div class="aw-dropdown">
<div class="mod-body">
<p class="title">输入关键字进行搜索</p>
<ul class="aw-dropdown-list hide"></ul>
<p class="search"><span>搜索:</span><a onClick="$('#global_search_form').submit();"></a></p>
</div>
<div class="mod-footer">
<a href="#publish" onClick="$('#header_publish').click();" class="pull-right btn btn-mini btn-success publish">发起问题</a>
</div>
</div>
</form>
</div>
<!-- end 搜索框 -->
<!-- 导航 -->
<div class="aw-top-nav navbar">
<div class="navbar-header">
<button class="navbar-toggle pull-left">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<nav role="navigation" class="collapse navbar-collapse bs-navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="#" class="active"><i class="icon icon-list"></i> 文章</a></li>
<!-- <li><a href="#question/" class="">问题</a></li>
<li><a href="#article/" class="">文章</a></li> -->
<li><a href="#" ><i class="icon icon-topic"></i> 讨论</a></li>
<li><a href="#"><i class="icon icon-bulb"></i> Help</a></li>
<?php if (!empty($_smarty_tpl->tpl_vars['islogin']->value)) {?>
<li><a href="#"><i class="icon icon-bulb"></i> 消息</a></li>
<?php }?>
<li>
<a style="font-weight:bold;" title="more...">· · ·</a>
<div class="dropdown-list pull-right">
<ul id="extensions-nav-list"></ul>
</div>
</li>
</ul>
</nav>
</div>
<!-- end 导航 -->
<?php if (empty($_smarty_tpl->tpl_vars['islogin']->value)) {?>
<!-- 用户栏 -->
<div class="aw-user-nav">
<!-- 登陆&注册栏 -->
<a class="login btn btn-normal btn-primary" href="/login">登录</a>
<a class="register btn btn-normal btn-success" href="/register">注册</a> <!-- end 登陆&注册栏 -->
</div>
<!-- end 用户栏 -->
<!-- 发起 -->
<?php } else { ?>
<!-- end 发起 -->
<!-- 用户栏 -->
<div class="aw-user-nav">
<!-- 登陆&注册栏 -->
<a href="" class="aw-user-nav-dropdown">
<img alt="godruoyi" src="" />
</a>
<div class="aw-dropdown dropdown-list pull-right">
<ul class="aw-dropdown-list">
<li><a href=""><i class="icon icon-inbox"></i> 个人中心<span class="badge badge-important hide" id="inbox_unread">0</span></a></li>
<li class="hidden-xs"><a href=""><i class="icon icon-setting"></i> 设置</a></li>
<li><a href=""><i class="icon icon-logout"></i> 退出</a></li>
</ul>
</div>
<!-- end 登陆&注册栏 -->
</div>
<!-- end 用户栏 -->
<!-- 发起 -->
<div class="aw-publish-btn">
<a id="header_publish" class="btn-primary" href="" onclick=""><i class="icon icon-ask"></i>发起</a>
<div class="dropdown-list pull-right">
<ul>
<li>
<a href="/articles/create">文章</a>
</li>
</ul>
</div>
</div>
<!-- end 发起 -->
<?php }?>
</div>
</div><?php }} ?>
<?php /* Smarty version Smarty-3.1.19, created on 2016-03-23 13:49:27
compiled from "F:\Zend\git\yaf\application\views\common\footer.tpl" */ ?>
<?php if ($_valid && !is_callable('content_56f22e67a789b7_29803353')) {function content_56f22e67a789b7_29803353($_smarty_tpl) {?><div class="aw-footer-wrap">
<div class="aw-footer">
Copyright © 2016 · <a target="_blank" href="#">Godruoyi</a></span>
<span class="hidden-xs"> · <a href="#" target="blank">Godruoyi</a></span>
</div>
</div><?php }} ?>
<file_sep><?php
class A
{
public $name = 'name';
private static $instance = null;
private function __construct()
{}
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
}
$a = A::getInstance();
echo $a->name;<file_sep><?php
trait trait_Session
{
public function wocao()
{
echo "trait_Session wocao";
}
private function __construct()
{
}
}<file_sep><?php
class Helper_Smarty extends Smarty
{
public function __construct()
{
parent::__construct();
$this->setTemplateDir(APP_PATH . '/views/');
$this->setConfigDir(BASE_PATH . '/log/smarty/config/');
$this->setCompileDir(BASE_PATH . '/log/smarty/compile/');
$this->setCacheDir(BASE_PATH . '/log/smarty/cache/');
//开启smarty调试, un-comment the following line to show the debug console
//$this->debugging = true;
$this->left_delimiter = '{%';
$this->right_delimiter = '%}';
}
}<file_sep><?php /* Smarty version Smarty-3.1.19, created on 2016-03-23 13:49:27
compiled from "static\common\inc\css_common.tpl" */ ?>
<?php /*%%SmartyHeaderCode:1404056f22e67aa77c5-76919150%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'd34a940ff1b1d41b8a91b53c1b4810b12d987eec' =>
array (
0 => 'static\\common\\inc\\css_common.tpl',
1 => 1458620714,
2 => 'file',
),
),
'nocache_hash' => '1404056f22e67aa77c5-76919150',
'function' =>
array (
),
'has_nocache_code' => false,
'version' => 'Smarty-3.1.19',
'unifunc' => 'content_56f22e67aab647_82063725',
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_56f22e67aab647_82063725')) {function content_56f22e67aab647_82063725($_smarty_tpl) {?><link rel="stylesheet" type="text/css" href="/static/common/css/bs.css" />
<link rel="stylesheet" type="text/css" href="/static/common/css/icon.css" />
<link href="/static/common/css/common.css" rel="stylesheet" type="text/css" />
<link href="/static/common/css/link.css" rel="stylesheet" type="text/css" />
<link href="/static/common/css/style.css" rel="stylesheet" type="text/css" />
<?php }} ?>
<file_sep><?php /* Smarty version Smarty-3.1.19, created on 2016-03-23 16:57:28
compiled from "F:\Zend\git\yaf\application\views\articles\index.tpl" */ ?>
<?php /*%%SmartyHeaderCode:2116056f22ee3acb017-56056684%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'0a4cd3c1ae63125eb18d5465826ee84667e07238' =>
array (
0 => 'F:\\Zend\\git\\yaf\\application\\views\\articles\\index.tpl',
1 => 1458723444,
2 => 'file',
),
'b7aba38bca2edd88e759555da3d41a3d050d194e' =>
array (
0 => 'F:\\Zend\\git\\yaf\\application\\views\\common\\base.tpl',
1 => 1458622089,
2 => 'file',
),
'00bb99ef4a9bc68c1e51c7d435e33d9abfa8f392' =>
array (
0 => 'F:\\Zend\\git\\yaf\\application\\views\\common\\header.tpl',
1 => 1458623402,
2 => 'file',
),
'25d0cfc6ae6a2d07f03e53021daf49c4789747eb' =>
array (
0 => 'F:\\Zend\\git\\yaf\\application\\views\\common\\footer.tpl',
1 => 1457685727,
2 => 'file',
),
),
'nocache_hash' => '2116056f22ee3acb017-56056684',
'function' =>
array (
),
'version' => 'Smarty-3.1.19',
'unifunc' => 'content_56f22ee3cc6d83_86300865',
'has_nocache_code' => false,
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_56f22ee3cc6d83_86300865')) {function content_56f22ee3cc6d83_86300865($_smarty_tpl) {?>
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1" />
<meta name="renderer" content="webkit" />
<meta charset="utf-8" />
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<title>写文章---Godruoyi</title>
<meta name="description" content="This is description , you can input everthing.">
<meta name="keywords" content="KEY WORDS">
<!-- setting icon -->
<!-- <link rel="shortcut icon" href="resource/common/favicon.ico" type="image/x-icon"/>-->
<?php echo $_smarty_tpl->getSubTemplate ("static/common/inc/css_common.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0);?>
<?php echo $_smarty_tpl->getSubTemplate ("static/common/inc/js_lib.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0);?>
<link rel="stylesheet" type="text/css" href="/static/plugins/editor/css/editormd.css">
</head>
<body>
<?php /* Call merged included template "../common/header.tpl" */
$_tpl_stack[] = $_smarty_tpl;
$_smarty_tpl = $_smarty_tpl->setupInlineSubTemplate("../common/header.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0, '2116056f22ee3acb017-56056684');
content_56f25a78bed699_95607996($_smarty_tpl);
$_smarty_tpl = array_pop($_tpl_stack);
/* End of included template "../common/header.tpl" */?>
<div class="aw-container-wrap">
<div class="container aw-publish aw-publish-article">
<div class="row">
<div class="aw-content-wrap clearfix">
<div class="aw-main-content">
<!-- tab 切换 -->
<ul class="nav nav-tabs aw-nav-tabs active">
<h2 class="hidden-xs"><i class="icon icon-ask"></i> 文章发布</h2>
</ul>
<!-- end tab 切换 -->
<form id="question_form">
<div class="aw-mod aw-mod-publish">
<div class="mod-body">
<h3>文章标题:</h3>
<!-- 文章标题 -->
<div class="aw-publish-title">
<input type="text" name="title_articles" id="title_articles" value="" class="form-control" minlength="20" required/>
<input type="hidden" name="classify_id_hidden" value="" id="classify_id_hidden" required/>
<div class="aw-dropdown aw-question-dropdown">
<i class="aw-icon i-dropdown-triangle active"></i>
<p class="title">没有找到相关结果</p>
<ul class="aw-question-dropdown-list"></ul>
</div>
<div class="dropdown">
<div class="dropdown-toggle" data-toggle="dropdown">
<div id="aw-topic-tags-select">
<span>选择分类</span>
<a href="javascript:;">
<i class="icon icon-down"></i>
</a>
</div>
<div aria-labelledby="dropdownMenu" role="menu" class="aw-dropdown" id="menu-arr">
<ul class="aw-dropdown-list">
<?php if (!empty($_smarty_tpl->tpl_vars['classify']->value)) {?>
<?php $_smarty_tpl->tpl_vars['item'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['item']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['classify']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['item']->key => $_smarty_tpl->tpl_vars['item']->value) {
$_smarty_tpl->tpl_vars['item']->_loop = true;
?>
<li><a data-value="<?php echo $_smarty_tpl->tpl_vars['item']->value['id'];?>
"><?php echo $_smarty_tpl->tpl_vars['item']->value['name'];?>
</a></li>
<?php } ?>
<?php } else { ?>
<li><a data-value="0">暂无分组</a></li>
<?php }?>
</ul>
</div>
</div>
</div>
</div>
<!-- end 文章标题 -->
<h3>文章内容:</h3>
<div class="aw-mod aw-editor-box">
<div class="mod-head">
<div id="test-editormd">
<textarea name="content_articles" id="content_articles" required></textarea>
</div>
</div>
</div>
</div>
<div class="mod-footer clearfix">
<a href="" target="_blank">[积分规则]</a>
<span class="aw-anonymity"></span>
<a class="btn btn-large btn-success btn-publish-submit" id="publish_submit">确认发布</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var testEditor;
$(function() {
testEditor = editormd("test-editormd", {
width : "90%",
height : 640,
syncScrolling : "single",
path : "/static/plugins/editor/lib/",
saveHTMLToTextarea: true,
});
});
</script>
<?php /* Call merged included template "../common/footer.tpl" */
$_tpl_stack[] = $_smarty_tpl;
$_smarty_tpl = $_smarty_tpl->setupInlineSubTemplate("../common/footer.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0, '2116056f22ee3acb017-56056684');
content_56f25a78c76237_31284340($_smarty_tpl);
$_smarty_tpl = array_pop($_tpl_stack);
/* End of included template "../common/footer.tpl" */?>
<script type="text/javascript" src="/static/plugins/editor/editormd.min.js"></script>
<script type="text/javascript" src="/static/articles/js/index.js"></script>
<script type="text/javascript" src="/static/articles/js/form.js"></script>
<!-- <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script> -->
<!-- <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script> -->
<!-- 百度统计 -->
<script type="text/javascript">
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3F777acfdc44fd57af7be29408af76bcba' type='text/javascript'%3E%3C/script%3E"));
</script>
<a class="aw-back-top hidden-xs" href="javascript:;" onclick="$.scrollTo(1, 600, {queue:true});"><i class="icon icon-up"></i></a>
<!-- DO NOT REMOVE -->
<div id="aw-ajax-box" class="aw-ajax-box"></div>
<div style="display:none;" id="__crond">
<script type="text/javascript">
/*$(document).ready(function () {
$('#__crond').html(unescape('%3Cimg%20src%3D%22' + G_BASE_URL + '/crond/run/1456901234%22%20width%3D%221%22%20height%3D%221%22%20/%3E'));
});*/
</script>
</div>
</body>
</html><?php }} ?>
<?php /* Smarty version Smarty-3.1.19, created on 2016-03-23 16:57:28
compiled from "F:\Zend\git\yaf\application\views\common\header.tpl" */ ?>
<?php if ($_valid && !is_callable('content_56f25a78bed699_95607996')) {function content_56f25a78bed699_95607996($_smarty_tpl) {?>
<div class="aw-top-menu-wrap">
<div class="container">
<!-- logo -->
<div class="aw-logo hidden-xs">
<a href="http://www.godruoyi.com"></a>
</div>
<!-- end logo -->
<!-- 搜索框 -->
<div class="aw-search-box hidden-xs hidden-sm">
<form class="navbar-search" action="#" id="global_search_form" method="post">
<input class="form-control search-query" type="text" placeholder="搜索问题、话题或人" autocomplete="off" name="q" id="aw-search-query" />
<span title="搜索" id="global_search_btns" onClick="$('#global_search_form').submit();"><i class="icon icon-search"></i></span>
<div class="aw-dropdown">
<div class="mod-body">
<p class="title">输入关键字进行搜索</p>
<ul class="aw-dropdown-list hide"></ul>
<p class="search"><span>搜索:</span><a onClick="$('#global_search_form').submit();"></a></p>
</div>
<div class="mod-footer">
<a href="#publish" onClick="$('#header_publish').click();" class="pull-right btn btn-mini btn-success publish">发起问题</a>
</div>
</div>
</form>
</div>
<!-- end 搜索框 -->
<!-- 导航 -->
<div class="aw-top-nav navbar">
<div class="navbar-header">
<button class="navbar-toggle pull-left">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<nav role="navigation" class="collapse navbar-collapse bs-navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="#" class="active"><i class="icon icon-list"></i> 文章</a></li>
<!-- <li><a href="#question/" class="">问题</a></li>
<li><a href="#article/" class="">文章</a></li> -->
<li><a href="#" ><i class="icon icon-topic"></i> 讨论</a></li>
<li><a href="#"><i class="icon icon-bulb"></i> Help</a></li>
<?php if (!empty($_smarty_tpl->tpl_vars['islogin']->value)) {?>
<li><a href="#"><i class="icon icon-bulb"></i> 消息</a></li>
<?php }?>
<li>
<a style="font-weight:bold;" title="more...">· · ·</a>
<div class="dropdown-list pull-right">
<ul id="extensions-nav-list"></ul>
</div>
</li>
</ul>
</nav>
</div>
<!-- end 导航 -->
<?php if (empty($_smarty_tpl->tpl_vars['islogin']->value)) {?>
<!-- 用户栏 -->
<div class="aw-user-nav">
<!-- 登陆&注册栏 -->
<a class="login btn btn-normal btn-primary" href="/login">登录</a>
<a class="register btn btn-normal btn-success" href="/register">注册</a> <!-- end 登陆&注册栏 -->
</div>
<!-- end 用户栏 -->
<!-- 发起 -->
<?php } else { ?>
<!-- end 发起 -->
<!-- 用户栏 -->
<div class="aw-user-nav">
<!-- 登陆&注册栏 -->
<a href="" class="aw-user-nav-dropdown">
<img alt="godruoyi" src="" />
</a>
<div class="aw-dropdown dropdown-list pull-right">
<ul class="aw-dropdown-list">
<li><a href=""><i class="icon icon-inbox"></i> 个人中心<span class="badge badge-important hide" id="inbox_unread">0</span></a></li>
<li class="hidden-xs"><a href=""><i class="icon icon-setting"></i> 设置</a></li>
<li><a href=""><i class="icon icon-logout"></i> 退出</a></li>
</ul>
</div>
<!-- end 登陆&注册栏 -->
</div>
<!-- end 用户栏 -->
<!-- 发起 -->
<div class="aw-publish-btn">
<a id="header_publish" class="btn-primary" href="" onclick=""><i class="icon icon-ask"></i>发起</a>
<div class="dropdown-list pull-right">
<ul>
<li>
<a href="/articles/create">文章</a>
</li>
</ul>
</div>
</div>
<!-- end 发起 -->
<?php }?>
</div>
</div><?php }} ?>
<?php /* Smarty version Smarty-3.1.19, created on 2016-03-23 16:57:28
compiled from "F:\Zend\git\yaf\application\views\common\footer.tpl" */ ?>
<?php if ($_valid && !is_callable('content_56f25a78c76237_31284340')) {function content_56f25a78c76237_31284340($_smarty_tpl) {?><div class="aw-footer-wrap">
<div class="aw-footer">
Copyright © 2016 · <a target="_blank" href="#">Godruoyi</a></span>
<span class="hidden-xs"> · <a href="#" target="blank">Godruoyi</a></span>
</div>
</div><?php }} ?>
<file_sep><?php
class Helper_Validate
{
private $config = NULL;
private $_validate = NULL;
private $_errors = NULL;
private $allow_methhod = ['GET', 'POST'];
public function __construct(array $config)
{
if ( !empty($config)) $this->config = $config;
$this->_validate = new Helper_FormValidate();
}
public function validate($key = '', $method = 'GET')
{
if (empty($key) || !isset($this->config[$key])) return FALSE;
if ( !in_array(strtoupper($method), $this->allow_methhod)) return FALSE;
$data = $this->config[$key];
foreach ($data as $key2 => $value) {
// $field = $key2;//name
// $assign = '';//名字
// if ( stripos($key2, '|') != FALSE) {
// $field_assign = explode('|', $key2);
// $assign = $field_assign[1];
// $field = $field_assign[0];
// }
$validates = $value;//require
if (stripos($value, '|') != FALSE) {
$validates = explode('|', $value);//array [require, minlength[10],]
}
if (is_string($validates)) {
$request_method = $validates;
$param = NULL;
if (stripos($validates, '[') != FALSE && stripos($validates, ']') != FALSE) { // minlength[20|
$method_params = explode('[', $validates);
$request_method = $method_params[0];
$param = $method_params[1];
} else {
throw new exception_Exception('方法验证错误,缺少中括号'.$validates);
}
if (empty($param)) {
$isok = $this->_validate->$request_method($key2);
} else {
$isok = $this->_validate->$request_method($key2, $param);
}
if ($isok) continue;
$this->_errors[] = $this->_validate->getError();
}
}
}
}<file_sep><?php /* Smarty version Smarty-3.1.19, created on 2016-03-24 11:15:19
compiled from "F:\Zend\git\yaf\application\views\common\404.tpl" */ ?>
<?php /*%%SmartyHeaderCode:1193756f35b9bb80a52-27027791%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'b8f333fe2be235e6e69d621ef2bb2cc841c3ce17' =>
array (
0 => 'F:\\Zend\\git\\yaf\\application\\views\\common\\404.tpl',
1 => 1458789318,
2 => 'file',
),
),
'nocache_hash' => '1193756f35b9bb80a52-27027791',
'function' =>
array (
),
'version' => 'Smarty-3.1.19',
'unifunc' => 'content_56f35b9bb9bfe9_38696813',
'has_nocache_code' => false,
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_56f35b9bb9bfe9_38696813')) {function content_56f35b9bb9bfe9_38696813($_smarty_tpl) {?><!DOCTYPE html>
<html lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
<meta name="robots" content="noindex, nofollow" />
<title>404 Not Found</title>
<link rel="icon" type="image/png" href="favicon.png" />
<style type="text/css" media="screen">
html, body{ margin: 0; padding: 0; border: 0; font-size: 100%; vertical-align: baseline; }
body{ font: 100%/160% Georgia, Constantia, "<NAME>", LucidaBright, "DejaVu Serif", "Bitstream Vera Serif", "Liberation Serif", Times, Serif; text-align: center; color: #2A2925; background: #E1E0DC; padding-top: 10%; }
img{ float: right; width: 25%; min-width: 150px; max-width: 300px; height: auto; margin-top: -5%; }
p{ margin: 0; padding: 0 2% 2% 2%; line-height: 1em; font-size: 1.8em; }
.error{ font-size: 4em; }
.funny{ font-style: italic; }
a, a:link, a:visited{ color: #fff; background: #2A2925; text-decoration: none; padding: .2em .4em; line-height: 2em; -webkit-border-radius: .5em; -moz-border-radius: .5em; border-radius: .5em; }
a:hover{ background: #281d30; }
</style>
</head>
<body>
<p class="error">404 Not Found</p><p class="funny">No Coffee, No Workee!</p>
<p><a href="/" title="Back on track trooper!">←godruoyi.com/</a></p>
</body>
</html><?php }} ?>
<file_sep><?php
/**
*
*
*
*/
class ArticlesController extends core_Commonents
{
public function init()
{
parent::init(FALSE);
}
public function createAction()
{
if ($this->_is_ajax) return $this->_do_create();
//$this->_checkLogging();
$classify = new ClassifyModel();
$res = $classify->select(NULL, ['fields' => 'c_name as `name`, c_id as `id`']);
$this->getView()->assign('classify', $res);
$this->getView()->display('articles/index.tpl');
}
public function detailAction()
{
$id = $this->getRequest()->getParam('id');
$id = intval($id);
if ($id <= 0) {
$this->show_404();
}
$article = new ArticleModel();
$result = $article->selectOne(['a_id' => $id], ['fields' => 'a_id, a_title, a_brower,u_id,c_id,a_createtime']);
if ( empty($result)) $this->show_404();
$user_id = $result['u_id'];
$group_id = $result['c_id'];
$brower_num = $result['a_brower'];
$fenlei = new ClassifyModel();
$names = $fenlei->selectOne(['c_id' => $group_id], ['fields' => 'c_name as `name`']);
//$user = new UsersModel();
//$users = $user->selectOne(['u_id' => $user_id], ['fields' => 'u_name as `username`, u_img as `image_url`']);
//评论
$tops = new TopsModel();
$countn = $tops->selectCount(['a_id' => $id]);
$top = NULL;
if ($countn > 0) {
$top = $tops->select(['a_id' => $id], ['order_by' => 't_id DESC','offset' => 0, 'limit' => 20]);
}
$data = [
'user' => [
'user_id' => 1,
'user_name' => 'xulianbo',//$users['username'],
'user_img' => '',//$users['image_url'],
'user_nickname' => '大牛牛',//$users['image_url'],
],
'group' => [
'group_id' => $group_id,
'group_name' => $names['name'],
],
'article' =>[
'article_id' => $result['a_id'],
'article_title' => $result['a_title'],
'article_brower' => $result['a_brower'],
'article_createtime' => date('Y-m-d', strtotime($result['a_createtime'])),
],
'tops' => [
'count' => $countn,
'data' => $top,
],
];
//更新浏览量, , 这里应该用插件的。。。。。
//TODO...............
$this->getView()->assign('articles_data', $data);
$this->getView()->display('articles/detail.tpl');
}
public function getContentAction()
{
$id = intval( $_GET['id']);
if (!$this->_is_ajax || $id <= 0) {
$this->_ajax_return_failed('获取文章失败,请尝试重新加载!');
}
$article = new ArticleModel();
$result = $article->selectOne(['a_id' => $id], ['fields' => 'a_content as `content`']);
if ( empty($result)) $this->_ajax_return_failed('获取文章失败,请尝试重新加载!');
$this->_ajax_return_success('success', $result['content']);
}
private function _do_create()
{
$title = $_POST['title'];
$id = $_POST['id'];
$content = $_POST['content'];
if(empty($title)) {
$this->_ajax_return_failed('标题不能为空!!');
}
if(empty($id) || (int)$id <= 0) {
$this->_ajax_return_failed('请选择分类!!');
}
if(empty($content)) {
$this->_ajax_return_failed('内容不能为空!!');
}
$articles = new ArticleModel();
$data = [
'a_title' => $title,
'a_content' => $content,
'a_brower' => 0,
'c_id' => $id,
'u_id' => $this->_id,
'a_createtime' => date('Y-m-d H:i:s'),
];
$ok = $articles->insert($data, NULL, FALSE);
if (!$ok){
$errors = $articles->getErrors();
$this->_ajax_return_failed('插入失败!!', $errors);
}
$this->_ajax_return_success();
}
}<file_sep><?php
$dbconfig = [
'DBConfig' => [
'write' => [
'dns' => 'mysql:host=localhost;dbname=test_my;port=3306',
'user' => 'root',
'password' => '<PASSWORD>',
'charset' => 'utf8',
'prefix' => 'g_',
],
'read' => [
//从机可能有很多歌
[
'dns' => 'mysql:host=localhost;dbname=test_my;port=3306',
'user' => 'root',
'password' => '<PASSWORD>',
'charset' => 'utf8',
'prefix' => 'g_',
],
[
'dns' => 'mysql:host=localhost;dbname=test_my;port=3306',
'user' => 'root',
'password' => '<PASSWORD>',
'charset' => 'utf8',
'prefix' => 'g_',
]
],
],
];<file_sep><?php
class ArticleModel extends MysqldbModel
{
public function __construct()
{
parent::__construct('articles');
}
}<file_sep><?php
class ClassifyModel extends MysqldbModel
{
public function __construct()
{
parent::__construct('classify');
}
}<file_sep><?php
class Acticleslugin extends Yaf_Plugin_Abstract
{
public function dispatchLoopShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
}
}
<file_sep><?php
/**
* 应用全局引导配置
*
* 在这里可以定义通用的配置文件, 自定义的加载器等
*
*/
date_default_timezone_set("Asia/Chongqing");
error_reporting(E_ALL);
//定义用户类库路径
defined('LIB_PPATH') or define('LIB_PPATH', APP_PATH . '/library/');
//定义环境, 默认是在开发环境
defined('APP_EVE') or define('APP_EVE', 'develop');
//######################################################## 暂时先这样处理
//引入数据库配置
$file = BASE_PATH . '/conf/' . APP_EVE . '/DB.php';
if (file_exists($file)) require $file;
//引入全局配置
require BASE_PATH . '/conf/common.config.php';
//########################################################
require PUBLIC_PATH . '/route.php';
//set composer autoload
require BASE_PATH . '/vendor/autoload.php';
//smarty引入放在全局引导文件里, 放在YAF引导类下有点xiaobug
require LIB_PPATH . '/thirdlib/smarty/Smarty.class.php';
require LIB_PPATH . '/thirdlib/smarty/smarty-gettext.php';<file_sep><?php /* Smarty version Smarty-3.1.19, created on 2016-03-23 13:49:36
compiled from "F:\Zend\git\yaf\application\views\register\index.tpl" */ ?>
<?php /*%%SmartyHeaderCode:130256f22e701896c4-43225257%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'c8534be8fc39005a2fdb84f93c89f0160bb868a0' =>
array (
0 => 'F:\\Zend\\git\\yaf\\application\\views\\register\\index.tpl',
1 => 1458632347,
2 => 'file',
),
'b7aba38bca2edd88e759555da3d41a3d050d194e' =>
array (
0 => 'F:\\Zend\\git\\yaf\\application\\views\\common\\base.tpl',
1 => 1458622089,
2 => 'file',
),
'00bb99ef4a9bc68c1e51c7d435e33d9abfa8f392' =>
array (
0 => 'F:\\Zend\\git\\yaf\\application\\views\\common\\header.tpl',
1 => 1458623402,
2 => 'file',
),
'25d0cfc6ae6a2d07f03e53021daf49c4789747eb' =>
array (
0 => 'F:\\Zend\\git\\yaf\\application\\views\\common\\footer.tpl',
1 => 1457685727,
2 => 'file',
),
),
'nocache_hash' => '130256f22e701896c4-43225257',
'function' =>
array (
),
'has_nocache_code' => false,
'version' => 'Smarty-3.1.19',
'unifunc' => 'content_56f22e7032b6b7_21840410',
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_56f22e7032b6b7_21840410')) {function content_56f22e7032b6b7_21840410($_smarty_tpl) {?>
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1" />
<meta name="renderer" content="webkit" />
<meta charset="utf-8" />
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<title>注册---Godruoyi</title>
<meta name="description" content="This is description , you can input everthing.">
<meta name="keywords" content="KEY WORDS">
<!-- setting icon -->
<!-- <link rel="shortcut icon" href="resource/common/favicon.ico" type="image/x-icon"/>-->
<?php echo $_smarty_tpl->getSubTemplate ("static/common/inc/css_common.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0);?>
<?php echo $_smarty_tpl->getSubTemplate ("static/common/inc/js_lib.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0);?>
<link rel="stylesheet" type="text/css" href="/static/register/css/register.css">
</head>
<body>
<div class="aw-register-box">
<div class="mod-head">
<a href="http://www.godruoyi.com/"><img src="/ /images/login_logo.png" alt="" /></a>
<h1>注册新用户</h1>
</div>
<div class="mod-body">
<form class="aw-register-form" action="" method="post" id="register_form">
<ul>
<li class="alert alert-danger hide error_message text-left">
<i class="icon icon-delete"></i> <em></em>
</li>
<li>
<input class="aw-register-name form-control" type="text" name="user_name" placeholder="用户名" tips="请输入一个 2-14 位的用户名" errortips="用户名长度不符合" value="" />
</li>
<li>
<input class="aw-register-email form-control" type="text" placeholder="邮箱" name="email" tips="请输入你常用的电子邮箱作为你的账号" value="" errortips="邮箱格式不正确" />
</li>
<li>
<input class="aw-register-pwd form-control" type="<PASSWORD>" name="password" placeholder="密码" tips="请输入 6-16 个字符,区分大小写" errortips="密码不符合规则" />
</li>
<li class="aw-register-verify">
<img class="pull-right" id="captcha" onclick="" src="">
<input type="text" class="form-control" name="seccode_verify" placeholder="验证码" />
</li>
<li class="last">
<label><input type="checkbox" checked="checked" value="agree" name="agreement_chk" /> 我同意</label> <a href="javascript:;" class="aw-agreement-btn">用户协议</a>
<a href="/login" class="pull-right">已有账号?</a>
<div class="aw-register-agreement hide">
<div class="aw-register-agreement-txt" id="register_agreement"></div>
</div>
</li>
<li class="clearfix">
<button class="btn btn-large btn-blue btn-block" onclick="">注册</button>
</li>
</ul>
</form>
</div>
</div>
<?php /* Call merged included template "../common/footer.tpl" */
$_tpl_stack[] = $_smarty_tpl;
$_smarty_tpl = $_smarty_tpl->setupInlineSubTemplate("../common/footer.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0, '130256f22e701896c4-43225257');
content_56f22e70317e20_46335524($_smarty_tpl);
$_smarty_tpl = array_pop($_tpl_stack);
/* End of included template "../common/footer.tpl" */?>
<!-- 百度统计 -->
<script type="text/javascript">
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3F777acfdc44fd57af7be29408af76bcba' type='text/javascript'%3E%3C/script%3E"));
</script>
<a class="aw-back-top hidden-xs" href="javascript:;" onclick="$.scrollTo(1, 600, {queue:true});"><i class="icon icon-up"></i></a>
<!-- DO NOT REMOVE -->
<div id="aw-ajax-box" class="aw-ajax-box"></div>
<div style="display:none;" id="__crond">
<script type="text/javascript">
/*$(document).ready(function () {
$('#__crond').html(unescape('%3Cimg%20src%3D%22' + G_BASE_URL + '/crond/run/1456901234%22%20width%3D%221%22%20height%3D%221%22%20/%3E'));
});*/
</script>
</div>
</body>
</html><?php }} ?>
<?php /* Smarty version Smarty-3.1.19, created on 2016-03-23 13:49:36
compiled from "F:\Zend\git\yaf\application\views\common\header.tpl" */ ?>
<?php if ($_valid && !is_callable('content_56f22e702aa818_92717795')) {function content_56f22e702aa818_92717795($_smarty_tpl) {?>
<div class="aw-top-menu-wrap">
<div class="container">
<!-- logo -->
<div class="aw-logo hidden-xs">
<a href="http://www.godruoyi.com"></a>
</div>
<!-- end logo -->
<!-- 搜索框 -->
<div class="aw-search-box hidden-xs hidden-sm">
<form class="navbar-search" action="#" id="global_search_form" method="post">
<input class="form-control search-query" type="text" placeholder="搜索问题、话题或人" autocomplete="off" name="q" id="aw-search-query" />
<span title="搜索" id="global_search_btns" onClick="$('#global_search_form').submit();"><i class="icon icon-search"></i></span>
<div class="aw-dropdown">
<div class="mod-body">
<p class="title">输入关键字进行搜索</p>
<ul class="aw-dropdown-list hide"></ul>
<p class="search"><span>搜索:</span><a onClick="$('#global_search_form').submit();"></a></p>
</div>
<div class="mod-footer">
<a href="#publish" onClick="$('#header_publish').click();" class="pull-right btn btn-mini btn-success publish">发起问题</a>
</div>
</div>
</form>
</div>
<!-- end 搜索框 -->
<!-- 导航 -->
<div class="aw-top-nav navbar">
<div class="navbar-header">
<button class="navbar-toggle pull-left">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<nav role="navigation" class="collapse navbar-collapse bs-navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="#" class="active"><i class="icon icon-list"></i> 文章</a></li>
<!-- <li><a href="#question/" class="">问题</a></li>
<li><a href="#article/" class="">文章</a></li> -->
<li><a href="#" ><i class="icon icon-topic"></i> 讨论</a></li>
<li><a href="#"><i class="icon icon-bulb"></i> Help</a></li>
<?php if (!empty($_smarty_tpl->tpl_vars['islogin']->value)) {?>
<li><a href="#"><i class="icon icon-bulb"></i> 消息</a></li>
<?php }?>
<li>
<a style="font-weight:bold;" title="more...">· · ·</a>
<div class="dropdown-list pull-right">
<ul id="extensions-nav-list"></ul>
</div>
</li>
</ul>
</nav>
</div>
<!-- end 导航 -->
<?php if (empty($_smarty_tpl->tpl_vars['islogin']->value)) {?>
<!-- 用户栏 -->
<div class="aw-user-nav">
<!-- 登陆&注册栏 -->
<a class="login btn btn-normal btn-primary" href="/login">登录</a>
<a class="register btn btn-normal btn-success" href="/register">注册</a> <!-- end 登陆&注册栏 -->
</div>
<!-- end 用户栏 -->
<!-- 发起 -->
<?php } else { ?>
<!-- end 发起 -->
<!-- 用户栏 -->
<div class="aw-user-nav">
<!-- 登陆&注册栏 -->
<a href="" class="aw-user-nav-dropdown">
<img alt="godruoyi" src="" />
</a>
<div class="aw-dropdown dropdown-list pull-right">
<ul class="aw-dropdown-list">
<li><a href=""><i class="icon icon-inbox"></i> 个人中心<span class="badge badge-important hide" id="inbox_unread">0</span></a></li>
<li class="hidden-xs"><a href=""><i class="icon icon-setting"></i> 设置</a></li>
<li><a href=""><i class="icon icon-logout"></i> 退出</a></li>
</ul>
</div>
<!-- end 登陆&注册栏 -->
</div>
<!-- end 用户栏 -->
<!-- 发起 -->
<div class="aw-publish-btn">
<a id="header_publish" class="btn-primary" href="" onclick=""><i class="icon icon-ask"></i>发起</a>
<div class="dropdown-list pull-right">
<ul>
<li>
<a href="/articles/create">文章</a>
</li>
</ul>
</div>
</div>
<!-- end 发起 -->
<?php }?>
</div>
</div><?php }} ?>
<?php /* Smarty version Smarty-3.1.19, created on 2016-03-23 13:49:36
compiled from "F:\Zend\git\yaf\application\views\common\footer.tpl" */ ?>
<?php if ($_valid && !is_callable('content_56f22e70317e20_46335524')) {function content_56f22e70317e20_46335524($_smarty_tpl) {?><div class="aw-footer-wrap">
<div class="aw-footer">
Copyright © 2016 · <a target="_blank" href="#">Godruoyi</a></span>
<span class="hidden-xs"> · <a href="#" target="blank">Godruoyi</a></span>
</div>
</div><?php }} ?>
<file_sep><?php
abstract public class core_AbcBase extends core_Base
{
abstract public function init();
}<file_sep><?php
class Helper_FormValidate
{
private static $instance = NULL;
public function __construct()
{
if (self::$instance == NULL)
{
self::$instance = new self();
}
return self::$instance;
}
public function required($name, $data)
{
if (strlen($data)<=0) {
return "'{$name}' 不能为空";
} else {
return TRUE;
}
}
//最小值
public function min($name, $data, $min)
{
$min = (int) $min;
if (!is_null($data) && $data >= $min) {
return TRUE;
} else {
return "'{$name}' 最小值为{$min}";
}
}
public function max($name, $data, $max)
{
$max = (int) $max;
if (!is_null($data) && $data <= $max) {
return TRUE;
} else {
return "'{$name}' 最大值为{$max}";
}
}
public function integer($name, $data)
{
if (empty($data)) {
return TRUE;
}
$data = (int) $data;
if (!empty($data)) {
return TRUE;
} else {
return "'{$name}' 必须为整数";
}
}
public function numeric($name, $data)
{
if (empty($data)) {
return TRUE;
}
if (is_numeric($data)) {
return TRUE;
} else {
return "'{$name}' 必须为数字";
}
}
//用户名的检查,只能是字母数字和下划线
public function username($name, $data)
{
if (empty($data)) {
return TRUE;
}
$pattern = '/^[_\w\d]+$/i';
if (!preg_match($pattern, $data))
{
return "'{$name}' 只能是字母数字和下划线";
}
return TRUE;
}
public function valid_url($name, $str)
{
if (empty($str)) {
return TRUE;
}
$pattern = "/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";
if (!preg_match($pattern, $str))
{
return "'{$name}' 不是有效的URL地址";
}
return TRUE;
}
/**
* 密码校验,不能是全数字或全字母
*/
public function valid_password($name, $str)
{
if (empty($str)) {
return TRUE;
}
$pattern = '/^(?!\d+$)(?![a-zA-Z]+$)(?![ ]+$).+?/';
if (!preg_match($pattern, $str))
{
return "'{$name}' 不符合密码规则";
}
return TRUE;
}
/**
* 匹配格式:
* 11位手机号码
* 3-4位区号,7-8位直播号码,1-4位分机号
* 如:12345678901、1234-12345678-1234
* 2015-03-23新增美国电话格式:xxx-xxx-xxxx、+xx-xxx-xxx-xxxx或没有连接字符串
*/
public function valid_phone($name, $str)
{
if (empty($str)) {
return TRUE;
}
$pattern = "(^\+?((\d{1}|\d{2})-?\d{3}-?\d{3}-?\d{4})$|(\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}))$)";
if (!preg_match($pattern, $str))
{
return "'{$name}' 不是有效的电话号码";
}
return TRUE;
}
public function valid_datetime($name, $str)
{
if (empty($str)) {
return TRUE;
}
if (Helper_Date::isDateTime($str) && !Helper_Date::isEmpty($str)) {
return TRUE;
} else {
return "'{$name}' 不是有效的日期";
}
}
public function valid_date($name, $str)
{
if (empty($str)) {
return TRUE;
}
if (Helper_Date::isDate($str) && !Helper_Date::isEmpty($str)) {
return TRUE;
} else {
return "'{$name}' 不是有效的日期";
}
}
public function valid_email($name, $str)
{
if (empty($str)) {
return TRUE;
}
$pattern = '/^(\w)+([\.\w\-]+)*@(\w)+((\.\w+){1,5})$/i';
if(!preg_match($pattern, $str)) {
return "'{$name}' 不是有效的电子邮箱";
}
return TRUE;
}
//字符串最小长度
public function min_length($name, $str, $len)
{
if (empty($str)) {
return TRUE;
}
if (!empty($str) && strlen($str) >= $len)
{
return TRUE;
} else {
return "'{$name}'至少输入{$len}个字符";
}
}
//字符串最大长度
public function max_length($name, $str, $len)
{
if (empty($str) || strlen($str) <= $len)
{
return TRUE;
} else {
return "'{$name}'最多输入{$len}个字符";
}
}
//字符串最小长度
public function utf8min_length($name, $str, $len)
{
if (!empty($str) && mb_strlen($str, 'UTF-8') >= $len)
{
return TRUE;
} else {
return "'{$name}'至少输入{$len}个字符";
}
}
//字符串最大长度
public function utf8max_length($name, $str, $len)
{
if (empty($str) || mb_strlen($str, 'UTF-8') <= $len)
{
return TRUE;
} else {
return "'{$name}'最多输入{$len}个字符";
}
}
//检查是否是一个合理的价格
public function price($name, $data)
{
if (empty($data)) {
return TRUE;
}
if (!is_numeric($data)) {
return "'{$name}'不是有效的数字";
}
$nums = explode('.', $data);
if (count($nums) < 2) {
//证明是整数
return TRUE;
}
if (strlen($nums[1]) > 2) {
return "'{$name}' 只能精确到小数点2位";
}
return TRUE;
}
} | b676ffa0e42eaf32f03f1fdc05ba521d89efa01e | [
"JavaScript",
"Markdown",
"PHP",
"INI"
] | 45 | PHP | godruoyi/yaf | be83f2494011b35a47eb982923734bbf87eed11f | bfa45d54a5fe98c34c40c811a47e4837967bb483 | |
refs/heads/master | <repo_name>MartinShishkov/blog-demos<file_sep>/clean-controllers/CleanControllers.Web/Controllers/DirtyController.cs
using System;
using System.Linq;
using System.Net;
using CleanControllers.Web.Models.Business;
using CleanControllers.Web.Models.Web;
using Microsoft.AspNetCore.Mvc;
namespace CleanControllers.Web.Controllers
{
public class DirtyController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult DoStuff(SimpleFormPostModel model)
{
if (model.Consent == null || model.Consent.Contains("yes") == false)
{
// This is business logic right here
// we could have created a custom ValidationAttribute.
// Although this is going to be slightly better -
// the issue still remains. Furthermore, we are going
// to have some trouble if we want to use localization for
// our errors if we rely on [ValidationAttribute]s
ModelState.AddModelError(
nameof(SimpleFormPostModel.Consent),
"You have to give your consent"
);
}
if (ModelState.IsValid == false)
return new JsonResult(new
{
// even getting the error messages is an abomination
errors = ModelState.Values.SelectMany(e => e.Errors.Select(err => err.ErrorMessage))
}) {StatusCode = (int)HttpStatusCode.BadRequest};
try
{
var person = new Person(model.FirstName, model.LastName, model.Age);
if(model.ShouldCauseServerError)
throw new InvalidOperationException("Something happened with our Person because our validation logic is all over the place! It was not in valid state to begin with!");
// ...execute operations with 'person'...
return new JsonResult(new
{
message = "Everything went smooth"
}) {StatusCode = (int)HttpStatusCode.OK};
}
catch (Exception e)
{
return new JsonResult(new
{
errors = new string[]{e.Message}
}){ StatusCode = (int)HttpStatusCode.InternalServerError};
}
}
}
}
<file_sep>/clean-controllers/CleanControllers.Web/Controllers/CleanController.cs
using System;
using System.Net;
using CleanControllers.Web.Models.Business;
using Microsoft.AspNetCore.Mvc;
namespace CleanControllers.Web.Controllers
{
public class CleanController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult DoStuff(Person.Builder builder)
{
var buildResult = builder.Build();
if(buildResult.IsValid == false)
return new JsonResult(new
{
errorCodes = buildResult.ErrorCodes
}) {StatusCode = (int)HttpStatusCode.BadRequest};
try
{
// we have a valid person at this point for sure
var person = buildResult.Value;
// ...execute operations with 'person'...
if(builder.ShouldCauseServerError)
throw new InvalidOperationException("Something happened but this time we can be sure that our Person was valid which means something else failed in our services.");
return new JsonResult(new
{
message = "Everything went smooth"
}) {StatusCode = (int)HttpStatusCode.OK};
}
catch (Exception e)
{
return new JsonResult(new
{
errors = new string[]{e.Message}
}){ StatusCode = (int)HttpStatusCode.InternalServerError};
}
}
}
}<file_sep>/problems/HackerRank/_02.Sort-1-and-0s/README.md
# Sort 1s and 0s
This problem was given to me in an interview with SBTech in HackerRank,
alongside with 79.Minimum-Window and MinimumSum
I don't have the exact problem description but it goes something like this:
Given an array of 1s and 0s, find the least number of swaps of adjacent elements required to
sort the array. The direction of sorting does not matter.
Example:
[1, 1, 1, 0, 0, 0] => 0
[0, 0, 0, 1, 1, 1] => 0
[1, 0, 1, 0, 0, 0] => 1
[1, 0, 0, 1, 0, 1, 1, 0, 0, 1] => 12<file_sep>/problems/HackerRank/_01.MininumSum/README.md
*Minimum Sum
This problem was given to me in an interview with SBTech in HackerRank,
alongside with 79.Minimum-Window problem
I don't have the exact problem description but it goes something like this:
There's an input array with integers say [10, 20, 7], and a number **k** operations.
For each operation you must take the ceiling of a single number in the array / 2.
Math.Ceiling(n / 2), and replace the old number with the new one. You have to choose such numbers so
that the end sum is the smallest possible. Example
input: [10, 20, 7]
k: 4
------- k = 1 -------
[10, 20, 7] => [10, 10, 7] // we take 20, divide by 2, and take the ceiling, so 10
------- k = 2 -------
[10, 10, 7] => [10, 5, 7] // Math.Ceiling(10 / 2) = 5
------- k = 3 -------
[10, 5, 7] => [5, 5, 7] // Math.Ceiling(10 / 2) = 5
------- k = 4 -------
[5, 5, 7] => [5, 5, 4] // Math.Ceiling(7 / 2) = 4
So we have to print out '14' since this is the sum of all numbers
<file_sep>/problems/LeetCode/76.Minimum-Window-Substring/README.md
# Minimum Window Substring Problem
## The solution currently scores 267/268 tests
https://leetcode.com/problems/minimum-window-substring/
Difficulty: **HARD**
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
Example:
> Input: S = "ADOBECODEBANC", T = "ABC"
>
> Output: "BANC"
Note:
If there is no such window in S that covers all characters in T, return the empty string "".
If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
**This problem was given to me in an interview with SBTech**
It was the 1 of 3 problems at HackerRank, but I couldn't find it there
so I managed to get it in LeetCode<file_sep>/problems/LeetCode/205.Isomorphic-Strings/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace _205.Isomorphic_Strings
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(AreIsomorphic("ab", "aa"));
/*
Runtime: 120 ms, faster than 21.31% of C# online submissions for Isomorphic Strings.
Memory Usage: 23.4 MB, less than 66.39% of C# online submissions for Isomorphic Strings.
*/
}
public static bool AreIsomorphic(string str1, string str2)
{
if (string.IsNullOrWhiteSpace(str1) &&
string.IsNullOrWhiteSpace(str2))
return true;
if (str1?.Length != str2.Length) return false;
var map = new Dictionary<char, char>();
var reverseMap = new Dictionary<char, char>();
var length = str1.Length;
for (int i = 0; i < length; i++)
{
var key = str1[i];
var value = str2[i];
if (map.ContainsKey(key) && value != map[key])
return false;
if (reverseMap.ContainsKey(value) && key != reverseMap[value])
return false;
map.TryAdd(key, value);
reverseMap.TryAdd(value, key);
}
return true;
}
}
}
<file_sep>/problems/HackerRank/_02.Sort-1-and-0s/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace _02.Sort_1_and_0s
{
class Program
{
// This problem really looks like a bubblesort to me
// or at least the brute force solution. The only issue
// is that we have to determine in which direction to sort
// so that we actually get the least amount of swaps
static int BubbleSort(List<int> arr)
{
var count = 0;
var n = arr.Count;
var comparer = GetComparer(arr);
for (var i = 0; i < n - 1; i++)
{
for (var j = 0; j < n - i - 1; j++)
{
if (comparer(arr[j], arr[j + 1]))
{
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
count++;
}
}
}
return count;
}
static Func<int, int, bool> GetComparer(List<int> arr)
{
var take = (int) Math.Ceiling((decimal) (arr.Count - 1) / 2);
var leftPart = arr.GetRange(0, take);
var startIndex = take;
var rightPart = arr.GetRange(startIndex, arr.Count - take);
if (leftPart.Sum() > rightPart.Sum())
return (i, i1) => i < i1; // descending 111 -> 000
return (i, i1) => i > i1; // ascending 000 -> 111
}
static void Main(string[] args)
{
var inputs = new List<List<int>>
{
/*new List<int>{ 0, 1 },
new List<int> {1, 1, 1, 1, 0, 0, 0, 0},
new List<int> {1, 1, 1, 1, 0, 0, 1, 0},
new List<int> {0, 1, 1, 1, 1, 0, 0, 1, 0},*/
new List<int> {0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1},
/*new List<int> {0, 0, 0, 0, 0, 0, 1, 1},*/
};
foreach (var input in inputs)
{
var res = BubbleSort(input);
Console.WriteLine(res);
}
}
}
}
<file_sep>/problems/LeetCode/1138.Alphabet-Board-Path/Program.cs
using System;
namespace _1138.Alphabet_Board_Path
{
class Program
{
public static readonly string[] _board = new string[] {
"abcde",
"fghij",
"klmno",
"pqrst",
"uvwxy",
"z"
};
static void Main(string[] args)
{
Console.WriteLine(3 - -3);
Console.WriteLine(AlphabetBoardPath("leet"));
}
public static string AlphabetBoardPath(string target) {
string path = string.Empty;
int curCol = 0, curRow = 0;
string GetHorizontalPath(int colsDiff)
{
if(colsDiff == 0) return string.Empty;
var ch = colsDiff > 0 ? 'R' : 'L';
return new string(ch, Math.Abs(colsDiff));
}
string GetVerticalPath(int rowsDiff)
{
if(rowsDiff == 0) return string.Empty;
var ch = rowsDiff > 0 ? 'D' : 'U';
return new string(ch, Math.Abs(rowsDiff));
}
string ProcessHorizontalDir(char direction, int rowsDiff, int colsDiff){
if(direction == 'U')
{
if(curCol - colsDiff < 0)
{
rowsDiff++;
colsDiff = 5 - colsDiff;
}
return GetVerticalPath(rowsDiff) + GetHorizontalPath(colsDiff);
}
else
{
}
return string.Empty;
};
void ProcessVerticalDir(char direction, int rowsDiff, int colsDiff){
};
foreach(char targetCh in target)
{
var currentCh = _board[curRow][curCol];
if(currentCh == targetCh)
{
path += '!';
continue;
}
var diff = (int)targetCh - (int)currentCh;
var shouldSearchForward = diff > 0;
var rowsDiff = Math.Abs(diff / 5);
var colsDiff = Math.Abs(diff % 5);
if(!shouldSearchForward)
{
if(curCol - colsDiff < 0)
{
rowsDiff++;
colsDiff = 5 - colsDiff;
}
}
else
{
// target char is ahead relative to the current char
}
var directionV = diff > 0 ? 'D' : 'U';
var directionH = diff > 0 ? 'R' : 'L';
ProcessVerticalDir(directionV, rowsDiff, colsDiff);
ProcessHorizontalDir(directionH, rowsDiff, colsDiff);
}
return path;
}
}
}
<file_sep>/problems/LeetCode/76.Minimum-Window-Substring/Program.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace _76.Minimum_Window_Substring
{
class Program
{
static string MinimumWindowSubstr(string haystack, string letters)
{
var length = haystack.Length;
var minWindowLength = letters.Length;
if (minWindowLength > length) return string.Empty;
if (minWindowLength == 1 && haystack.IndexOf(letters) < 0) return string.Empty;
if (minWindowLength == 1 && haystack.IndexOf(letters) != -1) return letters;
var map = ToMap(letters);
var startPointer = 0;
var endPointer = minWindowLength - 1;
var currentSmallestWindow = string.Empty;
do
{
var take = (endPointer + 1) - startPointer;
var window = haystack.Substring(startPointer, take);
if (window.Length >= minWindowLength
&& WindowMatchesCondition(window, map))
{
startPointer++;
if (window.Length < currentSmallestWindow.Length
|| currentSmallestWindow == string.Empty)
{
currentSmallestWindow = window;
}
}
else
{
if (endPointer == length - 1)
{
if (length - Math.Max(1, startPointer) <= minWindowLength)
{
break;
}
else
{
startPointer++;
}
}
endPointer = Math.Min(endPointer + 1, length - 1);
}
} while (true);
return currentSmallestWindow;
}
static bool WindowMatchesCondition(string window, Dictionary<char, int> map)
{
var copy = new Dictionary<char, int>(map);
for (var i = 0; i < window.Length; i++)
{
var ch = window[i];
if (copy.ContainsKey(ch))
{
copy[ch]--;
if (copy[ch] == 0)
copy.Remove(ch);
}
}
return !(copy.Values.Count > 0);
}
static Dictionary<char, int> ToMap(string str)
{
var map = new Dictionary<char, int>();
foreach (var ch in str)
{
if (!map.ContainsKey(ch))
map.Add(ch, 0);
map[ch]++;
}
return map;
}
static void Main(string[] args)
{
/* var tests = new Dictionary<string, string>{
{"ADOBECODEBANC", "ABC"},
//{"abc", "ac"},
{"abc", "a"},
//{"ab", "b"},
{"aa", "aa"},
{"ab", "A"},
{"cabwefgewcwaefgcf", "cae"}
}; */
/* foreach (var test in tests)
{
Console.WriteLine(MinimumWindowSubstr(test.Key, test.Value));
} */
var s = "<KEY>";
var t = "<KEY>qiqrzwugtr";
var sw = new Stopwatch();
sw.Reset();
sw.Start();
var res = MinimumWindowSubstr(s, t);
sw.Stop();
Console.WriteLine($"Time: {sw.ElapsedMilliseconds}ms");
Console.WriteLine(res);
}
}
}
<file_sep>/problems/LeetCode/217.Contains-Duplicate/Program.cs
using System;
using System.Collections.Generic;
namespace _217.Contains_Duplicate
{
class Program
{
static void Main(string[] args)
{
var input = new int[] {1,1,1,3,3,4,3,2,4,2};
Console.WriteLine(ContainsDuplicate(input));
}
static bool ContainsDuplicate(int[] nums)
{
var set = new HashSet<int>(nums);
return set.Count != nums.Length;
}
}
}
<file_sep>/problems/HackerRank/_01.MininumSum/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace _01.MininumSum
{
class Program
{
static int MinSum(List<int> input, int k)
{
input.Sort();
// we know that the last element is the largest
// since we've sorted the input
var largestNumIndex = input.Count - 1;
int largestNum;
void CompareToPrev()
{
var prevIndex = largestNumIndex - 1;
var prev = input[prevIndex];
if (largestNum < prev)
{
largestNum = prev;
largestNumIndex = prevIndex;
}
}
void CompareToNext()
{
var nextIndex = largestNumIndex + 1;
var next = input[nextIndex];
if (largestNum < next)
{
largestNum = next;
largestNumIndex = nextIndex;
}
}
for (int i = 0; i < k; i++)
{
largestNum = input[largestNumIndex];
if (largestNumIndex == input.Count - 1)
{
// largest num is the last element
// so compare it with the previous element
CompareToPrev();
}
else if (largestNumIndex == 0)
{
// largest num is the first element
// so compare it to the next
CompareToNext();
}
else
{
// largest num is somewhere in the middle
// compare it with the elements from both sides
CompareToNext();
CompareToPrev();
}
var valueToInsert = (int) Math.Ceiling((decimal)largestNum / 2);
input[largestNumIndex] = valueToInsert;
}
return input.Sum();
}
static void Main(string[] args)
{
var input = new List<int> { 10, 20, 7 };
var k = 4;
Console.WriteLine(MinSum(input, k));
}
}
}
<file_sep>/clean-controllers/CleanControllers.Web/Models/Business/BuildResult.cs
using System;
using Microsoft.EntityFrameworkCore.Internal;
namespace CleanControllers.Web.Models.Business
{
public class BuildResult<T>
{
public BuildResult(string[] errorCodes, T value)
{
ErrorCodes = errorCodes ?? throw new ArgumentNullException(nameof(errorCodes));
Value = value;
}
public string[] ErrorCodes { get; }
public T Value { get; }
public bool IsValid => ErrorCodes.Any() == false;
}
}<file_sep>/clean-controllers/CleanControllers.Web/Models/Web/SimpleFormPostModel.cs
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace CleanControllers.Web.Models.Web
{
public class SimpleFormPostModel
{
// We can't use our Person error codes here because of a compile time error.
// We can try to create some workaround but it's going to get messy.
[Required]
[MinLength(3, ErrorMessage = "This has to be at least 3 chars long dammit")]
public string FirstName { get; set; }
[Required]
[MinLength(3, ErrorMessage = "This has to be at least 3 chars long dammit")]
public string LastName { get; set; }
[Required]
[Range(minimum: 18, maximum: 1000, ErrorMessage = "You have to be between 18 and 1000 years old")]
public int Age { get; set; }
[Required]
public string[] Consent { get; set; }
public bool ShouldCauseServerError => SimulateServerError != null && SimulateServerError.Contains("yes");
public string[] SimulateServerError { get; set; }
}
}<file_sep>/problems/LeetCode/206.Reverse-Linked-List/ListNode.cs
using System;
namespace _206.Reverse_Linked_List
{
public class ListNode<T>
{
public ListNode(T val, ListNode<T> next = null)
{
this.Value = val;
this.Next = next;
}
public T Value { get; }
public ListNode<T> Next { get; set; }
public void Insert(T value)
{
if (this.Next == null)
{
this.Next = new ListNode<T>(value);
}
else
{
this.Next.Insert(value);
}
}
public void Print()
{
var p = this;
while (p != null)
{
Console.WriteLine(p.Value);
p = p.Next;
}
}
}
}
<file_sep>/clean-controllers/CleanControllers.Web/Models/Business/Person.cs
using System.Collections.Generic;
using System.Linq;
namespace CleanControllers.Web.Models.Business
{
public class Person
{
// this constructor is obsolete; the Person class needs only properties with private setters
public Person(string firstName, string lastName, int age)
{
FirstName = firstName;
LastName = lastName;
Age = age;
}
public string FirstName { get; }
public string LastName { get; }
public int Age { get; }
public static readonly string ERROR_FIRST_NAME_LENGTH = "person.firstname.length";
public static readonly string ERROR_LAST_NAME_LENGTH = "person.lastname.length";
public static readonly string ERROR_AGE_INVALID = "person.age.invalid";
public static readonly string ERROR_CONSENT_REQUIRED = "person.consent.required";
public class Builder
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string[] Consent { get; set; }
public bool ShouldCauseServerError => SimulateServerError != null && SimulateServerError.Contains("yes");
public string[] SimulateServerError { get; set; }
public BuildResult<Person> Build()
{
var errorCodes = new List<string>();
if (string.IsNullOrEmpty(FirstName))
errorCodes.Add(ERROR_FIRST_NAME_LENGTH);
if(string.IsNullOrEmpty(LastName))
errorCodes.Add(ERROR_LAST_NAME_LENGTH);
if(Age < 18)
errorCodes.Add(ERROR_AGE_INVALID);
if(Consent == null || Consent.Contains("yes") == false)
errorCodes.Add(ERROR_CONSENT_REQUIRED);
// kinda dumb
var person = errorCodes.Any() ? null : new Person(FirstName, LastName, Age);
return new BuildResult<Person>(errorCodes.ToArray(), person);
}
}
}
}<file_sep>/problems/LeetCode/206.Reverse-Linked-List/Program.cs
namespace _206.Reverse_Linked_List
{
class Program
{
static void Main(string[] args)
{
var input = new[] {1, 2, 3, 4, 5};
var list = ListFromArray(input);
//list.Print();
var r = Reverse(list);
r.Print();
}
static ListNode<int> ListFromArray(int[] array)
{
var head = new ListNode<int>(array[0]);
for (int i = 1; i < array.Length; i++)
{
head.Insert(array[i]);
}
return head;
}
static ListNode<int> ReverseIterative(ListNode<int> head)
{
ListNode<int> prev = null;
ListNode<int> current = head;
ListNode<int> next = null;
while (current != null)
{
next = current.Next;
current.Next = prev;
prev = current;
current = next;
}
return prev;
}
// recursive
static ListNode<int> Reverse(ListNode<int> head)
{
// we should be asking the code to reverse a smaller
// and smaller list until there's only 1 element left
// and the reversed version of that is itself
if (head == null || head.Next == null)
return head;
var reversed = Reverse(head.Next);
head.Next.Next = head;
head.Next = null;
return reversed;
}
}
}
<file_sep>/clean-controllers/README.md
This project contains demo code for https://shishkov.me/article/1000012/clean-up-your-controllers-builder-pattern-for-refactoring-your-asp-net-core-app
<file_sep>/problems/LeetCode/219.Contains-Duplicate-II/Program.cs
using System;
using System.Collections.Generic;
namespace _219.Contains_Duplicate_II
{
class Program
{
static void Main(string[] args)
{
/*
* Runtime: 156 ms, faster than 18.31% of C# online submissions for Contains Duplicate II.
Memory Usage: 29.3 MB, less than 21.21% of C# online submissions for Contains Duplicate II.
*/
var input = new int[] {1, 0, 1, 1};
var k = 1;
Console.WriteLine(ContainsNearbyDuplicate(input, k));
}
static bool ContainsNearbyDuplicate(int[] nums, int k)
{
if (k == 0)
return false;
var map = new Dictionary<int, int>();
for (var i = 0; i < nums.Length; i++)
{
if (!map.ContainsKey(nums[i]))
{
map[nums[i]] = i;
continue;
}
var index = map[nums[i]];
if (Math.Abs(i - index) <= k)
return true;
map[nums[i]] = i;
}
return false;
}
}
}
| 769c2a3ae04788c289d2e138faa288bc907fb2e9 | [
"Markdown",
"C#"
] | 18 | C# | MartinShishkov/blog-demos | c2d7a632b778a1dd60ca76d22ae9e8372580a352 | 667d4a855c95a9bff6cbbc7e2a9914d251df5150 | |
refs/heads/master | <repo_name>codyzazulak1/LargestOfArray<file_sep>/C-Starter-Project/main.c
//
// main.c
// Project Name
//
// Created by <NAME>.
// All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
int array[] = {33, 74, 98, 21, 19};
int storedValue = 0;
for(int i = 0; i < sizeof(array)/sizeof(array[0]); i++) {
int currentValue = array[i];
if (currentValue > storedValue) {
storedValue = currentValue;
}
}
printf("%d\n", storedValue);
return 0;
}
| 89e70af9dbcad0485861826c81ae1f1c770f509b | [
"C"
] | 1 | C | codyzazulak1/LargestOfArray | 478daad99af74ede3d7551d161e3a6289c8b7fc9 | 76e0599a04d823fb4773bec02c67403882378895 | |
refs/heads/master | <repo_name>rahulshanwal/metal-trade<file_sep>/refdataServices/models/Commodity.js
const mongoose = require('mongoose');
const CommoditySchema = new mongoose.Schema({
value: String,
primaryText: String
});
module.exports = mongoose.model("Commodity", CommoditySchema);<file_sep>/refdataServices/router.js
const express = require('express');
const router = express.Router();
const CounterParty = require('./models/CounterParty');
const Commodity = require('./models/Commodity');
const Location = require('./models/Location');
const Side = require('./models/Side');
router.get("/", function(req, res) {
res.json({
status: "My Ref Data API is alive!"
});
});
router.get('/getRefData', function(req, res){
let refData = {};
//TODO - refactor below callback hell
Commodity.find({}, (err1, commodities) => {
if(err1){
refData.commodity = [];
}else{
refData.commodity = commodities;
}
Location.find({}, (err2, locations) => {
if(err2){
refData.location = [];
}else{
refData.location = locations;
}
CounterParty.find({}, (err3, counterParties)=> {
if(err3){
refData.counterParty = [];
}else{
refData.counterParty = counterParties;
}
Side.find({}, (err4, sides) => {
if(err4){
refData.side = [];
}else{
refData.side = sides;
}
res.json({refData: refData});
});
})
});
});
});
module.exports = router;<file_sep>/metallica-backend/auth.js
var passport = require("passport");
var passportJWT = require("passport-jwt");
var cfg = require("./config.js");
var ExtractJwt = passportJWT.ExtractJwt;
var Strategy = passportJWT.Strategy;
var params = {
secretOrKey: cfg.jwtSecret,
jwtFromRequest: ExtractJwt.fromUrlQueryParameter('auth_token')
};
var User = require('./models/User');
module.exports = function() {
var strategy = new Strategy(params, function(payload, done) {
User.findById(payload.id, (err, user) => {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
});
passport.use(strategy);
return {
initialize: function() {
return passport.initialize();
},
authenticate: function() {
return passport.authenticate("jwt", cfg.jwtSession);
}
};
};<file_sep>/UI/src/components/UI/Username/Username.js
import React from 'react';
import classes from './Username.css';
import Aux from '../../../hoc/Auxiliary/Auxiliary';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import ContentAdd from 'material-ui/svg-icons/social/person';
import {Link} from 'react-router-dom';
import FlatButton from 'material-ui/FlatButton';
const style = {
height: 56,
marginLeft: 10,
marginRight: 20,
marginTop: 3
};
const logoutButtonStyle = {
color: 'white',
margin: 'auto'
};
const UserName = (props) => {
return (
<Aux>
<div className={classes.username}>{props.children}</div>
<FlatButton label="Logout" style={logoutButtonStyle}>
<Link to='/logout' className={classes.Logout}></Link>
</FlatButton>
<FloatingActionButton style={style}>
<ContentAdd />
</FloatingActionButton>
</Aux>);
}
export default UserName;<file_sep>/UI/src/components/UI/ConfirmationDialog/ConfirmationDialog.js
import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
const ConfirmationDialog = (props) => {
const actions = [
<FlatButton
label="No"
primary={true}
onClick={props.handleCancelClick}
/>,
<FlatButton
label="YES"
primary={true}
onClick={props.handleSubmitClick}
/>,
];
return (
<div>
<Dialog
title={props.title}
actions={actions}
modal={true}
open={props.open}>
{props.text}
</Dialog>
</div>
);
}
export default ConfirmationDialog;<file_sep>/UI/src/containers/Trade/TradeHeader/RightElements.js
import React from 'react';
import ActionDelete from 'material-ui/svg-icons/action/delete';
import ActionEdit from 'material-ui/svg-icons/editor/mode-edit';
import Aux from '../../../hoc/Auxiliary/Auxiliary';
const style = {color: 'white', cursor: 'pointer'};
const rightElements = (props) => (<Aux>
<ActionEdit style={style} onClick={()=> props.changeEditMode(true)}/>
<ActionDelete style={style} onClick={()=> props.onDelete()}/>
</Aux>);
rightElements.muiName = 'IconMenu';
export default rightElements;<file_sep>/README.md
This project is built as a part of the Full Stack Program for the Metallica assignment.
The running app can be checked at the below location :
[Metallica - metal trading](https://shielded-bayou-75551.herokuapp.com/)
## Table of Contents
- [Folder Structure](#folder-structure)
- [High level Architecture](#high-level-architecture)
- [Technology Stack](#technology-stack)
## Folder Structure
**UI**: Contains the UI side project build on React/redux
- 'src' - src folder containes the source for all the js/html/css files
- 'components' - contains the custom stateless components used in the app.
- 'conatainers' - contains the custom containers holding some state used in the app.
- 'hoc' - higher order components
- 'Store' - the Redux store - holding actions and reducers acting as models for the app
**metallica-backend**: Contains the backend side code build using node. API gateway/proxy and authentication is handled here
**tradeServices**: microservice for the trade actions. To change add/edit/delete trades.
**refdataServices**: microservice to handle the static data for counterparty, location, side and commodity.
**marketDataServices**: microservice to feed the market data for different metals. here I have kept the data in a js file and changing it every 10 seconds to feed to the tickr.
**notificationServices**: microservice to consume all the message from amqp queues and send notification to UI via websockets.
## High Level Architecture
All the requests from the frontend are routed through the API gateway, the authentication happens here and then the calls are routed to the appropriate microservices. These microservices then publishes the event on the message broker which are then picked up by the notification services to be fed to the frontend via the websockets.
Each microservices has its own db
## Technology Stack
**Front End**
- ES6
- React
- Redux
- Material UI
**API Gateway**
- http-proxy-middleware (node module)
**Authentication**
- passport (node module)
- passport-jwt (node module)
**Microservices**
- Node.js
**Messaging Infrastructure**
- amqplib (node module for rabitmq)
**Streaming**
- socket.io (websockets)
**Database**
- MongoDB
<file_sep>/UI/src/containers/TradeContainer/TradeContainer.js
import React, {Component} from 'react';
import { connect } from 'react-redux';
import {Link} from 'react-router-dom';
import classes from './TradeContainer.css';
import TradesList from '../TradesList/TradesList';
import Trade from '../Trade/Trade';
import * as TradeActions from '../../Store/action/tradeActions';
import ConfirmationDialog from '../../components/UI/ConfirmationDialog/ConfirmationDialog';
import Loader from '../../components/UI/Loader/Loader';
class TradeContainer extends Component {
render () {
let tradeContainer = (<div className={classes.Container}>
<TradesList/>
<Trade/>
<ConfirmationDialog title={'Delete Trade'}
text={'Are you sure you want delete this trade ?'}
open={this.props.isConfirmationDialogOpen}
handleSubmitClick={()=>{this.props.deleteSelectedTrade(this.props.selectedTrade, this.props.authToken)}}
handleCancelClick={()=>{this.props.toggleDeleteTradeDialog(false)}}/>
<Loader show={this.props.isLoading}/>
</div>);
if(!this.props.isAuthenticated) {
tradeContainer = <div className={classes.UnAuthenticContainer}>
<span>You need to login to trade in metals. To login or register </span>
<Link to='/'>Click here</Link>
</div>
}
return (tradeContainer);
}
}
const mapStateToProps = state => {
return {
isConfirmationDialogOpen: state.tradeReducer.showDeleteDialog,
isLoading: state.tradeReducer.loading,
isAuthenticated: state.auth.token !== null,
authToken: state.auth.token,
selectedTrade: state.tradeReducer.selectedTrade
}
};
const mapDispatchToProps = dispatch => {
return {
toggleDeleteTradeDialog: (open) => dispatch(TradeActions.toggleDeleteTrade(open)),
deleteSelectedTrade: (tradeData, authToken) => dispatch(TradeActions.deleteSelectedTrade(tradeData, authToken)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(TradeContainer);<file_sep>/tradeServices/models/Trade.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const autoIncrement = require('mongoose-auto-increment');
let TradeSchema = new Schema({
tradeDate: String,
price: String,
quantity: Number,
side: String,
userId: String,
commodity: String,
counterParty: String,
location: String
});
autoIncrement.initialize(mongoose.connection);
TradeSchema.plugin(autoIncrement.plugin, 'Trade')
// Export the model
module.exports = mongoose.model('Trade', TradeSchema);<file_sep>/marketDataServices/prices.js
module.exports = [
{
name: "Aluminium",
price: 100
},
{
name: "Zinc",
price: 10
},
{
name: "Copper",
price: 25
},
{
name: "Gold",
price: 200
},
{
name: "Silver",
price: 14
},
{
name: "Platinum",
price: 389
},
{
name: "Titanium",
price: 257
},
{
name: "Magnesium",
price: 146
},
{
name: "Tin",
price: 23
},
{
name: "Bismuth",
price: 129
},
{
name: "Nickel",
price: 68
},
{
name: "Cobalt",
price: 37
},
];<file_sep>/UI/src/containers/Auth/Auth.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import Input from '../../components/UI/InputFields/InputFields';
import RaisedButton from 'material-ui/RaisedButton';
import Loader from '../../components/UI/Loader/Loader';
import classes from './Auth.css';
import * as AuthActions from '../../Store/action/authActions';
class Auth extends Component {
state = {
controls: {
email: {
elementType: 'input',
elementConfig: {
type: 'email',
hintText: 'Mail Address'
},
value: '',
validation: {
required: true,
isEmail: true
},
valid: false,
touched: false
},
password: {
elementType: 'input',
elementConfig: {
type: 'password',
hintText: '<PASSWORD>'
},
value: '',
validation: {
required: true,
minLength: 6
},
valid: false,
touched: false
}
},
formIsValid: false,
isSignup: false
}
checkValidity ( value, rules ) {
let isValid = true;
if ( !rules ) {
return true;
}
if ( rules.required ) {
isValid = value.trim() !== '' && isValid;
}
if ( rules.minLength ) {
isValid = value.length >= rules.minLength && isValid
}
if ( rules.maxLength ) {
isValid = value.length <= rules.maxLength && isValid
}
if ( rules.isEmail ) {
const pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
isValid = pattern.test( value ) && isValid
}
if ( rules.isNumeric ) {
const pattern = /^[0-9]*[.][0-9]+$/;
isValid = pattern.test( value ) && isValid
}
return isValid;
}
inputChangedHandler = ( event, controlName ) => {
const updatedControls = {
...this.state.controls,
[controlName]: {
...this.state.controls[controlName],
value: event.target.value,
valid: this.checkValidity( event.target.value, this.state.controls[controlName].validation ),
touched: true
}
};
let formIsValid = true;
for (let identifier in updatedControls) {
formIsValid = updatedControls[identifier].valid && formIsValid;
if(!updatedControls[identifier].valid && updatedControls[identifier].touched) {
updatedControls[identifier].elementConfig.errorText = 'Invalid value';
}else{
updatedControls[identifier].elementConfig.errorText = null;
}
}
this.setState( { controls: updatedControls, formIsValid: formIsValid } );
}
submitHandler = ( event ) => {
event.preventDefault();
this.props.onAuth( this.state.controls.email.value, this.state.controls.password.value, this.state.isSignup );
}
switchAuthModeHandler = () => {
this.setState(prevState => {
return {isSignup: !prevState.isSignup};
});
}
render () {
const formElementsArray = [];
for ( let key in this.state.controls ) {
formElementsArray.push( {
id: key,
config: this.state.controls[key]
} );
}
let form = formElementsArray.map( formElement => (
<Input
key={formElement.id}
elementType={formElement.config.elementType}
elementConfig={formElement.config.elementConfig}
value={formElement.config.value}
invalid={!formElement.config.valid}
shouldValidate={formElement.config.validation}
touched={formElement.config.touched}
changed={( event ) => this.inputChangedHandler( event, formElement.id )} />
) );
if (this.props.loading) {
form = <Loader show={true}/>
}
let errorMessage = null;
if (this.props.error) {
errorMessage = (
<p className={classes.ErrorMessage}>{this.props.error.message}</p>
);
}
let authRedirect = null;
if (this.props.isAuthenticated) {
authRedirect = <Redirect to={this.props.authRedirectPath}/>
}
let switchLabel = `SWITCH TO ${this.state.isSignup ? 'SIGNIN' : 'REGISTER'}`;
let submitLabel = this.state.isSignup ? 'REGISTER' : 'SIGN IN';
const style = {
margin: 5,
width: 200
};
return (
<div className={classes.Auth}>
{authRedirect}
{errorMessage}
<form onSubmit={this.submitHandler}>
{form}
<RaisedButton type={'submit'} primary={true} label={submitLabel}
style={style} disabled={!this.state.formIsValid}/>
</form>
<RaisedButton
onClick={this.switchAuthModeHandler} style={style}
label={switchLabel} secondary={true}/>
</div>
);
}
}
const mapStateToProps = state => {
return {
loading: state.auth.loading,
error: state.auth.error,
isAuthenticated: state.auth.token !== null,
authRedirectPath: state.auth.authRedirectPath
};
};
const mapDispatchToProps = dispatch => {
return {
onAuth: ( email, password, isSignup ) => dispatch( AuthActions.auth( email, password, isSignup ) ),
onSetAuthRedirectPath: () => dispatch(AuthActions.setAuthRedirectPath('/trades'))
};
};
export default connect( mapStateToProps, mapDispatchToProps )( Auth );<file_sep>/tradeServices/amqp-connect.js
const amqp = require('amqplib/callback_api');
let channel, rabbitmqurl = process.env.AMQPURL || 'amqp://localhost';
amqp.connect(rabbitmqurl, function(err, conn) {
if (err) {
console.log("[AMQP] error --> "+err.message);
return;
}
conn.on("error", function(err) {
console.log("[AMQP] error --> " + err.message);
return;
});
conn.createChannel(function(err, ch) {
if(err) {
console.log('Not able to create channel');
}
ch.assertQueue('tradeupdate', {durable: true}); //create queue
channel = ch;
});
conn.on("close", function() {
console.log("[AMQP] close");
return setTimeout(function() { conn.close(); process.exit(0) }, 500);
});
});
module.exports = {
sendDataToQueue : (alltrades) => {
if(channel) {
channel.sendToQueue('tradeupdate', Buffer.from(JSON.stringify(alltrades))); //send alltrades on the queue
}
}
};<file_sep>/UI/src/components/UI/Loader/Loader.js
import React from 'react';
import CircularProgress from 'material-ui/CircularProgress';
import Backdrop from '../Backdrop/Backdrop';
const style = {
position: 'fixed',
top: '45vh',
left: '45vw'
}
const Loader = (props) => {
let loader = props.show ? <Backdrop show={props.show}><CircularProgress style={style} size={80} thickness={5}/></Backdrop> : null
return loader;
}
export default Loader;<file_sep>/UI/src/components/UI/AddButton/AddButton.js
import React from 'react';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import ContentAdd from 'material-ui/svg-icons/content/add';
const style = {
position: 'absolute',
right: 2,
top: 2
}
const AddButton = (props) => {
return (
<FloatingActionButton style={style} onClick={()=> props.clicked()}>
<ContentAdd />
</FloatingActionButton>
);
}
export default AddButton;<file_sep>/UI/src/__test__/TradeList.spec.js
import React from 'react';
import {configure, shallow} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import {Table} from 'material-ui/Table';
import {TradeList} from '../containers/TradesList/TradesList';
configure({adapter: new Adapter()});
describe('TradesList component', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<TradeList tabledata={[]} fetchTrades={()=>{}}/>);
});
it('should not render the table if there is an error property set', () => {
wrapper.setProps({error: 'not able to fetch data'});
expect(wrapper.find(Table)).toHaveLength(0);
});
it('should not render the table if no data is present', () => {
expect(wrapper.find(Table)).toHaveLength(0);
});
it('should render the table if data is present', () => {
let data = {"_id":12,"tradeDate":"2018-1-29","commodity":"Bi","side":"sell","counterParty":"Ipsum","price":"62","quantity":19,"location":"tky"};
wrapper.setProps({tabledata: [data], refData: {commodity:[],side:[],counterParty:[],location:[]}});
expect(wrapper.find(Table)).toHaveLength(1);
});
});<file_sep>/UI/src/containers/Home/Home.js
import React, {Component} from 'react';
import { connect } from 'react-redux';
import Header from '../../components/Header/Header';
import TradesContainer from '../TradeContainer/TradeContainer';
import Aux from '../../hoc/Auxiliary/Auxiliary';
import Ticker from '../../components/UI/Ticker/Ticker';
import * as TradeActions from '../../Store/action/tradeActions';
import socketIOClient from 'socket.io-client';
const config = require('Config');
const webSocketConnectionEndpoint = config.websocketUrl;
let socket;
class Home extends Component {
state = {
tickerData: null
}
componentDidMount() {
socket = socketIOClient(webSocketConnectionEndpoint);
socket.on("metalPrices", data => this.setState({ tickerData: data }));
socket.on("tradeUpdate", data => this.props.updateTrades(data));
}
componentWillUnmount() {
socket.disconnect();
}
render () {
return (
<Aux>
<Ticker data={this.state.tickerData}/>
<Header/>
<TradesContainer/>
</Aux>
);
}
}
const mapDispatchToProps = dispatch => {
return {
updateTrades: (trades) => dispatch(TradeActions.fetchTradeSuccess(trades))
};
};
export default connect(null, mapDispatchToProps)(Home)<file_sep>/UI/src/containers/Trade/TradeHeader/TradeHeader.js
import React from 'react';
import AppBar from 'material-ui/AppBar';
import RightElements from './RightElements';
const style = {
color: 'white',
height: '35px',
paddingLeft: '5px'
}
const titleStyle = {
fontSize: 16,
lineHeight: '35px'
}
/**
* A simple example of `AppBar` with an icon on the right.
* By default, the left icon is a navigation-menu.
*/
const TradeHeader = (props) => (
<AppBar
title= {`Trade ID : ${props.tradeId}`}
showMenuIconButton={false}
style= {style}
titleStyle = {titleStyle}
iconElementRight={<RightElements onDelete={props.onDelete} changeEditMode={props.changeEditMode}/>}>
</AppBar>
);
export default TradeHeader;<file_sep>/metallica-backend/routes.js
var express = require('express');
var router = express.Router();
var User = require('./models/User');
var cfg = require("./config");
var jwt = require("jwt-simple");
// Register new users
router.post('/register', function(req, res) {
if (!req.body.email || !req.body.password || req.body.password.length < 6) {
res.status(401).send({message: 'Email or password not valid'});
} else {
let newUser = new User({
email: req.body.email,
password: req.body.password
});
// Attempt to save the user
newUser.save(function(err, user) {
if (err) {
res.status(401).send({message: 'Email address already exists.'});
}
let token = jwt.encode({id: user.id}, cfg.jwtSecret);
res.json({
token: token,
expiresIn: 3600,
userId: user.id
});
});
}
});
router.get('/', function(req, res) {
res.json('Auth service is up');
});
// Authenticate the user and get a JSON Web Token to include in the header of future requests.
router.post('/login', (req, res) => {
User.findOne({
email: req.body.email
}, function(err, user) {
if (err) throw err;
if (!user) {
res.status(401).send({message: 'User not found.'});
} else {
// Check if password matches
user.comparePassword(req.body.password, function(err, isMatch) {
if (isMatch && !err) {
console.log('user id ------------------> '+user.id);
// Create token if the password matched and no error was thrown
let token = jwt.encode({id: user.id}, cfg.jwtSecret);
res.json({
token: token,
userId: user.id,
expiresIn: 3600
});
}
else {
res.status(401).send({message: 'Authentication failed. Passwords did not match.'});
}
});
}
});
});
module.exports = router;<file_sep>/UI/src/Store/action/tradeActions.js
import * as actionTypes from './actionTypes';
import axios from '../../axios-instance';
//start updating a trade
export const updateTradeStart = () => {
return {
type: actionTypes.UPADTE_TRADE
};
};
//add or edit trade success
export const updateTradeSuccess = (trades) => {
return {
type: actionTypes.UPDATE_TRADE_SUCCESS,
trades: trades
};
};
//update trade failure
export const updateTradeFailure = (err) => {
return {
type: actionTypes.UPDATE_TRADE_FAILURE,
error: err.message
};
};
//update trade when edit/added by clicking on the save button
export const updateTrade = (tradeData, authToken, userId) => {
return dispatch => {
dispatch(updateTradeStart());
tradeData.userId = userId;
tradeData.tradeDate = `${tradeData.tradeDate.getFullYear()}-${tradeData.tradeDate.getMonth() + 1}-${tradeData.tradeDate.getDate()}`;
let tradePromise;
if(typeof tradeData._id !== 'undefined' && tradeData._id !== null) {
tradePromise = axios.put('/trade?auth_token='+authToken, {trade: tradeData});
}
else {
tradePromise = axios.post('/trade?auth_token='+authToken, {trade: tradeData});
}
tradePromise.then(response => {
dispatch(updateTradeSuccess(response.data.trades));
}).catch(err => {
dispatch(updateTradeFailure(err));
});
}
}
//update selected trade property of the model when a row is selected from the list
export const updateSelectedTrade = (tradeData, auth_token) => {
return dispatch => {
dispatch({type: actionTypes.UPADTE_SELECTED_TRADE, tradeData:tradeData});
}
}
//delete selected trade by clicking the delete butotn from list or trade container
export const deleteSelectedTrade = (tradeData, authToken) => {
return dispatch => {
dispatch(updateTradeStart());
if(tradeData._id !== 'undefined' && tradeData._id !== null){
axios.delete('/trade?auth_token='+authToken, {headers: { 'Content-Type': 'application/json'}, data:{id: tradeData._id, userId: tradeData.userId}})
.then(response => {
dispatch({type: actionTypes.DELETE_SELECTED_TRADE, trades: response.data.trades});
}).catch(err => {
dispatch(updateTradeFailure(err));
});
}
}
}
//open or close the delete confirmation dialog
export const toggleDeleteTrade = (open) => {
return dispatch => {
dispatch({type: actionTypes.SHOW_DELETE_TRADE, open: open});
}
}
//start fetching trades
export const fetchTradeStart = () => {
return {
type: actionTypes.FETCH_TRADE_START
};
};
//get All trades success
export const fetchTradeSuccess = (trades) => {
return {
type: actionTypes.FETCH_TRADE_SUCCESS,
trades: trades
};
};
//get All trades failure
export const fetchTradeFailure = (err) => {
return {
type: actionTypes.FETCH_TRADE_FAILURE,
error: err.message
};
};
//fetch all trades for the user
export const fetchTrades = (authToken, userId) => {
return dispatch => {
dispatch(fetchTradeStart());
axios.get('/trades?auth_token='+authToken+'&userId='+userId)
.then(response => {
dispatch(fetchTradeSuccess());
}).catch(err => {
dispatch(fetchTradeFailure(err));
})
}
}
//start fetching ref data
export const fetchTradeRefDataStart = () => {
return {
type: actionTypes.FETCH_TRADE_REF_DATA_START
};
};
//get metadata success
export const fetchTradeRefDataSuccess = (refData) => {
return {
type: actionTypes.FETCH_TRADE_REF_DATA_SUCCESS,
refData: refData
};
};
//get metadata failure
export const fetchTradeRefDataFailure = () => {
return {
type: actionTypes.FETCH_TRADE_REF_DATA_FAILURE
};
};
//fetch metadata for location, counter party and side
export const getTradeRefData = () => {
return dispatch => {
dispatch(fetchTradeRefDataStart());
axios.get('/getRefData')
.then(response => {
dispatch(fetchTradeRefDataSuccess(response.data.refData));
}).catch(err => {
dispatch(fetchTradeRefDataFailure(err));
})
}
}
//update all trades from websocket connection
export const updateAlltrades = (trades) => {
return dispatch => {
dispatch(fetchTradeSuccess(trades));
}
}<file_sep>/tradeServices/routes.js
const express = require('express');
const amqp = require('./amqp-connect');
const router = express.Router();
const Trade = require('./models/Trade');
router.get("/", function(req, res) {
res.json({
status: "My Trade API is alive!"
});
});
const getAllTrades = (req, res, uid) => {
Trade.find({userId: uid}, function(err, allTrades){
if(err) {
res.status(500).send(new Error('Not able to fetch all trades'));
}
amqp.sendDataToQueue(allTrades);
res.send({message: 'Trade updated successfully'});
});
};
router.get("/trades", function(req, res) {
getAllTrades(req, res, req.query.userId);
});
router.post('/trade', function(req, res){
Trade.create(req.body.trade, function(err, savedTrade){
if(err){
res.status(500).send(new Error('Not able to save the trade'));
}
getAllTrades(req, res, req.body.trade.userId);
});
});
router.put('/trade', function(req, res){
Trade.findByIdAndUpdate(req.body.trade._id, req.body.trade, function(err, savedTrade){
if(err){
res.status(500).send(new Error('Not able to save the trade'));
}
getAllTrades(req, res, req.body.trade.userId);
});
});
router.delete('/trade', function(req, res){
Trade.findByIdAndRemove(req.body.id, function(err, savedTrade){
if(err){
res.status(500).send(new Error('Not able to save the trade'));
}
getAllTrades(req, res, req.body.userId);
});
});
module.exports = router;<file_sep>/UI/src/components/Header/Header.js
import React from 'react';
import AppBar from 'material-ui/AppBar';
import UserName from '../UI/Username/Username'
/**
* A simple example of `AppBar` with an icon on the right.
* By default, the left icon is a navigation-menu.
*/
const Header = () => (
<AppBar
style={{marginTop: 30}}
title="TRADES"
showMenuIconButton={false}>
<UserName />
</AppBar>
);
export default Header;<file_sep>/UI/src/__test__/TradeReducer.spec.js
import TradeReducer from '../Store/reducers/trades';
import * as ActionTypes from '../Store/action/actionTypes';
describe('Trade reducer', () => {
let initialState = {
trades : [],
refData: {
counterParty: [],
location: [],
side: [],
commodity: []
},
error: null,
loading: false,
selectedTrade: null,
showDeleteDialog: false
};
it('should return the initial state', () => {
expect(TradeReducer(undefined, {})).toEqual(initialState);
});
it('should return the ref data on the success event type', () => {
expect(TradeReducer(initialState, {
type: ActionTypes.FETCH_TRADE_REF_DATA_SUCCESS,
refData: {counterParty:'lorem'}
})).toEqual({
trades : [],
refData: {counterParty:'lorem'},
error: null,
loading: false,
selectedTrade: null,
showDeleteDialog: false
})
});
});<file_sep>/tradeServices/server.js
var express = require("express"),
bodyParser = require("body-parser"),
app = express(),
routes = require('./routes'),
mongoose = require("mongoose");
mongoose.connect(process.env.TRADEDATABASEURL || 'mongodb://localhost/tradesdb');
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use('/', routes);
app.listen(process.env.PORT || 3002, function(){
console.log('Trade service has started');
});
module.exports = app; <file_sep>/UI/src/__test__/Ticker.spec.js
import React from 'react';
import {configure, shallow} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Ticker from '../components/UI/Ticker/Ticker';
configure({adapter: new Adapter()});
describe('Ticker component', () => {
it('should have one span element for each metal', () => {
const metals = [
{
name: "Aluminium",
price: 100
},
{
name: "Zinc",
price: 10
},
{
name: "Copper",
price: 25
},
{
name: "Gold",
price: 200
},
{
name: "Silver",
price: 14
}
];
const wrapper = shallow(<Ticker data={metals}/>);
expect(wrapper.find('span')).toHaveLength(5);
});
});<file_sep>/UI/src/containers/TradesList/TradesList.js
import React, {Component} from 'react';
import { connect } from 'react-redux';
import IconButton from 'material-ui/IconButton';
import ActionDelete from 'material-ui/svg-icons/action/delete';
import AddButton from '../../components/UI/AddButton/AddButton';
import classes from './TradesList.css';
import * as TradeActions from '../../Store/action/tradeActions';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'material-ui/Table';
const findNameFromRefData = (arr, val, prop) => {
const matchedObj = arr.find( obj => obj.value === val);
return matchedObj && matchedObj[prop] ? matchedObj[prop] : null;
}
export class TradeList extends Component {
//row selection handler
handleRowSelection = (selectedRowIndex) => {
this.props.updateSelectedTrade(this.props.tabledata[selectedRowIndex]);
this.props.tabledata.forEach((row, i) => { //TODO - anti- pattern - look into it later
row.selected = selectedRowIndex.indexOf(i) > -1;
});
}
//delete button handler
handleDeleteButton = event => {
event.stopPropagation();
if(this.props.selectedTrade){
this.props.showDeleteDialog(true);
}
}
//life cycle method
componentDidMount() {
this.props.fetchTrades(this.props.authToken, this.props.userId);
}
// life cycle method
render(){
let table, deleteButtonStyle = {
opacity : 1
},
deleteButtonHidden = {
opacity : 0.1
};
if(this.props.error) {
table = <div className={classes.TradeListParentError}>{this.props.error}</div>
}
else if(this.props.tabledata.length > 0) {
table = <Table
fixedHeader={true}
selectable={true}
multiSelectable={false}
onRowSelection={this.handleRowSelection}>
<TableHeader displaySelectAll={false} adjustForCheckbox={false}>
<TableRow>
<TableHeaderColumn>Trade Date</TableHeaderColumn>
<TableHeaderColumn>Commodity</TableHeaderColumn>
<TableHeaderColumn>Side</TableHeaderColumn>
<TableHeaderColumn>QTY(MT)</TableHeaderColumn>
<TableHeaderColumn>Price(/MT)</TableHeaderColumn>
<TableHeaderColumn>CounterParty</TableHeaderColumn>
<TableHeaderColumn>Location</TableHeaderColumn>
<TableHeaderColumn></TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody
displayRowCheckbox={false}
deselectOnClickaway={false}
showRowHover={true}
stripedRows={true}
>
{this.props.tabledata.map( (row, index) => (
<TableRow key={index}>
<TableRowColumn>{row.tradeDate}</TableRowColumn>
<TableRowColumn>{findNameFromRefData(this.props.refData['commodity'], row.commodity, 'primaryText')}</TableRowColumn>
<TableRowColumn>{findNameFromRefData(this.props.refData['side'], row.side, 'label')}</TableRowColumn>
<TableRowColumn>{row.quantity}</TableRowColumn>
<TableRowColumn>{row.price}</TableRowColumn>
<TableRowColumn>{findNameFromRefData(this.props.refData['counterParty'], row.counterParty, 'primaryText')}</TableRowColumn>
<TableRowColumn>{findNameFromRefData(this.props.refData['location'], row.location, 'primaryText')}</TableRowColumn>
<TableRowColumn>
<IconButton style={row.selected ? deleteButtonStyle : deleteButtonHidden}>
<ActionDelete onClick={this.handleDeleteButton}/>
</IconButton>
</TableRowColumn>
</TableRow>
))}
</TableBody>
</Table>
} else if(this.props.tabledata.length === 0){
table = <div className={classes.TradeListParentError}>No trade data found. Add new trades</div>
}
return (<div className={classes.TradeListParent}>
{table}
<AddButton className={classes.AddButton} clicked={()=>{this.props.updateSelectedTrade(undefined)}}/>
</div>);
}
}
const mapStateToProps = state => {
return {
tabledata: state.tradeReducer.trades,
authToken: state.auth.token,
error: state.tradeReducer.error,
refData: state.tradeReducer.refData,
selectedTrade: state.tradeReducer.selectedTrade,
userId: state.auth.userId
}
};
const mapDispatchToProps = dispatch => {
return {
updateSelectedTrade: (tradeData) => dispatch(TradeActions.updateSelectedTrade(tradeData)),
showDeleteDialog: (open) => dispatch(TradeActions.toggleDeleteTrade(open)),
fetchTrades: (token, userId) => dispatch(TradeActions.fetchTrades(token, userId))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(TradeList);<file_sep>/UI/src/__test__/InputFields.spec.js
import React from 'react';
import {configure, shallow} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import TextField from 'material-ui/TextField';
import SelectField from 'material-ui/SelectField';
import {RadioButtonGroup} from 'material-ui/RadioButton';
import DatePicker from 'material-ui/DatePicker';
import Input from '../components/UI/InputFields/InputFields';
configure({adapter: new Adapter()});
describe('InputField component', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<Input/>);
});
it('should have one text field for the element of type text', () => {
wrapper.setProps({
elementType:'input',
invalid:'false',
changed: () => {}
});
expect(wrapper.find(TextField)).toHaveLength(1);
});
it('should have one date picker field for the element of type date', () => {
wrapper.setProps({
elementType:'date',
invalid:'false',
changed: () => {}
});
expect(wrapper.find(DatePicker)).toHaveLength(1);
});
it('should have one select field for the element of type select', () => {
wrapper.setProps({
elementType:'select',
invalid:'false',
changed: () => {}
});
expect(wrapper.find(SelectField)).toHaveLength(1);
});
it('should have a radio group for the element of type radiogroup', () => {
wrapper.setProps({
elementType:'radiogroup',
invalid:'false',
elementConfig: {name: 'side'},
changed: () => {}
});
expect(wrapper.find(RadioButtonGroup)).toHaveLength(1);
});
});<file_sep>/UI/src/components/UI/Ticker/Ticker.js
import React from 'react';
import classes from './Ticker.css';
const Ticker = (props) => {
let metals = null;
if(props.data){
metals = props.data.map((metal, index) => (
<span className={classes.TickerText} key={metal.name+index}>{metal.name + ' : '+ metal.price}</span>
));
}
return (
<div className={classes.TickerParent}>
<div className={classes.Ticker + ' Ticker'}>
<div className={classes.TickerAnimation}>
{metals}
</div>
</div>
</div>
)
}
export default Ticker;<file_sep>/UI/src/containers/Trade/Trade.js
import React, {Component} from 'react';
import { connect } from 'react-redux';
import TradeHeader from './TradeHeader/TradeHeader';
import classes from './Trade.css';
import Input from '../../components/UI/InputFields/InputFields';
import * as TradeActions from '../../Store/action/tradeActions';
import RaisedButton from 'material-ui/RaisedButton';
class Trade extends Component {
state = {
tradeForm: {
tradeDate: {
elementType: 'date',
elementConfig: {
hintText: 'Trade date'
},
value: '',
validation: {
required: true
},
valid: false,
touched: false
},
commodity: {
elementType: 'select',
elementConfig: {
hintText: 'Commodity'
},
value: '',
validation: {
required: true
},
childConfig: [],
valid: false,
touched: false
},
side: {
elementType: 'radiogroup',
elementConfig: {
name: 'side'
},
childConfig: [{
value: 'Buy',
label: 'BUY'
},
{
value: 'Sell',
label: 'SELL'
}],
value: 'Buy',
valid: true,
touched: false
},
counterParty: {
elementType: 'select',
elementConfig: {
hintText: 'Counter Party'
},
childConfig:[],
value: '',
validation: {
required: true
},
valid: false,
touched: false
},
price: {
elementType: 'input',
elementConfig: {
hintText: 'Price',
id: 'priceInput',
errorText : null
},
value: '',
validation: {
required: true,
isNumeric: true
},
valid: false,
touched: false
},
quantity: {
elementType: 'input',
elementConfig: {
hintText: 'Quantity',
id: 'qtyInput',
errorText : null
},
value: '',
validation: {
required: true,
isNumeric: true
},
valid: false,
touched: false
},
location: {
elementType: 'select',
elementConfig: {
hintText: 'Location'
},
childConfig:[],
value: '',
validation: {
required: true
},
valid: false,
touched: false
}
},
formIsValid: false,
isAddEditMode: false
}
//utiity method to check of the trade values entered are valid. Should be moved to a separate utilities file
checkValidity(value, rules) {
let isValid = true;
if (!rules) {
return true;
}
if (rules.required) {
isValid = typeof value !== 'object' ? value.trim() !== '' && isValid : true;
}
if (rules.minLength) {
isValid = value.length >= rules.minLength && isValid
}
if (rules.maxLength) {
isValid = value.length <= rules.maxLength && isValid
}
if (rules.isEmail) {
const pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
isValid = pattern.test(value) && isValid
}
if (rules.isNumeric) {
const pattern = /^\d*[.]?[0-9]+$/;
isValid = pattern.test(value) && isValid
}
return isValid;
}
//submit click handler
submitHandler = ( event ) => {
event.preventDefault();
const formData = {};
for (let formElementIdentifier in this.state.tradeForm) {
formData[formElementIdentifier] = this.state.tradeForm[formElementIdentifier].value;
}
formData._id = this.props.tradeData ? this.props.tradeData._id : null;
this.props.updateTrade(formData, this.props.authToken, this.props.userId);
}
//cancel click handler, switch to old data and make the fields non-editable
cancelHandler = (event) => {
this.syncUpdatedStatefromProps();
this.updateAddEditMode(false);
}
//method to handle all the input changes for a trade
inputChangedHandler = (value, selectValue, inputIdentifier) => {
const updatedTradeForm = {
...this.state.tradeForm
};
const updatedFormElement = {
...updatedTradeForm[inputIdentifier]
};
updatedFormElement.value = selectValue ? selectValue : value;
updatedFormElement.valid = this.checkValidity(updatedFormElement.value, updatedFormElement.validation);
updatedFormElement.touched = true;
updatedTradeForm[inputIdentifier] = updatedFormElement;
let formIsValid = true;
for (let identifier in updatedTradeForm) {
formIsValid = updatedTradeForm[identifier].valid && formIsValid;
if(!updatedTradeForm[identifier].valid && updatedTradeForm[identifier].touched) {
updatedTradeForm[identifier].elementConfig.errorText = 'This is a required numeric field';
}else{
updatedTradeForm[identifier].elementConfig.errorText = null;
}
}
this.setState({tradeForm: updatedTradeForm, formIsValid: formIsValid});
}
//utility method to switch the add-edit / non-editable mode
updateAddEditMode = (val) => {
this.setState({isAddEditMode: val});
}
//dispatch the delete action from here, to be handled by the model/trade reducer
handleDeleteAction = () => {
if(this.props.tradeData){
this.props.showDeleteDialog(true);
}
}
//life cycle method
componentWillMount() {
this.syncUpdatedStatefromProps();
}
//life cycle method
componentWillReceiveProps(nextProps) {
this.syncUpdatedStatefromProps(nextProps);
this.addRefData(nextProps)
}
//life cycle method
componentDidMount() {
this.props.getTradeRefData();
}
addRefData(nextProps) {
const updatedTradeFormData = {
...this.state.tradeForm
};
//checking only for commodity here, ideally should check for all the props with 'childConfig'
//but this should be fine since all the metadata is coming together
if(this.state.tradeForm.commodity.childConfig.length === 0){
for (let key in updatedTradeFormData) {
if(key === 'commodity' || key === 'counterParty' || key === 'location' || key === 'side'){
updatedTradeFormData[key].childConfig = nextProps.refData[key];
}
}
this.setState({tradeForm: updatedTradeFormData});
}
}
//sync state to props - called from life cycle methods
syncUpdatedStatefromProps(nextProps, nextState) {
const _props = nextProps || this.props;
const _state = nextState || this.state;
const updatedTradeFormData = {
..._state.tradeForm
};
for (let key in updatedTradeFormData) {
if(_props.tradeData) {
if(key === 'tradeDate'){
updatedTradeFormData[key].value = new Date(_props.tradeData[key]);
}
else {
updatedTradeFormData[key].value = _props.tradeData[key];
}
updatedTradeFormData[key].valid = true;
updatedTradeFormData[key].elementConfig.errorText = null;
}
else {
updatedTradeFormData[key].value = undefined;
updatedTradeFormData[key].elementConfig.errorText = null;
updatedTradeFormData[key].valid = false;
}
}
this.setState({tradeForm: updatedTradeFormData, formIsValid: !!_props.tradeData, isAddEditMode: !_props.tradeData});
}
// life cycle method
render() {
const formElementsArray = [];
for (let key in this.state.tradeForm) {
formElementsArray.push({
id: key,
config: this.state.tradeForm[key]
});
}
return (<div className={classes.TradeParent}>
<TradeHeader tradeId={this.props.tradeData ? this.props.tradeData._id : ''}
changeEditMode={this.updateAddEditMode}
onDelete={this.handleDeleteAction}/>
<form onSubmit={this.submitHandler}>
{formElementsArray.map(formElement => {
formElement.config.elementConfig.disabled = !this.state.isAddEditMode;
return (<Input
key={formElement.id}
elementType={formElement.config.elementType}
elementConfig={formElement.config.elementConfig}
childConfig={formElement.config.childConfig}
value={formElement.config.value}
invalid={!formElement.config.valid}
shouldValidate={formElement.config.validation}
touched={formElement.config.touched}
changed={(event, value, selectValue) => this.inputChangedHandler(value, selectValue, formElement.id)} />
)
})}
<RaisedButton label="Cancel" onClick={this.cancelHandler} disabled={!this.state.isAddEditMode}/>
<RaisedButton label="Save" primary={true} style={{marginLeft: '10px'}} disabled={!(this.state.formIsValid && this.state.isAddEditMode)} onClick={this.submitHandler}/>
</form>
</div>);
}
}
const mapStateToProps = state => {
return {
tradeData: state.tradeReducer.selectedTrade,
refData: state.tradeReducer.refData,
authToken: state.auth.token,
userId: state.auth.userId
}
};
const mapDispatchToProps = dispatch => {
return {
updateTrade: (tradeData, authToken, userId) => dispatch(TradeActions.updateTrade(tradeData, authToken, userId)),
showDeleteDialog: (open) => dispatch(TradeActions.toggleDeleteTrade(open)),
getTradeRefData: () => dispatch(TradeActions.getTradeRefData()),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Trade); | f64b736bc303e56f0ae54f6e4b7be61d67b42bf6 | [
"JavaScript",
"Markdown"
] | 28 | JavaScript | rahulshanwal/metal-trade | b5d4d276e7bc35fa747d6a65e0bbe4cc23688bc5 | eca380418d23dbe0c28c124ae9bf5634b1482ae6 | |
refs/heads/master | <repo_name>DrDet/parser-generator<file_sep>/src/NonTerm.h
#pragma once
#include <vector>
#include "Unit.h"
using unit_name_t = std::string;
using Rule = std::vector<unit_name_t>;
struct NonTerm : public Unit {
std::vector<Rule> rules;
std::vector<std::vector<std::string> > exp_lists; // rule_num -> std::vector<exp_list>
std::vector<std::string> code;
std::string arg_list;
std::string ret_type;
NonTerm();
explicit NonTerm(std::string const & name);
void add_rule(Rule const & rule, std::string const & code, const std::vector<std::string> & exp_list);
bool is_non_term() override;
void print();
};
using non_term_t = std::shared_ptr<NonTerm>;<file_sep>/src/main.cpp
#include <iostream>
#include <fstream>
#include <regex>
#include "antlr4-runtime.h"
#include "GrammarLexer.h"
#include "GrammarParser.h"
#include "Grammar.h"
using namespace antlr4;
int main(int , const char **) {
std::ifstream in("calculator.gr");
// std::ifstream in("hw2-regexps-language.gr");
ANTLRInputStream input(in);
GrammarLexer lexer(&input);
CommonTokenStream tokens(&lexer);
tokens.fill();
GrammarParser parser(&tokens);
Grammar res = parser.start()->grammar;
res.gen_code();
return 0;
}<file_sep>/src/Term.h
#pragma once
#include <string>
#include "Unit.h"
struct Term : public Unit {
std::string regex;
Term() = default;
Term(std::string const & name, std::string const & regex);
bool is_term() override;
void print();
};
using term_t = std::shared_ptr<Term>;
<file_sep>/src/Grammar.h
#pragma once
#include <unordered_map>
#include <unordered_set>
#include "Term.h"
#include "NonTerm.h"
struct Grammar {
std::string start;
std::unordered_map<std::string, non_term_t> non_terms;
std::unordered_map<std::string, term_t> terms;
std::unordered_set<char> skip_symbols;
std::unordered_map<std::string, std::unordered_set<std::string>> first;
std::unordered_map<std::string, std::unordered_set<std::string>> follow;
void gen_code();
Grammar() = default;
explicit Grammar(std::string const & start);
void add_term(Term const &);
void add_non_term(NonTerm const &);
void print();
void calc_first();
void calc_follow();
std::unordered_set<std::string> get_first(Rule const& alpha);
private:
int choose_rule(std::string const & non_term_name, std::string const & first_e);
void gen_parser();
void gen_lexer();
void gen_tree();
std::string get_parse_rule(non_term_t const & non_term, int rule_num);
};
<file_sep>/src/Unit.cpp
#include "Unit.h"
#include "Term.h"
#include "NonTerm.h"
Unit::Unit(std::string const &s) : name(s) {
}
Term* Unit::as_term() {
return dynamic_cast<Term*>(this);
}
NonTerm* Unit::as_non_term() {
return dynamic_cast<NonTerm*>(this);
}
bool Unit::is_term() {
return false;
}
bool Unit::is_non_term() {
return false;
}
<file_sep>/src/NonTerm.cpp
#include <iostream>
#include <memory>
#include "NonTerm.h"
void NonTerm::add_rule(Rule const &rule, std::string const & code, const std::vector<std::string> & exp_list) {
rules.push_back(rule);
this->code.push_back(code);
exp_lists.push_back(exp_list);
}
NonTerm::NonTerm(std::string const &name) : Unit(name) {
}
bool NonTerm::is_non_term() {
return true;
}
void NonTerm::print() {
using std::cout;
using std::endl;
cout << name << ":\n";
for (auto &rule : rules) {
cout << "| ";
for (auto &unit : rule) {
cout << unit << " ";
}
cout << endl;
}
cout << "ret type: " << ret_type << endl;
cout << "code:\n";
for (auto &c: code) {
cout << c << endl;
}
}
NonTerm::NonTerm() : ret_type("int") {
}
<file_sep>/src/Term.cpp
#include <iostream>
#include "Term.h"
Term::Term(std::string const &name, std::string const ®ex) : Unit(name), regex(regex) {
}
bool Term::is_term() {
return true;
}
void Term::print() {
using std::cout;
using std::endl;
cout << name << ": " << regex << endl;
}
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(parser-generator)
set(CMAKE_CXX_STANDARD 14)
AUX_SOURCE_DIRECTORY(${PROJECT_SOURCE_DIR}/generated parser-generator-GENERATED_SRC)
AUX_SOURCE_DIRECTORY(${PROJECT_SOURCE_DIR}/src parser-generator-SRC)
include_directories(${PROJECT_SOURCE_DIR}/include/antlr4-runtime)
include_directories(${PROJECT_SOURCE_DIR}/generated)
include_directories(${PROJECT_SOURCE_DIR}/src)
add_executable(parser-generator ${parser-generator-SRC} ${parser-generator-GENERATED_SRC})
target_link_libraries(parser-generator ${PROJECT_SOURCE_DIR}/lib/libantlr4-runtime.a)
<file_sep>/src/Grammar.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <cassert>
#include "Grammar.h"
void Grammar::add_term(Term const & term) {
terms[term.name] = std::make_shared<Term>(term);
}
void Grammar::add_non_term(NonTerm const & non_term) {
non_terms[non_term.name] = std::make_shared<NonTerm>(non_term);
}
void Grammar::print() {
using std::cout;
using std::endl;
cout << "start-rule: " << start << endl;
cout << "Non-terms:\n";
for (auto &non_term : non_terms) {
non_term.second->print();
}
cout << "~~~~~~~~~~~~\n";
cout << "Terms:\n";
for (auto &term : terms) {
term.second->print();
}
cout << "~~~~~~~~~~~~\n";
cout << "FIRST:\n";
for (auto &non_term : non_terms) {
cout << non_term.second->name << ":" << endl;
for (auto &e: first[non_term.second->name]) {
cout << e << "; ";
}
cout << endl;
}
cout << "~~~~~~~~~~~~\n";
cout << "FOLLOW:\n";
for (auto &non_term : non_terms) {
cout << non_term.second->name << ":" << endl;
for (auto &e: follow[non_term.second->name]) {
cout << e << "; ";
}
cout << endl;
}
cout << "~~~~~~~~~~~~\n";
}
void Grammar::calc_first() {
bool changed = true;
while (changed) {
changed = false;
for (auto &non_term : non_terms) {
std::string& rule_name = non_term.second->name;
for (auto &rule : non_term.second->rules) {
auto res = get_first(rule);
size_t before_size = first[rule_name].size();
first[rule_name].insert(res.begin(), res.end());
changed = changed || (before_size != first[rule_name].size());
}
}
}
}
void Grammar::calc_follow() {
follow[start].insert("END$");
bool changed = true;
while (changed) {
changed = false;
for (auto &non_term : non_terms) {
std::string& rule_name = non_term.second->name;
for (auto &rule : non_term.second->rules) {
for (size_t i = 0; i < rule.size(); ++i) {
size_t before_size = follow[rule[i]].size();
if (islower(rule[i][0])) {
auto tmp = get_first(Rule(rule.begin() + i + 1, rule.end()));
if (tmp.find("#") != tmp.end()) {
tmp.erase("#");
follow[rule[i]].insert(tmp.begin(), tmp.end());
follow[rule[i]].insert(follow[rule_name].begin(), follow[rule_name].end());
} else {
follow[rule[i]].insert(tmp.begin(), tmp.end());
}
changed = changed || (before_size != follow[rule[i]].size());
}
}
}
}
}
}
std::unordered_set<std::string> Grammar::get_first(Rule const &alpha) {
if (alpha.empty() || (alpha.size() == 1 && alpha[0] == "#")) {
return {"#"};
}
if (isupper(alpha[0][0])) {
return { alpha[0] };
} else {
auto lhs = first[alpha[0]];
if (lhs.find("#") != lhs.end()) {
lhs.erase("#");
auto rhs = get_first(Rule(alpha.begin() + 1, alpha.end()));
lhs.insert(rhs.begin(), rhs.end());
return lhs;
} else {
return lhs;
}
}
}
Grammar::Grammar(std::string const &start) : start(start) {
}
void Grammar::gen_parser() {
std::ofstream parser_h_code("gen/Parser.h");
parser_h_code <<
"#pragma once\n"
"\n"
"#include \"Lexer.h\"\n"
"#include \"Tree.h\"\n"
"\n"
"template <typename T>\n"
"struct result {\n"
" node_t node;\n"
" T val;\n"
" result() = default;\n"
"};\n"
"class Parser {\n"
"public:\n"
" Parser() = default;\n"
" result<" << non_terms[start]->ret_type << "> parse(const std::string & s);\n"
"private:\n"
" Lexer lexer;\n";
for (auto &non_term : non_terms) {
parser_h_code << " result<" << non_term.second->ret_type << "> " << non_term.second->name << "(" << non_term.second->arg_list << ");\n";
}
parser_h_code <<
" result<std::string> term_symbol(std::string const & s);\n"
" node_t eps_symbol();\n"
" void parser_error();\n"
"};\n"
"\n"
"class parser_exception : public std::exception {\n"
" std::string message;\n"
"public:\n"
" explicit parser_exception(const std::string &);\n"
" virtual const char* what() const noexcept override;\n"
"};";
std::ofstream parser_cpp_code("gen/Parser.cpp");
parser_cpp_code <<
"#include \"Parser.h\"\n"
"#include <memory>\n"
"#include <iostream>\n"
"\n"
"using std::unique_ptr;\n"
"using std::string;\n"
"int calc_fact(int x) {\n"
" if (x < 2) {\n"
" return 1; \n"
" }\n"
" return x * calc_fact(x - 1);\n"
"}\n"
"\n"
"result<" << non_terms[start]->ret_type << "> Parser::parse(const string &__str) {\n"
" lexer = Lexer(__str);\n"
" result<" << non_terms[start]->ret_type << "> root = " << start << "();\n"
" if (lexer.get_cur_tok() == END$) {\n"
" return root;\n"
" }\n"
" parser_error();\n"
"}\n\n";
for (auto &non_term : non_terms) {
std::string& name = non_term.second->name;
parser_cpp_code <<
"result<" << non_term.second->ret_type << "> Parser::" << name << "(" << non_term.second->arg_list << ") {\n"
" result<" << non_term.second->ret_type << "> res;\n"
" node_t root(new Node(\"" << name << "\"));\n"
" " << non_term.second->ret_type << " $val = res.val;\n"
" switch (lexer.get_cur_tok()) {\n";
bool has_eps = false;
for (auto &term_name: first[name]) {
if (term_name == "#") {
has_eps = true;
continue;
}
parser_cpp_code <<
" case " << term_name << ": {\n";
int rule_num = choose_rule(name, term_name);
parser_cpp_code << get_parse_rule(non_term.second, rule_num);
parser_cpp_code << " }\n";
}
if (has_eps) {
for (auto &term_name: follow[name]) {
parser_cpp_code << " case " << term_name << ":\n";
}
int eps_rule_num = choose_rule(name, "#");
parser_cpp_code << " {\n";
parser_cpp_code << get_parse_rule(non_term.second, eps_rule_num);
parser_cpp_code << " }\n";
}
parser_cpp_code <<
" default: {\n"
" parser_error();\n"
" }\n"
" }\n"
" res.node = std::move(root);\n"
" res.val = $val;\n"
" return res;\n"
"}\n\n"
"\n";
}
parser_cpp_code <<
"result<std::string> Parser::term_symbol(string const & s) {\n"
" result<std::string> res;\n"
" node_t node(new Node(s));\n"
" lexer.next_token();\n"
" res.node = std::move(node);\n"
" res.val = s;\n"
" return res;\n"
"}\n"
"\n"
"node_t Parser::eps_symbol() {\n"
" return node_t(new Node(\"\"));\n"
"}\n"
"\n"
"void Parser::parser_error() {\n"
" size_t pos = lexer.get_cur_pos();\n"
" char buf[50];\n"
" sprintf(buf, \"Unexpected token: %s at position: %zu\", lexer.get_cur_tok_text().c_str(), pos);\n"
" throw parser_exception(buf);\n"
"}\n"
"\n"
"parser_exception::parser_exception(const string & s) : message(s) {}\n"
"\n"
"const char *parser_exception::what() const noexcept {\n"
" return message.c_str();\n"
"}\n";
}
void Grammar::gen_lexer() {
std::ofstream lexer_h_code("gen/Lexer.h");
lexer_h_code <<
"#pragma once\n"
"#include <string>\n"
"#include <regex>\n"
"#include <unordered_set>\n\n"
"enum Token {\n";
for (auto &term : terms) {
std::string& name = term.second->name;
lexer_h_code <<
" " << name << ",\n";
}
lexer_h_code <<
" END$\n"
"};\n\n"
"class Lexer {\n"
"public:\n"
" Lexer() = default;\n"
" explicit Lexer(const std::string & s);\n"
"\n"
" void next_token();\n"
" Token get_cur_tok();\n"
" size_t get_cur_pos();\n"
" std::string get_cur_tok_text();\n"
"private:\n"
" static const int tokens_num = " << terms.size() << ";\n"
" std::regex token_regexps[tokens_num];\n"
" std::unordered_set<char> skip_symbols;\n"
"\n"
" Token cur_tok;\n"
" std:: string cur_tok_text;\n"
" size_t cur_pos;\n"
" std::string s;\n"
"};\n"
"\n"
"class lexer_exception : public std::exception {\n"
" std::string message;\n"
"public:\n"
" explicit lexer_exception(const std::string &);\n"
" virtual const char* what() const noexcept override;\n"
"};\n";
std::ofstream lexer_cpp_code("gen/Lexer.cpp");
lexer_cpp_code <<
"#include \"Lexer.h\"\n"
"#include <cctype>\n"
"#include <stdexcept>\n"
"\n"
"using std::string;\n"
"\n"
"inline bool starts_with(std::string const & s, std::string const & start) {\n"
" if (s.length() < start.length()) {\n"
" return false;\n"
" }\n"
" return s.substr(0, start.length()) == start;\n"
"}\n"
"\n"
"Lexer::Lexer(const string & s) : s(s), cur_pos(0) {\n";
lexer_cpp_code << " skip_symbols = {";
for (char c : skip_symbols) {
if (c != *skip_symbols.begin()) {
lexer_cpp_code << ", ";
}
lexer_cpp_code << "(char) " << static_cast<int>(c);
}
lexer_cpp_code << "};\n";
for (auto &term: terms) {
std::string& name = term.second->name;
lexer_cpp_code << " token_regexps[" << name << "] = std::regex(" << term.second->regex << ");\n";
}
lexer_cpp_code <<
" next_token();\n"
"}\n"
"\n"
"void Lexer::next_token() {\n"
" while (true) {\n"
" if (cur_pos >= s.length()) {\n"
" cur_tok = END$;\n"
" return;\n"
" }\n"
" std::sregex_token_iterator no_match;\n"
" for (int i = 0; i < tokens_num; ++i) {\n"
" std::sregex_token_iterator it(s.begin() + cur_pos, s.end(), token_regexps[i]);\n"
" if (it != no_match && starts_with(s.substr(cur_pos), it->str())) {\n"
" cur_tok = static_cast<Token>(i);\n"
" cur_tok_text = it->str();\n"
" cur_pos += it->str().length();\n"
" return;\n"
" }\n"
" }\n"
" if (skip_symbols.find(s[cur_pos]) != skip_symbols.end()) {\n"
" char skip = s[cur_pos];\n"
" while (cur_pos < s.length() && s[cur_pos] == skip) {\n"
" cur_pos++;\n"
" }\n"
" } else {\n"
" char buf[50];\n"
" sprintf(buf, \"Unexpected symbol: '%c' at position: %zu\", s[cur_pos], cur_pos);\n"
" throw lexer_exception(buf);\n"
" }\n"
" }\n"
"}\n"
"\n"
"Token Lexer::get_cur_tok() {\n"
" return cur_tok;\n"
"}\n"
"\n"
"size_t Lexer::get_cur_pos() {\n"
" return cur_pos;\n"
"}\n"
"\n"
"std::string Lexer::get_cur_tok_text() {\n"
" return cur_tok_text;\n"
"}\n"
"\n"
"lexer_exception::lexer_exception(const std::string & s) : message(s) {}\n"
"\n"
"const char *lexer_exception::what() const noexcept {\n"
" return message.c_str();\n"
"}\n";
}
void Grammar::gen_code() {
system("if [ ! -d \"gen\" ]; then\n"
" mkdir gen\n"
"fi");
calc_first();
calc_follow();
gen_parser();
gen_lexer();
gen_tree();
}
int Grammar::choose_rule(std::string const &non_term_name, std::string const &first_e) {
auto &rules = non_terms[non_term_name]->rules;
int ans = -1;
for (size_t i = 0; i < rules.size(); ++i) {
auto first = get_first(rules[i]);
if (first.find(first_e) != first.end()) {
assert(ans == -1);
ans = static_cast<int>(i);
}
}
assert(ans != -1);
return ans;
}
void Grammar::gen_tree() {
std::ofstream tree_h_code("gen/Tree.h");
tree_h_code <<
"#pragma once\n"
"#include <memory>\n"
"#include <list>\n"
"\n"
"class Node;\n"
"using node_t = std::unique_ptr<Node>;\n"
"\n"
"class Node {\n"
"public:\n"
" explicit Node(std::string type);\n"
" Node(const Node & other) = delete;\n"
" void append_child(std::unique_ptr<Node> node);\n"
" std::string to_string();\n"
" std::string to_dot();\n"
"private:\n"
" std::string to_dot_impl();\n"
" std::list<std::unique_ptr<Node>> children;\n"
" std::string type;\n"
"};";
std::ofstream tree_cpp_code("gen/Tree.cpp");
tree_cpp_code <<
"#include \"Tree.h\"\n"
"#include <utility>\n"
"#include <iostream>\n"
"#include <queue>\n"
"#include <sstream>\n"
"\n"
"using std::string;\n"
"using std::queue;\n"
"\n"
"Node::Node(std::string type) : type(std::move(type)) {}\n"
"\n"
"void Node::append_child(node_t node) {\n"
" children.emplace_back(std::move(node));\n"
"}\n"
"\n"
"string Node::to_string() {\n"
" string res(type);\n"
" for (auto &it : children) {\n"
" res += it->to_string();\n"
" }\n"
" return res;\n"
"}\n"
"\n"
"std::string Node::to_dot() {\n"
" string res;\n"
" res += \"digraph G {\\n\";\n"
" res += to_dot_impl();\n"
" res += \"}\";\n"
" return res;\n"
"}\n"
"\n"
"std::string Node::to_dot_impl() {\n"
" static int id = 0;\n"
" std::stringstream ss;\n"
" int v_id = id++;\n"
" string color = (children.empty() ? \"; color = red\" : \"\");\n"
" ss << \"\\t\" << v_id << \" [label = \\\"\" << type << \"\\\"\" << color << \"];\\n\";\n"
" for (auto &c: children) {\n"
" int c_id = id;\n"
" ss << c->to_dot_impl();\n"
" ss << \"\\t\" << v_id << \" -> \" << c_id << \";\\n\";\n"
" }\n"
" return ss.str();\n"
"}\n"
"\n";
}
std::string Grammar::get_parse_rule(non_term_t const &non_term, int rule_num) {
std::stringstream parser_cpp_code;
int idx = 0;
for (auto &unit: non_term->rules[rule_num]) {
parser_cpp_code << " ";
if (unit == "#") {
parser_cpp_code << "root->append_child(eps_symbol());\n";
} else if (islower(unit[0])) {
parser_cpp_code << "auto $" << unit << " = " << unit << "(" << non_term->exp_lists[rule_num][idx] << ");\n";
parser_cpp_code << " ";
parser_cpp_code << "root->append_child(std::move($" << unit << ".node));\n";
} else {
parser_cpp_code << "auto $" << unit << " = term_symbol(lexer.get_cur_tok_text());\n";
parser_cpp_code << " ";
parser_cpp_code << "root->append_child(std::move($" << unit << ".node));\n";
}
++idx;
}
parser_cpp_code << " " << non_term->code[rule_num] << "\n";
parser_cpp_code << " break;\n";
return parser_cpp_code.str();
}
<file_sep>/src/Unit.h
#pragma once
#include <string>
#include <memory>
struct Term;
struct NonTerm;
struct Unit {
std::string name;
Unit() = default;
explicit Unit(std::string const &);
Term* as_term();
NonTerm* as_non_term();
virtual bool is_term();
virtual bool is_non_term();
virtual ~Unit() = default;
};
using unit_t = std::shared_ptr<Unit>;
<file_sep>/gen.sh
#!/usr/bin/env bash
export CLASSPATH=".:/usr/local/lib/antlr-4.7.1-complete.jar:$CLASSPATH"
java -Xmx500M -cp "/usr/local/lib/antlr-4.7.1-complete.jar:$CLASSPATH" org.antlr.v4.Tool -Dlanguage=Cpp -no-listener -no-visitor -o generated/ Grammar.g4
<file_sep>/README.md
# parser-generator
This is a simple generator of parsers for text which is suited for the given grammar.
| 127ddadd4105ac3d009c49ca1cc17e257221178b | [
"Markdown",
"CMake",
"C++",
"Shell"
] | 12 | C++ | DrDet/parser-generator | 89ce643dfab9869ef971a00dd422a30efd700529 | 4c787b5874c9ae78c359858998ca37d2bb984099 | |
refs/heads/master | <file_sep># Coder: <NAME>, 2019.5.25, Ver:1
# The code is a digital reprentation of the constellation Orion
# Angle/Distance references taken from the following webpage:
# http://wordpress.mrreid.org/2011/10/30/constellations-from-a-different-angle/
import turtle
turtle.hideturtle()
turtle.pensize(3)
#Draw Betelgeuse
turtle.penup()
turtle.goto(-400,370)
turtle.pendown()
turtle.dot(14)
turtle.penup()
turtle.goto(-400,360)
turtle.pendown()
turtle.write(" Betelgeuse", move=False, align="left", font=(10))
turtle.penup()
turtle.goto(-400,370)
turtle.pendown()
#Draw Alnitak
turtle.goto(-260,-100)
turtle.pendown()
turtle.dot(14)
turtle.penup()
turtle.goto(-260,-120)
turtle.pendown()
turtle.write(" Alnitak", move=False, align="left", font=(10))
turtle.penup()
turtle.goto(-260,-100)
turtle.pendown()
#Draw Saiph
turtle.goto(-380,-480)
turtle.pendown()
turtle.dot(14)
turtle.penup()
turtle.goto(-400,-508)
turtle.pendown()
turtle.write("Saiph", move=False, align="left", font=(10))
turtle.penup()
#Draw Alnilam
turtle.goto(-260,-100)
turtle.pendown()
turtle.goto(-180,-60)
turtle.dot(14)
turtle.penup()
turtle.goto(-180,-80)
turtle.pendown()
turtle.write(" Alnilam", move=False, align="left", font=(10))
turtle.penup()
turtle.goto(-180,-60)
turtle.pendown()
#Draw Mintaka
turtle.goto(-115,-20)
turtle.dot(14)
turtle.penup()
turtle.goto(-115,-30)
turtle.pendown()
turtle.write(" Mintaka", move=False, align="left", font=(10))
turtle.penup()
turtle.goto(-115,-20)
turtle.pendown()
#Draw Meissa
turtle.goto(-10,320)
turtle.dot(14)
turtle.penup()
turtle.goto(-31,328)
turtle.pendown()
turtle.write("Meissa", move=False, align="left", font=(10))
turtle.penup()
turtle.goto(-115,-20)
turtle.pendown()
#Draw Rigel
turtle.goto(170,-405)
turtle.dot(14)
turtle.penup()
turtle.goto(154,-432)
turtle.pendown()
turtle.write("Rigel", move=False, align="left", font=(10))
| 0adb387b306a13cf251f6f37119f28c44428d1d5 | [
"Python"
] | 1 | Python | usf-cs-spring-2019-anita-rathi/110-project-constellation-AndrewRCabezudo | 1304911b880ab8c273ba2a2b1784ac739b8321a4 | 76d744ebba6111985474aeb6843cc0d9f53c9eac | |
refs/heads/master | <file_sep>package com.haya.entity;
import lombok.Data;
import javax.persistence.*;
import java.util.Collection;
import java.util.List;
/**
* @author haya
*/
@Entity
@Table(name = "course")
@Data
public class Course {
@Id
@Column(name = "id")
private int id;
@Basic
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "course",fetch = FetchType.LAZY,cascade = CascadeType.ALL)
private List<TeacherCourse> teacherCoursesById;
@Override
public String toString() {
final StringBuilder sb = new StringBuilder( "{" );
sb.append( "\"id\":" )
.append( id );
sb.append( ",\"name\":\"" )
.append( name ).append( '\"' );
sb.append( '}' );
return sb.toString();
}
}
<file_sep>package com.haya.service;
import com.haya.entity.TeacherCourse;
import java.util.List;
/**
* @author haya
*/
public interface TeacherCourseService {
List<TeacherCourse> find(int teacherId);
}
<file_sep>package com.haya.service.impl;
import com.haya.bean.Page;
import com.haya.dao.CourseDao;
import com.haya.entity.Course;
import com.haya.entity.User;
import com.haya.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author haya
*/
@Transactional(rollbackFor = Exception.class)
@Service
public class CourseServiceImpl implements CourseService {
@Autowired
private CourseDao courseDao;
@Override
public Page<Course> getAllCourse(Page<Course> page) {
return courseDao.findPageByHql( "from Course course", page);
}
@Override
public void updateOrSave(Course course) {
if (course.getId() == 0) {
courseDao.save( course );
} else {
courseDao.update( course );
}
}
@Override
public Page<Course> like(Page<Course> page, Course course) {
page = courseDao.findPageByHql( "from Course c where c.name like '%" + course.getName()+"%'", page );
return page;
}
}
<file_sep>package com.haya.entity;
import lombok.Data;
import javax.persistence.*;
/**
* @author haya
*/
@Data
@Entity
@Table(name = "stu_course")
public class StuCourse {
@Id
@Column(name = "id")
private int id;
@Column(name = "stu_id")
private Integer stuId;
@Column(name = "teacher_course_id")
private Integer teacherCourseId;
@Column(name = "result")
private Integer result;
@ManyToOne
@JoinColumn(name = "stu_id", referencedColumnName = "id",insertable=false ,updatable=false)
private User user;
@ManyToOne
@JoinColumn(name = "teacher_course_id", referencedColumnName = "id",insertable=false ,updatable=false)
private TeacherCourse teacherCourse;
@Override
public String toString() {
final StringBuilder sb = new StringBuilder( "{" );
sb.append( "\"id\":" )
.append( id );
sb.append( ",\"stuId\":" )
.append( stuId );
sb.append( ",\"teacherCourseId\":" )
.append( teacherCourseId );
sb.append( ",\"result\":" )
.append( result );
sb.append( ",\"user\":" )
.append( user );
sb.append( ",\"teacherCourse\":" )
.append( teacherCourse );
sb.append( '}' );
return sb.toString();
}
}
<file_sep>package com.haya.action;
import com.haya.bean.Page;
import com.haya.bean.VALUE;
import com.haya.entity.Course;
import com.haya.entity.StuCourse;
import com.haya.entity.User;
import com.haya.service.CourseService;
import com.haya.service.StudentCourseService;
import com.haya.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import static com.haya.bean.VALUE.*;
/**
* @author haya
*/
@EqualsAndHashCode(callSuper = true)
@Data
@ParentPackage("myStruts")
@Namespace("/")
public class UserAction extends SuperAction {
@Autowired
private UserService userService;
private User user = new User();
@Action(value = "login", results = {
@Result(name = "admin", location = "/admin/getTeacherPage.action", type = "redirect"),
@Result(name = "teacher", location = "/teacher/getTeacherCoursePage.action", type = "redirect"),
@Result(name = "student", location = "/student/getStudentResult.action", type = "redirect"),
@Result(name = "error", location = "/error.jsp", type = "redirect")
})
public String login() {
user = userService.login( user );
if (user == null) {
return "error";
}
Integer roleId = user.getRoleId();
session.put( ROLE_ID.toString(), roleId );
session.put( LOGIN_USER_ACCOUNT.toString(), user.getAccount() );
session.put( LOGIN_USER_ID.toString(), user.getId() );
if (roleId == 2) {
return "teacher";
} else if (roleId == 3) {
return "student";
} else {
return "admin";
}
}
@Action(value = "logout", results = {
@Result(name = "success", location = "/login.jsp", type = "redirect"),
@Result(name = "error", location = "/error.jsp", type = "redirect")
})
public String logout() {
session.remove( "loginUserAccount" );
return "success";
}
}
<file_sep>package com.haya.action;
import com.haya.bean.Page;
import com.haya.entity.Course;
import com.haya.entity.User;
import com.haya.service.CourseService;
import com.haya.service.StudentCourseService;
import com.haya.service.TeacherCourseService;
import com.haya.service.UserService;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author haya
*/
@EqualsAndHashCode(callSuper = true)
@Data
@ParentPackage("myStruts")
@Namespace("/admin")
public class AdminAction extends SuperAction {
@Autowired
private UserService userService;
@Autowired
private StudentCourseService studentCourseService;
@Autowired
private CourseService courseService;
@Autowired
private TeacherCourseService teacherCourseService;
private User user = new User();
private Page<User> page = new Page<>();
private Page<Course> pageCourse = new Page<>();
private Course course= new Course();
/**
* 管理员 分页获取学生
*
* @return
*/
@Action(value = "getStudentPage", results = {
@Result(name = "success", location = "/admin/admin_student.jsp", type = "redirect"),
@Result(name = "error", location = "/error.jsp", type = "redirect")
})
public String getStudentPage() {
Page<User> list = userService.getAllStudent( 1, 10 );
System.out.println( list );
if (list != null) {
session.put( "studentPage", list );
return "success";
}
return "error";
}
/**
* 管理员 分页获取老师
*
* @return
*/
@Action(value = "getTeacherPage", results = {
@Result(name = "success", location = "/admin/admin_teacher.jsp", type = "redirect"),
@Result(name = "error", location = "/error.jsp", type = "redirect")
})
public String getTeacherPage() {
if (page.getPageNum() == 0) {
page.setPageNum( 1 );
page.setPageSize( 10 );
}
Page<User> list = userService.getAllTeacher( page );
if (list != null) {
System.out.println( list );
session.put( "teacherList", list );
return "success";
}
return "error";
}
/**
* 管理员 更新用户
*
* @return
*/
@Action(value = "updateUser", results = {
@Result(name = "teacher", location = "/admin/getTeacherPage.action", type = "redirect"),
@Result(name = "student", location = "/admin/getStudentPage.action", type = "redirect"),
@Result(name = "error", location = "/error.jsp", type = "redirect")
})
public String updateUser() {
userService.updateOrSave( user );
Integer roleId = user.getRoleId();
return roleId == 2 ? "teacher"
: roleId == 3 ? "student"
: "error";
}
/**
* 管理员 删除用户
*
* @throws IOException
*/
@Action(value = "removeUser")
public void removeUser() throws IOException {
userService.remove( user );
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
out.println( "seccess" );
out.close();
}
@Action(value = "searchUser", results = {
@Result(name = "teacher", location = "/admin/admin_teacher.jsp", type = "redirect"),
@Result(name = "student", location = "/admin/admin_student.jsp", type = "redirect"),
@Result(name = "error", location = "/error.jsp", type = "redirect")
})
public String searchUser() {
if (page.getPageNum() == 0) {
page.setPageNum( 1 );
page.setPageSize( 10 );
}
Page<User> list = userService.like( page, user );
if (user.getRoleId() == 2) {
session.put( "teacherList", list );
return "teacher";
} else {
session.put( "studentPage", list );
return "student";
}
}
/**
* 管理员 分页获取课程
* @return
*/
@Action(value = "getCoursePage", results = {
@Result(name = "success", location = "/admin/admin_course.jsp", type = "redirect"),
@Result(name = "error", location = "/login.jsp", type = "redirect")
})
public String getCoursePage() {
if (pageCourse.getPageNum() == 0) {
pageCourse.setPageNum( 1 );
pageCourse.setPageSize( 10 );
}
Page<Course> list = courseService.getAllCourse( pageCourse );
System.out.println(list);
if (list != null) {
session.put( "coursePage", list );
return "success";
}
return "error";
}
/**
* 管理员更新课程
* @return
*/
@Action(value = "updateCourse", results = {
@Result(name = "success", location = "/admin/getCoursePage.action", type = "redirect"),
@Result(name = "error", location = "/error.jsp", type = "redirect")
})
public String updateCourse() {
courseService.updateOrSave( course );
return "success";
}
@Action(value = "searchCourse", results = {
@Result(name = "success", location = "/admin/admin_course.jsp", type = "redirect"),
@Result(name = "error", location = "/error.jsp", type = "redirect")
})
public String search() {
if (page.getPageNum() == 0) {
page.setPageNum( 1 );
page.setPageSize( 10 );
}
Page<Course> list = courseService.like( pageCourse, course );
session.put( "coursePage", list );
return "success";
}
}
<file_sep>package com.haya.service;
import com.haya.bean.Page;
import com.haya.entity.StuCourse;
import com.haya.entity.TeacherCourse;
import com.haya.entity.User;
import java.util.List;
/**
* @author haya
*/
public interface UserService {
User getById(int id);
User getByNo(int no);
User login(User user);
Page<User> getAllStudent(int pageNum, int pageSize);
List<StuCourse> getStudentByCourse(TeacherCourse tc);
Page<User> getAllTeacher(Page<User> page);
void remove(User user);
void update(User user);
void updateOrSave(User user);
Page<User> like(Page<User> page,User user);
}
<file_sep>package com.haya.service.impl;
import com.haya.bean.Page;
import com.haya.dao.StuCourseDao;
import com.haya.dao.TeacherCourseDao;
import com.haya.dao.UserDao;
import com.haya.entity.StuCourse;
import com.haya.entity.TeacherCourse;
import com.haya.entity.User;
import com.haya.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @author haya
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Autowired
private TeacherCourseDao teacherCourseDao;
@Autowired
private StuCourseDao stuCourseDao;
@Override
public User getById(int id) {
return userDao.findById( id ) ;
}
@Override
public User getByNo(int no) {
return userDao.findByColumn( "no", no );
}
@Override
public User login(User user) {
List<User> list = userDao.getHibernateTemplate().findByExample( user );
if (list != null && list.size() != 0) {
return list.get( 0 );
}
return null;
}
@Override
public Page<User> getAllStudent(int pageNum, int pageSize) {
return userDao.findPageByHql( "from User user where user.roleId=3", new Page<>( pageNum, pageSize ) );
}
@Override
public List<StuCourse> getStudentByCourse(TeacherCourse tc) {
if (tc.getId() == 0) {
tc = teacherCourseDao.find( tc );
}
System.out.println( tc );
List<StuCourse> list = stuCourseDao.findListByColumn( "teacherCourseId", tc.getId() );
return list;
}
@Override
public Page<User> getAllTeacher(Page<User> page) {
return userDao.findPageByHql( "from User user where user.roleId=2", page );
}
@Transactional(rollbackFor = Exception.class)
@Override
public void remove(User user) {
userDao.deleteById( user.getId() );
}
@Transactional(rollbackFor = Exception.class)
@Override
public void update(User user) {
userDao.update( user );
}
@Transactional(rollbackFor = Exception.class)
@Override
public void updateOrSave(User user) {
if (user.getId() == 0) {
userDao.save( user );
} else {
userDao.update( user );
}
}
@Override
public Page<User> like(Page<User> page, User user) {
page = userDao.findPageByHql( "from User u where u.no like '%" + user.getNo()+"%' and u.roleId="+user.getRoleId(), page );
return page;
}
}
<file_sep>package com.haya.interceptor;
import com.opensymphony.xwork2.ActionContext;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import static com.haya.bean.VALUE.ROLE_ID;
/**
* @author haya
*/
@WebFilter(filterName = "FilterDemo01", urlPatterns = { "/*" })
public class JspFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse)servletResponse;
HttpServletRequest request = (HttpServletRequest)servletRequest;
String uri = request.getRequestURI();
String root = request.getContextPath() + "/";
System.out.println("filter:");
System.out.println(uri);
Map<String, Object> session = ActionContext.getContext().getSession();
// 访问非登陆页面 且 未登录
if (!uri.contains( "login" ) && session.get( "loginUserAccount" ) == null) {
response.sendRedirect( root + "login.jsp" );
return;
}
// 访问登陆页面 且 已登录
if (uri.contains( "login" ) && session.get( "loginUserAccount" ) != null) {
int roleId = (int) session.get( ROLE_ID.toString() );
if (roleId == 1) {
response.sendRedirect( root + "admin/admin_teacher.jsp" );
} else if (roleId == 2) {
response.sendRedirect( root + "teacher/index.jsp" );
} else if (roleId == 3){
response.sendRedirect( root + "student/index.jsp" );
}
return;
}
if (uri.contains( "admin" )) {
int roleId = (int) session.get( ROLE_ID.toString() );
if (roleId != 1) {
response.sendRedirect( root + "error.jsp" );
return;
}
} else if (uri.contains( "teacher" )) {
System.out.println("teacher");
int roleId = (int) session.get( ROLE_ID.toString() );
if (roleId != 2) {
response.sendRedirect( root + "error.jsp" );
return;
}
} else if (uri.contains( "student" )) {
System.out.println("student");
int roleId = (int) session.get( ROLE_ID.toString() );
if (roleId != 3) {
response.sendRedirect( root + "error.jsp" );
return;
}
}
filterChain.doFilter( request, response );
}
@Override
public void destroy() {
}
}
<file_sep>package com.haya.interceptor;
import com.haya.bean.VALUE;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import static com.haya.bean.VALUE.LOGIN_USER_ACCOUNT;
import static com.haya.bean.VALUE.ROLE_ID;
/**
* @author haya
*/
public class SessionInterceptor extends SuperInterceptor {
private final String loginPage = "login";
@Override
public String intercept(ActionInvocation invocation) throws Exception {
super.intercept( invocation );
if (loginPage.equals( ActionContext.getContext().getName() )) {
return invocation.invoke();
}
if (session.get( LOGIN_USER_ACCOUNT.toString() ) == null) {
return "error";
}
System.out.println( invocation.getProxy().getNamespace() );
if (invocation.getProxy().getNamespace().contains( "admin" )) {
int roleId = (int) session.get( ROLE_ID.toString() );
if (roleId != 1) {
return "error";
}
} else if ( invocation.getProxy().getNamespace().contains( "teacher" )) {
int roleId = (int) session.get( ROLE_ID.toString() );
if (roleId != 2) {
return "error";
}
} else if ( invocation.getProxy().getNamespace() .contains( "student" )) {
int roleId = (int) session.get( ROLE_ID.toString() );
if (roleId != 3) {
return "error";
}
}
return invocation.invoke();
}
}
<file_sep>hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true
jdbc.url=jdbc:mysql:///cjgl?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=<PASSWORD>
| 5e844ae247093ad31db58a302378f5cacb09a935 | [
"Java",
"INI"
] | 11 | Java | Hayaking/SSH | c6a537d9e10c6d718ae410466ff88443b8611328 | ee466fab5b331039e4c0c177d45c435224a9cc3c | |
refs/heads/master | <file_sep>
// basic setup
ENT.Type = "anim";
ENT.PrintName = "";
ENT.Author = "";
ENT.Contact = "";
ENT.Purpose = "";
ENT.Instructions = "";
ENT.Spawnable = false;
ENT.AdminSpawnable = false;
ENT.AutomaticFrameAdvance = true;
ENT.Model = "models/Humans/Group03/male_02.mdl";
// precache
util.PrecacheModel( ENT.Model );
<file_sep>Hoverboard
==========
Update of hoverboard addon for Garry's Mod 13.
This addon does not currently work.
Garry removed player:GetScriptedVehicle() - Currently looking into workaround
Credits:
* ab0mbs - Update to Gmod 13... in progress
* BobYD - Unknown
* Dav0r - Hackjob model
* SCopE5000 - Huvaboard model
* Jaanus - Stuntboard & True Hoverboard models
* Squint - Aperture HotRod and Gyro Board models
* cloud_strife - 3 SSX models<file_sep>
// hoverboard limit
CreateConVar( "sbox_maxhoverboards", 1, { FCVAR_NOTIFY, FCVAR_ARCHIVE } );
CreateConVar( "sv_hoverboard_adminonly", 0, { FCVAR_NOTIFY, FCVAR_ARCHIVE } );
CreateConVar( "sv_hoverboard_cansteal", 0, { FCVAR_NOTIFY, FCVAR_ARCHIVE } );
CreateConVar( "sv_hoverboard_canshare", 1, { FCVAR_NOTIFY, FCVAR_ARCHIVE } );
local points = CreateConVar( "sv_hoverboard_points", 45, { FCVAR_NOTIFY, FCVAR_ARCHIVE } );
timer.Create( "HoverPointsThink", 1, 0, function() SetGlobalInt( "HoverPoints", points:GetInt() ); end );
// downloads
resource.AddFile( "data/hoverboards.txt" );
resource.AddFile( "materials/modulus_hoverboard/glow.vmt" );
resource.AddFile( "materials/modulus_hoverboard/trail.vmt" );
resource.AddFile( "materials/modulus_hoverboard/deathicon.vmt" );
resource.AddFile( "materials/modulus_hoverboard/deathicon.vtf" );
<file_sep>
// setup
ENT.Base = "base_anim";
ENT.Type = "anim";
// unspawnable
ENT.Spawnable = false;
ENT.AdminSpawnable = false;
| 99fa743a2fa442a9ddd217958f2586f3b910b085 | [
"Markdown",
"Lua"
] | 4 | Lua | hoverboard-apps/hoverboard | e84fad3f1065372b02b7364d3ae1bc558a671fb6 | 25970c359acaa8e14d526ec28e782fe51ce99969 | |
refs/heads/master | <repo_name>linocontreras/paralell-drc<file_sep>/src/sequential/SequentialCompressor.java
/**
* Programación avanzada: Proyecto final
* Fecha: 2019-12-03
* Autor: A01700457 - <NAME>
*/
package sequential;
import java.io.*;
import java.nio.*;
public class SequentialCompressor {
double[] frames;
double threshold;
double ratio;
double gain;
public SequentialCompressor(double[] frames, double threshold, double ratio, double gain) {
this.frames = frames;
this.threshold = threshold;
this.ratio = ratio;
this.gain = gain;
}
public double[] compress() {
for (int i = 0; i < frames.length; i++) {
if (frames[i] == 0)
continue;
int sign = frames[i] < 0 ? -1 : 1;
frames[i] = frames[i] < 0 ? -frames[i] : frames[i];
frames[i] *= Math.log10(10 + this.gain);
if (frames[i] > threshold) {
frames[i] = threshold + ((frames[i] - threshold) * (1 / ratio));
}
frames[i] = frames[i] <= 1 ? frames[i] : 1;
frames[i] = frames[i] * sign;
}
return frames;
}
public static void main(String[] args) {
if (args.length != 4) {
PrintUsage();
System.exit(1);
}
File inputFile = new File(args[0]);
if (!inputFile.exists()) {
System.err.println("El archivo especificado no existe.");
System.exit(2);
}
double threshold = Double.parseDouble(args[1]);
if (threshold < 0 || threshold > 1) {
System.err.println("El threshold debe ser entre 0 y 1.");
System.exit(3);
}
double ratio = Double.parseDouble(args[2]);
if (ratio < 1) {
System.err.println("El ratio debe ser a partir de 1.");
System.exit(4);
}
double gain = Double.parseDouble(args[3]);
if (gain < 0) {
System.err.println("La ganancia debe ser mayor o igual a 0.");
System.exit(5);
}
try {
FileInputStream input = new FileInputStream(inputFile);
byte[] dataBytes = input.readAllBytes();
ByteBuffer dataBytesBuffer = ByteBuffer.wrap(dataBytes);//.order(ByteOrder.BIG_ENDIAN);
DoubleBuffer dataBuffer = DoubleBuffer.allocate(dataBytes.length / Double.BYTES);
double[] data = dataBuffer.put(dataBytesBuffer.asDoubleBuffer()).array();
input.close();
SequentialCompressor sc = new SequentialCompressor(data, threshold, ratio, gain);
System.out.println("SequentialCompressor Starting...");
long start = System.nanoTime();
double[] compressed = sc.compress();
System.out.println("Time elapsed: " + ((System.nanoTime() - start) / 1000000) + "ms");
String outputFilePath = args[0].substring(0, args[0].lastIndexOf("."));
FileOutputStream output = new FileOutputStream(new File(outputFilePath + ".cps"));
ByteBuffer compressedData = ByteBuffer.allocate(compressed.length * Double.BYTES);
compressedData.asDoubleBuffer().put(compressed);
output.write(compressedData.array());
output.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(100);
}
}
private static void PrintUsage() {
System.err.println("Usage: java sequential.SequentialCompressor file.frames threshold ratio gain");
}
}<file_sep>/src/tbb/tbbcompressor.cpp
/**
* Programación avanzada: Proyecto final
* Fecha: 2019-12-03
* Autor: A01700457 - <NAME>
*/
#include <iostream>
#include <cstring>
#include <tbb/task_scheduler_init.h>
#include <tbb/parallel_for.h>
#include <tbb/blocked_range.h>
#include "cppheader.h"
#include <cmath>
using namespace std;
using namespace tbb;
#define N 10
#define GRAIN 200
class Compressor {
private:
double *frames;
int size;
double threshold;
double ratio;
double gain;
public:
Compressor(double *frames, int size, double threshold, double ratio, double gain)
: frames(frames), size(size), threshold(threshold), ratio(ratio), gain(gain) {}
void operator()
(const blocked_range<int> &r) const {
int sign;
for (int i = r.begin(); i != r.end(); i++) {
if (frames[i] == 0)
continue;
sign = frames[i] < 0 ? -1 : 1;
frames[i] = frames[i] < 0 ? -frames[i] : frames[i];
frames[i] *= log10(10 + gain);
if (frames[i] > threshold) {
frames[i] = threshold + ((frames[i] - threshold) * (1 / ratio));
}
frames[i] = frames[i] <= 1 ? frames[i] : 1;
frames[i] = frames[i] * sign;
}
}
};
void printUsage(char *program) {
printf("Usage: %s file.frames threshold ratio gain\n", program);
}
typedef union
{
double d;
unsigned char s[8];
} Union_t;
// reverse little to big endian or vice versa as per requirement
double reverse_endian(double in)
{
int i, j;
unsigned char t;
Union_t val;
val.d = in;
// swap MSB with LSB etc.
for(i=0, j=7; i < j; i++, j--)
{
t = val.s[i];
val.s[i] = val.s[j];
val.s[j] = t;
}
return val.d;
}
int main(int argc, char* argv[]) {
if (argc != 5) {
printUsage(argv[0]);
return 1;
}
FILE *file = fopen(argv[1], "rb");
if (file == NULL) {
perror(argv[0]);
return 2;
}
double threshold = strtod(argv[2], NULL);
if (threshold < 0 || threshold > 1) {
fprintf(stderr, "El threshold debe ser entre 0 y 1.");
return 3;
}
double ratio = strtod(argv[3], NULL);
if (ratio < 1) {
fprintf(stderr, "El ratio debe ser a partir de 1.");
return 4;
}
double gain = strtod(argv[4], NULL);
if (gain < 0) {
fprintf(stderr, "La ganancia debe ser mayor o igual a 0.");
return 5;
}
fseek(file, 0L, SEEK_END);
int size = ftell(file) / sizeof (double);
rewind(file);
double *frames = new double[size * sizeof *frames];
fread(frames, sizeof *frames, size, file);
int i;
for (i = 0;i < size; i++) {
frames[i] = reverse_endian(frames[i]);
}
Timer t;
double ms = 0;
printf("Starting TBB...\n");
for (int i = 0; i < N; i++) {
t.start();
parallel_for(
blocked_range<int>(0, size, GRAIN),
Compressor(frames, size, threshold, ratio, gain));
ms += t.stop();
}
printf("Elapsed time: %lf ms.\n", (ms /N));
char newpath[FILENAME_MAX];
int lastindex = strrchr(argv[1], '.') - argv[1];
strcpy(newpath, argv[1]);
strcpy(newpath + lastindex, ".cps");
FILE *newfile = fopen(newpath, "wb");
for (i = 0;i < size; i++) {
frames[i] = reverse_endian(frames[i]);
}
fwrite(frames, sizeof *frames, size, newfile);
delete[] frames;
fclose(file);
fclose(newfile);
return 0;
}
<file_sep>/README.md
# Compresor de rango dinámico para archivos wav
Implementación con diferentes tecnologías de una paralelización del algoritmo de compresión de rango dinámico.
## Librerías de terceros
Para la lectura y escritura de los archivos de audio se ha utilizado una librería obtenida de aquí: [http://www.labbookpages.co.uk](http://www.labbookpages.co.uk).
## Build
Para generar los archivos executables ejecuta el programa ```make```
<file_sep>/src/copenmp/copenmp.c
/**
* Programación avanzada: Proyecto final
* Fecha: 2019-12-03
* Autor: A01700457 - <NAME>
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <omp.h>
#include <string.h>
struct timeval startTime, stopTime;
int started = 0;
void start_timer() {
started = 1;
gettimeofday(&startTime, NULL);
}
double stop_timer() {
long seconds, useconds;
double duration = -1;
if (started) {
gettimeofday(&stopTime, NULL);
seconds = stopTime.tv_sec - startTime.tv_sec;
useconds = stopTime.tv_usec - startTime.tv_usec;
duration = (seconds * 1000.0) + (useconds / 1000.0);
started = 0;
}
return duration;
}
typedef union
{
double d;
unsigned char s[8];
} Union_t;
// reverse little to big endian or vice versa as per requirement
double reverse_endian(double in)
{
int i, j;
unsigned char t;
Union_t val;
val.d = in;
// swap MSB with LSB etc.
for(i=0, j=7; i < j; i++, j--)
{
t = val.s[i];
val.s[i] = val.s[j];
val.s[j] = t;
}
return val.d;
}
void compress(double *frames, int size, double threshold, double ratio, double gain) {
int i, sign;
#pragma omp parallel for shared(frames, threshold, ratio, gain) private(sign)
for (i = 0; i < size; i++) {
if (frames[i] == 0)
continue;
sign = frames[i] < 0 ? -1 : 1;
frames[i] = frames[i] < 0 ? -frames[i] : frames[i];
frames[i] *= log10(10 + gain);
if (frames[i] > threshold) {
frames[i] = threshold + ((frames[i] - threshold) * (1 / ratio));
}
frames[i] = frames[i] <= 1 ? frames[i] : 1;
frames[i] = frames[i] * sign;
}
}
void printUsage(char *program) {
printf("Usage: %s file.frames threshold ratio gain\n", program);
}
int main(int argc, char **argv) {
if (argc != 5) {
printUsage(argv[0]);
return 1;
}
FILE *file = fopen(argv[1], "rb");
if (file == NULL) {
perror(argv[0]);
return 2;
}
double threshold = strtod(argv[2], NULL);
if (threshold < 0 || threshold > 1) {
fprintf(stderr, "El threshold debe ser entre 0 y 1.");
return 3;
}
double ratio = strtod(argv[3], NULL);
if (ratio < 1) {
fprintf(stderr, "El ratio debe ser a partir de 1.");
return 4;
}
double gain = strtod(argv[4], NULL);
if (gain < 0) {
fprintf(stderr, "La ganancia debe ser mayor o igual a 0.");
return 5;
}
fseek(file, 0L, SEEK_END);
int size = ftell(file) / sizeof (double);
rewind(file);
double *frames = malloc(size * sizeof *frames);
fread(frames, sizeof *frames, size, file);
int i;
for (i = 0;i < size; i++) {
frames[i] = reverse_endian(frames[i]);
}
start_timer();
double ms;
printf("Starting OpenMP...\n");
compress(frames, size, threshold, ratio, gain);
ms = stop_timer();
printf("Elapsed time: %lf ms.\n", ms);
char newpath[FILENAME_MAX];
int lastindex = strrchr(argv[1], '.') - argv[1];
strcpy(newpath, argv[1]);
strcpy(newpath + lastindex, ".cps");
FILE *newfile = fopen(newpath, "wb");
for (i = 0;i < size; i++) {
frames[i] = reverse_endian(frames[i]);
}
fwrite(frames, sizeof *frames, size, newfile);
free(frames);
fclose(file);
fclose(newfile);
return 0;
}<file_sep>/src/tbb/cppheader.h
/**
* Programación avanzada: Proyecto final
* Fecha: 2019-12-03
* Autor: A01700457 - <NAME>
* Archivo compartido por el profesor durante la clase.
*/
#ifndef TIMER_H
#define TIMER_H
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <sys/time.h>
#include <sys/types.h>
const int N = 10;
class Timer {
private:
timeval startTime;
bool started;
public:
Timer() :started(false) {}
void start(){
started = true;
gettimeofday(&startTime, NULL);
}
double stop(){
timeval endTime;
long seconds, useconds;
double duration = -1;
if (started) {
gettimeofday(&endTime, NULL);
seconds = endTime.tv_sec - startTime.tv_sec;
useconds = endTime.tv_usec - startTime.tv_usec;
duration = (seconds * 1000.0) + (useconds / 1000.0);
started = false;
}
return duration;
}
};
#endif
<file_sep>/src/parser/ExtractFrames.java
/**
* Programación avanzada: Proyecto final
* Fecha: 2019-12-03
* Autor: A01700457 - <NAME>
*/
package parser;
import java.io.*;
import java.nio.ByteBuffer;
public class ExtractFrames {
private WavFile wav;
public ExtractFrames(String inputFile) throws WavFileException, IOException {
this.wav = WavFile.openWavFile(new File(inputFile));
}
public ByteBuffer extract() throws WavFileException, IOException {
ByteBuffer data = ByteBuffer.allocate((int) wav.getNumFrames() * wav.getNumChannels() * Double.BYTES);
this.wav.readFrames(data.asDoubleBuffer(), (int)wav.getNumFrames() * wav.getNumChannels());
return data;
}
public void close() throws IOException
{
this.wav.close();
}
public static void main(String[] args) {
if (args.length != 1) {
PrintUsage();
System.exit(1);
}
try {
ExtractFrames extractFrames = new ExtractFrames(args[0]);
ByteBuffer data = extractFrames.extract();
extractFrames.close();
DataOutputStream out = new DataOutputStream(new FileOutputStream(args[0] + ".frames"));
out.write(data.array());
out.close();
} catch(Exception ex) {
System.err.println("Ha ocurrido un error al intentar extraer los frames.");
System.err.print(ex);
ex.printStackTrace();
System.exit(2);
}
}
private static void PrintUsage() {
System.out.println("Usage: java parser.ExtractFrames audiofile.wav");
}
}<file_sep>/Makefile
all: Parser SequentialCompressor ThreadsCompressor FJCompressor CSequentialCompressor TBBCompressor
Parser:
javac -d ./bin ./src/parser/*
SequentialCompressor: Parser
javac -d ./bin ./src/sequential/*
ThreadsCompressor: Parser
javac -d ./bin ./src/threads/*
FJCompressor: Parser
javac -d ./bin ./src/forkjoin/*
CSequentialCompressor: Parser
gcc -o ./bin/csequential ./src/csequential/csequential.c -lm -ggdb -Wall
COpenMPCompressor: Parser
gcc -o ./bin/copenmp ./src/copenmp/copenmp.c -lm -Wall -fopenmp
TBBCompressor: Parser
gcc -o ./bin/tbbcompressor ./src/tbb/tbbcompressor.cpp -lm -Wall -ltbb | cd9e799538bef0766331670815631e73e9bf4b7e | [
"Markdown",
"Makefile",
"Java",
"C",
"C++"
] | 7 | Java | linocontreras/paralell-drc | ed1458efdb8ebe1f9b700e4c06f391f9e2118c1b | 2b5ce0464b13487bf2989d25362198701c04cd5d | |
refs/heads/master | <repo_name>GuysFromLab/GuysFromLab.github.io<file_sep>/README.md
# GuysFromLab
Our official website
## Projects
<file_sep>/js/preloader.js
$(document).ready(function () {
jQuery(window).load(function () {
// fade out the load-screen
jQuery(".loader").fadeOut();
// fade out <div> that covers the website.
jQuery(".preloader").delay(1000).fadeOut("slow");
});
});
| 2f435561ce1d3ad5f8cd3b973084ca318c859606 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | GuysFromLab/GuysFromLab.github.io | cfadbb0d7f8e89b603aa69d1a3a632339d8fc511 | 76cc8ba14ff4771039bd4f6176e242172301bc14 | |
refs/heads/main | <repo_name>Piyush-syst/FirstProjGitiOS<file_sep>/Podfile
platform :ios, '8.1'
target "FirstProj" do
pod 'Firebase'
pod 'Firebase/Messaging'
pod 'Firebase/Analytics'
pod 'Firebase/Crashlytics'
pod 'Firebase/Crashlytics'
pod 'GoogleSignIn'
pod 'FBSDKLoginKit'
pod 'FBSDKCoreKit'
pod 'Branch'
end
<file_sep>/File.swift
//
// File.swift
// FirstProj
//
// Created by macmini39 on 07/10/20.
//
import Foundation
| c0d3b30b496dca4814b3f5a5e62b48305e0b958d | [
"Swift",
"Ruby"
] | 2 | Ruby | Piyush-syst/FirstProjGitiOS | eaca7ca450b5b299fb92ab1060f54a5d525e118d | 53d3af2a3e833fe663a8f83bf9ed60af9b099a43 | |
refs/heads/master | <repo_name>gzharun/SFND_Lidar_Obstacle_Detection<file_sep>/src/render/box.h
#ifndef BOX_H
#define BOX_H
#include <Eigen/Geometry>
struct BoxQ
{
Eigen::Vector3f bboxTransform;
Eigen::Quaternionf bboxQuaternion;
float cube_length;
float cube_width;
float cube_height;
float volume()
{
return cube_length * cube_width * cube_height;
}
};
struct Box
{
float x_min;
float y_min;
float z_min;
float x_max;
float y_max;
float z_max;
float volume()
{
return (x_max - x_min) * (y_max - y_min) * (z_max - z_min);
}
};
#endif<file_sep>/src/processPointClouds.cpp
// PCL lib Functions for processing point clouds
#include "processPointClouds.h"
#include "kdtree.h"
namespace {
template<typename PointT>
void proximity(typename pcl::PointCloud<PointT>::Ptr cloud, int idx, std::vector<uint8_t>& processed,
KdTree<PointT>* tree, float distanceTol, pcl::PointIndices& cluster)
{
processed[idx] = 1;
cluster.indices.push_back(idx);
std::vector<int> found = tree->search(cloud->points[idx], distanceTol);
for (size_t i = 0; i < found.size(); ++i) {
if (processed[found[i]])
continue;
proximity(cloud, found[i], processed, tree, distanceTol, cluster);
}
}
}
template<typename PointT>
std::vector<typename pcl::PointCloud<PointT>::Ptr> ProcessPointClouds<PointT>::Clustering(typename pcl::PointCloud<PointT>::Ptr cloud, float distanceTol, int minSize, int maxSize)
{
// Time clustering process
auto startTime = std::chrono::steady_clock::now();
auto tree = new KdTree<PointT>();
tree->build(cloud);
std::vector<pcl::PointIndices> clusters;
const size_t n = cloud->points.size();
std::vector<uint8_t> processed(n, 0);
for (size_t i = 0; i < n; ++i)
{
if (processed[i])
continue;
pcl::PointIndices cluster;
proximity(cloud, i, processed, tree, distanceTol, cluster);
if (cluster.indices.size() >= minSize && cluster.indices.size() <= maxSize)
clusters.emplace_back(std::move(cluster));
}
std::vector<typename pcl::PointCloud<PointT>::Ptr> cloudClusters;
for (auto it = clusters.begin(); it != clusters.end(); ++it)
{
typename pcl::PointCloud<PointT>::Ptr cloudCluster (new pcl::PointCloud<PointT>);
for (auto pit = it->indices.begin(); pit != it->indices.end(); ++pit)
{
cloudCluster->points.push_back(cloud->points[*pit]);
}
cloudCluster->width = cloudCluster->points.size();
cloudCluster->height = 1;
cloudCluster->is_dense = true;
cloudClusters.emplace_back(std::move(cloudCluster));
}
auto endTime = std::chrono::steady_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
std::cout << "clustering took " << elapsedTime.count() << " milliseconds and found " << clusters.size() << " clusters" << std::endl;
return cloudClusters;
}
//constructor:
template<typename PointT>
ProcessPointClouds<PointT>::ProcessPointClouds() {}
//de-constructor:
template<typename PointT>
ProcessPointClouds<PointT>::~ProcessPointClouds() {}
template<typename PointT>
void ProcessPointClouds<PointT>::numPoints(typename pcl::PointCloud<PointT>::Ptr cloud)
{
std::cout << cloud->points.size() << std::endl;
}
template<typename PointT>
typename pcl::PointCloud<PointT>::Ptr ProcessPointClouds<PointT>::FilterCloud(typename pcl::PointCloud<PointT>::Ptr cloud, float filterRes, Eigen::Vector4f minPoint, Eigen::Vector4f maxPoint)
{
// Time filtering process
auto startTime = std::chrono::steady_clock::now();
typename pcl::PointCloud<PointT>::Ptr filteredCloud{new pcl::PointCloud<PointT>};
// Filter point cloud
pcl::VoxelGrid<PointT> sor;
sor.setInputCloud (cloud);
sor.setLeafSize (filterRes, filterRes, filterRes);
sor.filter (*filteredCloud);
// Crop the region of interest
pcl::CropBox<PointT> roi;
roi.setInputCloud(filteredCloud);
roi.setMin(minPoint);
roi.setMax(maxPoint);
roi.filter(*filteredCloud);
// Remove ego car points
const Eigen::Vector4f minPointCar = {-1.5f, -1.5f, -1.0f, 1.0f};
const Eigen::Vector4f maxPointCar = {2.7f, 1.5f, -0.4f, 1.0f};
pcl::PointIndices::Ptr carPoints (new pcl::PointIndices());
pcl::CropBox<PointT> roof;
roof.setInputCloud(filteredCloud);
roof.setMin(minPointCar);
roof.setMax(maxPointCar);
roof.setNegative(true);
roof.filter(*filteredCloud);
auto endTime = std::chrono::steady_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
std::cout << "filtering took " << elapsedTime.count() << " milliseconds" << std::endl;
return filteredCloud;
}
template<typename PointT>
std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> ProcessPointClouds<PointT>::SeparateClouds(pcl::PointIndices::Ptr inliers, typename pcl::PointCloud<PointT>::Ptr cloud)
{
// TODO: Create two new point clouds, one cloud with obstacles and other with segmented plane
typename pcl::PointCloud<PointT>::Ptr plainCloud{new pcl::PointCloud<PointT>};
typename pcl::PointCloud<PointT>::Ptr obstCloud{new pcl::PointCloud<PointT>};
// Extract the inliers
pcl::ExtractIndices<PointT> extract;
extract.setInputCloud (cloud);
extract.setIndices (inliers);
extract.setNegative (false);
extract.filter (*plainCloud);
// Create the filtering object
extract.setNegative (true);
extract.filter (*obstCloud);
std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> segResult(obstCloud, plainCloud);
return segResult;
}
template<typename PointT>
std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> ProcessPointClouds<PointT>::SegmentPlane(typename pcl::PointCloud<PointT>::Ptr cloud, int maxIterations, float distanceThreshold)
{
// Time segmentation process
auto startTime = std::chrono::steady_clock::now();
srand(time(NULL));
const size_t n = cloud->points.size();
std::vector<int> tmp;
tmp.reserve(n);
std::vector<int> inliersResult;
inliersResult.reserve(n);
// TODO: Fill in this function
// For max iterations
// Randomly sample subset and fit line
// Measure distance between every point and fitted line
// If distance is smaller than threshold count it as inlier
// Return indicies of inliers from fitted line with most inliers
for(int i = 0 ; i < maxIterations; ++i) {
// select three points
int p1 = std::rand() % n;
int p2 = p1, p3 = p1;
while (p1 == p2) {
p2 = std::rand() % n;
}
while (p3 == p1 || p3 == p2) {
p3 = std::rand() % n;
}
const auto & point1 = cloud->points[p1];
const auto & point2 = cloud->points[p2];
const auto & point3 = cloud->points[p3];
const float x1 = point1.x, x2 = point2.x, x3 = point3.x;
const float y1 = point1.y, y2 = point2.y, y3 = point3.y;
const float z1 = point1.z, z2 = point2.z, z3 = point3.z;
const float a = (y2 - y1)*(z3 - z1) - (z2 - z1)*(y3 - y1);
const float b = (z2 - z1)*(x3 - x1) - (x2 - x1)*(z3 - z1);
const float c = (x2 - x1)*(y3 - y1) - (y2 - y1)*(x3 - x1);
const float d = -(a*x1 + b*y1 + c*z1);
const float norm = std::sqrt(a*a + b*b + c*c);
//std::cout << "Norm: " << norm << std::endl;
tmp.clear();
for (size_t j = 0; j < cloud->points.size(); ++j) {
const auto& point = cloud->points[j];
const float dist = std::abs(a*point.x + b*point.y + c*point.z + d) / norm;
if (dist <= distanceThreshold) {
//std::cout << "Dist: " << dist << std::endl;
tmp.push_back(j);
}
}
if (tmp.size() > inliersResult.size()) {
swap(inliersResult, tmp);
}
}
pcl::PointIndices::Ptr inliers (new pcl::PointIndices());
inliers->indices = std::move(inliersResult);
auto endTime = std::chrono::steady_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
std::cout << "plane segmentation took " << elapsedTime.count() << " milliseconds" << std::endl;
std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> segResult = SeparateClouds(inliers,cloud);
return segResult;
}
template<typename PointT>
std::vector<typename pcl::PointCloud<PointT>::Ptr> ProcessPointClouds<PointT>::ClusteringPCL(typename pcl::PointCloud<PointT>::Ptr cloud, float clusterTolerance, int minSize, int maxSize)
{
// Time clustering process
auto startTime = std::chrono::steady_clock::now();
std::vector<typename pcl::PointCloud<PointT>::Ptr> clusters;
// TODO:: Fill in the function to perform euclidean clustering to group detected obstacles
typename pcl::search::KdTree<PointT>::Ptr tree (new pcl::search::KdTree<PointT>);
tree->setInputCloud (cloud);
std::vector<pcl::PointIndices> cluster_indices;
pcl::EuclideanClusterExtraction<PointT> ec;
ec.setClusterTolerance(clusterTolerance);
ec.setMinClusterSize(minSize);
ec.setMaxClusterSize(maxSize);
ec.setSearchMethod(tree);
ec.setInputCloud(cloud);
ec.extract (cluster_indices);
for (auto it = cluster_indices.begin(); it != cluster_indices.end(); ++it)
{
typename pcl::PointCloud<PointT>::Ptr cloud_cluster (new pcl::PointCloud<PointT>);
for (auto pit = it->indices.begin(); pit != it->indices.end(); ++pit)
{
cloud_cluster->points.push_back(cloud->points[*pit]);
}
cloud_cluster->width = cloud_cluster->points.size();
cloud_cluster->height = 1;
cloud_cluster->is_dense = true;
clusters.emplace_back(std::move(cloud_cluster));
}
auto endTime = std::chrono::steady_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
std::cout << "clustering took " << elapsedTime.count() << " milliseconds and found " << clusters.size() << " clusters" << std::endl;
return clusters;
}
template<typename PointT>
Box ProcessPointClouds<PointT>::BoundingBox(typename pcl::PointCloud<PointT>::Ptr cluster)
{
// Find bounding box for one of the clusters
PointT minPoint, maxPoint;
pcl::getMinMax3D(*cluster, minPoint, maxPoint);
Box box;
box.x_min = minPoint.x;
box.y_min = minPoint.y;
box.z_min = minPoint.z;
box.x_max = maxPoint.x;
box.y_max = maxPoint.y;
box.z_max = maxPoint.z;
return box;
}
template<typename PointT>
BoxQ ProcessPointClouds<PointT>::BoundingBoxQ(typename pcl::PointCloud<PointT>::Ptr cluster)
{
const bool EXPERIMENTAL_BASIS_ROTATION = false;
// PCA
Eigen::Vector4f pcaCentroid;
pcl::compute3DCentroid(*cluster, pcaCentroid);
Eigen::Matrix3f covariance;
computeCovarianceMatrixNormalized(*cluster, pcaCentroid, covariance);
if (!EXPERIMENTAL_BASIS_ROTATION)
{
covariance.col(2) << 0, 0, 1;
covariance.row(2) << 0, 0, 1;
}
Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigen_solver(covariance, Eigen::ComputeEigenvectors);
Eigen::Matrix3f eigenVectorsPCA = eigen_solver.eigenvectors();
if (EXPERIMENTAL_BASIS_ROTATION)
{
// ****************** Experimental code *****************
// Let's experiment with basis rotation, setting z covariance of covarience matrix to 0 and z var to 1 is trivial
// How to ignore z rotation.
// First rearrange eigen vector matrix
// e3 vector will be a vector with max Z coordinate
// We want to project e1 and e2 on XY plane, so if one of them has max Z we should swap it with e3
// However we should avoid flipping ove XY plane.
// Thus if e3 z coordinate is negative e3 will be multiplied by -1, this is easier to code I suppose.
// We will restore the basis right hand property after rotation.
Eigen::Vector3f::Index idx;
eigenVectorsPCA.row(2).cwiseAbs().maxCoeff(&idx);
Eigen::Vector3f tmp = eigenVectorsPCA.col(idx);
eigenVectorsPCA.col(idx) = eigenVectorsPCA.col(2);
eigenVectorsPCA.col(2) = tmp;
if (eigenVectorsPCA.row(2)[2] < 0)
eigenVectorsPCA.row(2) = eigenVectorsPCA.row(2) * (-1);
// We need to rotate basis so that e3 become collinear with z
// x axis rotation
const float y = eigenVectorsPCA.col(2)[1];
const float z1 = eigenVectorsPCA.col(2)[2];
const float norm1 = std::sqrt(y * y + z1 * z1);
Eigen::Matrix3f xAxisRot;
xAxisRot << 1, 0, 0,
0, z1/norm1, -y/norm1,
0, y/norm1, z1/norm1;
eigenVectorsPCA = xAxisRot * eigenVectorsPCA;
// y axis rotation
const float x = eigenVectorsPCA.col(2)[0];
const float z2 = eigenVectorsPCA.col(2)[2];
const float norm2 = std::sqrt(x * x + z2 * z2);
Eigen::Matrix3f yAxisRot;
yAxisRot << z2/norm2, 0, -x/norm2,
0, 1, 0,
x/norm2, 0, z2/norm2;
eigenVectorsPCA = yAxisRot * eigenVectorsPCA;
// ******************** End of experimental code *****************
}
// Restore right hand property
eigenVectorsPCA.col(2) = eigenVectorsPCA.col(0).cross(eigenVectorsPCA.col(1));
// Form transformation matrix.
Eigen::Matrix4f projectionTransform(Eigen::Matrix4f::Identity());
projectionTransform.block<3,3>(0,0) = eigenVectorsPCA.transpose();
// Transform centroid coordinates
projectionTransform.block<3,1>(0,3) = -1.f * (projectionTransform.block<3,3>(0,0) * pcaCentroid.head<3>());
typename pcl::PointCloud<PointT>::Ptr cloudPointsProjected (new pcl::PointCloud<PointT>);
// Transform the original cloud.
pcl::transformPointCloud(*cluster, *cloudPointsProjected, projectionTransform);
// Get the minimum and maximum points of the transformed cloud.
PointT minPoint, maxPoint;
pcl::getMinMax3D(*cloudPointsProjected, minPoint, maxPoint);
BoxQ box;
box.cube_length = maxPoint.x - minPoint.x;
box.cube_width = maxPoint.y - minPoint.y;
box.cube_height = maxPoint.z - minPoint.z;
// Bbox quaternion and transforms
box.bboxQuaternion = Eigen::Quaternionf(eigenVectorsPCA);
const Eigen::Vector3f meanDiagonal = 0.5f*(maxPoint.getVector3fMap() + minPoint.getVector3fMap());
box.bboxTransform = eigenVectorsPCA * meanDiagonal + pcaCentroid.head<3>();
return box;
}
template<typename PointT>
void ProcessPointClouds<PointT>::savePcd(typename pcl::PointCloud<PointT>::Ptr cloud, std::string file)
{
pcl::io::savePCDFileASCII (file, *cloud);
std::cerr << "Saved " << cloud->points.size () << " data points to "+file << std::endl;
}
template<typename PointT>
typename pcl::PointCloud<PointT>::Ptr ProcessPointClouds<PointT>::loadPcd(std::string file)
{
typename pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT>);
if (pcl::io::loadPCDFile<PointT> (file, *cloud) == -1) //* load the file
{
PCL_ERROR ("Couldn't read file \n");
}
std::cerr << "Loaded " << cloud->points.size () << " data points from "+file << std::endl;
return cloud;
}
template<typename PointT>
std::vector<boost::filesystem::path> ProcessPointClouds<PointT>::streamPcd(std::string dataPath)
{
std::vector<boost::filesystem::path> paths(boost::filesystem::directory_iterator{dataPath}, boost::filesystem::directory_iterator{});
// sort files in accending order so playback is chronological
sort(paths.begin(), paths.end());
return paths;
}<file_sep>/src/kdtree.h
/* \author <NAME> */
// Quiz on implementing kd tree
#include "render/render.h"
// Structure to represent node of kd tree
template<typename PointT>
struct Node
{
PointT point;
int id;
Node* left;
Node* right;
Node(PointT arr, int setId)
: point(arr), id(setId), left(NULL), right(NULL)
{}
};
template<typename PointT, size_t dim = 3>
struct KdTree
{
Node<PointT>* root;
KdTree()
: root(NULL)
{}
void build(typename pcl::PointCloud<PointT>::Ptr cloud)
{
std::srand(std::time(nullptr));
const size_t n = cloud->points.size();
std::vector<int> indices(n, 0);
std::iota(indices.begin(), indices.end(), 0);
// shuffle
for (int i = 0; i < n; ++i) {
std::swap(indices[i], indices[i + rand() % (n - i)]);
}
build(root, cloud, indices, 0, n, 0);
}
void insert(const PointT& point, int id)
{
insert(root, point, id, 0);
}
// return a list of point ids in the tree that are within distance of target
std::vector<int> search(const PointT& target, float distanceTol)
{
std::vector<int> ids;
search(root, target, ids, distanceTol, 0);
return ids;
}
private:
int rand_median(typename pcl::PointCloud<PointT>::Ptr cloud, int coord, std::vector<int>& indices, int st, int end, int i) {
if (st == end - 1) {
return st;
}
int x = cloud->points[indices[end-1]].data[coord];
int pos = st;
for (int i = st; i < end-1; ++i) {
if (cloud->points[indices[i]].data[coord] <= x) {
std::swap(indices[i], indices[pos]);
++pos;
}
}
std::swap(indices[end-1], indices[pos]);
int k = pos - st;
if (i == k) {
return pos;
} else if (i < k) {
return rand_median(cloud, coord, indices, st, pos, i);
} else {
return rand_median(cloud, coord, indices, pos + 1, end, i - k - 1);
}
}
void build(Node<PointT>*& node, typename pcl::PointCloud<PointT>::Ptr cloud, std::vector<int>& indices, int st, int end, int depth)
{
if (st == end) {
return;
}
const int median = rand_median(cloud, depth % dim, indices, st, end, (end - st) / 2);
const int id = indices[median];
node = new Node<PointT>(cloud->points[id], id);
build(node->left, cloud, indices, st, median, depth + 1);
build(node->right, cloud, indices, median + 1, end, depth + 1);
}
void insert(Node<PointT>*& node, const PointT& point, int id, int depth)
{
const int idx = depth % dim;
if (node == nullptr)
{
node = new Node<PointT>(point, id);
}
else if (point.data[idx] < node->point.data[idx])
{
insert(node->left, point, id, depth + 1);
}
else
{
insert(node->right, point, id, depth + 1);
}
}
void search(Node<PointT>* node, const PointT& target, std::vector<int>& ids, float distanceTol, int depth)
{
if (node == nullptr)
return;
bool check = true;
for (size_t i = 0; check && i < dim; ++i) {
check = check &&
target.data[i] + distanceTol >= node->point.data[i] &&
target.data[i] - distanceTol <= node->point.data[i];
}
if (check && dist(target, node->point) <= distanceTol)
{
ids.push_back(node->id);
}
const int idx = depth % dim;
if (target.data[idx] - distanceTol < node->point.data[idx])
{
search(node->left, target, ids, distanceTol, depth + 1);
}
if (target.data[idx] + distanceTol > node->point.data[idx])
{
search(node->right, target, ids, distanceTol, depth + 1);
}
}
float dist(const PointT& p1, const PointT& p2) {
float res = 0.0f;
for (int i = 0; i < dim; ++i)
{
res += (p1.data[i] - p2.data[i]) * (p1.data[i] - p2.data[i]);
}
return std::sqrt(res);
}
};
| ca51f75055e7de31b3e51190b3ebeac904490de2 | [
"C",
"C++"
] | 3 | C | gzharun/SFND_Lidar_Obstacle_Detection | 25dcc73590739d5a9ab494fe2bbc2d76518652a3 | 772429a7590a1d4b0d5931e39d36feba75b65409 | |
refs/heads/master | <repo_name>dgdagadin87/test_redux<file_sep>/resources/js/service/reducers.jsx
import {combineReducers} from 'redux';
import application from '../reducers/application';
import books from '../reducers/books';
import errors from '../reducers/errors';
const allReducers = combineReducers({
commonData: application,
booksData: books,
errorsData: errors
});
export default allReducers;<file_sep>/resources/js/core/coreUtils.js
function isEmpty(value){
if (value === null || value === '' || value === undefined ){
return true;
}
else {
return false;
}
}
function emptyFunction () {
return;
}
function checkEmail (value) {
return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value);
}
function applyParams (object, config) {
let property;
if (object) {
for (property in config) {
object[property] = config[property];
}
}
return object;
}
function createUrl (settings, url) {
return settings['serverProtocol'] + '://' + settings['serverHost'] + ':' + settings['serverPort'] + url;
}
export {isEmpty, createUrl, applyParams, emptyFunction, checkEmail};<file_sep>/resources/js/actions/errors.jsx
export const cleanErrors = (errorsData) => {
return {
type: 'ERRORS_CLEAN',
payload: errorsData
}
};<file_sep>/resources/js/config/settings.js
let defaultSettings = {
'serverHost' : '127.0.0.1',
'serverPort': 9001,
'serverProtocol': 'http'
};
let pageSettings = {
'start' : 1,
'end': 1,
'left': 2,
'right': 2
};
let urlSettings = {
'getCommonData' : '/common',
'getBooksData' : '/mybooks',
'sendToMail' : '/sendtomail/',
'deleteMyBook' : '/deletebook/'
};
export {defaultSettings, pageSettings, urlSettings};<file_sep>/resources/js/components/rootComponents/ErrorsModalComponent.jsx
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import { connect } from 'react-redux';
import {cleanErrors} from '../../actions/errors';
const mapStateToProps = state => {
return {
errors: state.errorsData.errors
}
};
function matchDispatchToProps(dispatch) {
return bindActionCreators({
cleanErrors: cleanErrors
}, dispatch);
}
class Errors extends Component {
_onClickHandler() {
const {cleanErrors} = this.props;
cleanErrors(null);
}
_renderErrorTemplate(error, index) {
const errorText = !!error ? error : 'Неизвестная ошика';
return (
<div key={index}>{errorText}</div>
);
}
render () {
const {errors = []} = this.props;
if (errors.length > 0) {
return (
<div>
{errors.map((error, index) => this._renderErrorTemplate(error, index))}
<button onClick={this._onClickHandler.bind(this)}>Закрыть</button>
</div>
);
return errors
}
else {
return null;
}
}
}
export default connect(mapStateToProps, matchDispatchToProps)(Errors);<file_sep>/resources/js/components/moduleComponents/HomeComponent.jsx
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {setTitle} from '../../actions/application';
const mapStateToProps = () => {
return {};
};
function matchDispatchToProps(dispatch) {
return bindActionCreators({
setTitle: setTitle
}, dispatch);
}
class Home extends Component {
componentDidMount() {
console.log(this.props);
let {setTitle} = this.props;
setTitle('Домашняя страница');
}
render () {
return (
<div>Домашняя страница</div>
);
}
}
export default connect(mapStateToProps, matchDispatchToProps)(Home);<file_sep>/resources/js/reducers/books.jsx
const initialState = {
collection: false,
sortField: 'bookName',
sortType: 'ASC',
searchTerm: '',
page: 1,
pages: 1,
totalCount: 0,
disabled: false,
globalLoading: false
};
export default function (state = null, action) {
let {payload} = action;
let returnState = !!state ? state : initialState;
switch (action.type) {
case 'BOOKS_LIST_LOADED':
return {...payload, disabled: false, globalLoading: false};
case 'START_BOOKS_LOADING':
return {...returnState, ...payload, disabled: true, globalLoading: false};
case 'START_BOOKS_GLOBAL_LOADING':
return {...returnState, ...payload, disabled: false, globalLoading: true};
case 'ERROR_BOOKS_LOADING':
return {...returnState, disabled: false, globalLoading: false};
default:
return returnState;
}
}<file_sep>/resources/js/actions/application.jsx
export const loadApplication = (appData) => {
return {
type: 'APP_COMMON_LOAD',
payload: appData
}
};
export const setTitle = (headerData) => {
return {
type: 'APP_SET_HEADER',
payload: headerData
}
};
export const errorAppLoading = (appData) => {
return {
type: 'ERROR_APP_LOADING',
payload: appData
}
};
export const errorDefaultLoading = (errorData) => {
return {
type: 'ERROR_DEFAULT_LOADING',
payload: errorData
}
};<file_sep>/resources/js/reducers/errors.jsx
const initialState = {
errors: []
};
export default function (state = null, action) {
let {payload} = action;
let returnState = !!state ? state : initialState;
switch (action.type) {
case 'ERROR_APP_LOADING':
case 'ERROR_DEFAULT_LOADING':
case 'ERROR_BOOKS_LOADING':
const {errorMessage = null} = payload;
const errors = returnState.errors || [];
const returnResult = {
errors: errors.concat([errorMessage])
};
return returnResult;
case 'ERRORS_CLEAN':
return initialState;
default:
return returnState;
}
}<file_sep>/resources/js/components/AppContainer.jsx
import '../../css/style.css';
import React, {Component} from 'react';
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
import { Route, Switch } from 'react-router-dom';
import Axios from 'axios';
import {loadApplication, errorAppLoading} from '../actions/application';
import {defaultSettings, urlSettings} from '../config/settings';
import {createUrl} from '../core/coreUtils';
import HeaderComponent from './rootComponents/Header';
import ErrorsComponent from './rootComponents/ErrorsModalComponent';
import HomeComponent from './moduleComponents/HomeComponent';
import BooksComponent from './moduleComponents/BooksComponent';
import AboutComponent from './moduleComponents/AboutComponent';
const mapStateToProps = state => {
return {
isLoaded: state.commonData.isLoaded,
appData: state.commonData.data,
title: state.commonData.title
}
};
function matchDispatchToProps(dispatch) {
return bindActionCreators({
loadApplication: loadApplication,
errorAppLoading: errorAppLoading
}, dispatch);
}
class AppContainer extends Component {
componentDidMount() {
const {loadApplication, errorAppLoading} = this.props;
Axios.get(createUrl(defaultSettings, urlSettings['getCommonData']))
.then( (response) => {
const {data : {data = {}}} = response;
loadApplication(Object.assign({data: data}, {isLoaded: true, title: 'Начало работы'}));
})
.catch((error) => {
const {message = ''} = error;
errorAppLoading({
errorMessage: message
});
});
}
render () {
const {isLoaded, appData, title} = this.props;
if (!isLoaded) {
return (
<div>
<div>Wait, application is loading...</div>
<ErrorsComponent />
</div>
);
}
return (
<div>
<HeaderComponent commonData={appData} title={title} />
<Switch>
<Route exact path="/" render={ (props) => <HomeComponent {...props} /> } />
<Route path="/books" render={ (props) => <BooksComponent{...props} /> } />
<Route path="/about" render={ (props) => <AboutComponent {...props} /> } />
</Switch>
<ErrorsComponent />
</div>
);
}
}
export default connect(mapStateToProps, matchDispatchToProps)(AppContainer); | c210d37feca641893c36f48148d3f937073f0f1b | [
"JavaScript"
] | 10 | JavaScript | dgdagadin87/test_redux | de604c6afa2ff473c5e4dde04f1385da402ac081 | 4bac9b6efb11cf24fd4bc6aac2dd1304353033b4 | |
refs/heads/master | <file_sep>"""
>>> A = [2, 3, -2, 4]
>>> max_product(A)
6
>>> A = [-7, -4, -2, 4]
>>> max_product(A)
28
>>> A = [2, 3]
>>> max_product(A)
6
>>> A = [2, 3, 9, 4]
>>> max_product(A)
36
>>> A = [-2, -3, -2, 0]
>>> max_product(A)
6
>>> A = [-2, -10, 2, 3, -2, 4, 20]
>>> max_product(A)
80
>>> A = [0, 0, 0, 0]
>>> max_product(A)
0
"""
def max_product(A):
if not A:
return
if len(A) == 1:
return A[0]
else:
max_prod = None
for ind in range(len(A)-1):
if A[ind] <= 0:
if A[ind+1] >= 0:
curr_prod = A[ind+1]
else:
curr_prod = A[ind] * A[ind+1]
else:
curr_prod = A[ind] * A[ind+1]
if curr_prod > max_prod:
max_prod = curr_prod
return max_prod
<file_sep># https://oj.leetcode.com/problems/palindrome-number/
import unittest
class Solution:
# @return a boolean
def isPalindrome(self, x):
return self.isPalindromeNumeric(x)
def isPalindromeNumeric(self, x):
# print "\n--------------\nx:{}\n".format(x)
i = 0
if(x<0 or (x % 10 == 0 and x != 0)):
return False
while (i < x):
i = i * 10 + x % 10
x = x / 10
# print "i: {0: >6}\t\tx: {1: >6}\t\ti/10: {2: >6}".format(i, x, i/10)
return (i == x or i/10 == x)
def isPalindromeAsStr(self, x):
# print "-------------------------"
if x < 0:
return False
elif x / 10 == 0:
return True
else:
return self.isPalindromeStrRec(str(x))
def isPalindromeStrRec(self, x):
#print x
l = len(x)
if not l or l == 1:
return True
if x[0] == x[-1]:
return self.isPalindromeStrRec(x[1:-1])
else:
return False
def isPalindromeNumericFail(self, x):
print "-------------------------"
if x < 0:
return False
if x / 10 == 0:
return True
pow10 = 0
tenx = x / 10
while tenx:
tenx = tenx / 10
pow10 += 1
mag = int(pow(10,pow10))
least = x % 10
most = x / mag
print "%d %d %d %d %d" % (x, pow10, mag, least, most)
if least == most:
new_x = (x / 10) - ((mag / 10) * (x / mag))
print "new_x = %d" % new_x
return self.isPalindrome(new_x)
else:
return False
def isPalindromeTooEasy(self, x):
return int(str(abs(x))[::-1]) == x
class TestSolution(unittest.TestCase):
def test_a1000021(self):
sln = Solution()
self.assertEqual(False, sln.isPalindrome(1000021))
def test_a1200021(self):
sln = Solution()
self.assertEqual(True, sln.isPalindrome(1202021))
def test_121(self):
sln = Solution()
self.assertEqual(True, sln.isPalindrome(121))
def test_11(self):
sln = Solution()
self.assertEqual(True, sln.isPalindrome(11))
def test_1(self):
sln = Solution()
self.assertEqual(True, sln.isPalindrome(1))
def test_1221(self):
sln = Solution()
self.assertEqual(True, sln.isPalindrome(1221))
def test_12521(self):
sln = Solution()
self.assertEqual(True, sln.isPalindrome(12521))
def test_12(self):
sln = Solution()
self.assertEqual(False, sln.isPalindrome(12))
def test_115(self):
sln = Solution()
self.assertEqual(False, sln.isPalindrome(115))
if __name__ == '__main__':
unittest.main()
<file_sep>"""
>>> from DataStruct import Node
>>> headC = Node(4)
>>> headC.next = Node(5)
>>> headC.next.next = Node(6)
>>> headA = Node(2)
>>> headA.next = Node(3)
>>> headA.next.next = headC
>>> headB = Node(1)
>>> headB.next = Node(2)
>>> headB.next.next = Node(3)
>>> headB.next.next.next = headC
>>> intersectNode = get_intersection_node(headA, headB)
>>> print intersectNode.val
4
>>> headA.next.next = None
>>> intersectNode = get_intersection_node(headA, headB)
>>> print intersectNode
None
"""
def get_intersection_node(headA, headB):
""" Intersection of Two Linked Lists """
# scan through for intersection and length of each linked list
cnt_a = 0
cnt_b = 0
node_a = headA
node_b = headB
while node_a or node_b:
if node_a == node_b:
return node_a
if node_a:
node_a = node_a.next
cnt_a += 1
if node_b:
node_b = node_b.next
cnt_b += 1
a_leads_by = cnt_b - cnt_a
# scan through for intersection by delaying the start through the
# shorter linked list
cnt_a = 0
cnt_b = 0
node_a = headA
node_b = headB
while node_a or node_b:
if node_a == node_b:
return node_a
if a_leads_by > 0:
# a leads b so have a wait
if cnt_a >= a_leads_by and node_a:
node_a = node_a.next
if node_b:
node_b = node_b.next
cnt_a += 1
cnt_b += 1
else:
# b leads a so have b wait
if node_a:
node_a = node_a.next
if cnt_b >= -a_leads_by and node_b:
node_b = node_b.next
cnt_a += 1
cnt_b += 1
if __name__ == "__main__":
import doctest
doctest.testmod()
<file_sep>"""
>>> plus_one([0])
[1]
>>> plus_one([9, 9, 9])
[1, 0, 0, 0]
"""
def plus_one(digits):
""" Plus One """
overflow = True
idx = 0
while overflow:
idx -= 1
if -idx > len(digits):
digits = [1] + digits
overflow = False
else:
digits[idx] += 1
if digits[idx] > 9:
digits[idx] = 0
else:
overflow = False
return digits
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>def testRemoveDuplicates():
case_1 = [1, 1, 4, 5, 6, 6, 6]
case_2 = [3, 9, 10]
assert removeDuplicates(case_1) == 4
# assert case_1 == [1, 4, 5, 6]
assert removeDuplicates(case_2) == 3
# assert case_2 == [3, 9, 10]
def removeDuplicates(A):
"""
for each element in the list do
if the current element is the same as last element in new list
do nothing
else
append the current element to new list
"""
new_list = []
for ind, val in enumerate(A):
if ind == 0:
new_list.append(val)
if ind > 0:
if val != new_list[-1]:
new_list.append(val)
print(new_list)
return(len(new_list))
def betterRemoveDuplicates(A):
"""
"""
testRemoveDuplicates()
<file_sep>import unittest
# https://oj.leetcode.com/problems/single-number/
class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
return reduce(lambda i,n: i^n, A, 0)
def singleNumberUsingForLoop(self, A):
i = 0
for n in A:
i ^= n
return i
class TestSolution(unittest.TestCase):
def test_one_three(self):
sln = Solution()
self.assertEqual(3, sln.singleNumber([1,1,2,2,3,4,4]))
def test_two_zeros(self):
sln = Solution()
self.assertEqual(4, sln.singleNumber([3,3,0,1,1,0,4]))
def test_one_zero(self):
sln = Solution()
self.assertEqual(0, sln.singleNumber([3,3,0,1,1,4,4]))
def test_neg_one(self):
sln = Solution()
self.assertEqual(-1, sln.singleNumber([3,3,-1,1,1,4,4]))
if __name__ == '__main__':
unittest.main()
<file_sep>"""
>>> search_range([1, 2, 4, 5, 7, 7, 7, 8, 8, 8], 8)
[7, 9]
>>> search_range([1, 2, 4, 5, 7, 7, 7, 8, 8, 8], 3)
[-1, -1]
"""
def midpoint(start, end):
return (end-start)/2 + start
def search_range(A, target):
""" Search for a Range """
# find a single target
ptr_l, ptr_r = -1, -1
imin, imax = 0, len(A)-1
while imax >= imin:
ptr = midpoint(imin, imax)
if A[ptr] == target:
ptr_l = ptr
ptr_r = ptr
break
elif A[ptr] > target:
imax = ptr-1
else:
imin = ptr+1
# search for neighboring targets if present
if ptr_l != -1 and ptr_r != -1:
at_beg = ptr_l == 0
while not at_beg:
if A[ptr_l-1] == target:
ptr_l -= 1
else:
break
at_beg = ptr_l == 0
at_end = ptr_r == len(A)-1
while not at_end:
if A[ptr_r+1] == target:
ptr_r += 1
else:
break
at_end = ptr_r == len(A)-1
return [ptr_l, ptr_r]
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>"""
>>> board = ["OOO","OOO","OOO"]
>>> solve(board)
>>> print board
['OOO', 'OOO', 'OOO']
>>> print board[0]
OOO
"""
def solve(board):
""" Surrounded Regions """
# search for "O" on border
# replace any neighboring "O" with "P"
# iterate until end of perimeter
# replace all "O" with "X"
# replace all "P" with "O"
# minimum size has to be 3 by 3
m = len(board)
if m <= 2:
return
n = len(board[0])
if n <= 2:
return
def tag_non_enclosed(board_in, curr_x, curr_y):
board_in[curr_x][curr_y] = "P"
try:
# check if you can move down
if curr_x-1 >= 0:
if board_in[curr_x-1][curr_y] == "O":
tag_non_enclosed(board_in, curr_x-1, curr_y)
except:
pass
try:
# check if you can move up
if curr_x+1 < len(board_in):
if board_in[curr_x+1][curr_y] == "O":
tag_non_enclosed(board_in, curr_x+1, curr_y)
except:
pass
try:
# check if you can move left
if curr_y-1 >= 0:
if board_in[curr_x][curr_y-1] == "O":
tag_non_enclosed(board_in, curr_x, curr_y-1)
except:
pass
try:
# check if you can move right
if curr_y+1 < len(board_in[0]):
if board_in[curr_x][curr_y+1] == "O":
tag_non_enclosed(board_in, curr_x, curr_y+1)
except:
pass
m_border = range(0, m)
n_border = range(0, n)
mn_border = [0, m-1, n-1, 0]
board[:] = [list(a) for a in board]
for border, mn_val in enumerate(mn_border):
# iterate on top, right, bottom, left border
along_m = border % 2 != 0
if along_m:
x = mn_val
for y in n_border:
if board[x][y] == "O":
tag_non_enclosed(board, x, y)
else:
y = mn_val
for x in m_border:
if board[x][y] == "O":
tag_non_enclosed(board, x, y)
for m_ind in range(m):
for n_ind in range(n):
if board[m_ind][n_ind] == "O":
board[m_ind][n_ind] = "X"
elif board[m_ind][n_ind] == "P":
board[m_ind][n_ind] = "O"
board[:] = ["".join(a) for a in board]
<file_sep>"""
>>> from DataStruct import Node
>>> head = Node(1)
>>> head.next = Node(2)
>>> head.next.next = Node(3)
>>> head.next.next.next = Node(4)
>>> head.next.next.next.next = Node(5)
>>> head = remove_nth_from_end(head, 5)
>>> print head.val, head.next.val, head.next.next.val, head.next.next.next.val
"""
def remove_nth_from_end(head, n):
""" Remove Nth Node From the End of List """
if head is None:
return
cnt = 0
node_del = head
node_search = head
while node_search.next is not None:
node_search = node_search.next
if cnt == n:
node_del = node_del.next
else:
cnt += 1
if cnt == n:
node_del.next = node_del.next.next
else:
head = head.next
return head<file_sep>"""
>>> from DataStruct import TreeNode
>>> root = TreeNode(2)
>>> root.left = TreeNode(4)
>>> root.right = TreeNode(7)
>>> root.left.left = TreeNode(5)
>>> root.left.right = TreeNode(8)
>>> root.right.left = TreeNode(1)
>>> has_path_sum(root, 22)
False
>>> has_path_sum(root, 10)
True
"""
def has_path_sum(root, sum):
""" Path Sum """
if not root:
return False
next_sum = sum - root.val
if not root.left and not root.right:
return sum-root.val == 0
if root.left and root.right:
return has_path_sum(root.left, next_sum) or \
has_path_sum(root.right, next_sum)
elif root.left:
return has_path_sum(root.left, next_sum)
else:
return has_path_sum(root.right, next_sum)<file_sep># Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isSymmetric(self, root):
"""
BFS: in each level, do comparison on the list of node values with its .reverse()
"""
# special case of {}
if root is None:
return True
reached_bottom = False
current_nodes = [root]
current_nodes_vals = [root.val]
while reached_bottom is False:
current_nodes_vals_reverse = current_nodes_vals[:]
current_nodes_vals_reverse.reverse()
if current_nodes_vals_reverse != current_nodes_vals:
return False
# update next nodes and vals
next_nodes = []
next_nodes_vals = []
for node in current_nodes:
if node.left is not None:
next_nodes.append(node.left)
next_nodes_vals.append(node.left.val)
else:
next_nodes_vals.append(None)
if node.right is not None:
next_nodes.append(node.right)
next_nodes_vals.append(node.right.val)
else:
next_nodes_vals.append(None)
current_nodes = next_nodes[:]
current_nodes_vals = next_nodes_vals[:]
if len(current_nodes) == 0:
reached_bottom = True
return True
<file_sep>class Solution:
# @param root, a tree node
# @return an integer
def minDepth(self, root):
if root is None:
return 0
if root.left is None and root.right is None:
return 1
elif root.right is None:
return 1 + self.minDepth(root.left)
elif root.left is None:
return 1 + self.minDepth(root.right)
else:
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
<file_sep>"""
>>> is_palindrome("aA")
True
>>> is_palindrome("1aA2")
False
>>> is_palindrome("ra c,e.c:ar")
True
"""
def is_palindrome(s):
""" Is Valid Palindrome """
if s is None:
return True
m = 0
n = len(s)-1
while m < n:
while not s[m].isalnum():
m += 1
if m > n:
return True
while not s[n].isalnum():
n -= 1
if m > n:
return True
if s[m].lower() != s[n].lower():
return False
m += 1
n -= 1
return True
<file_sep>"""
>>> from DataStruct import Node
>>> head = Node(1)
>>> head.next = Node(2)
>>> head.next.next = Node(3)
>>> head.next.next.next = Node(4)
>>> head.next.next.next.next = Node(5)
>>> head = rotate_right(head, 5)
>>> print head.val, head.next.val, head.next.next.val, head.next.next.next.val, head.next.next.next.next.val
"""
def rotate_right(head, k):
if head is None:
return
node_tail = head
node_new_tail = head
cnt = 0
len = 0
while node_tail.next is not None:
node_tail = node_tail.next
if cnt == k:
node_new_tail = node_new_tail.next
else:
cnt += 1
len += 1
if cnt != len:
node_tail.next = head
new_head = node_new_tail.next
node_new_tail.next = None
head = new_head
return head<file_sep>"""
>>> grid = [[0, 0, 0],
... [0, 1, 0],
... [0, 0, 0]]
>>> unique_paths_with_obstacles(grid)
2
"""
memo = {}
def unique_paths_with_obstacles(obstacle_grid):
""" Unique Paths With Obstacles """
def unique_paths(m, n):
if obstacle_grid[m-1][n-1] == 1:
return 0
if m == 1 and n == 1:
return 1
if m == 1:
if (m, n-1) not in memo:
memo[(m, n-1)] = unique_paths(m, n-1)
return memo[(m, n-1)]
elif n == 1:
if (m-1, n) not in memo:
memo[(m-1, n)] = unique_paths(m-1, n)
return memo[(m-1, n)]
else:
if (m, n-1) not in memo:
memo[(m, n-1)] = unique_paths(m, n-1)
if (m-1, n) not in memo:
memo[(m-1, n)] = unique_paths(m-1, n)
return memo[(m, n-1)] + memo[(m-1, n)]
m_grid, n_grid = len(obstacle_grid), len(obstacle_grid[0])
return unique_paths(m_grid, n_grid)
<file_sep>"""
>>> from DataStruct import Node
>>> head = Node(1)
>>> head.next = Node(1)
>>> head.next.next = Node(2)
>>> head.next.next.next = Node(3)
>>> head.next.next.next.next = Node(3)
>>> head = delete_duplicates(head)
>>> print head.val, head.next.val, head.next.next.val, head.next.next.next
1 2 3 None
"""
def delete_duplicates(head):
""" Remove Duplicates from Sorted List """
if not head:
return
curr_head = head
search = head
while search:
if curr_head.val != search.val:
curr_head.next = search
curr_head = search
search = search.next
curr_head.next = None
return head<file_sep>"""
>>> add_binary("0","0")
'0'
>>> add_binary("0","1")
'1'
>>> add_binary("1","0")
'1'
>>> add_binary("1","1")
'10'
>>> add_binary("1010","101")
'1111'
>>> add_binary("1111","1")
'10000'
"""
def add_binary(a, b):
""" Add Binary """
a_len = len(a)
b_len = len(b)
offset = a_len - b_len
max_len = a_len
if offset > 0:
b = "0"*offset + b
max_len = a_len
elif offset < 0:
a = "0"*-offset + a
max_len = b_len
carryover = 0
c = ""
for idx in range(max_len):
rev_idx = max_len - idx - 1
a_val = a[rev_idx]
b_val = b[rev_idx]
if a_val == "1" and b_val == "1":
if carryover == 1:
c = "1" + c
else:
c = "0" + c
carryover = 1
elif (a_val == "1" and b_val == "0") or \
(a_val == "0" and b_val == "1"):
if carryover == 1:
c = "0" + c
carryover = 1
else:
c = "1" + c
carryover = 0
else:
if carryover == 1:
c = "1" + c
carryover = 0
else:
c = "0" + c
if carryover == 1:
c = "1" + c
return c<file_sep>"""
>>> stack = MinStack()
>>> stack.push(5)
>>> stack.push(1)
>>> stack.push(2)
>>> stack.push(3)
>>> stack.push(7)
>>> stack.push(4)
>>> stack.top()
4
>>> stack.pop()
>>> stack.top()
7
>>> stack.get_min()
1
>>> stack.pop()
>>> stack.get_min()
1
>>> stack.pop()
>>> stack.get_min()
1
>>> stack.pop()
>>> stack.get_min()
1
>>> stack.pop()
>>> stack.get_min()
5
"""
class MinStack(object):
""" Min Stack """
def __init__(self):
self.__my_list = []
self.__min_list = []
def push(self, x):
self.__my_list.append(x)
if not self.__min_list or x <= self.__min_list[-1]:
self.__min_list.append(x)
def pop(self):
if self.__my_list:
val = self.__my_list.pop()
if val == self.get_min():
self.__min_list.pop()
def top(self):
return self.__my_list[-1]
def get_min(self):
return self.__min_list[-1]<file_sep>__author__ = 'aouyang1'
import unittest
from DataStruct import StackClass, sort_stack
# run nosetests in the terminal
class TestStack(unittest.TestCase):
def test_stack(self):
s = StackClass()
self.assertEqual(s.is_empty(), True)
s.push(4)
s.push('dog')
self.assertEqual(s.peek(), 'dog')
s.push(True)
self.assertEqual(s.size(), 3)
self.assertEqual(s.is_empty(), False)
s.push(8.4)
self.assertEqual(s.pop(), 8.4)
self.assertEqual(s.pop(), True)
self.assertEqual(s.size(), 2)
def test_min(self):
s = StackClass()
num_list = [1, 2, 3, 4, 5]
for val in num_list:
s.push(val)
self.assertEqual(s.min(), 1)
s = StackClass()
num_list = [5, 4, 3, 2, 1, 2, 3, 4, 5]
for val in num_list:
s.push(val)
self.assertEqual(s.min(), 1)
s.pop()
self.assertEqual(s.min(), 1)
s.pop()
self.assertEqual(s.min(), 1)
s.pop()
self.assertEqual(s.min(), 1)
s.pop()
self.assertEqual(s.min(), 1)
s.pop()
self.assertEqual(s.min(), 2)
s.pop()
self.assertEqual(s.min(), 3)
def test_sort_stack(self):
s1 = StackClass()
num_list = [5, 7, 2, 4, 9, 1, 3, 6]
for val in num_list:
s1.push(val)
s1 = sort_stack(s1=s1)
num_list = sorted(num_list, reverse=True)
for val in num_list:
self.assertEqual(s1.pop(), val)
<file_sep>"""
>>> generate(5)
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
"""
def generate(num_rows):
""" Pascal's Triangle """
tri = []
for i in range(num_rows):
if i == 0:
tri.append([1])
elif i == 1:
tri.append(tri[i-1] + [1])
else:
prev_tri = tri[i-1]
new_tri = [1]
for k in range(len(prev_tri)-1):
new_tri.append(prev_tri[k] + prev_tri[k+1])
new_tri.append(1)
tri.append(new_tri)
return tri
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep># https://oj.leetcode.com/problems/implement-strstr/
import unittest
class Solution:
# @param haystack, a string
# @param needle, a string
# @return an integer
def strStr(self, haystack, needle, depth=0):
# print "{} in {} ? d={}".format(needle,haystack,depth)
if not len(needle):
return 0
if not len(haystack):
return -1
if len(haystack) < len(needle):
return -1
if haystack[:len(needle)] == needle:
return depth
else:
return self.strStr(haystack[1:], needle, depth+1)
def strStrSlowWithHelperMethod(self, haystack, needle):
for i in range(len(haystack)):
if self.starts_with(haystack[i:], needle):
return i
if len(haystack) == 0:
if len(needle) == 0:
return 0
return -1
def starts_with(self, full, prefix):
f_len = len(full)
p_len = len(prefix)
if f_len < p_len:
return False
# print "Full: {}, Prefix: {}".format(full, prefix)
for i in range(p_len):
if full[i] != prefix[i]:
return False
return True
def strStrBrute(self, haystack, needle):
h_len = len(haystack)
n_len = len(needle)
if not n_len:
return 0
if h_len < n_len:
return -1
# print "Full: {} ({}), Prefix: {} ({})".format(haystack, h_len, needle, n_len)
for i in range(h_len):
for j in range(n_len):
# print "h[{}]:n[{}] {}:{}".format(i+j, j, haystack[i+j], needle[j])
if i + n_len > h_len :
return -1
if haystack[i+j] == needle[j]:
if j == n_len-1:
return i
next
else:
break
return -1
class TestSolution(unittest.TestCase):
def test_01(self):
sln = Solution()
haystack = 'abcffoob'
needle = 'foo'
self.assertEqual(haystack.find(needle), sln.strStr(haystack, needle))
def test_mississippi(self):
sln = Solution()
haystack = 'mississippi'
needle = 'issipi'
self.assertEqual(haystack.find(needle), sln.strStr(haystack, needle))
def test_aaa(self):
sln = Solution()
haystack = 'aaa'
needle = 'aaaa'
self.assertEqual(haystack.find(needle), sln.strStr(haystack, needle))
def test_a_empty(self):
sln = Solution()
haystack = 'a'
needle = ''
self.assertEqual(haystack.find(needle), sln.strStr(haystack, needle))
def test_empty_a(self):
sln = Solution()
haystack = ''
needle = 'a'
self.assertEqual(haystack.find(needle), sln.strStr(haystack, needle))
def test_a_a(self):
sln = Solution()
haystack = 'a'
needle = 'a'
self.assertEqual(haystack.find(needle), sln.strStr(haystack, needle))
def test_empty_empty(self):
sln = Solution()
haystack = ''
needle = ''
self.assertEqual(haystack.find(needle), sln.strStr(haystack, needle))
if __name__ == '__main__':
unittest.main()
<file_sep>__author__ = 'aouyang1'
import unittest
from DataStruct import QueueClass
# run nosetests in the terminal
class TestQueue(unittest.TestCase):
def test_queue(self):
q = QueueClass()
q.enqueue(4)
q.enqueue('dog')
q.enqueue(True)
self.assertEqual(q.size(), 3)
self.assertEqual(q.is_empty(), False)
q.enqueue(8.4)
self.assertEqual(q.dequeue(), 4)
self.assertEqual(q.dequeue(), 'dog')
self.assertEqual(q.size(), 2)
<file_sep>"""
>>> from DataStruct import TreeNode
>>> p = TreeNode(3)
>>> p.left = TreeNode(9)
>>> p.right = TreeNode(20, left=TreeNode(15), right=TreeNode(7))
>>> q = TreeNode(3)
>>> q.left = TreeNode(9)
>>> q.right = TreeNode(20, left=TreeNode(15), right=TreeNode(7))
>>> is_same_tree(p, q)
True
>>> q = TreeNode(3)
>>> q.left = TreeNode(2)
>>> q.right = TreeNode(20, left=TreeNode(15), right=TreeNode(7))
>>> is_same_tree(p, q)
False
>>> q = TreeNode(3)
>>> q.left = TreeNode(9)
>>> q.right = TreeNode(20, left=TreeNode(15))
>>> is_same_tree(p, q)
False
"""
def is_same_tree(p, q):
""" Same Tree """
if not p and not q:
return True
else:
if p and q:
if p.val != q.val:
return False
else:
return is_same_tree(p.left, q.left) and \
is_same_tree(p.right, q.right)
else:
return False
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>"""
>>> majority_element([1, 2, 3, 4, 4, 4, 7, 2, 3])
4
"""
def majority_element(num):
""" Majority Element """
elem = {}
maj_elem = num[0]
for val in num:
if val not in elem:
elem[val] = 1
else:
elem[val] += 1
if elem[val] > elem[maj_elem]:
maj_elem = val
return maj_elem
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>"""
>>> title_to_number("A")
1
>>> title_to_number("Z")
26
>>> title_to_number("AA")
27
>>> title_to_number("AAA")
703
"""
def map_chr_to_int(char_in):
return ord(char_in)-64
def title_to_number(s):
""" Excel Sheet Column Number """
if len(s) == 0:
return 0
tot_sum = map_chr_to_int(s[0])*26**(len(s)-1)
return tot_sum + title_to_number(s[1:])
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>"""
>>> is_valid("{([])([][])}")
True
>>> is_valid("{([])([]])}")
False
"""
def is_valid(s):
""" Valid Parentheses """
brackets = {"(": ")", "{": "}", "[": "]"}
if len(s) % 2 == 1 or s[0] not in brackets:
return False
char_stack = []
for val in s:
if val in brackets:
char_stack.append(val)
elif val == brackets[char_stack[-1]]:
char_stack.pop()
else:
return False
if len(char_stack) != 0:
return False
return True
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>class MinStack:
"""
[1, 4, 5, 5, 7, 0, 8]
[1, 4, 5, 5, 7, 8]
"""
def __init__(self):
self.__stack = []
self.__min = []
def push(self, x):
self.__stack.append(x)
if self.min_top() is not None:
if x <= self.min_top():
self.__min.append(x)
else:
self.__min.append(x)
# @return nothing
def pop(self):
if self.top() == self.min_top():
self.__min.pop()
self.__stack.pop()
# @return an integer
def top(self):
if len(self.__stack) == 0:
return None
else:
return self.__stack[-1]
def min_top(self):
if len(self.__min) == 0:
return None
else:
return self.__min[-1]
# @return an integer
def getMin(self):
return self.min_top()
lol = MinStack()
<file_sep>class Solution:
# @param root, a tree node
# @return an integer
def minDepth(self, root):
if root is None:
return 0
if root.left is None or root.right is None:
return 1 + self.minDepth(root.left) + self.minDepth(root.right)
else:
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
<file_sep>"""
>>> remove_element([4,5,4], 4)
1
>>> remove_element([1], 1)
0
>>> remove_element([1, 4, 3, 1, 7, 2, 8, 2, 9, 3, 10, 3, 3, 3, 5], 3)
10
"""
def remove_element(a, elem):
""" Remove Element """
if not a:
return
a_len = len(a)
a_idx = a_len-1
for idx in range(a_len):
if a[a_len-idx-1] == elem:
a[a_len-idx-1], a[a_idx] = a[a_idx], a[a_len-idx-1]
a_idx -= 1
return a_idx+1
if __name__ == "__main__":
import doctest
doctest.testmod()
<file_sep>"""
>>> from DataStruct import Node
>>> head = Node(1)
>>> head.next = Node(2)
>>> head.next.next = Node(3)
>>> head.next.next.next = Node(4)
>>> head.next.next.next.next = Node(5)
>>> head = swap_pairs(head)
>>> print head.val, head.next.val, head.next.next.val, head.next.next.next.val, head.next.next.next.next.val
2 1 4 3 5
"""
def swap_pairs(head):
""" Swap Nodes in Pairs """
if not head:
return
if head.next is None:
return head
curr_tail = head
curr_head = curr_tail.next
next_head = curr_head.next
curr_head.next = curr_tail
curr_tail.next = next_head
prev_node = curr_tail
head = curr_head
print prev_node, prev_node.next
while prev_node.next is not None and prev_node.next.next is not None:
curr_tail = prev_node.next
curr_head = curr_tail.next
next_head = curr_head.next
prev_node.next = curr_head
curr_head.next = curr_tail
curr_tail.next = next_head
prev_node = curr_tail
return head
<file_sep>"""
>>> count_and_say(5)
'111221'
>>> count_and_say(6)
'312211'
>>> count_and_say(10)
'13211311123113112211'
"""
def count_and_say(n):
""" Count and Say """
num_list = [1]
for i in range(n-1):
curr_val = num_list[0]
val_cnt = 0
list_str = []
for val in num_list:
if val == curr_val:
val_cnt += 1
else:
list_str.append(val_cnt)
list_str.append(curr_val)
curr_val = val
val_cnt = 1
list_str.append(val_cnt)
list_str.append(curr_val)
num_list = list_str
return reduce(lambda x, y: x+y, map(lambda x: str(x), num_list))
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>def testIsValid():
assert isValid("(([]))") is True
assert isValid("([]}") is False
def isValid(s):
"""
for each char inside for loop,
if char is an opening parenthesis:
we push it onto our stack
else
we check if it is the correct closing parenthesis for
last item in stack
(return False if not correct)
if correct we pop the last item in stack
if either stack or remaining list is not empty return False
return True
"""
parentheses = {'(': ')', '{': '}', '[': ']'}
s_list = list(s)
stack = []
for char_position in range(len(s_list)):
char = s_list.pop(0)
if char in parentheses:
stack.append(char)
else:
if char != parentheses[stack[-1]]:
return False
stack.pop()
if len(stack) + len(s_list) > 0:
return False
return True
testIsValid()
<file_sep>"""
>>> from DataStruct import TreeNode
>>> root = TreeNode(1)
>>> root.left = TreeNode(2)
>>> level_order(root)
[[1], [2]]
"""
def level_order(root):
""" Binary Tree Level Order Traversal """
if root is None:
return []
level_list = []
level = [root]
while level:
temp_level = []
next_level = []
for node in level:
temp_level.append(node.val)
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
level_list.append(temp_level)
level = next_level
return level_list<file_sep>"""
>>> get_row(3)
[1, 3, 3, 1]
>>> get_row(5)
[1, 5, 10, 10, 5, 1]
"""
def get_row(rowIndex):
""" Pascal's Triangle II """
rowIndex += 1
for i in range(rowIndex):
if i == 0:
tri = [1]
elif i == 1:
tri.append(1)
else:
last_val = tri[0]
for j in range(len(tri)-1):
new_val = last_val + tri[j+1]
last_val = tri[j+1]
tri[j+1] = new_val
tri.append(last_val)
return tri
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>"""
>>> climb_stairs(5)
8
>>> climb_stairs(20)
10946
"""
def climb_stairs(n):
""" Climbing Stairs """
arr = []
for i in range(n+1):
if i <= 1:
arr.append(1)
else:
arr.append(arr[-1]+arr[-2])
return arr[-1]
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>Practice Questions and Solutions for Insight Interview Practice
=============================================
Compiled by <NAME> and <NAME>
WHERE DID THESE CAMELS COME FROM
## Table Of Contents
- [Data Structure](#data-structure)
- [SQL](#sql)
## Data Structure
[3Sum Closest](https://oj.leetcode.com/problems/3sum-closest/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/three_sum_closest_austin.py)
[Add Binary](https://oj.leetcode.com/problems/add-binary/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/add_binary_austin.py)
[Binary Tree Zigzag Level Order Traversal](https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/zigzag_level_order_austin.py)
[Climbing Stairs](https://oj.leetcode.com/problems/climbing-stairs/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/climb_stairs_austin.py)
[Compare Version Numbers](https://oj.leetcode.com/problems/compare-version-numbers/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/compare_version_austin.py)
[Count and Say](https://oj.leetcode.com/problems/count-and-say/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/count_and_say_austin.py)
- [Brant](https://github.com/aouyang1/InsightInterviewPractice/blob/master/count_and_say_brant.py)
[Excel Sheet Column Number](https://oj.leetcode.com/problems/excel-sheet-column-number/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/title_to_number_austin.py)
[Implement strStr](https://github.com/aouyang1/InsightInterviewPractice/blob/master/implement_strstr_brant.py)
- [Brant](https://oj.leetcode.com/problems/implement-strstr/)
[Intersection of Two Linked Lists](https://oj.leetcode.com/problems/intersection-of-two-linked-lists/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/get_intersection_node_austin.py)
- [Brant](https://github.com/aouyang1/InsightInterviewPractice/blob/master/intersection_of_two_linked_lists_brant.py)
[Largest Number](https://oj.leetcode.com/problems/largest-number/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/largest_number_austin.py)
[Length of Last Word](https://oj.leetcode.com/problems/length-of-last-word/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/length_of_last_word_austin.py)
[Majority Element](https://oj.leetcode.com/prsoblems/majority-element/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/majority_element_austin.py)
- [Brant](https://github.com/aouyang1/InsightInterviewPractice/blob/master/majority_element_brant.py)
[Merge Sorted Array](https://oj.leetcode.com/problems/merge-sorted-array/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/merge_austin.py)
[Merge Two Sorted Lists](https://oj.leetcode.com/problems/merge-two-sorted-lists/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/merge_two_lists_austin.py)
[Pascal's Triangle](https://oj.leetcode.com/problems/pascals-triangle/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/generate_austin.py)
[Pascal's Triangle II](https://oj.leetcode.com/problems/pascals-triangle-ii/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/get_row_austin.py)
[Palindrome Number](https://oj.leetcode.com/problems/palindrome-number/)
-[Brant](https://github.com/aouyang1/InsightInterviewPractice/blob/master/palindrome_number_brant.py)
[Plus One](https://oj.leetcode.com/problems/plus-one/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/plus_one_austin.py)
[Remove Duplicates from Sorted Array](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/remove_duplicates_austin.py)
[Remove Element](https://oj.leetcode.com/problems/remove-element/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/remove_element_austin.py)
[Reverse Integer](https://oj.leetcode.com/problems/reverse-integer/)
-[Brant](https://github.com/aouyang1/InsightInterviewPractice/blob/master/reverse_number_brant.py)
[Rotate Array](https://oj.leetcode.com/problems/rotate-array/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/rotate_austin.py)
[Same Tree](https://oj.leetcode.com/problems/same-tree/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/is_same_tree_austin.py)
[Search for a Range](https://oj.leetcode.com/problems/search-for-a-range/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/search_range_austin.py)
[Single Number](https://oj.leetcode.com/problems/single-number/)
-[Brant](https://github.com/aouyang1/InsightInterviewPractice/blob/master/single_number_brant.py)
[Spiral Matrix](https://oj.leetcode.com/problems/spiral-matrix/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/spiral_order_austin.py)
[Two Sum](https://oj.leetcode.com/problems/two-sum/)
- [Guang]
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/two_sum_austin.py)
[Valid Parentheses](https://oj.leetcode.com/problems/valid-parentheses/)
- [Guang](https://github.com/aouyang1/InsightInterviewPractice/raw/master/valid_parentheses_guang.py)
- [Austin](https://github.com/aouyang1/InsightInterviewPractice/raw/master/is_valid_austin.py)
- [Brant](https://github.com/aouyang1/InsightInterviewPractice/blob/master/valid_parentheses_brant.py)
## SQL
<file_sep>"""
>>> A = [1, 1, 2, 2, 2, 3, 3, 5, 7]
>>> idx = remove_duplicates(A)
>>> print idx, A[:idx]
5 [1, 2, 3, 5, 7]
"""
def remove_duplicates(A):
""" Remove Duplicates from Sorted Array """
if not A:
return
a_idx = 0
for idx, val in enumerate(A):
if A[a_idx] != val:
a_idx += 1
A[a_idx], A[idx] = A[idx], A[a_idx]
return a_idx+1
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>__author__ = 'aouyang1'
import unittest
from DataStruct import TreeNode
class TestTree(object):
def test_binary_tree(self):
root = TreeNode(7)
root.left = TreeNode(4)
root.right = TreeNode(6)
<file_sep>"""
>>> from DataStruct import Node
>>> head = Node(1)
>>> head.append_data([2, 3, 4, 5, 6, 7])
>>> head.print_values()
1
2
3
4
5
6
7
>>> head = reverse_between(head, 1, 7)
>>> head.print_values()
7
6
5
4
3
2
1
"""
def reverse_between(head, m, n):
""" Reverse Linked List II """
if not head:
return
lag = n - m + 1
if lag == 1:
return head
run_tail = head
run_n = head
while n > 0:
run_n = run_n.next
if n == m:
run_tail = run_tail.next
n -= 1
run_m = run_tail.next
for i in range(lag):
temp_node = run_m.next
run_m.next = run_n
run_n = run_m
if i == lag-1:
break
run_m = temp_node
run_tail.next = run_m
return head
<file_sep>"""
>>> str_str(",nkzkergqkwe,kawef", "ker")
4
"""
def str_str(haystack, needle):
if not needle:
return 0
elif not haystack:
return -1
for i in range(len(haystack)-len(needle)+1):
if haystack[i] == needle[0]:
valid = True
for j in range(len(needle)):
if haystack[i+j] != needle[j]:
valid = False
break
if valid:
return i
return -1<file_sep>"""
>>> three_sum_closest([0, 1, 2, -3], 1)
0
>>> three_sum_closest([5, 7, -4, -10, 0, 12, 21, -3], 15)
15
"""
def three_sum_closest(num, target):
""" 3Sum Closest """
num.sort()
curr_sum = None
curr_delta = None
jk_sum = {}
for i in range(len(num)-2):
j = i+1
k = len(num)-1
while j != k:
if (j, k) not in jk_sum:
jk_sum[(j, k)] = num[j] + num[k]
temp_sum = num[i] + jk_sum[(j, k)]
if temp_sum == target:
return target
elif temp_sum < target:
j += 1
else:
k -= 1
temp_delta = temp_sum - target
if temp_delta < 0:
temp_delta *= -1
if curr_sum is None or temp_delta < curr_delta:
curr_sum = temp_sum
curr_delta = temp_delta
return curr_sum
if __name__ == "__main__":
import doctest
doctest.testmod()
<file_sep>import unittest
class Solution:
# @param num, a list of integers
# @return an integer
def majorityElementDict1(self, num):
threshold = len(num)/2
# print "threshold = %d" % threshold
counts = {}
for i in num:
n_occur = 1
if i in counts:
n_occur = counts[i]+1
if n_occur > threshold:
return i
counts[i] = n_occur
# print "counts of %d's = %d" % (i, counts[i])
# print "Shouldn't get here! No majority found"
return None
def majorityElementDict2(self, num):
threshold = len(num)/2
counts = {}
for i in num:
n_occur = 1
if i in counts:
n_occur = counts[i]+1
if n_occur > threshold:
return i
counts[i] = n_occur
return None
majorityElementDict = majorityElementDict1
class TestSolution(unittest.TestCase):
def test_number_of_the_feast(self):
l = [6,6,5,5,5]
a = 5
self.assertEqual(a, Solution().majorityElementDict(l))
def test_one_two_one_two(self):
l = [1,2,1,2,1,2,1]
a = 1
self.assertEqual(a, Solution().majorityElementDict(l))
if __name__ == '__main__':
unittest.main()
<file_sep>"""
>>> find_peak_element([3, 2])
0
>>> find_peak_element([1, 2, 3])
2
>>> find_peak_element([0, 1, 2, 3, 2])
3
"""
def slope(val0, val1):
if val1 > val0:
return 1
elif val1 < val0:
return -1
else:
return 0
def find_peak_element(num):
""" Find Peak Element """
num_len = len(num)
if num_len == 1:
return 0
elif num_len >= 2:
if slope(num[0], num[1]) == -1:
return 0
if num_len >= 3:
curr_slope = slope(num[0], num[1])
for idx in range(num_len-2):
next_slope = slope(num[idx+1], num[idx+2])
if curr_slope == 1 and next_slope == -1:
return idx + 1
curr_slope = next_slope
if slope(num[num_len-2], num[num_len-1]) == 1:
return num_len - 1
<file_sep>import unittest
class Solution:
# @return an integer
def reverse(self, x):
debug = False
if debug:
print "x: %d" % x
sign = 1
if x < 0:
sign = -1
x = 0 - x
rx = 0
while x:
rx = rx * 10 + x % 10
x = x / 10
if debug:
print "x: {0: >6}\t rx: {1: >6}\t rem = {2}".format(x,rx,x%10)
if debug:
print "rx: %d" % rx * sign
# Special case for silly fake overflow
if 2147483648 < rx:
return 0
return rx * sign
class TestSolution(unittest.TestCase):
def test_1234(self):
sln = Solution()
self.assertEqual(4321, sln.reverse(1234))
def test_1(self):
sln = Solution()
self.assertEqual(1, sln.reverse(1))
def test_0(self):
sln = Solution()
self.assertEqual(0, sln.reverse(0))
def test_100021(self):
sln = Solution()
self.assertEqual(120001, sln.reverse(100021))
def test_neg12(self):
sln = Solution()
self.assertEqual(-21, sln.reverse(-12))
def test_overflow(self):
sln = Solution()
#self.assertEqual(9646324351, sln.reverse(1534236469))
self.assertEqual(0, sln.reverse(1534236469))
if __name__ == '__main__':
unittest.main()
<file_sep>"""
>>> num = [1,2,3,4,5,6,7]
>>> rotate(num, 3)
>>> print num
[5, 6, 7, 1, 2, 3, 4]
>>> num = [1,2,3,4,5,6,7]
>>> rotate(num, 7)
>>> print num
[1, 2, 3, 4, 5, 6, 7]
>>> num = [1]
>>> rotate(num, 3)
>>> print num
[1]
>>> num = []
>>> rotate(num, 3)
>>> print num
[]
>>> num = [1, 2, 3, 4, 5, 6]
>>> rotate(num, 2)
>>> print num
[5, 6, 1, 2, 3, 4]
"""
def rotate(nums, k):
""" Rotate Array """
num_len = len(nums)
if num_len <= 1:
return
offset = 0
idx = (offset + k) % num_len
for rep in range(num_len-1):
nums[idx], nums[offset] = nums[offset], nums[idx]
prev_idx = idx
if prev_idx == offset:
offset += 1
idx = offset
idx = (idx + k) % num_len
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>"""
>>> from DataStruct import TreeNode
>>> root = TreeNode(2)
>>> root.left = TreeNode(4)
>>> root.right = TreeNode(7)
>>> root.left.left = TreeNode(5)
>>> root.left.right = TreeNode(8)
>>> min_depth(root)
2
"""
def min_depth(root):
""" Minimum Depth of Binary Tree """
if not root:
return 0
if not root.left and not root.right:
return 1
if root.left and root.right:
return min(min_depth(root.left), min_depth(root.right)) + 1
elif root.left:
return min_depth(root.left) + 1
else:
return min_depth(root.right) + 1<file_sep>"""
>>> length_of_last_word("Hello")
5
>>> length_of_last_word(" Hello")
5
>>> length_of_last_word("Hello ")
5
>>> length_of_last_word(" Hello ")
5
>>> length_of_last_word("He l lo00 ")
4
"""
def length_of_last_word(s):
""" Length of Last Word """
space_idx = None
space_from_end = True
num_spaces_from_end = 0
for idx in range(len(s)):
rev_idx = len(s)-idx-1
if s[rev_idx] == " ":
if space_from_end:
num_spaces_from_end += 1
else:
space_idx = rev_idx
return len(s) - space_idx - num_spaces_from_end - 1
else:
space_from_end = False
if space_idx is None:
return len(s) - num_spaces_from_end<file_sep>"""
>>> from DataStruct import TreeNode
>>> root = TreeNode(3)
>>> root.left = TreeNode(9)
>>> root.right = TreeNode(20, left=TreeNode(15), right=TreeNode(7))
>>> zigzag_level_order(root)
[[3], [20, 9], [15, 7]]
"""
def zigzag_level_order(root):
""" Binary Tree Zigzag Level Order Traversal """
if not root:
return []
# breadth first approach
level_list = [root]
tree_list = []
scan_right = True
while level_list:
curr_level = []
next_level = []
for node in level_list:
curr_level.append(node.val)
if scan_right:
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
else:
if node.right:
next_level.append(node.right)
if node.left:
next_level.append(node.left)
scan_right = not scan_right
next_level.reverse()
level_list = next_level
tree_list.append(curr_level)
return tree_list
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>"""
>>> compare_str("824", "8247")
1
>>> largest_number([3, 30, 34, 5, 9])
'9534330'
>>> largest_number([0, 0])
'0'
>>> largest_number([824,938,1399,5607,6973,5703,9609,4398,8247])
'9609938824824769735703560743981399'
"""
def compare_str(str1, str2):
if str1 + str2 > str2 + str1:
return 1
elif str1 + str2 < str2 + str1:
return -1
else:
return 0
def merge_str(num1, num2):
ptr1 = 0
ptr2 = 0
new_num = []
while ptr1 < len(num1) and ptr2 < len(num2):
if compare_str(num1[ptr1], num2[ptr2]) == 1:
new_num.append(num1[ptr1])
ptr1 += 1
else:
new_num.append(num2[ptr2])
ptr2 += 1
if ptr2 == len(num2):
new_num.extend(num1[ptr1:])
return new_num
if ptr1 == len(num1):
new_num.extend(num2[ptr2:])
return new_num
def mergesort_str(num):
num_len = len(num)
left = num[:num_len/2]
right = num[num_len/2:]
if not right:
return left
elif not left:
return right
else:
return merge_str(mergesort_str(left), mergesort_str(right))
def largest_number(num):
""" Largest Number """
num = map(lambda x: str(x), num)
num = mergesort_str(num)
while num[0] == "0" and len(num) > 1:
num = num[1:]
return "".join(num)
if __name__ == "__main__":
import doctest
doctest.testmod()
<file_sep>"""
>>> A = [1, 3, 5, 7]
>>> B = [2, 4, 6, 8]
>>> merge(A, len(A), B, len(B))
>>> print A
[1, 2, 3, 4, 5, 6, 7, 8]
>>> A = [1, 2, 10]
>>> B = [3, 4, 6, 8, 12, 15, 19, 200]
>>> merge(A, len(A), B, len(B))
>>> print A
[1, 2, 3, 4, 6, 8, 10, 12, 15, 19, 200]
"""
def merge(A, m, B, n):
""" Merge Sorted Array """
A.extend([0]*n)
ptrA = m-1
ptrB = n-1
ptrAex = m+n-1
while True:
if ptrB < 0:
#done
return
if ptrA < 0:
# flush remaining B list to A
A[ptrAex] = B[ptrB]
ptrAex -= 1
ptrB -= 1
else:
# checking for swaps
if A[ptrA] > B[ptrB]:
A[ptrAex] = A[ptrA]
ptrAex -= 1
ptrA -= 1
else:
A[ptrAex] = B[ptrB]
ptrAex -= 1
ptrB -= 1
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>
def is_leaf(node):
return node.left is None and node.right is None
def funnel(left, right, first_pass=True):
if left.next is None:
print "{} next is: {}".format(left.val, right.val)
left.next = right
if is_leaf(left) or is_leaf(right):
return
if left.right and right.left:
funnel(left.right, right.left, first_pass)
if not first_pass:
if left.left and right.left:
funnel(left.left, right.left, first_pass)
if left.right and right.right:
funnel(left.right, right.right, first_pass)
if left.left and right.right:
funnel(left.left, right.right, first_pass)
def connect(root):
""" Populating Next Right Pointers In Each Node """
def build(root, first_pass=True):
if not root or is_leaf(root):
return
if first_pass:
if root.left and root.right:
funnel(root.left, root.right, first_pass)
build(root.left, first_pass)
build(root.right, first_pass)
else:
if not root.left:
build(root.right, first_pass)
elif not root.right:
build(root.left, first_pass)
else:
funnel(root.left, root.right, first_pass)
build(root.left, first_pass)
build(root.right, first_pass)
build(root, True)
build(root, False)
from DataStruct import TreeNode
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
root.left.left.left = TreeNode(8)
root.left.left.right = TreeNode(9)
#root.left.right.left = TreeNode(10)
#root.left.right.right = TreeNode(11)
root.right.left.left = TreeNode(12)
#root.right.left.right = TreeNode(13)
#root.right.right.left = TreeNode(14)
root.right.right.right = TreeNode(15)
connect(root)
print "level 1: val: {}".format(root.val)
print " : next: {}\n".format(root.next)
print "level 2: val: {}".format([root.left.val,
root.right.val])
print " : next: {}\n".format([root.left.next.val,
root.right.next])
print "level 3: val: {}".format([root.left.left.val,
root.left.right.val,
root.right.left.val,
root.right.right.val])
print " : next: {}\n".format([root.left.left.next.val,
root.left.right.next.val,
root.right.left.next.val,
root.right.right.next])
print "level 4: val: {}".format([root.left.left.left.val,
root.left.left.right.val,
#root.left.right.left.val,
#root.left.right.right.val,
root.right.left.left.val,
#root.right.left.right.val,
#root.right.right.left.val,
root.right.right.right.val])
print " : next: {}\n".format([root.left.left.left.next.val,
root.left.left.right.next.val,
#root.left.right.left.next.val,
#root.left.right.right.next.val,
root.right.left.left.next.val,
#root.right.left.right.next,
#root.right.right.left.next.val,
root.right.right.right.next])
<file_sep>"""
>>> from DataStruct import TreeNode
>>> root = TreeNode(1)
>>> root.left = TreeNode(2)
>>> root.left.left = TreeNode(3)
>>> root.left.right = TreeNode(4)
>>> root.right = TreeNode(5)
>>> root.right.right = TreeNode(6)
>>> flatten(root)
>>> print root.val, root.right.val, root.right.right.val, root.right.right.right.val, root.right.right.right.right.val, root.right.right.right.right.right.val, root.right.right.right.right.right.right
1 2 3 4 5 6 None
"""
def append_right(root):
temp_right = root.right
root.right = root.left
root.left = None
tail = root.right
while tail.right is not None:
tail = tail.right
tail.right = temp_right
def is_leaf(root):
return not root.left and not root.right
def flatten(root):
""" Flatten Binary Tree to Linked List """
if not root or is_leaf(root):
return
if root.left:
append_right(root)
flatten(root.right)<file_sep>def count_and_say(n):
""" computes nth element in the sequence of count-and-say
numbers.
Args:
n: how many elements should be in the sequence
Returns:
nth_elt: resulting element in count-and-say sequence
Examples:
>>> count_and_say(0)
'1'
>>> count_and_say(1)
'11'
>>> count_and_say(2)
'21'
>>> count_and_say(3)
'1211'
>>> count_and_say(4)
'111221'
"""
if n == 0:
return '1'
else:
raw = count_and_say(n-1)
return say(raw)
def say(raw_str):
""" say a given raw string
partition into substrings that have identical elements
get (len, val) pair for each substring
concatenate the resulting (len, val) pairs
Examples:
>>> say('11')
'21'
>>> say('21')
'1211'
>>> say('1211')
'111221'
"""
if len(raw_str) == 1:
return '11'
else:
curr_len = 1
len_val_pairs = []
raw_str = raw_str + ' ' # appends space at end
for ind in range(1, len(raw_str)):
val = raw_str[ind]
prev_val = raw_str[ind-1]
if val == prev_val:
curr_len += 1
else:
len_val_pairs.append(str(curr_len))
len_val_pairs.append(prev_val)
curr_len = 1
return ''.join(len_val_pairs)
<file_sep># https://oj.leetcode.com/problems/valid-parentheses/
import unittest
class Solution:
# @return a string
def countAndSay(self, n):
if n == 1:
return "1"
i = 1
for x in range(n-1):
i = self.say_num_of(i)
return str(i)
def say_num_of(self, n):
accum = []
prev = None
seq_count = 0
for i in str(n):
if not prev:
seq_count = 1
prev = i
elif i == prev:
seq_count += 1
else:
accum.append("%d%s" % (seq_count, prev))
seq_count = 1
prev = i
accum.append("%d%s" % (seq_count, prev))
result = int("".join(accum))
# print "%d -> %d" % (n, result)
return result
def countAndSayConcise(self, n):
res = '1'
for i in range(n-1):
stack = []
for (k, g) in itertools.groupby(res):
stack.append(str(len(list(g)))+k)
res = ''.join(stack)
return res
class TestSolution(unittest.TestCase):
def test_01(self):
sln = Solution()
self.assertEqual("1", sln.countAndSay(1))
def test_02(self):
sln = Solution()
self.assertEqual("11", sln.countAndSay(2))
def test_03(self):
sln = Solution()
self.assertEqual("21", sln.countAndSay(3))
def test_04(self):
sln = Solution()
self.assertEqual("1211", sln.countAndSay(4))
def test_05(self):
sln = Solution()
self.assertEqual("111221", sln.countAndSay(5))
def test_06(self):
sln = Solution()
self.assertEqual("312211", sln.countAndSay(6))
def test_07(self):
sln = Solution()
self.assertEqual("13112221", sln.countAndSay(7))
if __name__ == '__main__':
unittest.main()
<file_sep>"""
>>> from DataStruct import Node
>>> l1 = Node(5)
>>> l1.next = Node(8)
>>> l2 = Node(2)
>>> l2.next = Node(4)
>>> l2.next.next = Node(6)
>>> l2.next.next.next = Node(7)
>>> l2.next.next.next.next = Node(9)
>>> l3 = merge_two_lists(l1, l2)
>>> for i in range(7):
... print l3.val
... l3 = l3.next
2
4
5
6
7
8
9
"""
def merge_two_lists(l1, l2):
""" Merge Two Sorted Lists """
if l1 is None and l2 is None:
return
elif l1 is None:
head = l2
return head
elif l2 is None:
head = l1
return head
if l1.val < l2.val:
head = l1
l1 = l1.next
else:
head = l2
l2 = l2.next
curr_head = head
while l1 or l2:
if l1 and l2:
if l1.val < l2.val:
curr_head.next = l1
l1 = l1.next
else:
curr_head.next = l2
l2 = l2.next
elif l1 and l2 is None:
curr_head.next = l1
l1 = l1.next
elif l2 and l1 is None:
curr_head.next = l2
l2 = l2.next
curr_head = curr_head.next
return head<file_sep># https://oj.leetcode.com/problems/valid-parentheses/
import unittest
from collections import deque
class Solution:
# @return a boolean
# openers = {'{':'}','[':']', '(':')'}
# closers = {v: k for k, v in openers.items()}
# def isValid1(self, s):
# next_close = []
# for c in s:
# #print "c: %c" % c
# if c in self.openers.keys():
# next_close.append(self.openers[c])
# elif c in self.closers.keys():
# if not next_close or next_close.pop() != c:
# #print "INVALID"
# return False
# #print "next_close len = %d --> %r" % (len(next_close), len(next_close) == 0)
# return not next_close
def isValid(self, s):
paren_stack = deque()
for c in s:
#print "<-- %c" % c
if not paren_stack:
paren_stack.append(c)
else:
if (ord(c) == 1 + ord(paren_stack[-1]) or (ord(c) == 2 + ord(paren_stack[-1]))):
paren_stack.pop()
else:
paren_stack.append(c)
#print paren_stack
if not paren_stack:
return True
return False
class TestSolution(unittest.TestCase):
def test_one_of_each(self):
sln = Solution()
self.assertEqual(True, sln.isValid("{}()[]"))
def test_one_of_each_nested(self):
sln = Solution()
self.assertEqual(True, sln.isValid("{([])}"))
def test_two_interleaved(self):
sln = Solution()
self.assertEqual(False, sln.isValid("([)]"))
def test_two_left_open(self):
sln = Solution()
self.assertEqual(False, sln.isValid("(["))
def test_two_close_only(self):
sln = Solution()
self.assertEqual(False, sln.isValid("])"))
def test_extra_open(self):
sln = Solution()
self.assertEqual(False, sln.isValid("([)"))
if __name__ == '__main__':
unittest.main()
<file_sep>"""
>>> from DataStruct import TreeNode
>>> root = TreeNode(2)
>>> root.left = TreeNode(4)
>>> root.right = TreeNode(7)
>>> root.left.left = TreeNode(5)
>>> root.left.right = TreeNode(8)
>>> root.right.left = TreeNode(1)
>>> max_depth(root)
3
"""
def max_depth(root):
""" Maximum Depth of Binary Tree """
if not root:
return 0
if not root.left and not root.right:
return 1
if root.left and root.right:
return max(max_depth(root.left), max_depth(root.right)) + 1
elif root.left:
return max_depth(root.left) + 1
else:
return max_depth(root.right) + 1<file_sep>"""
>>> fizzbuzz(1, 17)
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
"""
def fizzbuzz(start_idx, end_idx):
""" Fizz Buzz """
for val in range(start_idx, end_idx):
if val % 3 == 0 and val % 5 == 0:
print "fizzbuzz"
elif val % 3 == 0:
print "fizz"
elif val % 5 == 0:
print "buzz"
else:
print val
if __name__ == "__main__":
import doctest
doctest.testmod()
<file_sep>"""
>>> compare_version("0.1", "1.1")
-1
>>> compare_version("1.2", "1.1")
1
>>> compare_version("13.37", "13")
1
>>> compare_version("1.2.3.4", "1.2.3.70")
-1
>>> compare_version("1.2.3.4", "1.2.3.4")
0
"""
def compare_version(version1, version2):
""" Compare Version Numbers """
split_ver1 = map(lambda x: int(x), version1.split("."))
split_ver2 = map(lambda x: int(x), version2.split("."))
ver1_len = len(split_ver1)
ver2_len = len(split_ver2)
if ver1_len > ver2_len:
split_ver2 += [0]*(ver1_len-ver2_len)
elif ver2_len > ver1_len:
split_ver1 += [0]*(ver2_len-ver1_len)
for ver1, ver2 in zip(split_ver1, split_ver2):
if ver1 > ver2:
return 1
elif ver2 > ver1:
return -1
return 0
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>class Solution:
# @param s, a string
# @return an integer
def lengthOfLastWord(self, s):
if len(s) == 0:
return 0
last_word_ind = None
current_ind = len(s) - 1
while (last_word_ind is None):
if current_ind == 0:
last_word_ind = 0
if s[current_ind] == ' ':
last_word_ind = current_ind + 1
else:
current_ind -= 1
return len(s) - last_word_ind + 1
<file_sep>"""
>>> two_sum([3, 2, 4], 6)
(2, 3)
>>> two_sum([4, 6, 2, 8, 3, 9], 9)
(2, 5)
"""
def two_sum(num, target):
""" Two Sum """
num_dict = {}
for idx, val in enumerate(num):
num_dict[val] = idx
for idx, val in enumerate(num):
search_val = target - val
if search_val in num_dict:
if num_dict[search_val] > idx:
index1 = idx+1
index2 = num_dict[search_val]+1
return index1, index2
if __name__ == "__main__":
import doctest
doctest.testmod()<file_sep>__author__ = 'aouyang1'
import ipdb
class TreeNode(object):
def __init__(self, item, left=None, right=None, next=None):
self.left = left
self.right = right
self.val = item
self.next = next
class Node(object):
def __init__(self, d):
self.next = None
self.prev = None
self.val = d
def print_values(self, num_elem=None):
cnt = 0
next_node = self.next
print self.val
while next_node is not None:
cnt += 1
if num_elem is not None and cnt == num_elem:
break
print next_node.val
next_node = next_node.next
def append_data(self, val_list):
curr_node = self
for val in val_list:
curr_node.next = Node(val)
curr_node = curr_node.next
class StackClass(object):
def __init__(self):
self.top = None
self.num_elem = 0
self.min_top = None
def push(self, item):
if not self.top:
self.top = Node(item)
self.min_top = Node(item)
else:
# push item to top of stack
old_top = self.top
self.top = Node(item)
self.top.next = old_top
# node with minimum value in stack to top
old_min = self.min_top
if self.min_top.val > item:
new_min = item
else:
new_min = self.min_top.val
self.min_top = Node(new_min)
self.min_top.next = old_min
self.num_elem += 1
def pop(self):
if not self.top:
return None
else:
item = self.top.val
self.top = self.top.next
self.min_top = self.min_top.next
self.num_elem -= 1
return item
def peek(self):
if not self.top:
return None
else:
item = self.top.val
return item
def is_empty(self):
return not self.top
def size(self):
return self.num_elem
def min(self):
if self.top:
return self.min_top.val
else:
return None
class QueueClass(object):
def __init__(self):
self.front = None
self.rear = None
self.num_elem = 0
def enqueue(self, item):
if not self.rear:
self.rear = Node(item)
self.front = self.rear
else:
old_rear = self.rear
self.rear = Node(item)
self.rear.next = old_rear
old_rear.prev = self.rear
self.num_elem += 1
def dequeue(self):
if not self.front:
return None
else:
item = self.front.val
print self.front.prev, self.size()
self.front = self.front.prev
self.front.next = None
self.num_elem -= 1
return item
def is_empty(self):
return not self.rear
def size(self):
return self.num_elem
def sort_stack(s1):
s2 = StackClass()
while not s1.is_empty():
if s2.is_empty() or s1.peek() >= s2.peek():
s2.push(s1.pop())
else:
temp_val = s1.pop()
while not s2.is_empty() and temp_val < s2.peek():
s1.push(s2.pop())
s2.push(temp_val)
return s2
class MyQueue(object):
s1 = StackClass()
s2 = StackClass()
def __init__(self):
self.front = None
self.rear = None
self.num_elem = 0
def enqueue(self, item):
if not self.rear:
self.rear = Node(item)
self.front = self.rear
else:
old_rear = self.rear
self.rear = Node(item)
self.rear.next = old_rear
old_rear.prev = self.rear
self.num_elem += 1
def dequeue(self):
if not self.front:
return None
else:
item = self.front.val
print self.front.prev, self.size()
self.front = self.front.prev
self.front.next = None
self.num_elem -= 1
return item
<file_sep># https://oj.leetcode.com/problems/valid-parentheses/
import unittest
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
return str(self.val)
class LList:
def __init__(self, head=None):
self.head = head
def insert(self, new_node):
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def len(self):
count = 0;
current = self.head
while current:
count += 1
current = current.next
return count
def __repr__(self):
current = self.head
nodes = []
while current:
nodes.append("{}".format(current))
current = current.next
return " -> ".join(nodes)
class Solution:
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA, headB):
long_head = headA
short_head = headB
long_len = self.list_len(headA)
short_len = self.list_len(headB)
if long_len < short_len: # nope, reverse it
temp = long_head
temp_len = long_len
long_head = short_head
long_len = short_len
short_head = temp
short_len = temp_len
long_start_offset = long_len - short_len
print "Offset = %d" % long_start_offset
short_node = short_head
long_node = long_head
for x in range(long_start_offset):
#print "Skipping {}".format(long_node)
long_node = long_node.next
for x in range(short_len):
#print "Comparing {} - {}".format(long_node, short_node)
if short_node == long_node:
return short_node
short_node = short_node.next
long_node = long_node.next
return None
def list_len(self, list_head):
count = 0;
current = list_head
while current:
count += 1
current = current.next
return count
class TestSolution(unittest.TestCase):
def test_prob_example(self):
sln = Solution()
la = LList()
la.insert(ListNode('a1'))
la.insert(ListNode('a2'))
lb = LList()
lb.insert(ListNode('b1'))
lb.insert(ListNode('b2'))
lb.insert(ListNode('b3'))
c1 = ListNode('c1')
lc = LList()
lc.insert(c1)
lc.insert(ListNode('c2'))
lc.insert(ListNode('c3'))
la.insert(c1)
lb.insert(c1)
# print la
# print lb
# print lc
sln = Solution()
self.assertEqual('c1', sln.getIntersectionNode(la.head, lb.head).val)
def test_a_longer(self):
sln = Solution()
la = LList()
la.insert(ListNode('a1'))
la.insert(ListNode('a2'))
la.insert(ListNode('a3'))
lb = LList()
lb.insert(ListNode('b1'))
lb.insert(ListNode('b2'))
c1 = ListNode('c1')
lc = LList()
lc.insert(c1)
lc.insert(ListNode('c2'))
lc.insert(ListNode('c3'))
la.insert(c1)
lb.insert(c1)
sln = Solution()
self.assertEqual('c1', sln.getIntersectionNode(la.head, lb.head).val)
def test_same_len(self):
sln = Solution()
la = LList()
la.insert(ListNode('a1'))
la.insert(ListNode('a2'))
lb = LList()
lb.insert(ListNode('b1'))
lb.insert(ListNode('b2'))
c1 = ListNode('c1')
lc = LList()
lc.insert(c1)
lc.insert(ListNode('c2'))
la.insert(c1)
lb.insert(c1)
sln = Solution()
self.assertEqual('c1', sln.getIntersectionNode(la.head, lb.head).val)
def test_only_one_list(self):
sln = Solution()
la = LList()
lb = LList()
c1 = ListNode('c1')
lc = LList()
lc.insert(c1)
lc.insert(ListNode('c2'))
la.insert(c1)
lb.insert(c1)
sln = Solution()
self.assertEqual('c1', sln.getIntersectionNode(la.head, lb.head).val)
if __name__ == '__main__':
unittest.main()
<file_sep>"""
>>> from DataStruct import TreeNode
>>> root = TreeNode(1)
>>> root.left = TreeNode(2)
>>> root.right = TreeNode(2)
>>> root.left.left = TreeNode(3)
>>> root.left.right = TreeNode(4)
>>> root.right.left = TreeNode(4)
>>> root.right.right = TreeNode(3)
>>> is_symmetric(root)
True
>>> root = TreeNode(1)
>>> root.left = TreeNode(2)
>>> root.right = TreeNode(2)
>>> root.left.right = TreeNode(3)
>>> root.right.right = TreeNode(3)
>>> is_symmetric(root)
False
"""
def is_symmetric(root):
""" Symmetric Tree """
def is_leaf(node):
return node.left is None and node.right is None
if not root or is_leaf(root):
return True
level = [root]
while level:
# fill next level and values of current level
next_level = []
node_val = []
for node in level:
if node.left:
next_level.append(node.left)
node_val.append(node.left.val)
else:
node_val.append(None)
if node.right:
next_level.append(node.right)
node_val.append(node.right.val)
else:
node_val.append(None)
#check if node_val list is symmetric
for n_idx in range(len(node_val)/2):
if node_val[n_idx] != node_val[len(node_val)-n_idx-1]:
return False
# clean level if all None
level = next_level
return True<file_sep>"""
>>> unique_paths(2, 2)
2
>>> unique_paths(3, 3)
6
>>> unique_paths(10, 10)
48620
>>> unique_paths(12, 12)
705432
>>> unique_paths(100, 100)
22750883079422934966181954039568885395604168260154104734000L
"""
memo = {}
def unique_paths(m, n):
""" Unique Paths """
if m == 1 and n == 1:
return 1
if m == 1:
if (m, n-1) not in memo:
memo[(m, n-1)] = unique_paths(m, n-1)
return memo[(m, n-1)]
elif n == 1:
if (m-1, n) not in memo:
memo[(m-1, n)] = unique_paths(m-1, n)
return memo[(m-1, n)]
else:
if (m, n-1) not in memo:
memo[(m, n-1)] = unique_paths(m, n-1)
if (m-1, n) not in memo:
memo[(m-1, n)] = unique_paths(m-1, n)
return memo[(m, n-1)] + memo[(m-1, n)]<file_sep># Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param p, a tree node
# @param q, a tree node
# @return a boolean
def isSameTree(self, p, q):
# first two levels edge cases
if p is None and q is None:
return True
if (p is None) is (q is not None):
return False
# check base structure is same
if (p.left is None) is (q.left is not None):
return False
if (p.right is None) is (q.right is not None):
return False
# check current node values
if p.val != q.val:
return False
# base case
if p.left is None and p.right is None:
return True
# other cases
elif p.left is None:
return self.isSameTree(p.right, q.right)
elif p.right is None:
return self.isSameTree(p.left, q.left)
else:
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
| a8de3c933a554005beafba692afccdb558887cb5 | [
"Markdown",
"Python"
] | 66 | Python | aouyang1/InsightInterviewPractice | 96532db8333e52ef250083e5adcf02ab64e7ba22 | abaaa53ba1ce65bfc089f01853526150b210b354 | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Threading.Tasks;
namespace LabDFP
{
public struct Response
{
public PointF Arg { get; set; }
public double Func { get; set; }
public int Iterations { get; set; }
}
class MainMethod
{
public double Function(PointF x)
{
return Math.Pow(x.X - 2, 2) + Math.Pow(x.Y - 3, 2);
//return 2 * Math.Pow(x.X, 2) + x.X * x.Y + Math.Pow(x.Y, 2);
}
private double FunctionGrad1(PointF x)
{
// (x^2 - 4x + 4) + (y^2 - 6y + 9)
//return 4 * x.X + x.Y;
return 2 * x.X - 4;
}
private double FunctionGrad2(PointF x)
{
//return x.X + 2 * x.Y;
return 2 * x.Y - 6;
}
private double Grad(int i, PointF x)
{
switch (i)
{
case 1:
return FunctionGrad1(x);
case 2:
return FunctionGrad2(x);
}
throw new ArgumentException("Ошибка!");
}
private double StepResolver(double x1, double x2, double c1, double c2)
{
return (4 * x1 * c1 + x1 * c2 + x2 * c1 + 2 * x2 * c2) /
(4 * c1 * c1 + 2 * c1 * c2 + 2 * c2 * c2);
}
private PointF _x, _xPrev, _xPrevPrev, deltaX;
private double _e1, _e2, _t;
private int k, _m;
private double[] fg, d, dg;
private double[,] A, Ac;
public Response FindMinValue(double x0, double y0, double e1, double e2, int m)
{
A = new double[,] { { 1, 0 }, { 0, 1 } };
d = new double[2];
dg = new double[2];
_x = new PointF(Convert.ToSingle(x0), Convert.ToSingle(y0));
_xPrev = _x;
k = 0;
_m = m;
_e1 = e1;
_e2 = e2;
THREE:
fg = new[]
{
Grad(1, _x),
Grad(2, _x)
};
FOUR:
double fgLength = (double)Math.Sqrt(fg[0] * fg[0] + fg[1] * fg[1]);
if (fgLength < _e1)
{
goto END;
}
FIVE:
if (k >= _m)
{
goto END;
}
if (k > 0)
{
goto SIX;
}
else
{
goto TEN;
}
SIX:
double[] fgPrev = { Grad(1, _xPrev), Grad(2, _xPrev) };
dg = new[] { fg[0] - fgPrev[0], fg[1] - fgPrev[1] };
SEVEN:
deltaX = new PointF(_x.X - _xPrev.X, _x.Y - _xPrev.Y);
EIGHT:
double c1 = deltaX.X * dg[0] + deltaX.Y * dg[1];
double[,] At1 =
{
{deltaX.X * deltaX.X / c1, deltaX.X * deltaX.Y / c1},
{deltaX.Y * deltaX.X / c1, deltaX.Y * deltaX.Y / c1}
};
PointF v1 = new PointF
{
X = Convert.ToSingle(A[0, 0] * dg[0] + A[0, 1] * dg[1]),
Y = Convert.ToSingle(A[1, 0] * dg[0] + A[1, 1] * dg[1])
};
double[,] At2 =
{
{v1.X * dg[0], v1.X * dg[1]},
{v1.Y * dg[0], v1.Y * dg[1]}
};
PointF v2 = new PointF
{
X = Convert.ToSingle(dg[0] * A[0, 0] + dg[1] * A[1, 0]),
Y = Convert.ToSingle(dg[1] * A[0, 1] + dg[1] * A[1, 1])
};
double c2 = v1.X * dg[0] + v1.Y * dg[1];
double[,] At3 =
{
{
(At2[0, 0] * A[0, 0] + At2[0, 1] * A[1, 0]) / c2,
(At2[0, 0] * A[0, 1] + At2[0, 1] * A[1, 1]) / c2
},
{
(At2[1, 0] * A[0, 0] + At2[1, 1] * A[1, 0]) / c2,
(At2[1, 0] * A[0, 1] + At2[1, 1] * A[1, 1]) / c2
}
};
Ac = new[,]
{
{At1[0, 0] - At3[0, 0], At1[0, 1] - At3[0, 1]},
{At1[1, 0] - At3[1, 0], At1[1, 1] - At3[1, 1]}
};
NINE:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
A[i, j] += Ac[i, j];
}
}
TEN:
d = new[]
{
-(A[0, 0] * fg[0] + A[0, 1] * fg[1]),
-(A[1, 0] * fg[0] + A[1, 1] * fg[1])
};
ELEVEN:
_t = StepResolver(_x.X, _x.Y, d[0], d[1]);
TWELVE:
_xPrev = _x;
PointF temp12 = new PointF
{
X = Convert.ToSingle(_x.X - _t * d[0]),
Y = Convert.ToSingle(_x.Y - _t * d[1])
};
_x = temp12;
THIRTEEN:
PointF temp13 = new PointF
{
X = _x.X - _xPrev.X,
Y = _x.Y - _xPrev.Y
};
double tempL = (double)Math.Sqrt(temp13.X * temp13.X + temp13.Y * temp13.Y);
double F = Function(_x);
double F1 = Function(_xPrev);
if (tempL < _e2 && Math.Abs(Function(_x) - Function(_xPrev)) < _e2)
{
goto END;
}
k++;
goto THREE;
END:
return new Response
{
Arg = _x,
Func = Function(_x),
Iterations = k
};
}
}
}
| 997af23b41ae54a978aba4b281e4f02c44b33a5f | [
"C#"
] | 1 | C# | MrMagic24/LabDFP | f659cdd8e63530a5b95be96aa8edef4116204132 | 6623c233f6b0769192c783345cedbb65ceb43ea6 | |
refs/heads/master | <file_sep>package uk.gov.meto.javaguild;
import javax.swing.*;
import java.util.ArrayDeque;
import java.util.Random;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Hello world!
*/
public class App {
static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
static PriceService priceService = new PriceService();
static PriceDisplay priceDisplay = new PriceDisplay();
static RollingBuffer rollingBuffer = new RollingBuffer();
public static void main(String[] args) throws InterruptedException {
Runtime.getRuntime().addShutdownHook(new Thread(executor::shutdown));
executor.scheduleWithFixedDelay(() -> {
final int price = priceService.getPrice();
rollingBuffer.add(price);
SwingUtilities.invokeLater(() -> priceDisplay.setPrice(price));
SwingUtilities.invokeLater(() -> priceDisplay.setAverage(rollingBuffer.getAverage()));
}, 0, 500, TimeUnit.MILLISECONDS);
}
public static class RollingBuffer {
private final ArrayDeque<Integer> buffer = new ArrayDeque<>(5);
private final int bufferSize = 5;
public synchronized void add(int value) {
if (buffer.size() == bufferSize) {
buffer.removeFirst();
}
buffer.addLast(value);
}
public synchronized double getAverage() {
if (buffer.size() < bufferSize) {
return 0;
} else {
return buffer.stream().mapToInt(Integer::valueOf).average().orElseGet(() -> 0);
}
}
}
public static class PriceDisplay {
private final JLabel priceLabel;
private final JLabel averageLabel;
private final JFrame jFrame;
public PriceDisplay() {
jFrame = new JFrame("Price Monitor");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.getContentPane().setLayout(new BoxLayout(jFrame.getContentPane(), BoxLayout.Y_AXIS));
priceLabel = new JLabel("Price: - ");
averageLabel = new JLabel("Average Price: - ");
jFrame.add(Box.createVerticalGlue());
jFrame.add(priceLabel);
jFrame.add(Box.createVerticalGlue());
jFrame.add(averageLabel);
jFrame.add(Box.createVerticalGlue());
jFrame.setSize(200, 100);
jFrame.setVisible(true);
}
public void setPrice(int price) {
priceLabel.setText("Price: " + price);
}
public void setAverage(double average) {
averageLabel.setText("Average Price: " + average);
}
}
public static class PriceService {
private final int maxDelay;
private final int minDelay;
private final Random random = new Random();
public PriceService() {
maxDelay = 500;
minDelay = 200;
}
public int getPrice() {
try {
Thread.sleep((int) (Math.random() * (maxDelay - minDelay) + minDelay));
} catch (InterruptedException e) {
e.printStackTrace();
}
return random.nextInt(1000);
}
}
}
| fa89bfd0a36cd3be3fd38c56edb9e0e173006058 | [
"Java"
] | 1 | Java | umdeeahhdee/rx-workshop | 69e9a88c19c7d72171ebbe3acdc842c61aa49efa | 1200b0ee3c7628347cdff73b68b1b00b85dd8a2e | |
refs/heads/master | <repo_name>ikyzmin/googletranslatelab1<file_sep>/app/src/main/java/com/ssau/googletranslateexample/TranslateActivity.java
package com.ssau.googletranslateexample;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
public class TranslateActivity extends AppCompatActivity {
private ActionBarDrawerToggle menuToggle;
private AppCompatSpinner sourceSpinner;
private AppCompatSpinner destSpinner;
private AppCompatImageView changeLangButton;
private String[] data;
private DrawerLayout drawer;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
data = getResources().getStringArray(R.array.languages);
setContentView(R.layout.a_translate);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sourceSpinner = (AppCompatSpinner) findViewById(R.id.source_lang);
destSpinner = (AppCompatSpinner) findViewById(R.id.dest_lang);
drawer = (DrawerLayout)findViewById(R.id.drawer);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
sourceSpinner.setAdapter(adapter);
destSpinner.setAdapter(adapter);
toolbar.setNavigationIcon(R.drawable.toggle);
menuToggle = new ActionBarDrawerToggle(this, drawer,
toolbar, 0, 0) {
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
menuToggle.syncState();
}
@Override
protected void onResume() {
super.onResume();
}
}
| 450549f74731b28d1e6225b7fb17f4661751a3e0 | [
"Java"
] | 1 | Java | ikyzmin/googletranslatelab1 | 0c012c8eda96fa867b36c1f46a423bd0bed8d8cd | e9ace1bb30328cc06b724284a78248a27e5b0218 | |
refs/heads/master | <file_sep>module.exports = (css, settings) => {
const sass = getSassImplementation();
const cssWithPlaceholders = css
.replace(
/%%styled-jsx-placeholder-(\d+)%%(\w*\s*[),;!{])/g,
(_, id, p1) => `styled-jsx-placeholder-${id}-${p1}`
)
.replace(
/%%styled-jsx-placeholder-(\d+)%%/g,
(_, id) => `/*%%styled-jsx-placeholder-${id}%%*/`
);
// Prepend option data to cssWithPlaceholders
const optionData = (settings.sassOptions && settings.sassOptions.data) || '';
const data = optionData + '\n' + cssWithPlaceholders;
const preprocessed = sass
.renderSync(Object.assign({}, settings.sassOptions, {data}))
.css.toString();
return preprocessed
.replace(
/styled-jsx-placeholder-(\d+)-(\w*\s*[),;!{])/g,
(_, id, p1) => `%%styled-jsx-placeholder-${id}%%${p1}`
)
.replace(
/\/\*%%styled-jsx-placeholder-(\d+)%%\*\//g,
(_, id) => `%%styled-jsx-placeholder-${id}%%`
);
};
function getSassImplementation() {
let sassImplPkg = 'sass';
try {
require.resolve('sass');
} catch {
try {
require.resolve('node-sass');
sassImplPkg = 'node-sass';
} catch {
sassImplPkg = 'sass';
}
}
return require(sassImplPkg);
}
| ae429ed9e667bfd5fa75c34d944a288356ba71d0 | [
"JavaScript"
] | 1 | JavaScript | xhuz/styled-jsx-plugin-sass | eabd57a286ecd88430dd707a20ffeca2ba50c14f | e8da90acd934d446ea743c361ca1513b6265bc96 | |
refs/heads/main | <file_sep>gdjs.StartCode = {};
gdjs.StartCode.GDGreenFloorObjects1= [];
gdjs.StartCode.GDGreenFloorObjects2= [];
gdjs.StartCode.GDGreenFloorObjects3= [];
gdjs.StartCode.GDbg3Objects1= [];
gdjs.StartCode.GDbg3Objects2= [];
gdjs.StartCode.GDbg3Objects3= [];
gdjs.StartCode.GDbg4Objects1= [];
gdjs.StartCode.GDbg4Objects2= [];
gdjs.StartCode.GDbg4Objects3= [];
gdjs.StartCode.GDbg5Objects1= [];
gdjs.StartCode.GDbg5Objects2= [];
gdjs.StartCode.GDbg5Objects3= [];
gdjs.StartCode.GDbg6Objects1= [];
gdjs.StartCode.GDbg6Objects2= [];
gdjs.StartCode.GDbg6Objects3= [];
gdjs.StartCode.GDbg7Objects1= [];
gdjs.StartCode.GDbg7Objects2= [];
gdjs.StartCode.GDbg7Objects3= [];
gdjs.StartCode.GDbg8Objects1= [];
gdjs.StartCode.GDbg8Objects2= [];
gdjs.StartCode.GDbg8Objects3= [];
gdjs.StartCode.GDbg9Objects1= [];
gdjs.StartCode.GDbg9Objects2= [];
gdjs.StartCode.GDbg9Objects3= [];
gdjs.StartCode.GDWinObjects1= [];
gdjs.StartCode.GDWinObjects2= [];
gdjs.StartCode.GDWinObjects3= [];
gdjs.StartCode.GDStartButtonObjects1= [];
gdjs.StartCode.GDStartButtonObjects2= [];
gdjs.StartCode.GDStartButtonObjects3= [];
gdjs.StartCode.conditionTrue_0 = {val:false};
gdjs.StartCode.condition0IsTrue_0 = {val:false};
gdjs.StartCode.condition1IsTrue_0 = {val:false};
gdjs.StartCode.condition2IsTrue_0 = {val:false};
gdjs.StartCode.mapOfGDgdjs_46StartCode_46GDStartButtonObjects1Objects = Hashtable.newFrom({"StartButton": gdjs.StartCode.GDStartButtonObjects1});gdjs.StartCode.eventsList0 = function(runtimeScene) {
{
gdjs.StartCode.condition0IsTrue_0.val = false;
{
gdjs.StartCode.condition0IsTrue_0.val = gdjs.evtTools.input.isMouseButtonPressed(runtimeScene, "Left");
}if (gdjs.StartCode.condition0IsTrue_0.val) {
gdjs.copyArray(gdjs.StartCode.GDStartButtonObjects1, gdjs.StartCode.GDStartButtonObjects2);
{for(var i = 0, len = gdjs.StartCode.GDStartButtonObjects2.length ;i < len;++i) {
gdjs.StartCode.GDStartButtonObjects2[i].getBehavior("Tween").addObjectScaleTween("pressed2", 1.1, 1.1, "easeTo", 500, false, true);
}
}{for(var i = 0, len = gdjs.StartCode.GDStartButtonObjects2.length ;i < len;++i) {
gdjs.StartCode.GDStartButtonObjects2[i].getBehavior("Tween").addObjectColorTween("pressed", "25;28;50", "easeTo", 500, false);
}
}}
}
{
gdjs.StartCode.condition0IsTrue_0.val = false;
{
gdjs.StartCode.condition0IsTrue_0.val = gdjs.evtTools.input.isMouseButtonReleased(runtimeScene, "Left");
}if (gdjs.StartCode.condition0IsTrue_0.val) {
{gdjs.evtTools.runtimeScene.replaceScene(runtimeScene, "New scene 1", false);
}}
}
};gdjs.StartCode.mapOfGDgdjs_46StartCode_46GDStartButtonObjects1Objects = Hashtable.newFrom({"StartButton": gdjs.StartCode.GDStartButtonObjects1});gdjs.StartCode.mapOfGDgdjs_46StartCode_46GDStartButtonObjects1Objects = Hashtable.newFrom({"StartButton": gdjs.StartCode.GDStartButtonObjects1});gdjs.StartCode.eventsList1 = function(runtimeScene) {
{
gdjs.StartCode.condition0IsTrue_0.val = false;
{
gdjs.StartCode.condition0IsTrue_0.val = gdjs.evtTools.runtimeScene.sceneJustBegins(runtimeScene);
}if (gdjs.StartCode.condition0IsTrue_0.val) {
gdjs.copyArray(runtimeScene.getObjects("bg9"), gdjs.StartCode.GDbg9Objects1);
{for(var i = 0, len = gdjs.StartCode.GDbg9Objects1.length ;i < len;++i) {
gdjs.StartCode.GDbg9Objects1[i].setColor("158;178;218");
}
}}
}
{
gdjs.copyArray(runtimeScene.getObjects("StartButton"), gdjs.StartCode.GDStartButtonObjects1);
gdjs.StartCode.condition0IsTrue_0.val = false;
{
gdjs.StartCode.condition0IsTrue_0.val = gdjs.evtTools.input.cursorOnObject(gdjs.StartCode.mapOfGDgdjs_46StartCode_46GDStartButtonObjects1Objects, runtimeScene, true, false);
}if (gdjs.StartCode.condition0IsTrue_0.val) {
{ //Subevents
gdjs.StartCode.eventsList0(runtimeScene);} //End of subevents
}
}
{
gdjs.copyArray(runtimeScene.getObjects("StartButton"), gdjs.StartCode.GDStartButtonObjects1);
gdjs.StartCode.condition0IsTrue_0.val = false;
gdjs.StartCode.condition1IsTrue_0.val = false;
{
gdjs.StartCode.condition0IsTrue_0.val = !(gdjs.evtTools.input.isMouseButtonPressed(runtimeScene, "Left"));
}if ( gdjs.StartCode.condition0IsTrue_0.val ) {
{
gdjs.StartCode.condition1IsTrue_0.val = gdjs.evtTools.input.cursorOnObject(gdjs.StartCode.mapOfGDgdjs_46StartCode_46GDStartButtonObjects1Objects, runtimeScene, true, false);
}}
if (gdjs.StartCode.condition1IsTrue_0.val) {
/* Reuse gdjs.StartCode.GDStartButtonObjects1 */
{for(var i = 0, len = gdjs.StartCode.GDStartButtonObjects1.length ;i < len;++i) {
gdjs.StartCode.GDStartButtonObjects1[i].getBehavior("Tween").addObjectScaleTween("hover2", 1.2, 1.2, "easeTo", 500, false, true);
}
}{for(var i = 0, len = gdjs.StartCode.GDStartButtonObjects1.length ;i < len;++i) {
gdjs.StartCode.GDStartButtonObjects1[i].getBehavior("Tween").addObjectColorTween("hover", "255;255;255", "easeTo", 500, false);
}
}}
}
{
gdjs.copyArray(runtimeScene.getObjects("StartButton"), gdjs.StartCode.GDStartButtonObjects1);
gdjs.StartCode.condition0IsTrue_0.val = false;
{
gdjs.StartCode.condition0IsTrue_0.val = gdjs.evtTools.input.cursorOnObject(gdjs.StartCode.mapOfGDgdjs_46StartCode_46GDStartButtonObjects1Objects, runtimeScene, true, true);
}if (gdjs.StartCode.condition0IsTrue_0.val) {
/* Reuse gdjs.StartCode.GDStartButtonObjects1 */
{for(var i = 0, len = gdjs.StartCode.GDStartButtonObjects1.length ;i < len;++i) {
gdjs.StartCode.GDStartButtonObjects1[i].getBehavior("Tween").addObjectScaleTween("normal2", 1, 1, "easeTo", 500, false, true);
}
}{for(var i = 0, len = gdjs.StartCode.GDStartButtonObjects1.length ;i < len;++i) {
gdjs.StartCode.GDStartButtonObjects1[i].getBehavior("Tween").addObjectColorTween("normal", "255;255;255", "easeTo", 500, false);
}
}}
}
};
gdjs.StartCode.func = function(runtimeScene) {
runtimeScene.getOnceTriggers().startNewFrame();
gdjs.StartCode.GDGreenFloorObjects1.length = 0;
gdjs.StartCode.GDGreenFloorObjects2.length = 0;
gdjs.StartCode.GDGreenFloorObjects3.length = 0;
gdjs.StartCode.GDbg3Objects1.length = 0;
gdjs.StartCode.GDbg3Objects2.length = 0;
gdjs.StartCode.GDbg3Objects3.length = 0;
gdjs.StartCode.GDbg4Objects1.length = 0;
gdjs.StartCode.GDbg4Objects2.length = 0;
gdjs.StartCode.GDbg4Objects3.length = 0;
gdjs.StartCode.GDbg5Objects1.length = 0;
gdjs.StartCode.GDbg5Objects2.length = 0;
gdjs.StartCode.GDbg5Objects3.length = 0;
gdjs.StartCode.GDbg6Objects1.length = 0;
gdjs.StartCode.GDbg6Objects2.length = 0;
gdjs.StartCode.GDbg6Objects3.length = 0;
gdjs.StartCode.GDbg7Objects1.length = 0;
gdjs.StartCode.GDbg7Objects2.length = 0;
gdjs.StartCode.GDbg7Objects3.length = 0;
gdjs.StartCode.GDbg8Objects1.length = 0;
gdjs.StartCode.GDbg8Objects2.length = 0;
gdjs.StartCode.GDbg8Objects3.length = 0;
gdjs.StartCode.GDbg9Objects1.length = 0;
gdjs.StartCode.GDbg9Objects2.length = 0;
gdjs.StartCode.GDbg9Objects3.length = 0;
gdjs.StartCode.GDWinObjects1.length = 0;
gdjs.StartCode.GDWinObjects2.length = 0;
gdjs.StartCode.GDWinObjects3.length = 0;
gdjs.StartCode.GDStartButtonObjects1.length = 0;
gdjs.StartCode.GDStartButtonObjects2.length = 0;
gdjs.StartCode.GDStartButtonObjects3.length = 0;
gdjs.StartCode.eventsList1(runtimeScene);
return;
}
gdjs['StartCode'] = gdjs.StartCode;
<file_sep>gdjs.ByeCode = {};
gdjs.ByeCode.GDGreenFloorObjects1= [];
gdjs.ByeCode.GDGreenFloorObjects2= [];
gdjs.ByeCode.GDGreenFloorObjects3= [];
gdjs.ByeCode.GDbg3Objects1= [];
gdjs.ByeCode.GDbg3Objects2= [];
gdjs.ByeCode.GDbg3Objects3= [];
gdjs.ByeCode.GDbg4Objects1= [];
gdjs.ByeCode.GDbg4Objects2= [];
gdjs.ByeCode.GDbg4Objects3= [];
gdjs.ByeCode.GDbg5Objects1= [];
gdjs.ByeCode.GDbg5Objects2= [];
gdjs.ByeCode.GDbg5Objects3= [];
gdjs.ByeCode.GDbg6Objects1= [];
gdjs.ByeCode.GDbg6Objects2= [];
gdjs.ByeCode.GDbg6Objects3= [];
gdjs.ByeCode.GDbg7Objects1= [];
gdjs.ByeCode.GDbg7Objects2= [];
gdjs.ByeCode.GDbg7Objects3= [];
gdjs.ByeCode.GDbg8Objects1= [];
gdjs.ByeCode.GDbg8Objects2= [];
gdjs.ByeCode.GDbg8Objects3= [];
gdjs.ByeCode.GDbg9Objects1= [];
gdjs.ByeCode.GDbg9Objects2= [];
gdjs.ByeCode.GDbg9Objects3= [];
gdjs.ByeCode.GDWinObjects1= [];
gdjs.ByeCode.GDWinObjects2= [];
gdjs.ByeCode.GDWinObjects3= [];
gdjs.ByeCode.GDStartButtonObjects1= [];
gdjs.ByeCode.GDStartButtonObjects2= [];
gdjs.ByeCode.GDStartButtonObjects3= [];
gdjs.ByeCode.conditionTrue_0 = {val:false};
gdjs.ByeCode.condition0IsTrue_0 = {val:false};
gdjs.ByeCode.condition1IsTrue_0 = {val:false};
gdjs.ByeCode.condition2IsTrue_0 = {val:false};
gdjs.ByeCode.mapOfGDgdjs_46ByeCode_46GDStartButtonObjects1Objects = Hashtable.newFrom({"StartButton": gdjs.ByeCode.GDStartButtonObjects1});gdjs.ByeCode.eventsList0 = function(runtimeScene) {
{
gdjs.ByeCode.condition0IsTrue_0.val = false;
{
gdjs.ByeCode.condition0IsTrue_0.val = gdjs.evtTools.input.isMouseButtonPressed(runtimeScene, "Left");
}if (gdjs.ByeCode.condition0IsTrue_0.val) {
gdjs.copyArray(gdjs.ByeCode.GDStartButtonObjects1, gdjs.ByeCode.GDStartButtonObjects2);
{for(var i = 0, len = gdjs.ByeCode.GDStartButtonObjects2.length ;i < len;++i) {
gdjs.ByeCode.GDStartButtonObjects2[i].getBehavior("Tween").addObjectScaleTween("pressed2", 1.1, 1.1, "easeTo", 500, false, true);
}
}{for(var i = 0, len = gdjs.ByeCode.GDStartButtonObjects2.length ;i < len;++i) {
gdjs.ByeCode.GDStartButtonObjects2[i].getBehavior("Tween").addObjectColorTween("pressed", "25;28;50", "easeTo", 500, false);
}
}}
}
{
gdjs.ByeCode.condition0IsTrue_0.val = false;
{
gdjs.ByeCode.condition0IsTrue_0.val = gdjs.evtTools.input.isMouseButtonReleased(runtimeScene, "Left");
}if (gdjs.ByeCode.condition0IsTrue_0.val) {
{gdjs.evtTools.runtimeScene.replaceScene(runtimeScene, "New scene 1", false);
}}
}
};gdjs.ByeCode.mapOfGDgdjs_46ByeCode_46GDStartButtonObjects1Objects = Hashtable.newFrom({"StartButton": gdjs.ByeCode.GDStartButtonObjects1});gdjs.ByeCode.mapOfGDgdjs_46ByeCode_46GDStartButtonObjects1Objects = Hashtable.newFrom({"StartButton": gdjs.ByeCode.GDStartButtonObjects1});gdjs.ByeCode.eventsList1 = function(runtimeScene) {
{
gdjs.ByeCode.condition0IsTrue_0.val = false;
{
gdjs.ByeCode.condition0IsTrue_0.val = gdjs.evtTools.runtimeScene.sceneJustBegins(runtimeScene);
}if (gdjs.ByeCode.condition0IsTrue_0.val) {
gdjs.copyArray(runtimeScene.getObjects("bg9"), gdjs.ByeCode.GDbg9Objects1);
{for(var i = 0, len = gdjs.ByeCode.GDbg9Objects1.length ;i < len;++i) {
gdjs.ByeCode.GDbg9Objects1[i].setColor("158;178;218");
}
}}
}
{
gdjs.copyArray(runtimeScene.getObjects("StartButton"), gdjs.ByeCode.GDStartButtonObjects1);
gdjs.ByeCode.condition0IsTrue_0.val = false;
{
gdjs.ByeCode.condition0IsTrue_0.val = gdjs.evtTools.input.cursorOnObject(gdjs.ByeCode.mapOfGDgdjs_46ByeCode_46GDStartButtonObjects1Objects, runtimeScene, true, false);
}if (gdjs.ByeCode.condition0IsTrue_0.val) {
{ //Subevents
gdjs.ByeCode.eventsList0(runtimeScene);} //End of subevents
}
}
{
gdjs.copyArray(runtimeScene.getObjects("StartButton"), gdjs.ByeCode.GDStartButtonObjects1);
gdjs.ByeCode.condition0IsTrue_0.val = false;
gdjs.ByeCode.condition1IsTrue_0.val = false;
{
gdjs.ByeCode.condition0IsTrue_0.val = !(gdjs.evtTools.input.isMouseButtonPressed(runtimeScene, "Left"));
}if ( gdjs.ByeCode.condition0IsTrue_0.val ) {
{
gdjs.ByeCode.condition1IsTrue_0.val = gdjs.evtTools.input.cursorOnObject(gdjs.ByeCode.mapOfGDgdjs_46ByeCode_46GDStartButtonObjects1Objects, runtimeScene, true, false);
}}
if (gdjs.ByeCode.condition1IsTrue_0.val) {
/* Reuse gdjs.ByeCode.GDStartButtonObjects1 */
{for(var i = 0, len = gdjs.ByeCode.GDStartButtonObjects1.length ;i < len;++i) {
gdjs.ByeCode.GDStartButtonObjects1[i].getBehavior("Tween").addObjectScaleTween("hover2", 1.2, 1.2, "easeTo", 500, false, true);
}
}{for(var i = 0, len = gdjs.ByeCode.GDStartButtonObjects1.length ;i < len;++i) {
gdjs.ByeCode.GDStartButtonObjects1[i].getBehavior("Tween").addObjectColorTween("hover", "255;255;255", "easeTo", 500, false);
}
}}
}
{
gdjs.copyArray(runtimeScene.getObjects("StartButton"), gdjs.ByeCode.GDStartButtonObjects1);
gdjs.ByeCode.condition0IsTrue_0.val = false;
{
gdjs.ByeCode.condition0IsTrue_0.val = gdjs.evtTools.input.cursorOnObject(gdjs.ByeCode.mapOfGDgdjs_46ByeCode_46GDStartButtonObjects1Objects, runtimeScene, true, true);
}if (gdjs.ByeCode.condition0IsTrue_0.val) {
/* Reuse gdjs.ByeCode.GDStartButtonObjects1 */
{for(var i = 0, len = gdjs.ByeCode.GDStartButtonObjects1.length ;i < len;++i) {
gdjs.ByeCode.GDStartButtonObjects1[i].getBehavior("Tween").addObjectScaleTween("normal2", 1, 1, "easeTo", 500, false, true);
}
}{for(var i = 0, len = gdjs.ByeCode.GDStartButtonObjects1.length ;i < len;++i) {
gdjs.ByeCode.GDStartButtonObjects1[i].getBehavior("Tween").addObjectColorTween("normal", "255;255;255", "easeTo", 500, false);
}
}}
}
};
gdjs.ByeCode.func = function(runtimeScene) {
runtimeScene.getOnceTriggers().startNewFrame();
gdjs.ByeCode.GDGreenFloorObjects1.length = 0;
gdjs.ByeCode.GDGreenFloorObjects2.length = 0;
gdjs.ByeCode.GDGreenFloorObjects3.length = 0;
gdjs.ByeCode.GDbg3Objects1.length = 0;
gdjs.ByeCode.GDbg3Objects2.length = 0;
gdjs.ByeCode.GDbg3Objects3.length = 0;
gdjs.ByeCode.GDbg4Objects1.length = 0;
gdjs.ByeCode.GDbg4Objects2.length = 0;
gdjs.ByeCode.GDbg4Objects3.length = 0;
gdjs.ByeCode.GDbg5Objects1.length = 0;
gdjs.ByeCode.GDbg5Objects2.length = 0;
gdjs.ByeCode.GDbg5Objects3.length = 0;
gdjs.ByeCode.GDbg6Objects1.length = 0;
gdjs.ByeCode.GDbg6Objects2.length = 0;
gdjs.ByeCode.GDbg6Objects3.length = 0;
gdjs.ByeCode.GDbg7Objects1.length = 0;
gdjs.ByeCode.GDbg7Objects2.length = 0;
gdjs.ByeCode.GDbg7Objects3.length = 0;
gdjs.ByeCode.GDbg8Objects1.length = 0;
gdjs.ByeCode.GDbg8Objects2.length = 0;
gdjs.ByeCode.GDbg8Objects3.length = 0;
gdjs.ByeCode.GDbg9Objects1.length = 0;
gdjs.ByeCode.GDbg9Objects2.length = 0;
gdjs.ByeCode.GDbg9Objects3.length = 0;
gdjs.ByeCode.GDWinObjects1.length = 0;
gdjs.ByeCode.GDWinObjects2.length = 0;
gdjs.ByeCode.GDWinObjects3.length = 0;
gdjs.ByeCode.GDStartButtonObjects1.length = 0;
gdjs.ByeCode.GDStartButtonObjects2.length = 0;
gdjs.ByeCode.GDStartButtonObjects3.length = 0;
gdjs.ByeCode.eventsList1(runtimeScene);
return;
}
gdjs['ByeCode'] = gdjs.ByeCode;
| c89b5820918591ebc34daa880b19cdf690abbd7f | [
"JavaScript"
] | 2 | JavaScript | Videojuegos-Secundaria-Tercero/3010-emilianoa | ebd19b886d3171834f6404fd070045c0cc524a59 | 945147a14d0cf249d3461c3e7dac03f1a6d24ce1 | |
refs/heads/master | <file_sep>package com.lti.portal.microallotmovie.controller;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lti.portal.microallotmovie.document.Allotmovie;
import com.lti.portal.microallotmovie.dto.AllotmovieDetailDto;
import com.lti.portal.microallotmovie.dto.AllotmovieDto;
import com.lti.portal.microallotmovie.service.AllotmovieService;
@RestController
@RequestMapping("/api/allotmovie")
public class AllotmovieDetailController {
private AllotmovieService allotmovieService;
public AllotmovieDetailController(AllotmovieService allotmovieService) {
// TODO Auto-generated constructor stub
this.allotmovieService=allotmovieService;
}
//post method
@PostMapping("/save/{movieId}/{multiplexId}")
public ResponseEntity<AllotmovieDetailDto> saveMovieMultiplexMapping(@PathVariable("movieId") String movieId,
@PathVariable("multiplexId") String multiplexId, @RequestBody AllotmovieDto allotmovieDto)
{
AllotmovieDetailDto allotmovieDetailDto2 = this.allotmovieService.saveMovieMultiplexMapping(allotmovieDto,
movieId,multiplexId);
ResponseEntity<AllotmovieDetailDto> respose = new ResponseEntity<AllotmovieDetailDto>(allotmovieDetailDto2, HttpStatus.OK);
return respose;
}
@GetMapping("/{multiplexId}/{screenno}")
public ResponseEntity<Allotmovie> findByMultiplexIdAndScreenno (@PathVariable("multiplexId") String multiplexId,
@PathVariable("screenno")int screenno)
{
Allotmovie allotmovie = this.allotmovieService.findByMultiplexIdAndScreenno(multiplexId, screenno);
ResponseEntity<Allotmovie> response= new ResponseEntity<Allotmovie>(allotmovie, HttpStatus.OK);
return response;
}
@GetMapping("/allotlist")
public List<AllotmovieDetailDto> getAllAllotedList()
{
List<AllotmovieDetailDto> allotedList= this.allotmovieService.getAlldetails();
return allotedList;
}
@GetMapping("/searchlist/{movieId}")
public List<AllotmovieDetailDto> findByMovieId(@PathVariable("movieId") String movieId)
{
List<AllotmovieDetailDto> allotedsearchList= this.allotmovieService.findByMovieId(movieId);
return allotedsearchList;
}
}
<file_sep>package com.lti.training.microuser.dto;
import org.hibernate.validator.constraints.Length;
import lombok.Data;
@Data
public class LoginDto {
private String loginId;
@Length(min = 6)
private String password;
}
<file_sep>export class allotMovie
{
id:String;
movieId:String;
multiplexId:string;
screenno:number;
}<file_sep>import { Component,OnInit } from '@angular/core';
import { AuthenticationService } from './service/authentication.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'multiplex';
loggedin:boolean;
constructor(private authser:AuthenticationService){}
ngOnInit(): void {
console.log("hi");
this.loggedin=this.authser.isUserLoggedIn();
console.log(this.loggedin);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import{MovieService} from "../service/movie.service";
import{Movie} from "../movie/movie";
import{Router} from "@angular/router";
@Component({
selector: 'app-list-movie',
templateUrl: './list-movie.component.html',
styleUrls: ['./list-movie.component.css']
})
export class ListMovieComponent implements OnInit {
movies:Movie[];
constructor(private movieService:MovieService,private router:Router) { }
ngOnInit(): void {
this.movieService.getMovies().subscribe(data=>{
console.log("list");
console.log(data);
this.movies=data;
});
}
deleteMovie(movie:Movie)
{
this.movieService.deleteMovie(movie.id).subscribe(data=>{
console.log(data);
if(data=="success")
{
this.router.navigate(['/listmovie']);
}
else{
alert("OOPS!Something went wrong");
}
});
}
updateMovie(movie:Movie)
{
window.localStorage.removeItem("editmovieid")
window.localStorage.setItem("editmovieid",movie.id.toString());
this.router.navigate(['/updatemovie']);
}
}
<file_sep>package com.lti.portal.micromovie.controller;
import java.util.List;
import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lti.portal.micromovie.document.MovieDetail;
import com.lti.portal.micromovie.dto.MovieDetailDto;
import com.lti.portal.micromovie.service.MovieService;
@RestController
@RequestMapping("/api/movie")
public class MovieDetailController {
private MovieService movieService;
@Autowired
public MovieDetailController(MovieService movieService) {
// TODO Auto-generated constructor stub
this.movieService=movieService;
}
@PostMapping("/create")
public ResponseEntity<MovieDetailDto> createMovie(@RequestBody MovieDetailDto movieDetailDto) {
System.out.println("create movie");
MovieDetailDto movieDetailDto2= this.movieService.createMovie(movieDetailDto);
ResponseEntity<MovieDetailDto> response=new ResponseEntity<MovieDetailDto>(movieDetailDto2,HttpStatus.OK);
return response;
}
//need to send both id and object
@PutMapping("/{id}")
public ResponseEntity<MovieDetailDto> updateMovie(@PathVariable(value="id")String movieId,@RequestBody MovieDetailDto movieDetailDto)
{
MovieDetailDto movieDetailDto2= this.movieService.updateMovie(movieId,movieDetailDto);
ResponseEntity<MovieDetailDto> response= new ResponseEntity<MovieDetailDto>(movieDetailDto2,HttpStatus.OK);
return response;
}
@DeleteMapping("/{id}")
public String deleteMovie(@PathVariable(value="id")String movieId)
{
String deleteResponse= this.movieService.deleteMovie(movieId);
return deleteResponse;
}
@GetMapping("/movies")
public List<MovieDetail> getAllMovies()
{
List<MovieDetail> movieList= this.movieService.getAllMovies();
return movieList;
}
@GetMapping("/{id}")
public ResponseEntity<MovieDetailDto> getMovieById(@PathVariable(value="id")String movieId)
{
MovieDetailDto movieDetailDto2= this.movieService.getMovieById(movieId);
ResponseEntity<MovieDetailDto> response= new ResponseEntity<MovieDetailDto>(movieDetailDto2,HttpStatus.OK);
return response;
}
@GetMapping("/search/{name}")
public List<MovieDetail> findByNameLike(@PathVariable(value="name") String name)
{
List<MovieDetail> movieList= this.movieService.findByNameLike(".*"+name+".*");
System.out.println(movieList.size());
return movieList;
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import{Movie} from '../movie/Movie';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import{AuthenticationService} from '../service/authentication.service';
import { debounceTime } from 'rxjs/internal/operators/debounceTime';
const VAIDATION_URL= "http://localhost:8765/micro-movie/api/movie";
@Injectable({
providedIn: 'root'
})
export class MovieService {
constructor(private http:HttpClient,private auth:AuthenticationService) {}
createMovie(movie: Movie):Observable<Movie>
{
let authToken = sessionStorage.getItem("token");
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.post(VAIDATION_URL+'/create', movie,{headers,responseType : "json"}).pipe(
map(res=> res as Movie));
}
getMovies():Observable<any>
{
let authToken = sessionStorage.getItem("token");
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.get(VAIDATION_URL+'/movies',{headers,responseType : "json"}).pipe(
map(res=> res ));
}
deleteMovie(id:String)
{
let authToken = sessionStorage.getItem("token");
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.delete(VAIDATION_URL +'/'+id,{headers,responseType : "text"}).pipe(
map(res=> res ));
}
getMovieByID(id:String)
{
let authToken = sessionStorage.getItem("token");
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.get(VAIDATION_URL +'/'+id,{headers,responseType : "json"}).pipe(
map(res=> res as Movie));
}
updateMovie(movie: Movie):Observable<Movie>
{
let authToken = sessionStorage.getItem("token");
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.put(VAIDATION_URL+'/'+movie.id, movie,{headers,responseType : "json"}).pipe(
map(res=> res as Movie));
}
getMovieByName(title:String):Observable<Movie[]>
{
let loginid="Visitor";
let password="abc";
let authToken = "Basic " + window.btoa(loginid + ":" + password);
console.log(authToken);
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.get(VAIDATION_URL +'/search/'+title,{headers,responseType : "json"}).pipe(
debounceTime(500), map(
( res:Movie[])=> {return (
res.length != 0 ? res as Movie[] : [{"name": "No Record Found"} as any]
);
}
));
}
}
<file_sep>export class Movie
{
id:String;
name:String;
category:string;
producer:string;
director:string;
}<file_sep>import { Injectable } from '@angular/core';
import { allotMovie } from '../movie/allotMovie';
import { Observable } from 'rxjs';
import {map} from 'rxjs/operators';
import { HttpClient,HttpHeaders } from '@angular/common/http';
const VAIDATION_URL= "http://localhost:8765/micro-allotmovie/api/allotmovie";
@Injectable({
providedIn: 'root'
})
export class AllotmovieService {
constructor(private http:HttpClient) { }
saveMovieMultiplexMapping(allotmovie:allotMovie):Observable<any>
{
let authToken = sessionStorage.getItem("token");
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.post(VAIDATION_URL+'/save'+'/'+allotmovie.movieId+'/'+allotmovie.multiplexId, allotmovie,{headers,responseType : "json"}).pipe(
map(res=> res as allotMovie)); }
findByMultiplexIdAndScreenno(allotmovie:allotMovie)
{
let authToken = sessionStorage.getItem("token");
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.get(VAIDATION_URL+'/'+allotmovie.multiplexId+'/'+allotmovie.screenno,{headers,responseType : "json"}).pipe(
map(res=> res as allotMovie));
}
getAllAllotedList():Observable<any>
{
let authToken = sessionStorage.getItem("token");
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.get(VAIDATION_URL+'/allotlist',{headers,responseType:"json"}).pipe(
map(res=> res)
);
}
findByMovieId(movieid:string):Observable<any>
{
let loginid="Visitor";
let password="abc";
let authToken = "Basic " + window.btoa(loginid + ":" + password);
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.get(VAIDATION_URL+'/searchlist/'+movieid,{headers,responseType:"json"}).pipe(
map(res=> res)
);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import{AllotmovieService} from '../service/allotmovie.service';
import { allotMovieDetail } from '../movie/allotMovieDetail';
@Component({
selector: 'app-list-allotmovie',
templateUrl: './list-allotmovie.component.html',
styleUrls: ['./list-allotmovie.component.css']
})
export class ListAllotmovieComponent implements OnInit {
allotlist:allotMovieDetail[];
constructor(private allotservice:AllotmovieService) { }
ngOnInit(): void {
this.allotservice.getAllAllotedList().subscribe(data=>{
console.log("allt- list");
console.log(data);
this.allotlist=data;
});
}
}
<file_sep><div class="container-fluid">
<div class="col-md-12">
<h2 style="margin: auto"> Movie Details</h2>
<table class="table table-striped">
<thead>
<tr>
<th class="d-none d-sm-none">Id</th>
<th>Movie name</th>
<th>Movie Category</th>
<th>Multiplex Name</th>
<th>Multiplex Location</th>
<th>Alloted Screen</th>
</tr>
</thead>
<tbody>
<tr *ngFor=" let allot of allotlist">
<td class="d-none d-sm-none">{{allot.id}}</td>
<td>{{allot.moviename.name}}</td>
<td>{{allot.moviename.category}}</td>
<td>{{allot.multiplexname.multiplexName}}</td>
<td>{{allot.multiplexname.location}}</td>
<td>{{allot.screenno}}</td>
</tr>
</tbody>
</table>
</div>
</div><file_sep>package com.lti.training.apigateway;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
@Component
public class LoggingFilter extends ZuulFilter {
private Logger log = LoggerFactory.getLogger(getClass());
@Override
public boolean shouldFilter() {
// TODO Auto-generated method stub
// true : this filter to be active
// false : inactive
return true;
}
@Override
public Object run() throws ZuulException {
// TODO Auto-generated method stub
// what to do in case request is intercepted
HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
log.info("Zuul Intercepts : " + request.getRequestURL()) ;
return null;
}
@Override
public String filterType() {
// TODO Auto-generated method stub
return "pre"; // "post"
}
@Override
public int filterOrder() {
// TODO Auto-generated method stub
// lower the value-higher the priority
return 0;
}
}
<file_sep>import{Multiplex} from '../multiplex/multiplex';
import{Movie} from '../movie/movie';
export class allotMovieDetail
{
id:String;
movieId:String;
multiplexId:string;
screenno:number;
multiplexname:Multiplex;
moviename: Movie;
}<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CreateMovieComponent } from './create-movie/create-movie.component';
import { UpdateMovieComponent } from './update-movie/update-movie.component';
import { DeleteMovieComponent } from './delete-movie/delete-movie.component';
import { ListMovieComponent } from './list-movie/list-movie.component';
import { FormsModule,ReactiveFormsModule} from '@angular/forms';
import{MovieService} from "./service/movie.service";
import {HttpClientModule} from '@angular/common/http';
import { MenuComponent } from './menu/menu.component';
import{LoginComponent} from './login/login.component';
import { CreateMultiplexComponent } from './create-multiplex/create-multiplex.component';
import { ListMultiplexComponent } from './list-multiplex/list-multiplex.component';
import { DeleteMultiplexComponent } from './delete-multiplex/delete-multiplex.component';
import { UpdateMultiplexComponent } from './update-multiplex/update-multiplex.component';
import { AllotMovieComponent } from './allot-movie/allot-movie.component';
import { ListAllotmovieComponent } from './list-allotmovie/list-allotmovie.component';
import { LogoutComponent } from './logout/logout.component';
import { SearchComponent } from './search/search.component';
import { MatInputModule } from '@angular/material/input';
import{MatAutocompleteModule} from '@angular/material/autocomplete';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
declarations: [
AppComponent,
CreateMovieComponent,
UpdateMovieComponent,
DeleteMovieComponent,
ListMovieComponent,
MenuComponent,LoginComponent, CreateMultiplexComponent, ListMultiplexComponent, DeleteMultiplexComponent, UpdateMultiplexComponent, AllotMovieComponent, ListAllotmovieComponent, LogoutComponent, SearchComponent
],
imports: [
BrowserModule,BrowserAnimationsModule,
AppRoutingModule,FormsModule,ReactiveFormsModule,HttpClientModule,
MatInputModule,MatAutocompleteModule
],
providers: [MovieService],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>package com.lti.training.microuser.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class UserExceptionDto {
private String message;
private Integer errorCode;
private Long timeStamp;
}
<file_sep>package com.lti.training.microuser.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lti.training.microuser.dto.RegisterDto;
import com.lti.training.microuser.dto.UserDetailDto;
import com.lti.training.microuser.service.UserService;
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)// internally managed object
public class TestUserController {
// MVC Test
// MVC calls need to be mocked
@Autowired
private MockMvc mockMvc; // help to generate a mock mvc call
@MockBean
private UserService service;
@Test
public void testRegister() throws Exception {
// mock the register method of userService
RegisterDto registerDto = new RegisterDto("<EMAIL>", "1234567", "1234567", "First", "Last");
UserDetailDto userDetailDto = new UserDetailDto("1","<EMAIL>", "First", "Last");
when(service.register(registerDto)).thenReturn(userDetailDto);
// build a request to our controller
RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/api/user/register")
// JSON format is required to be passed
.content(asJsonString(registerDto))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON);
// generate a request
/*this.mockMvc.perform(requestBuilder)
.andExpect(status().isOk())
.andExpect(content().json(asJsonString(userDetailDto)))*/
MvcResult result = this.mockMvc.perform(requestBuilder).andReturn();
assertEquals(200, result.getResponse().getStatus());
// assertEquals(asJsonString(userDetailDto), result.getResponse().getContentAsString());
}
// convert an object into JSON
public static String asJsonString(Object obj) {
ObjectMapper mapper = new ObjectMapper();
String jsonString= "";
try {
jsonString = mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Exception in JSON String conversion");
}
System.out.println("Json String : " + jsonString);
return jsonString;
}
}
<file_sep>package com.lti.portal.micromovie.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.lti.portal.micromovie.dao.MovieDetailRepository;
import com.lti.portal.micromovie.document.MovieDetail;
import com.lti.portal.micromovie.dto.MovieDetailDto;
@Service
public class MovieServiceImpl implements MovieService {
//convert dto to document and save
private MovieDetailRepository movieDetailRepository;
public MovieServiceImpl(MovieDetailRepository movieDetailRepository) {
// TODO Auto-generated constructor stub
this.movieDetailRepository=movieDetailRepository;
}
@Override
public MovieDetailDto createMovie(MovieDetailDto movieDetailDto) {
// TODO Auto-generated method stub
MovieDetail movieDetail = new MovieDetail(null, movieDetailDto.getName(), movieDetailDto.getCategory(),
movieDetailDto.getProducer(), movieDetailDto.getDirector());
movieDetail=this.movieDetailRepository.save(movieDetail);
MovieDetailDto movieDetailDto1 = new MovieDetailDto(movieDetail.getId(), movieDetail.getName(),
movieDetail.getCategory(), movieDetail.getProducer(), movieDetail.getDirector());
return movieDetailDto;
}
@Override
public MovieDetailDto updateMovie(String movieId,MovieDetailDto movieDetailDto) {
// TODO Auto-generated method stub
MovieDetail movieDetail = this.movieDetailRepository.findById(movieId).orElse(null);
movieDetail.setName(movieDetailDto.getName());
movieDetail.setCategory(movieDetailDto.getCategory());
movieDetail.setDirector(movieDetailDto.getDirector());
movieDetail.setProducer(movieDetailDto.getProducer());
MovieDetail updMovieDetail = this.movieDetailRepository.save(movieDetail);
MovieDetailDto movieDetailDto2= new MovieDetailDto(updMovieDetail.getId(),
updMovieDetail.getName(), updMovieDetail.getCategory(), updMovieDetail.getProducer(), updMovieDetail.getDirector());
return movieDetailDto2;
}
@Override
public String deleteMovie(String movieId) {
// TODO Auto-generated method stub
MovieDetail movieDetail =this.movieDetailRepository.findById(movieId).orElse(null);
this.movieDetailRepository.delete(movieDetail);
return "success";
}
@Override
public List<MovieDetail> getAllMovies() {
// TODO Auto-generated method stub
List<MovieDetail> moviesList = this.movieDetailRepository.findAll();
return moviesList;
}
@Override
public MovieDetailDto getMovieById(String movieId) {
// TODO Auto-generated method stub
MovieDetail movieDetail =this.movieDetailRepository.findById(movieId).orElse(null);
if(movieDetail!=null)
{
MovieDetailDto movieDetailDto2= new MovieDetailDto(movieDetail.getId(),
movieDetail.getName(), movieDetail.getCategory(), movieDetail.getProducer(), movieDetail.getDirector());
return movieDetailDto2;
}
return null;
}
@Override
public List<MovieDetail> findByNameLike(String name) {
// TODO Auto-generated method stub
List<MovieDetail> listbyname= this.movieDetailRepository.findByNameRegex(name);
return listbyname;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from '../service/authentication.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
errorMessage : string;
autherized : boolean
constructor(public auth: AuthenticationService, public router: Router) {
this.errorMessage = "Invalid Credentials!!!";
this.autherized = true;
}
login(txtLogin: HTMLInputElement, txtPass : HTMLInputElement){
this.auth.authenticate(txtLogin.value, txtPass.value)
.subscribe(
// success Method
(successData:string) => {
console.log("LOGIN SUCCESS :" + successData);
this.autherized = true;
this.router.navigate(['/listmovie']);
},
// failure
failureData => {
console.log("LOGIN FAILURE :" + failureData);
this.autherized = false;
}
);
/* if(this.auth.authenticate(txtLogin.value, txtPass.value)){
this.autherized = true;
this.router.navigate(['/product']);
}else{
this.autherized = false;
}*/
}
search()
{
console.log("hi");
this.router.navigate(['/search']);
}
ngOnInit() {
}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import{LoginComponent} from './login/login.component';
import{ListMovieComponent} from './list-movie/list-movie.component';
import{CreateMovieComponent} from './create-movie/create-movie.component';
import { UpdateMovieComponent } from './update-movie/update-movie.component';
import {ListMultiplexComponent} from './list-multiplex/list-multiplex.component';
import {CreateMultiplexComponent} from './create-multiplex/create-multiplex.component';
import{UpdateMultiplexComponent} from './update-multiplex/update-multiplex.component';
import{AllotMovieComponent} from './allot-movie/allot-movie.component';
import {ListAllotmovieComponent} from './list-allotmovie/list-allotmovie.component';
import{LogoutComponent} from './logout/logout.component';
import {SearchComponent} from './search/search.component';
const routes: Routes = [
{path:"", redirectTo : "login", pathMatch : "full"},
{path:"login", component : LoginComponent},
{path:"listmovie",component:ListMovieComponent},
{path:"createmovie",component:CreateMovieComponent},
{path:"updatemovie",component:UpdateMovieComponent},
{path:"listmultiplex",component:ListMultiplexComponent},
{path:"createmultiplex",component:CreateMultiplexComponent},
{path:"updatemultiplex",component:UpdateMultiplexComponent},
{path:"allotmovie",component:AllotMovieComponent},
{path:"listallotmovie",component:ListAllotmovieComponent},
{path:"logout",component:LogoutComponent},
{path:"search",component:SearchComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>package com.lti.portal.micromovie.dao;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.lti.portal.micromovie.document.MovieDetail;
@Repository
public interface MovieDetailRepository extends MongoRepository<MovieDetail, String> {
@Query("{'name': {$regex: ?0 }})")
List<MovieDetail> findByNameRegex(String name);
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {FormControl,FormBuilder, FormGroup, Validators,ReactiveFormsModule} from "@angular/forms";
import {Router} from "@angular/router";
import{MovieService} from "../service/movie.service";
@Component({
selector: 'app-create-movie',
templateUrl: './create-movie.component.html',
styleUrls: ['./create-movie.component.css']
})
export class CreateMovieComponent implements OnInit {
constructor(private formBuilder:FormBuilder,private router:Router,private movieService:MovieService) { }
createMovie:FormGroup;
name:FormControl;
category:FormControl;
producer:FormControl;
director:FormControl
ngOnInit(): void {;
this.createMovie=this.formBuilder.group({
id:[],
name:new FormControl("", Validators.required),
category:new FormControl("", Validators.required),
producer:new FormControl("", Validators.required),
director:new FormControl("", Validators.required)
});
}
onSubmit(){
//alert("success");
this.movieService.createMovie(this.createMovie.value)
.subscribe(data=>{
console.log("succ");
console.log(data);
this.router.navigate(['/listmovie']);
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import{Router} from '@angular/router';
import {MovieService} from '../service/movie.service';
import {MultiplexService} from '../service/multiplex.service';
import{Movie} from '../movie/movie';
import{Multiplex} from '../multiplex/multiplex';
import{AllotmovieService} from '../service/allotmovie.service';
import {FormBuilder, FormGroup, Validators,ReactiveFormsModule} from "@angular/forms";
@Component({
selector: 'app-allot-movie',
templateUrl: './allot-movie.component.html',
styleUrls: ['./allot-movie.component.css']
})
export class AllotMovieComponent implements OnInit {
movies:Movie[];
multiplexes:Multiplex[];
screens:number[]=[];
allotMovie:FormGroup;
screeno:number;
constructor(private router:Router,private movieService:MovieService,
private multiplexService:MultiplexService,private formBuilder:FormBuilder,
private allotmovieService:AllotmovieService) { }
ngOnInit(): void {
this.allotMovie=this.formBuilder.group({
id:[],
multiplexId:['',Validators.required],
movieId:['',Validators.required],
screenno:['',Validators.required]
});
this.movieService.getMovies().subscribe(data=>{
this.movies=data;
});
this.multiplexService.getMultiplexes().subscribe(data=>{
this.multiplexes=data;
console.log("allotmovie");
console.log(data);
});
}
onSubmit()
{
this.allotmovieService.saveMovieMultiplexMapping(this.allotMovie.value).subscribe(data=>
{
console.log(data);
alert("Mapped Successfully");
this.router.navigate(['/listallotmovie']);
});
}
loadScreens(event:any)
{
this.screens=[];
console.log("load screen");
let value=event.target.value;
console.log("value");
console.log(value);
this.multiplexService.getMultiplexByID(value).subscribe(data=>{
//console.log(data);
//console.log(JSON.parse(JSON.stringify(data)));
//this.updateMovie.setValue=JSON.parse(JSON.stringify(data));
this.screeno=data.noOfScreen;
console.log(this.screeno);
for (let i = 1; i <=this.screeno; i++) {
console.log ("Block statement execution no." + i);
// this.screenno=this.multiplexes[i].noOfScreen;
this.screens.push(i);
}
});
}
checkCombination(event:any)
{
// let screenno=event.target.value;
// let multiplexId= this.allotMovie.value.multiplexId;
// alert(multiplexId);
this.allotmovieService.findByMultiplexIdAndScreenno(this.allotMovie.value).subscribe(data=>
{
console.log(data);
if(data!=null)
{
alert("combination exist! please select different screen no");
this.router.navigate(['/listallotmovie']);
}
});
}
}
<file_sep>package com.lti.portal.microallotmovie.feignproxy;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import com.lti.portal.microallotmovie.dto.MovieDetailDto;
@FeignClient(name="micro-movie")
@RibbonClient(name="micro-movie")
public interface MicroMovieFeignProxy {
@GetMapping("/api/movie/{id}")
public ResponseEntity<MovieDetailDto> getMovieById(@PathVariable(value="id")String movieId);
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators,ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import{MultiplexService} from '../service/multiplex.service';
@Component({
selector: 'app-create-multiplex',
templateUrl: './create-multiplex.component.html',
styleUrls: ['./create-multiplex.component.css']
})
export class CreateMultiplexComponent implements OnInit {
constructor(private formBuilder:FormBuilder,private router:Router,private multiplexService:MultiplexService) { }
createMultiplex:FormGroup;
ngOnInit(): void {
this.createMultiplex=this.formBuilder.group({
id:[],
multiplexName:['',Validators.required],
location:['',Validators.required],
noOfScreen:['',Validators.required]
});
}
onSubmit(){
alert("success");
this.multiplexService.createMultiplex(this.createMultiplex.value)
.subscribe(data=>{
console.log("succ");
console.log(data);
this.router.navigate(['/listmultiplex']);
});
}
}
<file_sep>package com.lti.training.microuser.controller.dao;
import java.util.List;
import com.lti.training.microuser.document.UserDetail;
public interface CustomRepository {
List<UserDetail> complexLogic(String firstName, String emailId);
}
<file_sep>import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import {Multiplex} from '../multiplex/multiplex';
const VAIDATION_URL= "http://localhost:8765/micro-multiplex/api/multiplex";
@Injectable({
providedIn: 'root'
})
export class MultiplexService {
constructor(private http:HttpClient) { }
createMultiplex(multiplex: Multiplex):Observable<Multiplex>
{
let authToken = sessionStorage.getItem("token");
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.post(VAIDATION_URL+'/create', multiplex,{headers,responseType : "json"}).pipe(
map(res=> res as Multiplex));
}
getMultiplexes():Observable<any>
{
let authToken = sessionStorage.getItem("token");
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.get(VAIDATION_URL+'/multiplexes',{headers,responseType : "json"}).pipe(
map(res=> res ));
}
deleteMultiplex(id:String)
{
let authToken = sessionStorage.getItem("token");
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.delete(VAIDATION_URL +'/'+id,{headers,responseType : "text"}).pipe(
map(res=> res ));
}
getMultiplexByID(id:String)
{
let authToken = sessionStorage.getItem("token");
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.get(VAIDATION_URL +'/'+id,{headers,responseType : "json"}).pipe(
map(res=> res as Multiplex));
}
updateMultipplex(multiplex: Multiplex):Observable<Multiplex>
{
let authToken = sessionStorage.getItem("token");
let headers = new HttpHeaders({
Authorization : authToken,
});
return this.http.put(VAIDATION_URL+'/'+multiplex.id, multiplex,{headers,responseType : "json"}).pipe(
map(res=> res as Multiplex));
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import{MultiplexService} from '../service/multiplex.service';
import{Multiplex} from '../multiplex/multiplex';
@Component({
selector: 'app-list-multiplex',
templateUrl: './list-multiplex.component.html',
styleUrls: ['./list-multiplex.component.css']
})
export class ListMultiplexComponent implements OnInit {
multiplexes:Multiplex[];
constructor(private router:Router,private multiplexService :MultiplexService) { }
ngOnInit(): void {
this.multiplexService.getMultiplexes().subscribe(data=>{
console.log("list");
console.log(data);
this.multiplexes=data;
});
}
deleteMultiplex(multiplex:Multiplex)
{
this.multiplexService.deleteMultiplex(multiplex.id).subscribe(data=>{
console.log(data);
if(data=="success")
{
this.router.navigate(['/listmultiplex']);
}
else{
alert("OOPS!Something went wrong");
}
});
}
updateMultiplex(multiplex:Multiplex)
{
window.localStorage.removeItem("editmultiplexid")
window.localStorage.setItem("editmultiplexid",multiplex.id.toString());
this.router.navigate(['/updatemultiplex']);
}
}
<file_sep>
<h4> Search for Movie details</h4>
<div class="col-md-6">
<button class="btn btn-success" (click) = "searchCall();"> click here after selecting movie below</button>
</div>
<!--
<div ngIf="value == 'male'">Movie
<input type="search" placeholder="Search Test here..." #txt/>
<input type="button" value="SEARCH" (click) = "searchCall(txt)"/> -->
<div class="col-md-6 ">
<form class="example-form">
<mat-form-field appearance="fill" class="example-full-width">
<input type="text" matInput placeholder="Search movies ..." [(ngModel)]="proxyValue" [formControl]="movieTitle" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" (optionSelected)='selectedOption($event);'>
<mat-option *ngFor="let movie of movies" [value]="movie">{{ movie.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
</div>
<div *ngIf="searchedin" >
<div class="col-md-12">
<h2 style="margin: auto"> Movie Details</h2>
<table class="table table-striped">
<thead>
<tr>
<th class="d-none d-sm-none">Id</th>
<th>Movie name</th>
<th>Movie Category</th>
<th>Multiplex Name</th>
<th>Multiplex Location</th>
<th>Alloted Screen</th>
</tr>
</thead>
<tbody>
<tr *ngFor=" let allot of allotlist">
<td class="d-none d-sm-none">{{allot.id}}</td>
<td>{{allot.moviename.name}}</td>
<td>{{allot.moviename.category}}</td>
<td>{{allot.multiplexname.multiplexName}}</td>
<td>{{allot.multiplexname.location}}</td>
<td>{{allot.screenno}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<file_sep>package com.lti.training.microuser.dummy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import com.lti.training.microuser.controller.dao.DummyRepository;
import com.lti.training.microuser.service.DummyService;
// Mockito engine to run these test cases
@RunWith(MockitoJUnitRunner.class)
public class DummyMockTest {
// instance of original service (create a real object)
// inject the mock
@InjectMocks
DummyService service;
// dependency on repository (any other resource)
// create a mock object
@Mock
DummyRepository repository;
@Test
public void testCalculateSumFromDataService() {
// setup is done
// mock the implementation
when(repository.getNumberList()).thenReturn(new int[] {1, 2, 3});
int actual = this.service.calculateSumFromDataService();
int expected = 6;
assertEquals(expected, actual);
}
@Test
public void testCalculateSumFromDataServiceEmpty() {
// setup is done
// mock the implementation
when(repository.getNumberList()).thenReturn(new int[] {});
int actual = this.service.calculateSumFromDataService();
int expected = 0;
assertEquals(expected, actual);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { map, tap, debounceTime, distinctUntilChanged, switchMap, flatMap } from 'rxjs/operators';
import {Movie} from '../movie/movie';
import { Observable } from 'rxjs';
import { FormControl } from "@angular/forms";
import { MovieService } from '../service/movie.service';
import { Router } from '@angular/router';
import{AllotmovieService} from '../service/allotmovie.service';
import { allotMovieDetail } from '../movie/allotMovieDetail';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
movieTitle = new FormControl();
movies: Movie[];
allotlist:allotMovieDetail[];
searchedin:boolean;
show:boolean;
id:any;
constructor(private movieService:MovieService,private router:Router,private allotservice:AllotmovieService) { }
ngOnInit(): void {
// this.movies = this.movieTitle.valueChanges.pipe( debounceTime( 400 ),
// distinctUntilChanged(),
// tap(() => this.moviesLoading = true ),
// switchMap( title => this.movieService.getMovieByName( title ) ),
// tap(() => this.moviesLoading = false ) );
// console.log(this.movies);
this.movieTitle.valueChanges.subscribe(
term => {
if (term != '') {
this.movieService.getMovieByName(term).subscribe(
data => {
this.movies = data;
//console.log(data);
this.searchedin=false;
//console.log(data[0].BookName);
})
}
});
// console.log("init");
// this.movieService.getMovieByName("Toy Story").subscribe(data=>{
// console.log("inside");
// console.log(data);
}
searchCall()
{
let movieid= window.localStorage.getItem("selectedid");
console.log("name"+movieid);
this.allotservice.findByMovieId(movieid).subscribe(data=>{
console.log(data);
this.allotlist=data;
if(this.allotlist.length>0)
{
this.searchedin=true;
// this.show=false;
}else{
alert("No record Found");
//this.show=true;
}
window.localStorage.removeItem("selectedid");
});
}
proxyValue:any;
selectedOption(event$)
{
this.proxyValue = event$.option.value.name;
this.id = event$.option.value.id;
let selectdid= window.localStorage.setItem("selectedid",this.id);
// this.movieTitle.setValue=name;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators,ReactiveFormsModule} from "@angular/forms";
import {Router} from "@angular/router";
import{MovieService} from "../service/movie.service";
import{Movie} from "../movie/movie";
@Component({
selector: 'app-update-movie',
templateUrl: './update-movie.component.html',
styleUrls: ['./update-movie.component.css']
})
export class UpdateMovieComponent implements OnInit {
movie:Movie;
updateMovie:FormGroup;
constructor(private movieserice:MovieService,private router:Router, private formBuilder:FormBuilder) { }
ngOnInit(): void {
let movieId= window.localStorage.getItem("editmovieid");
this.updateMovie=this.formBuilder.group({
id:[''],
name:['',Validators.required],
category:['',Validators.required],
producer:['',Validators.required],
director:['',Validators.required]
});
this.movieserice.getMovieByID(movieId).subscribe(data=>{
console.log(data);
console.log(JSON.parse(JSON.stringify(data)));
//this.updateMovie.setValue=JSON.parse(JSON.stringify(data));
this.updateMovie.setValue({
name:data.name, category:data.category, producer:data.producer,director:data.director,id:data.id
});
});
}
onSubmit()
{
this.movieserice.updateMovie(this.updateMovie.value).subscribe(data=>{
alert('Movie updated successfully.');
this.router.navigate(['listmovie']);
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Multiplex } from '../multiplex/multiplex';
import { FormGroup, FormBuilder,Validators } from '@angular/forms';
import { Router } from '@angular/router';
import {MultiplexService} from '../service/multiplex.service';
@Component({
selector: 'app-update-multiplex',
templateUrl: './update-multiplex.component.html',
styleUrls: ['./update-multiplex.component.css']
})
export class UpdateMultiplexComponent implements OnInit {
multiplex:Multiplex;
updateMultiplex:FormGroup;
constructor(private multiplexService:MultiplexService,private router:Router,private formBuilder:FormBuilder) { }
ngOnInit(): void {
let multiplexid= window.localStorage.getItem("editmultiplexid");
this.updateMultiplex= this.formBuilder.group({
id:[''],
multiplexName:['',Validators.required],
location:['',Validators.required],
noOfScreen:['',Validators.required]
});
this.multiplexService.getMultiplexByID(multiplexid).subscribe(data=>{
console.log(data);
console.log(JSON.parse(JSON.stringify(data)));
//this.updateMovie.setValue=JSON.parse(JSON.stringify(data));
this.updateMultiplex.setValue({
multiplexName:data.multiplexName, location:data.location, noOfScreen:data.noOfScreen,id:data.id
});
});
}
onSubmit()
{
this.multiplexService.updateMultipplex(this.updateMultiplex.value).subscribe(data=>{
alert('Movie updated successfully.');
this.router.navigate(['listmovie']);
});
}
}
<file_sep>package com.lti.training.microuser.service;
import com.lti.training.microuser.dto.LoginDto;
import com.lti.training.microuser.dto.RegisterDto;
import com.lti.training.microuser.dto.UserDetailDto;
public interface UserService {
public UserDetailDto register(RegisterDto registerDto);
public UserDetailDto login(LoginDto loginDto);
public boolean checkAlreadyInUse(String emailId);
public UserDetailDto getUserDetail(String userId);
}
<file_sep>export class Multiplex
{
id:String;
multiplexName:String;
location:string;
noOfScreen:number;
}<file_sep>package com.lti.training.microuser.controller.dao;
public interface DummyRepository {
int[] getNumberList();
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-delete-multiplex',
templateUrl: './delete-multiplex.component.html',
styleUrls: ['./delete-multiplex.component.css']
})
export class DeleteMultiplexComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
<file_sep>package com.lti.training.microuser.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class UserDetailDto {
private String id;
private String emailId;
private String firstName;
private String lastName;
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import {map} from 'rxjs/operators';
const VAIDATION_URL= "http://localhost:8765/micro-user/api/user/login";
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
constructor(private http:HttpClient) { }
/*authenticate(loginid : string, password : string):boolean{
// hard coded validation
if(loginid === "First" && password === "abc"){
// need to maintain status : session storage
sessionStorage.setItem("user", loginid);
return true;
}else{
return false;
}
}*/
authenticate(loginid : string, password : string){
// convert credentials into basic auth token
let authToken = "Basic " + window.btoa(loginid + ":" + password);
console.log(authToken);
// header to sent with request
let headers = new HttpHeaders({
Authorization : authToken
});
return this.http.get(VAIDATION_URL, {headers,responseType : "text" }).pipe(
// success
map((successData:string) => {
console.log("AUTH SUCCESS :" + successData);
sessionStorage.setItem("user", loginid);
sessionStorage.setItem("token", authToken);
return successData;
}),
// failure
map((failureData:string) => {
console.log("AUTH FAILED :" + failureData);
return failureData;
})
);
}
// method to return token
getAuthenticationToken(){
return sessionStorage.getItem("token");
}
isUserLoggedIn(): boolean{
// if 'user' key is present
let user = sessionStorage.getItem('user');
if(user == null)
return false;
else
return true;
}
// can have method to return type of user
logout(){
sessionStorage.removeItem('user');
sessionStorage.removeItem('token');
}
}
| 825e1edfd9e5216b821b8d0d694a7b7cd2e8d5dd | [
"Java",
"TypeScript",
"HTML"
] | 38 | Java | Nandhinidevisekar/Lti-portal | 299034a2606457522ee12fdd749eb48aa4b6ff50 | 22f4ba59cea961007dc090cc412008f3246818d7 | |
refs/heads/master | <file_sep>import Base from 'formiojs/components/_classes/component/Component';
import editForm from 'formiojs/components/editgrid/EditGrid'
import Components from 'formiojs/components/Components';
var InspireTree = require("inspire-tree");
var InspireTreeDOM = require("inspire-tree-dom");
function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
export default class Corona extends Base {
constructor(component, options, data) {
super(component, options, data);
}
static schema() {
return Base.schema({
type: 'Corona'
});
}
static get builderInfo() {
return {
title: 'Corona',
group: 'basic',
icon: 'fa fa-table',
weight: 70,
documentation: 'http://help.form.io/userguide/#table',
schema: Corona.schema()
}
}
static get editForm() {
return editForm.editForm;
}
/**
* Render returns an html string of the fully rendered component.
*
* @param children - If this class is extendended, the sub string is passed as children.
* @returns {string}
*/
render(children) {
// Calling super.render will wrap it html as a component.
return super.render(`
<div><div class='' ref='isc_tree'>Tree Component</div></div>
`);
}
/**
* After the html string has been mounted into the dom, the dom element is returned here. Use refs to find specific
* elements to attach functionality to.
*
* @param element
* @returns {Promise}
*/
attach(element) {
var superAttach = _get(_getPrototypeOf(Corona.prototype), "attach", this).call(this, element);
// console.log('attach' + this.data.treeData)
this.refs.isc_tree = 'single'
this.loadRefs(element, {
isc_tree: 'single',
});
return superAttach;
}
/**
* Set the value of the component into the dom elements.
*
* @param value
* @returns {boolean}
*/
setValue(value) {
// if (!value) return;
this.loadData()
}
loadData() {
setTimeout(() => {
var values = this.evaluate(this.component.data.custom, {
values: []
}, 'values');
// console.log(values);
var tree = new InspireTree({
selection: {
mode: 'checkbox'
},
search: "matcher",
data: values
});
//handle check/uncheck items
tree.on('node.state.changed', (node, prop, oldValue, newValue) => {
if (prop != "checked") return;
// console.log(node.text + " " + prop + " " + newValue)
if (!this.dataValue) {
this.dataValue = [];
}
var nodeValue = node[this.component.valueProperty ? this.component.valueProperty : 'value'];
if (!nodeValue) nodeValue = node;
if (newValue) {
this.dataValue.push(nodeValue)
}
else {
this.dataValue.pop(nodeValue)
}
console.log(this.dataValue)
});
new InspireTreeDOM(tree, {
target: this.refs.isc_tree
});
}, 0)
}
}
// Register the component to the Formio.Components registry.
Components.addComponent('Corona', Corona); | 31c7873fe2b7e4cea765bad068eee7f0e1067818 | [
"JavaScript"
] | 1 | JavaScript | m-eydimorad/cdn | e8337666edfcf7290cbcae7f6f4f98f6e1c5b49c | 49aadabe5fca21d0bf1c201354fe4260720809e5 | |
refs/heads/master | <repo_name>evans760/js-control-flow<file_sep>/src/js/filterLongWords.js
// Hardcode an array of words. Have a variable maxLength,
// and push those words to only to an array filter long words.
// Return words less than maxLength.
array = ["Puppies", "a", "Surf", "dog", "Drink", "Sun"];
for (var i = 0, maxLength = 6; i < array.length; i++) {
if(array[i].length < maxLength) {
console.log(array[i]);
}
}
<file_sep>/readme.md
#JS Control Flow
##Getting Started
* Fork and clone this repository
* Run `npm install` to install dependencies
* Use a separate file for each exercise. This will make it easier to keep track of solutions
* It may also be beneficial to copy/paste any data structures provided
* Write JavaScript code to obtain the data prompted by each question
* Run each file by typing `node src/js/nameOfFile.js`
* Run `npm run lint:js` to style check your code
---
###reverse.js
Write a program that will take a hardcoded string, and console log the reversed version of it.
**Requirements**
* You must use a `for` loop. No `.reverse()`
* You may use the string below
```js
var inputString = "building"
```
---
###filterLongWords.js
Write a program that will take an array of words. Using a variable called `maxLength`, push words that are less than the `maxLength` into a new array, and `console.log` the value of `maxLength`.
**Requirements**
* Your array of words should be stored in a variable, which can be named whatever you like
* `maxLength` should be a positive number
---
###grade.js
Write a program that will print the letter grade, given a variable with a test score. Display either "A", "B", "C", "D", or "F", for an score that is an integer between 0 and 100.
**Requirements**
* Your program should have a variable to store the letter grade (an integer between 0 and 100)
* For the letter grades, you may use whatever grading scale you like
* You must use a switch statement (hint, you may need to review and think about how the `switch` statement works)
---
###pluralizer.js
Write a program that takes an input like...
```js
var thing = "cat"
var count = "5"
```
and output the pluralized form of the word, depending on what `count` is. For example, "5 cats" or "1 dog".
**Requirements**
* Your program should pluralize the word based on an integer (`count`)
---
###tempConvert.js
Write a program that converts a temperature from Fahrenheit to Celsius.
**Requirements**
* Your program should take an integer (in Fahrenheit) and convert the temperature to Celsius.
* The output of the program should read: "X degrees Fahrenheit is Y degrees Celsius"
| e72b7fe037a73cff444f16d123e5bd904d3606ab | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | evans760/js-control-flow | 324445cb314034ebaaa878a7d0f5027d47814812 | e4cae95a38a655238021c948218b11f155fda7db | |
refs/heads/master | <file_sep>// Copyright 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.
// Package peercredlistener is deprecated in favor of toolman.org/net/peercred.
package peercredlistener // import "toolman.org/net/peercredlistener"
import (
"context"
"net"
"toolman.org/net/peercred"
)
// ErrAddrInUse is a convenience wrapper around the Posix errno value for
// EADDRINUSE.
// Deprecated: Use package toolman.org/net/peercred instead.
const ErrAddrInUse = peercred.ErrAddrInUse
// PeerCredListener is an implementation of net.Listener that extracts
// the identity (i.e. pid, uid, gid) from the connection's client process.
// This information is then made available through the Ucred member of
// the *PeerCredConn returned by AcceptPeerCred or Accept (after a type
// assertion).
// Deprecated: Use package toolman.org/net/peercred instead.
type PeerCredListener peercred.Listener
// New returns a new PeerCredListener listening on the Unix domain socket addr.
// Deprecated: Use package toolman.org/net/peercred instead.
func New(ctx context.Context, addr string) (*PeerCredListener, error) {
lis, err := peercred.Listen(ctx, addr)
return (*PeerCredListener)(lis), err
}
// Accept is a convenience wrapper around AcceptPeerCred allowing
// PeerCredListener callers that utilize net.Listener to function
// as expected. The returned net.Conn is a *PeerCredConn which may
// be accessed through a type assertion. See AcceptPeerCred for
// details on possible error conditions.
//
// Accept contributes to implementing the net.Listener interface.
// Deprecated: Use package toolman.org/net/peercred instead.
func (pcl *PeerCredListener) Accept() (net.Conn, error) {
return (*peercred.Listener)(pcl).Accept()
}
// AcceptPeerCred accepts a connection from the receiver's listener
// returning a *PeerCredConn containing the process credentials for
// the client. If the underlying Accept fails or if process credentials
// cannot be extracted, AcceptPeerCred returns nil and an error.
// Deprecated: Use package toolman.org/net/peercred instead.
func (pcl *PeerCredListener) AcceptPeerCred() (*PeerCredConn, error) {
conn, err := (*peercred.Listener)(pcl).AcceptPeerCred()
return (*PeerCredConn)(conn), err
}
// PeerCredConn is a net.Conn containing the process credentials for the client
// side of a Unix domain socket connection.
// Deprecated: Use package toolman.org/net/peercred instead.
type PeerCredConn peercred.Conn
<file_sep>module toolman.org/net/peercredlistener
go 1.12
require toolman.org/net/peercred v0.4.0
<file_sep>
# peercredlistener
`import "toolman.org/net/peercredlistener"`
* [Overview](#pkg-overview)
* [Index](#pkg-index)
* [Subdirectories](#pkg-subdirectories)
## <a name="pkg-overview">Overview</a>
Package peercredlistener is deprecated in favor of toolman.org/net/peercred.
## <a name="pkg-index">Index</a>
* [Constants](#pkg-constants)
* [type PeerCredConn](#PeerCredConn)
* [type PeerCredListener](#PeerCredListener)
* [func New(ctx context.Context, addr string) (*PeerCredListener, error)](#New)
* [func (pcl *PeerCredListener) Accept() (net.Conn, error)](#PeerCredListener.Accept)
* [func (pcl *PeerCredListener) AcceptPeerCred() (*PeerCredConn, error)](#PeerCredListener.AcceptPeerCred)
#### <a name="pkg-files">Package files</a>
[listener.go](/src/toolman.org/net/peercredlistener/listener.go)
## <a name="pkg-constants">Constants</a>
``` go
const ErrAddrInUse = unix.EADDRINUSE
```
ErrAddrInUse is a convenience wrapper around the Posix errno value for EADDRINUSE.
Deprecated: Use package toolman.org/net/peercred instead.
## <a name="PeerCredConn">type</a> [PeerCredConn](/src/target/listener.go?s=4734:4791#L138)
``` go
type PeerCredConn struct {
Ucred *unix.Ucred
net.Conn
}
```
PeerCredConn is a net.Conn containing the process credentials for the client
side of a Unix domain socket connection.
Deprecated: Use package toolman.org/net/peercred instead.
## <a name="PeerCredListener">type</a> [PeerCredListener](/src/target/listener.go?s=2919:2965#L71)
``` go
type PeerCredListener struct {
net.Listener
}
```
PeerCredListener is an implementation of net.Listener that extracts
the identity (i.e. pid, uid, gid) from the connection's client process.
This information is then made available through the Ucred member of
the *PeerCredConn returned by AcceptPeerCred or Accept (after a type
assertion).
Deprecated: Use package toolman.org/net/peercred instead.
### <a name="New">func</a> [New](/src/target/listener.go?s=3047:3116#L76)
``` go
func New(ctx context.Context, addr string) (*PeerCredListener, error)
```
New returns a new PeerCredListener listening on the Unix domain socket addr.
Deprecated: Use package toolman.org/net/peercred instead.
### <a name="PeerCredListener.Accept">func</a> (\*PeerCredListener) [Accept](/src/target/listener.go?s=3657:3712#L93)
``` go
func (pcl *PeerCredListener) Accept() (net.Conn, error)
```
Accept is a convenience wrapper around AcceptPeerCred allowing
PeerCredListener callers that utilize net.Listener to function
as expected. The returned net.Conn is a *PeerCredConn which may
be accessed through a type assertion. See AcceptPeerCred for
details on possible error conditions.
Accept contributes to implementing the net.Listener interface.
Deprecated: Use package toolman.org/net/peercred instead.
### <a name="PeerCredListener.AcceptPeerCred">func</a> (\*PeerCredListener) [AcceptPeerCred](/src/target/listener.go?s=4020:4088#L101)
``` go
func (pcl *PeerCredListener) AcceptPeerCred() (*PeerCredConn, error)
```
AcceptPeerCred accepts a connection from the receiver's listener
returning a *PeerCredConn containing the process credentials for
the client. If the underlying Accept fails or if process credentials
cannot be extracted, AcceptPeerCred returns nil and an error.
Deprecated: Use package toolman.org/net/peercred instead.
<file_sep>
# pclcreds
`import "toolman.org/net/peercredlistener/pclcreds"`
* [Install](#pkg-install)
* [Overview](#pkg-overview)
* [Index](#pkg-index)
## <a name="pkg-install">Install</a>
```sh
go get toolman.org/net/peercredlistener/pclcreds
```
## <a name="pkg-overview">Overview</a>
Package pclcreds is deprecated in favor of toolman.org/net/peercred/grpcpeer.
## <a name="pkg-index">Index</a>
* [Variables](#pkg-variables)
* [func FromContext(ctx context.Context) (*unix.Ucred, error)](#FromContext)
* [func TransportCredentials() grpc.ServerOption](#TransportCredentials)
#### <a name="pkg-files">Package files</a>
[creds.go](/src/toolman.org/net/peercredlistener/pclcreds/creds.go)
## <a name="pkg-variables">Variables</a>
``` go
var ErrNoCredentials = grpcpeer.ErrNoCredentials
```
ErrNoCredentials is returned by FromContext if the provided Context
contains no peer process credentials.
Deprecated: Use package toolman.org/net/peercred/grpcpeer instead.
``` go
var ErrNoPeer = grpcpeer.ErrNoPeer
```
ErrNoPeer is returned by FromContext if the provided Context contains
no gRPC peer.
Deprecated: Use package toolman.org/net/peercred/grpcpeer instead.
## <a name="FromContext">func</a> [FromContext](/src/target/creds.go?s=5662:5720#L141)
``` go
func FromContext(ctx context.Context) (*unix.Ucred, error)
```
FromContext extracts peer process credentials, if any, from the given
Context. If the Context has no gRPC peer, ErrNoPeer is returned. If the
Context's peer is of the wrong type (i.e. contains no peer process
credentials), ErrNoCredentials will be returned.
Deprecated: Use package toolman.org/net/peercred/grpcpeer instead.
## <a name="TransportCredentials">func</a> [TransportCredentials](/src/target/creds.go?s=3701:3746#L89)
``` go
func TransportCredentials() grpc.ServerOption
```
TransportCredentials returns a grpc.ServerOption that exposes the peer
process credentials (i.e. pid, uid, gid) extracted by a PeerCredListener.
The peer credentials are available by passing a server method's Context
to the FromContext function.
Deprecated: Use package toolman.org/net/peercred/grpcpeer instead.
<file_sep>module toolman.org/net/peercredlistener/pclcreds
go 1.12
require (
golang.org/x/sys v0.0.0-20190526052359-791d8a0f4d09
google.golang.org/grpc v1.21.0
toolman.org/net/peercred/grpcpeer v0.4.0
)
<file_sep>// Copyright 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.
// Package pclcreds is deprecated in favor of toolman.org/net/peercred/grpcpeer.
package pclcreds
import (
"context"
"golang.org/x/sys/unix"
"google.golang.org/grpc"
"toolman.org/net/peercred/grpcpeer"
)
// ErrNoPeer is returned by FromContext if the provided Context contains
// no gRPC peer.
// Deprecated: Use package toolman.org/net/peercred/grpcpeer instead.
var ErrNoPeer = grpcpeer.ErrNoPeer
// ErrNoCredentials is returned by FromContext if the provided Context
// contains no peer process credentials.
// Deprecated: Use package toolman.org/net/peercred/grpcpeer instead.
var ErrNoCredentials = grpcpeer.ErrNoCredentials
// TransportCredentials returns a grpc.ServerOption that exposes the peer
// process credentials (i.e. pid, uid, gid) extracted by a PeerCredListener.
// The peer credentials are available by passing a server method's Context
// to the FromContext function.
// Deprecated: Use package toolman.org/net/peercred/grpcpeer instead.
func TransportCredentials() grpc.ServerOption { return grpcpeer.TransportCredentials() }
// FromContext extracts peer process credentials, if any, from the given
// Context. If the Context has no gRPC peer, ErrNoPeer is returned. If the
// Context's peer is of the wrong type (i.e. contains no peer process
// credentials), ErrNoCredentials will be returned.
// Deprecated: Use package toolman.org/net/peercred/grpcpeer instead.
func FromContext(ctx context.Context) (*unix.Ucred, error) { return grpcpeer.FromContext(ctx) }
| 39254a8f6c9139cbb11b4bac0839268e70129426 | [
"Markdown",
"Go Module",
"Go"
] | 6 | Go | tep/net-peercredlistener | c44d99b8a7136b456ae3e64e3962f206cc971889 | f08038f6de58ca1645b88a3656b21a9cf02f2319 | |
refs/heads/main | <file_sep>#bash ngantok.sh
ngantok.sh
<file_sep># bash DanuReal.sh
DanuReal.sh
| 9338c596170b719df75d50d3d0d609211af5319f | [
"Shell"
] | 2 | Shell | DanuRealid/ngantok | 99bd9db81ca2bd32f63a181e4137001334c364ab | 79bca3afc15c87294c576e9241462804d86eec92 | |
refs/heads/master | <file_sep>import java.util.HashMap;
import java.util.Random;
import edu.rit.util.Hex;
import edu.rit.util.Packing;
/**
* Class AttackRC5 is a attack program that attack one round RC5 algorithm
* <P>
* <I>Key</I> = Cipher Key
*/
public class AttackRC5 {
private final int w = Integer.SIZE; // Word size (32bits)
/**
* Do the digit left shift
*
* @return Integer value of after A left shift with B.
*/
public int rotateLeft(int A, int B) {
// B is 32bits integer
// need to mod w(32) to make sure the range of digit shift
return (A << (B & (w - 1))) | (A >>> (w - (B & (w - 1))));
}
/**
* Do the digit right shift
*
* @return Integer value of after A right shift with B.
*/
public int rotateRight(int A, int B) {
return (A >>> (B & (w - 1))) | (A << (w - (B & (w - 1))));
}
/**
* Do the half round decryption of B
*
* @param byte[] Test plaintext
* @param byte[] Test ciphertext
* @param Integer
* Test value of S3
*
* @return Integer the value after half round decryption of B
*/
public int decryptB(byte[] plaintext, byte[] ciphertext, int S3) {
// Convert the text from bytes to words
int A1 = Packing.packIntLittleEndian(ciphertext, 0);
int B1 = Packing.packIntLittleEndian(ciphertext, 4);
int B0 = Packing.packIntLittleEndian(plaintext, 4);
int Bmid = rotateRight(B1 - S3, A1) ^ A1;
int S1 = Bmid - B0;
return S1;
}
/**
* Do the half round decryption of A
*
* @param byte[] Test plaintext
* @param byte[] Test ciphertext
* @param Integer
* Certain value of S3
* @param Integer
* Test value of S2
*
* @return Integer the value after half round decryption of A
*/
public int decryptA(byte[] plaintext, byte[] ciphertext, int S3, int S2) {
// Convert the text from bytes to words
int A1 = Packing.packIntLittleEndian(ciphertext, 0);
int B1 = Packing.packIntLittleEndian(ciphertext, 4);
int A0 = Packing.packIntLittleEndian(plaintext, 0);
int Bmid = rotateRight(B1 - S3, A1) ^ A1;
int Amid = rotateRight(A1 - S2, Bmid) ^ Bmid;
int S0 = Amid - A0;
return S0;
}
/**
* Main method of the attack program. Run the program with the input(key) to
* get the output(S0, S1, S2, S3)
*/
public static void main(String[] args) {
AttackRC5 attack = new AttackRC5();
if (args.length != 1)
usage();
else {
byte[] key = Hex.toByteArray(args[0]);
Generator oracle = new Generator(key);
int[] S = oracle.GenerateS();
// Display the key and correct S0-S3
System.out.printf("KEY -- %s (Shhhhh..)%n", Hex.toString(key));
System.out.printf("S0 -- %s%nS1 -- %s%nS2 -- %s%nS3 -- %s%n%n",
Integer.toBinaryString(S[0]), Integer.toBinaryString(S[1]),
Integer.toBinaryString(S[2]), Integer.toBinaryString(S[3]));
// Generate the first pair of plaintext and ciphertext
byte[] plaintext1 = oracle.GeneratePlaintext();
byte[] ciphertext1 = oracle.GenerateCiphertext(plaintext1);
System.out.printf("PT1 -- %s%nCT1 -- %s%n%n",
Hex.toString(plaintext1), Hex.toString(ciphertext1));
// Generate the second pair of plaintext and ciphertext
byte[] plaintext2 = oracle.GeneratePlaintext();
byte[] ciphertext2 = oracle.GenerateCiphertext(plaintext2);
System.out.printf("PT2 -- %s%nCT2 -- %s%n%n",
Hex.toString(plaintext2), Hex.toString(ciphertext2));
// Generate the third pair of plaintext and ciphertext
byte[] plaintext3 = oracle.GeneratePlaintext();
byte[] ciphertext3 = oracle.GenerateCiphertext(plaintext3);
System.out.printf("PT3 -- %s%nCT3 -- %s%n%n",
Hex.toString(plaintext3), Hex.toString(ciphertext3));
HashMap<Integer, Integer> S31pair = new HashMap<Integer, Integer>();
// Begin to attack S3&S1 with first two pair PT&CT
System.out.printf("Attack with PT1&CT1 and PT2&CT2%n%n");
for (int S3 = Integer.MIN_VALUE; S3 < Integer.MAX_VALUE; S3++) {
int S1i = attack.decryptB(plaintext1, ciphertext1, S3);
int S1 = attack.decryptB(plaintext2, ciphertext2, S3);
// If match both of PT&CT, keep those
if (S1i == S1) {
S31pair.put(S3, S1);
System.out.printf("*S3*-- %s%n*S1*-- %s%n%n",
Integer.toBinaryString(S3),
Integer.toBinaryString(S1));
}
}
int S3 = 0;
int S1 = 0;
// If only one pair, that's the correct result of S3&S1
if (S31pair.size() == 1) {
for (int s3 : S31pair.keySet()) {
S3 = s3;
S1 = S31pair.get(S3);
}
} else {
// Begin to attack S3&S1 with the third pair PT&CT
System.out.printf("Attack with PT3&CT3%n%n");
for (int s3 : S31pair.keySet()) {
int s1i = attack.decryptB(plaintext1, ciphertext1, s3);
int s1 = attack.decryptB(plaintext3, ciphertext3, s3);
// If match every PT&CT, keep those
if (s1i == s1) {
S3 = s3;
S1 = s1;
System.out.printf("*S3*-- %s%n*S1*-- %s%n%n",
Integer.toBinaryString(S3),
Integer.toBinaryString(S1));
}
}
}
System.out.printf("Session 1 DONE%n%n");
HashMap<Integer, Integer> S20pair = new HashMap<Integer, Integer>();
// Begin to attack S2&S0 with first two pair PT&CT
System.out.printf("Attack with PT1&CT1 and PT2&CT2%n%n");
for (int S2 = Integer.MIN_VALUE; S2 < Integer.MAX_VALUE; S2++) {
int S0i = attack.decryptA(plaintext1, ciphertext1, S3, S2);
int S0 = attack.decryptA(plaintext2, ciphertext2, S3, S2);
// If match both of PT&CT, keep those
if (S0i == S0) {
S20pair.put(S2, S0);
System.out.printf("*S2*-- %s%n*S0*-- %s%n%n",
Integer.toBinaryString(S2),
Integer.toBinaryString(S0));
}
}
int S2 = 0;
int S0 = 0;
// If only one pair, that's the correct result of S2&S0
if (S20pair.size() == 1) {
for (int s2 : S20pair.keySet()) {
S2 = s2;
S0 = S20pair.get(S2);
}
} else {
// Begin to attack S2&S0 with the third pair PT&CT
System.out.printf("Attack with PT3&CT3%n%n");
for (int s2 : S20pair.keySet()) {
int s0i = attack.decryptA(plaintext1, ciphertext1, S3, s2);
int s0 = attack.decryptA(plaintext3, ciphertext3, S3, s2);
// If match every PT&CT, keep those
if (s0i == s0) {
S2 = s2;
S0 = s0;
System.out.printf("*S2*-- %s%n*S0*-- %s%n%n",
Integer.toBinaryString(S2),
Integer.toBinaryString(S0));
}
}
}
System.out.printf("Session 2 DONE%n%n");
// Compare with the correct set of S
if (S0 == S[0] && S1 == S[1] && S2 == S[2] && S3 == S[3]) {
System.out.printf("Block Cipher BROKE!%n%n");
System.out.printf(
"*S0*-- %s%n*S1*-- %s%n*S2*-- %s%n*S3*-- %s%n%n",
Integer.toBinaryString(S0), Integer.toBinaryString(S1),
Integer.toBinaryString(S2), Integer.toBinaryString(S3));
}
}
}
private static void usage() {
System.err.println("Usage: java AttackRC5 <Key>");
System.err.println("<Key> = 32 Charater Hex Key String");
System.exit(1);
}
}
/**
* Class Generator is used to generate the random plaintext and encrypt that to
* get the ciphertext of one round RC5 algorithm
* <P>
* <I>Key</I> = Cipher Key
*/
class Generator {
private Random prng = new Random();
private RC5 cipher = new RC5();
/**
* Constructor
*/
public Generator(byte[] key) {
this.prng.setSeed(8080);
this.cipher.setRounds(1);
this.cipher.setKey(key);
}
/**
* Generate random plaintext
*
* @return byte[] A random plaintext
*/
public byte[] GeneratePlaintext() {
byte[] pt = Hex.toByteArray(Long.toHexString(prng.nextLong()));
return pt;
}
/**
* Generate random ciphertext
*
* @param byte[] Input plaintext
*
* @return byte[] A random ciphertext
*/
public byte[] GenerateCiphertext(byte[] pt) {
byte[] ct = (byte[]) pt.clone();
cipher.encrypt(ct);
return ct;
}
/**
* Get the correct S array
*
* @return int[] The correct set of S
*/
public int[] GenerateS() {
return cipher.getS();
}
}
<file_sep>For the RC5 algorithm, the program files are:
RC5.java and BlockCipher.java.
The usage of RC5.java is as follows:
java RC5 <Type> <PlainText/CipherText> <Key> <Round>
where:
<Type>
= 1 Character String of 1 (Encryption) or 2 (Decryption)
<PlainText/CipherText>
= 16 Character Hex String
Type = 1 input PlainText; Type = 2 input CipherText
<Key>
= 32 Charater Hex Key String
<Round>
= Number of Rounds
For the One round RC5 Attack program, the program files are:
AttackRC5.java, RC5.java, and BlockCipher.java.
The usage of AttackRC5.java is as follows:
java AttackRC5 <Key>
where:
<Key>
= 32 Character Hex Key String | 271f40d7becd274646f20865c3dbfced654c901d | [
"Java",
"Text"
] | 2 | Java | zhenkuanghe0710/RC5CryptoAttack | c9e8c8bf8e70cbbc781f15b850f5f60c63b4ffb3 | 9b86ec4bf82190262b584d7fd559b4870ad6034e | |
refs/heads/master | <repo_name>gustavo-ren/numpy<file_sep>/PythonNumpy/spam/main.py
import numpy as np
my_list = [1, 2, 3, 4]
array_np = np.array(my_list)
print(type(array_np))
arr = np.arange(0, 1000)
print(arr * 8)
print(arr.mean())
filtro = arr > 500
print(arr[filtro])
arr_lin = np.linspace(0, 15, 10)
print(arr_lin)
print(arr_lin.mean())
print(arr_lin.max())<file_sep>/README.md
# numpy
Some numpy methods
| 0c01278311480816f490fb13b9f5c6c1a5ec9170 | [
"Markdown",
"Python"
] | 2 | Python | gustavo-ren/numpy | 93c464506965bc6288154d06d7b3eaf446dd7813 | dcc4a6d939019c8f7214ab186b053e9aacc5e00e | |
refs/heads/main | <repo_name>PhilipL1/project-2<file_sep>/service-1/requirements.txt
flask
requests
flask_sqlalchemy
pymysql
flask_testing
pytest
requests_mock
pytest-cov<file_sep>/service-3/tests/test_app.py
from flask import url_for
from flask_testing import TestCase
import requests_mock
from app import app
import re
class TestBase(TestCase):
def create_app(self):
return app
class TestHome(TestBase):
def test_get_day(self):
for _ in range(20):
response = self.client.get(url_for('get_day'))
day,year,month,date = re.findall("(\S+)\((\d{4})-(\d{2})-(\d{2})\)", response.data.decode())[0]
self.assertIn(day, {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"})
self.assertEqual(year, "2022")
self.assertIn(month,{"06", "07"})
self.assertIn(int(date), range(0, 31))
<file_sep>/venv/lib/python3.6/site-packages/pytest_cov/__init__.py
"""pytest-cov: avoid already-imported warning: PYTEST_DONT_REWRITE."""
__version__ = '2.12.0'
<file_sep>/service-3/app.py
from flask import Flask,request
import random
from os import getenv
import random
import datetime
import calendar
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = getenv("DATABASE_URI")
@app.route('/get_day',methods=['GET'])
def get_day():
start_date = datetime.date(2022, 6, 1)
end_date = datetime.date(2022, 7, 1)
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
random_number_of_days = random.randrange(days_between_dates)
random_date = start_date + datetime.timedelta(days=random_number_of_days)
date = str(random_date)
#print(date)
day = datetime.datetime.strptime(date, '%Y-%m-%d').weekday()
#print(day)
answer_day = calendar.day_name[day]
return_value =str(answer_day) + "("+str(date) + ")"
return return_value
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)
<file_sep>/deploy.sh
#!/bin/bash
scp docker-compose.yaml swarm-manager:
ssh swarm-manager << EOF
export DATABASE_URI=${DATABASE_URI}
docker stack deploy --compose-file docker-compose.yaml project
EOF
<file_sep>/service-4/tests/test_app.py
from flask import url_for
from flask_testing import TestCase
import requests_mock
from app import app
from unittest.mock import patch
class TestBase(TestCase):
def create_app(self):
return app
class TestHome(TestBase):
def test_get_fortune(self):
response = self.client.post(url_for('get_fortune', day = "Friday(2022-06-03)", number = 20))
self.assertEqual(response.data.decode(), "On Friday(2022-06-03) you will find nothing but peace & happiness")
<file_sep>/service-1/app.py
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
import requests
from os import getenv
#from SQLAlchemy import desc
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = getenv('DATABASE_URI')
db = SQLAlchemy(app)
class Fortunes(db.Model):
id = db.Column(db.Integer, primary_key=True)
fortune = db.Column(db.String(1000), nullable=False)
@app.route('/')
@app.route("/home")
def home():
number = requests.get('http://number_api:5000/get_number').json()['number']
day = requests.get('http://day_api:5000/get_day')
fortune = requests.post(f'http://fortune_api:5000/get_fortune/{day.text}/{number}')
db.session.add(
Fortunes(
fortune = fortune.text
)
)
db.session.commit()
last_three_fortune = Fortunes.query.order_by(Fortunes.id.desc()).limit(3).all()
return render_template("home.html", title="Home", number=number,\
day=day.text, fortune=fortune.text, all_fortune = last_three_fortune)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)<file_sep>/jenkins/test.sh
#!/bin/bash
sudo apt update
#sudo apt install chromium-chromedriver -y
#sudo apt install python3-venv
sudo apt install python3 python3-pip python3-venv -y
python3 -m venv venv
pip3 install requirements.txt
export DB_URI
export SECRET_KEY
source venv/bin/activate
#install pip requirements
pip3 install -r service-1/requirements.txt
#run pytest
python3 -m pytest service-1 --junitxml=junit/test-results.xml --cov=service-1 --cov-report=xml --cov-report=html --cov-report term-missing
python3 -m pytest service-2 --junitxml=junit/test-results.xml --cov=service-2 --cov-report=xml --cov-report=html --cov-report term-missing
python3 -m pytest service-3 --junitxml=junit/test-results.xml --cov=service-3 --cov-report=xml --cov-report=html --cov-report term-missing
python3 -m pytest service-4 --junitxml=junit/test-results.xml --cov=service-4 --cov-report=xml --cov-report=html --cov-report term-missing
#run app
#docker-compose up -d build
<file_sep>/venv/lib/python3.6/site-packages/requests_mock/mocker.pyi
# Stubs for requests_mock.mocker
from requests_mock.adapter import AnyMatcher
from requests import Response
from requests_mock.request import _RequestObjectProxy
from typing import Any, Callable, Dict, List, Optional, Pattern, Type, TypeVar, Union
DELETE: str
GET: str
HEAD: str
OPTIONS: str
PATCH: str
POST: str
PUT: str
class MockerCore:
case_sensitive: bool = ...
def __init__(self, **kwargs: Any) -> None: ...
def start(self) -> None: ...
def stop(self) -> None: ...
def add_matcher(self, matcher: Any) -> None: ...
@property
def request_history(self) -> List[_RequestObjectProxy]: ...
@property
def last_request(self) -> Optional[_RequestObjectProxy]: ...
@property
def called(self) -> bool: ...
@property
def called_once(self) -> bool: ...
@property
def call_count(self) -> int: ...
def register_uri(
self,
method: Union[str, AnyMatcher],
url: Union[str, Pattern[str], AnyMatcher],
response_list: Optional[List[Dict[str, Any]]] = ...,
request_headers: Dict[str, str] = ...,
complete_qs: bool = ...,
status_code: int = ...,
text: str = ...,
headers: Optional[Dict[str, str]] = ...,
additional_matcher: Optional[Callable[[_RequestObjectProxy], bool]] = ...,
**kwargs: Any) -> Response: ...
def request(
self,
method: Union[str, AnyMatcher],
url: Union[str, Pattern[str], AnyMatcher],
response_list: Optional[List[Dict[str, Any]]] = ...,
request_headers: Dict[str, str] = ...,
complete_qs: bool = ...,
status_code: int = ...,
text: str = ...,
headers: Optional[Dict[str, str]] = ...,
additional_matcher: Optional[Callable[[_RequestObjectProxy], bool]] = ...,
**kwargs: Any) -> Response: ...
def get(
self,
url: Union[str, Pattern[str], AnyMatcher],
response_list: Optional[List[Dict[str, Any]]] = ...,
request_headers: Dict[str, str] = ...,
complete_qs: bool = ...,
status_code: int = ...,
text: str = ...,
headers: Optional[Dict[str, str]] = ...,
additional_matcher: Optional[Callable[[_RequestObjectProxy], bool]] = ...,
**kwargs: Any) -> Response: ...
def head(
self,
url: Union[str, Pattern[str], AnyMatcher],
response_list: Optional[List[Dict[str, Any]]] = ...,
request_headers: Dict[str, str] = ...,
complete_qs: bool = ...,
status_code: int = ...,
text: str = ...,
headers: Optional[Dict[str, str]] = ...,
additional_matcher: Optional[Callable[[_RequestObjectProxy], bool]] = ...,
**kwargs: Any) -> Response: ...
def options(
self,
url: Union[str, Pattern[str], AnyMatcher],
response_list: Optional[List[Dict[str, Any]]] = ...,
request_headers: Dict[str, str] = ...,
complete_qs: bool = ...,
status_code: int = ...,
text: str = ...,
headers: Optional[Dict[str, str]] = ...,
additional_matcher: Optional[Callable[[_RequestObjectProxy], bool]] = ...,
**kwargs: Any) -> Response: ...
def post(
self,
url: Union[str, Pattern[str], AnyMatcher],
response_list: Optional[List[Dict[str, Any]]] = ...,
request_headers: Dict[str, str] = ...,
complete_qs: bool = ...,
status_code: int = ...,
text: str = ...,
headers: Optional[Dict[str, str]] = ...,
additional_matcher: Optional[Callable[[_RequestObjectProxy], bool]] = ...,
**kwargs: Any) -> Response: ...
def put(
self,
url: Union[str, Pattern[str], AnyMatcher],
response_list: Optional[List[Dict[str, Any]]] = ...,
request_headers: Dict[str, str] = ...,
complete_qs: bool = ...,
status_code: int = ...,
text: str = ...,
headers: Optional[Dict[str, str]] = ...,
additional_matcher: Optional[Callable[[_RequestObjectProxy], bool]] = ...,
**kwargs: Any) -> Response: ...
def patch(
self,
url: Union[str, Pattern[str], AnyMatcher],
response_list: Optional[List[Dict[str, Any]]] = ...,
request_headers: Dict[str, str] = ...,
complete_qs: bool = ...,
status_code: int = ...,
text: str = ...,
headers: Optional[Dict[str, str]] = ...,
additional_matcher: Optional[Callable[[_RequestObjectProxy], bool]] = ...,
**kwargs: Any) -> Response: ...
def delete(
self,
url: Union[str, Pattern[str], AnyMatcher],
response_list: Optional[List[Dict[str, Any]]] = ...,
request_headers: Dict[str, str] = ...,
complete_qs: bool = ...,
status_code: int = ...,
text: str = ...,
headers: Optional[Dict[str, str]] = ...,
additional_matcher: Optional[Callable[[_RequestObjectProxy], bool]] = ...,
**kwargs: Any) -> Response: ...
_T = TypeVar('_T')
class Mocker(MockerCore):
TEST_PREFIX: str = ...
def __init__(
self,
kw: str = ...,
case_sensitive: bool = ...,
adapter: Any = ...,
real_http: bool = ...) -> None: ...
def __enter__(self) -> Any: ...
def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ...
def __call__(self, obj: Any) -> Any: ...
def copy(self) -> Mocker: ...
def decorate_callable(self, func: Callable[..., _T]) -> Callable[..., _T]: ...
def decorate_class(self, klass: Type[_T]) -> Type[_T]: ...
mock = Mocker
<file_sep>/service-2/app.py
from flask import Flask,request, jsonify
import random
from os import getenv
import random
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = getenv("DATABASE_URI")
# animal generator route here
@app.route('/get_number',methods=['GET'])
def get_number():
result = {'number':random.randint(10, 20)}
return jsonify(result)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)<file_sep>/service-1/tests/test_app.py
from flask import url_for
from flask_testing import TestCase
import requests_mock
from app import app, db
class TestBase(TestCase):
def create_app(self):
app.config.update(
SQLALCHEMY_DATABASE_URI="sqlite:///test.db"
)
return app
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
class TestHome(TestBase):
def test_home(self):
with requests_mock.Mocker() as mocker:
mocker.get('http://number_api:5000/get_number', json = {'number': 19})
mocker.get('http://day_api:5000/get_day', text = 'Friday(2022-06-03)')
mocker.post('http://fortune_api:5000/get_fortune/Friday(2022-06-03)/19', text = 'On Friday(2022-06-03) you will becomone a millionaire, lucky you!!')
response = self.client.get(url_for('home'))
self.assertEqual(response.status_code, 200)
self.assertIn(b'On Friday(2022-06-03) you will becomone a millionaire, lucky you!!', response.data)
<file_sep>/service-2/tests/test_app.py
from flask import url_for
from flask_testing import TestCase
import requests_mock
from app import app
class TestBase(TestCase):
def create_app(self):
return app
class TestHome(TestBase):
def test_get_number(self):
for _ in range(20):
response = self.client.get(url_for('get_number'))
self.assertIn(response.json['number'], range(10, 21))
<file_sep>/README.md
## Contents
* [Introduction](#introduction)
* [Objective](#objective)
* [Proposal](#proposal)
* [The 4 Services](#The-4-Services)
* [Architecture](#architecture)
* [Risk Assessment](#Risk-Assessment)
* [Project Management](#Project-Management)
* [Test Analysis](#Analysis-of-Testing)
* [Continuous Integration pipeline](#continuous-integration)
* [Infrastructure](#development)
* [Jenkins](#Jenkins)
* [Entity Diagram](#Entity-Diagram)
* [Docker Swarm](#Interactions-Diagram)
* [Development](#development)
* [Unit Testing](#Unit-Testing)
* [Front-End Design](#Front-End)
* [Footer](#Footer)
*
## Introduction
### Objective
The objective provided for this project is as follows:
> To create a service-orientated architecture for your application, this application must be composed of at least 4 services that work together.
<br/>
More specifically, these 4 services should comprise of 1 front-end wrapper service, 2 (or more) back-end services, and 1 other back-end service that relies on data from the previous 2 back-end services in some way.
For this to be achieved, the following is required:
* Kanban Board: Asana or an equivalent Kanban Board
* Version Control: Git - using the feature-branch model
* CI Server: Jenkins
* Configuration Management: Ansible
* Cloud server: GCP virtual machines
* Containerisation: Docker
* Orchestration Tool: Docker Swarm
* Reverse Proxy: NGINX
* Database Layer: MySQL
### Proposal
To meet all of the requirements and to ensure the MVP was produced in the time-frame provided. I first had to concure the important aspect of the project which were the infrastructure and implementation of my CI/CD. This meant a basic application that hit the MVP requirements was create in the first sprint.
### Fortune Generator
* Service 1 (front-end): displays the results of the following 3 services for the user to see, as well as a brief history of past results.
* Service 2: returns a random number for the fortune.
* Service 3: a random date from a given range is formed. The day of that random date is then calculated. The date and day is then returned.
* Service 4: returns a fortune is generated based on the random number. The date and day that the fortune will take place will also be returned.
## The 4 Services
The diagram below shows how the services interact with one another.
<br/>
![services](https://i.imgur.com/ho2SPg1.png)
Summary
* The front-end sends GET requests to API-1 and API-2
* API-1 & API-2 sends their response to API-3 as a POST request
* API-3 returns the appropriate information to the front end as a POST request
* The front-end can send requests to the MySQL instance to INSERT the new entry and SELECT the old entries in order to display a history to the user as required.
<br/>
# Architecture
## Risk Assessment
My detailed Risk Assessment can be seen below, outlining the major and minor risks associated with this project.
<br/>
Here is a screenshot of my risk assessment at the start of my project :
<br/>
![risk assessment image](https://i.imgur.com/RkGAg0G.png)
<br/><br/>
Below is a screenshot of additional risks that where added at the end of my project when the risks became clear :
<br/>
![risk assessment image2](https://i.imgur.com/knTGlbx.png)
<br/>
The full risk assessment for this project can be found [here](https://docs.google.com/spreadsheets/d/1mq4bsv15Pg1NkuiAYihON9s1pke3uN9twct9S83Fh0c/edit?usp=sharing).
<br/>
## Project Management
Trello was used to track the progress of the project (pictured below). You can find the link to this board [here](https://trello.com/b/4UYzCR2H). I used Trello board rather than other project management tools such as Jira because it is free to use and user friendly which helps with visualisation of the project so that task can be completed efficiently.
<br/>
![trello board image 1](https://i.imgur.com/xRolMUn.png)
![trello board image 2](https://i.imgur.com/qeHTB02.png)
<br/>
## Analysis of Testing
Having a test driven approach is essential for any successful project. Since this project is using an CI/CD approach, it is key to plan out what areas of the application will need to be tested. Also, to implement a system to run automated tests.
<br/>
To start this process, I first had to understand the scope of the testing for this project.
<br/>
![image of testing](https://i.imgur.com/FxDBNDQ.png)
<br/>
Based on this result and the Moscow priorisitation, it is clear that unit testing is the only essential form of testing required to produce the MVP.
I then went on to plan the test that needed to be done, as well as pseudo-code for my own personal reference as a kick start before writing my code. This tables helped me keep track on what test needs to be implemented.
![image of testing 2](https://i.imgur.com/OX0APtR.png)
<br/>
[View the original documentation](https://docs.google.com/spreadsheets/d/1wvi8PupgVidEtxT-IOtfdUEc5q0HvxSPXRxG-yZY_QA/edit?usp=sharing)
<br/>
# Infrastructure
Continuous deployment is implemented throughout my project in order to allow rapid and smooth development-to-deployment. The approach I have taken allows deploying new versions of the application with limited down-time.
## Jenkins
Whenever new content is pushed to the dev branch, Github will send a webhook to Jenkins which tells it to run the following pipeline:
**1.** Unit Test: Pytest
```
Test the functionality of individual routes
```
<br/>
**2. & 3.** Build & Push: docker-compose
```
Jenkins' credentials system is used to handle logging into DockerHub, before the new images are pushed to the repository specified.
```
<br/>
**4.** Configure: ansible
```
Ansible configures several things:
Installing dependencies (such as docker and docker-compose),
Setting up the swarm, and joining the swarm on all worker nodes,
Reloading NGINX with any changes to the nginx.conf file.
```
<br/>
**5** Deploy: docker swarm/stack
```
Jenkins copies the docker-compose.yaml file over to the manager node, SSH's onto it, and then runs docker stack deploy
```
<br/>
The commands used in Jenkins' pipeline can be seen in the[ Jenkinsfile](https://github.com/PhilipL1/project-2/blob/test/jenkins/Jenkinsfile)
<br/>
![pipeline image](https://i.imgur.com/qKtGg9A.png)
## Entity Diagram
The project database only has one table which is shown below. Outlining the elements in a table means that the validation required for each element is outlined explicitly, and can be tested accordingly. The results of the fortune is stored in the SQL database available upon request. The front end application displays the end-user's last 3 Fortunes which are taken from the database.
<br/>
![Entity Diagram image](https://i.imgur.com/4FlhZgg.png)
## Interactions Diagram
The diagram below shows the layout of the virtual machines as used in this project. This displays where the information is taken from as a user connects to the NGINX machine on port 80.
<br/>
![user interface image](https://i.imgur.com/KGv5xpO.png)
<br/>
Using an orchestration tool (ansible), Docker Swarm. software developers are able to create a network of virtual machines that are all able to be accessed by end-users to provide the same service.
<br/>
Anonther layer has been added to the system in a form of an NGINX load-balancer which up-streams the user to the VM with the least connections. By adding this layer, the efficiency of the application improves as well as security as end-users have another stage in the application.
<br/>
## Development
### Front-End
When navigating to port 80 (default http port) on the NGINX's IP, the steps the end user will be taking has been mentioned previously, using a these diagram to help visualise the structure [here](https://i.imgur.com/ho2SPg1.png) and [here](https://i.imgur.com/KGv5xpO.png). The relevant information is displayed using HTML (with jinja2) for layout and CSS for styling.
![web application](https://i.imgur.com/Z41L2Y4.png)
### Unit Testing
Unit testing is used here by seperating the route functions and testing each function with various scenarios. Each function should return the expected response under each given scenario for the test to be successful. These tests are run automatically after every Git push using Jenkins. Jenkins prints out whether or not the tests were successsful.Each tests were ran individual using a bash for-loop.
<br/>
![test 1](https://i.imgur.com/NOH1JTA.png)
![test 2](https://i.imgur.com/T0Jj64y.png)
![test 3](https://i.imgur.com/vAz7FUa.png)
![test 4](https://i.imgur.com/5bePqpg.png)
<br/>
A coverage report is also displayed noting the percentage of the application that was tested. This information helps the developer understand how much of the code in the app has been successfully tested.
If any of the unit testing fails, the entire Jenkins build is marked as a fail. However, this project had a 100% coverage indicating efficiency as all the lines in in each of my routes was fully tested and there were no unnecessary syntax in my code.
<br/>
The results also produces a junit.xml file which is used by the Jenkins Junit plug-in to produce advanced testing reports, further easing traceback for the developer.
## Footer
### Future Improvements
* Using Integration testing to test the app as a whole, by the selenium approach would be ideal.
* Add a background colour for each fortune so the application is more apealing to end-users
* add functionality that allows user to input data.
### Author
<NAME>
### Acknowledgements
* [<NAME>](https://github.com/htr-volker)
* [<NAME>](https://github.com/OliverNichols)<file_sep>/venv/lib/python3.6/site-packages/requests_mock/__init__.pyi
# Stubs for requests_mock
from requests_mock.adapter import ANY as ANY, Adapter as Adapter
from requests_mock.exceptions import MockException as MockException, NoMockAddress as NoMockAddress
from requests_mock.mocker import DELETE as DELETE, GET as GET, HEAD as HEAD, Mocker as Mocker, MockerCore as MockerCore, OPTIONS as OPTIONS, PATCH as PATCH, POST as POST, PUT as PUT, mock as mock
from requests_mock.request import _RequestObjectProxy as _RequestObjectProxy
from requests_mock.response import CookieJar as CookieJar, create_response as create_response
<file_sep>/venv/lib/python3.6/site-packages/requests_mock/adapter.pyi
# Stubs for requests_mock.adapter
from requests.adapters import BaseAdapter
from requests_mock import _RequestObjectProxy
from typing import Any, Callable, Dict, List, NewType, Optional, Pattern, Union
AnyMatcher = NewType("AnyMatcher", object)
ANY: AnyMatcher = ...
class _RequestHistoryTracker:
request_history: List[_RequestObjectProxy] = ...
def __init__(self) -> None: ...
@property
def last_request(self) -> Optional[_RequestObjectProxy]: ...
@property
def called(self) -> bool: ...
@property
def called_once(self) -> bool: ...
@property
def call_count(self) -> int: ...
class _RunRealHTTP(Exception): ...
class _Matcher(_RequestHistoryTracker):
def __init__(self, method: Any, url: Any, responses: Any, complete_qs: Any, request_headers: Any, additional_matcher: Any, real_http: Any, case_sensitive: Any) -> None: ...
def __call__(self, request: Any) -> Any: ...
class Adapter(BaseAdapter, _RequestHistoryTracker):
def __init__(self, case_sensitive: bool = ...) -> None: ...
def register_uri(
self,
method: Union[str, AnyMatcher],
url: Union[str, Pattern[str], AnyMatcher],
response_list: Optional[List[Dict[str, Any]]] = ...,
request_headers: Dict[str, str] = ...,
complete_qs: bool = ...,
status_code: int = ...,
text: str = ...,
headers: Optional[Dict[str, str]] = ...,
additional_matcher: Optional[Callable[[_RequestObjectProxy], bool]] = ...,
**kwargs: Any
) -> Any: ...
def add_matcher(self, matcher: Any) -> None: ...
<file_sep>/venv/lib/python3.6/site-packages/requests_mock/exceptions.pyi
# Stubs for requests_mock.exceptions
from typing import Any
class MockException(Exception): ...
class NoMockAddress(MockException):
request: Any = ...
def __init__(self, request: Any) -> None: ...
class InvalidRequest(MockException): ...
<file_sep>/service-4/app.py
from flask import Flask,request
import random
from os import getenv
import random
import datetime
import calendar
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = getenv("DATABASE_URI")
@app.route('/get_fortune/<day>/<int:number>', methods=['POST'])
def get_fortune(day, number):
if number == 10:
return f"On {day} you loose you're house and fiance, Sorry about that!"
elif number <= 13 :
return f"On {day} you will win £300 from the lottery, that's it sorry!"
elif number <= 16:
return f"On {day} you will recieve unlimited food, Love dat!"
elif number <= 19:
return f"On {day} you will becomone a millionaire, lucky you!!"
else :
return f"On {day} you will find nothing but peace & happiness"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)<file_sep>/venv/lib/python3.6/site-packages/requests_mock/response.pyi
# Stubs for requests_mock.response
import six
from requests.cookies import RequestsCookieJar
from typing import Any
class CookieJar(RequestsCookieJar):
def set(self, name: Any, value: Any, **kwargs: Any) -> Any: ...
class _FakeConnection:
def send(self, request: Any, **kwargs: Any) -> None: ...
def close(self) -> None: ...
class _IOReader(six.BytesIO):
def read(self, *args: Any, **kwargs: Any) -> Any: ...
def create_response(request: Any, **kwargs: Any) -> Any: ...
class _Context:
headers: Any = ...
status_code: Any = ...
reason: Any = ...
cookies: Any = ...
def __init__(self, headers: Any, status_code: Any, reason: Any, cookies: Any) -> None: ...
class _MatcherResponse:
def __init__(self, **kwargs: Any) -> None: ...
def get_response(self, request: Any) -> Any: ...
| e9be6013dc6ee8a384bc2e54d4dc58a336fa94d6 | [
"Markdown",
"Python",
"Text",
"Shell"
] | 18 | Text | PhilipL1/project-2 | e59890708585f5c99dfcdd15080c2411db935cbb | c7abc27bbc23350004bc41418e5bcca6164911ba | |
refs/heads/master | <repo_name>avdeyArtem/my-first-shop<file_sep>/catalog/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-06 15:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CategoriesFirst',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, verbose_name='Название раздела')),
('slug', models.CharField(max_length=50, verbose_name='Ссылка')),
],
options={
'verbose_name_plural': 'Раздел',
},
),
migrations.CreateModel(
name='CategoriesSecond',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, verbose_name='Название категирии')),
('slug', models.CharField(max_length=50, verbose_name='Ссылка')),
],
options={
'verbose_name_plural': 'Категория',
},
),
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, verbose_name='Название товара')),
('description', models.TextField(verbose_name='Описание')),
('size', models.CharField(max_length=50, verbose_name='Размер')),
('compound', models.CharField(max_length=100, verbose_name='Состав')),
('price', models.DecimalField(decimal_places=2, max_digits=6, verbose_name='Цена')),
('count', models.IntegerField(default=0, verbose_name='Количество')),
('land', models.CharField(max_length=50, verbose_name='Страна производитель')),
('image', models.ImageField(upload_to='img', verbose_name='Изображение товара')),
],
options={
'verbose_name_plural': 'Продукты',
},
),
]
<file_sep>/user/views.py
from django.shortcuts import render_to_response, render
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.views.decorators import csrf
from .forms import RegistrationForm
from django.contrib.auth import authenticate, login as auth_login, logout
# Create your views here.
def register(request):
context = {}
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
username = request.POST['username']
password = request.POST['<PASSWORD>']
user = authenticate(request, username=username, password=password)
if user.is_active:
auth_login(request, user)
return HttpResponseRedirect('/')
return HttpResponseRedirect('/')
else:
form = RegistrationForm()
context = {'form':form}
return render(request, "catalog/reg.html", context)
def login(request):
context = {}
username = password = ''
if request.method == 'POST':
username = request.POST['login']
password = request.POST['<PASSWORD>']
user = authenticate(request, username=username, password=<PASSWORD>)
if user is not None:
if user.is_active:
auth_login(request, user)
return HttpResponseRedirect('/')
return render(request, "catalog/reg.html", context)
def logout_user(request):
logout(request)
return HttpResponseRedirect('/')
<file_sep>/catalog/migrations/0004_auto_20170626_2201.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-26 19:01
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('catalog', '0003_product_category'),
]
operations = [
migrations.CreateModel(
name='Brand',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, verbose_name='Название категории')),
('slug', models.CharField(max_length=50, verbose_name='Ссылка')),
],
options={
'verbose_name_plural': 'Брэнды',
},
),
migrations.AlterField(
model_name='categoriessecond',
name='name',
field=models.CharField(max_length=50, verbose_name='Название категории'),
),
migrations.AddField(
model_name='product',
name='brand',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='catalog.Brand'),
preserve_default=False,
),
]
<file_sep>/catalog/models.py
from django.db import models
class CategoriesFirst(models.Model):
name = models.CharField(max_length = 50, verbose_name = "Название раздела")
slug = models.CharField(max_length = 50, verbose_name = "Ссылка")
def __str__ (self):
return self.name
class Meta:
verbose_name_plural = "Раздел"
class CategoriesSecond(models.Model):
name = models.CharField(max_length = 50, verbose_name = "Название категории")
slug = models.CharField(max_length = 50, verbose_name = "Ссылка")
section = models.ForeignKey(CategoriesFirst)
def __str__ (self):
return self.name
class Meta:
verbose_name_plural = "Категория"
class Brand(models.Model):
name = models.CharField(max_length = 50, verbose_name = "Название категории")
slug = models.CharField(max_length = 50, verbose_name = "Ссылка")
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "Брэнды"
class Product(models.Model):
name = models.CharField(max_length = 50, verbose_name = "Название товара")
description = models.TextField(verbose_name = "Описание")
brand = models.ForeignKey(Brand)
size = models.CharField(max_length = 50, verbose_name = "Размер")
compound = models.CharField(max_length = 100, verbose_name = "Состав")
price = models.DecimalField(decimal_places = 2, max_digits = 6, verbose_name = "Цена")
count = models.IntegerField(default = 0, verbose_name = "Количество")
land = models.CharField(max_length = 50, verbose_name = "Страна производитель")
image = models.ImageField(upload_to = 'img', verbose_name = "Изображение товара")
category = models.ForeignKey(CategoriesSecond)
views = models.IntegerField(default = 0, verbose_name = "Просмотры", blank = True)
def __str__ (self):
return self.name
class Meta:
verbose_name_plural = "Продукты"
class Order(models.Model):
last_name = models.CharField(max_length = 256, verbose_name="Фамилия")
first_name = models.CharField(max_length = 256, verbose_name="Имя")
two_name = models.CharField(max_length = 256, verbose_name="Отчество")
phone = models.CharField(max_length = 256, verbose_name="Фамилия")
stat = models.CharField(max_length = 256, verbose_name="Город")
street = models.CharField(max_length = 256, verbose_name="Улица")
house = models.CharField(max_length = 256, verbose_name="Дом")
index = models.CharField(max_length = 256, verbose_name="Индекс")
att = models.TextField(verbose_name="Примечания")
product = models.TextField(verbose_name="Товары")
def __str__ (self):
return self.last_name + " " + self.first_name + " " + self.two_name
class Meta:
verbose_name_plural = "Заказы"
<file_sep>/catalog/static/catalog/js/scripts.js
$(document).ready(function() {
$('.top_menu').on('click', 'a.can_open', function(e) {
e.preventDefault();
$(this).parent().siblings().find('div').slideUp();
$(this).next().slideToggle();
});
$('.about_company').click(function(e) {
e.preventDefault();
$('section.slider').hide();
$('.unslider-nav').hide();
$('section.about_block').show();
});
$('#about_company_back').click(function(e) {
e.preventDefault();
$('section.about_block').hide();
$('section.slider').show();
$('.unslider-nav').show();
});
});
<file_sep>/catalog/views.py
from django.shortcuts import render, get_object_or_404
from cart.forms import CartAddProductForm
from .models import Product, CategoriesSecond, CategoriesFirst, Brand, Order
from cart.cart import Cart
from django.http import HttpResponseRedirect
import random
from django.db.models import Q
def index(request):
brands = Brand.objects.all()[:15]
popular = Product.objects.all().order_by('-views')[:15]
products = Product.objects.all()
categoryes = return_category()
cart = Cart(request)
context = {'products':products, 'category_1':categoryes['category_1'], 'category_2':categoryes['category_2'],
'category_3':categoryes['category_3'], 'cart':cart, 'brands':brands, 'popular':popular}
return render(request, "catalog/index.html", context)
def item(request, id):
brands = Brand.objects.all()[:15]
popular = Product.objects.all().order_by('-views')[:15]
cart = Cart(request)
randQuery = Product.objects.order_by('?')[:4]
categoryes = return_category()
item = get_object_or_404(Product, id = id)
item.views += 1
item.save()
category = CategoriesSecond.objects.get(name = item.category)
section = CategoriesFirst.objects.get(name = category.section)
cart_product_form = CartAddProductForm()
context = {'item':item, 'cart_product_form':cart_product_form, 'category': category, 'section':section,'category_1':categoryes['category_1'], 'category_2':categoryes['category_2'],
'category_3':categoryes['category_3'], 'randquery':randQuery, 'cart':cart, 'brands':brands, 'popular':popular}
return render(request, "catalog/item.html", context)
def category(request, slug):
brands = Brand.objects.all()[:15]
popular = Product.objects.all().order_by('-views')[:15]
cart = Cart(request)
category = CategoriesSecond.objects.get(slug = slug)
section = CategoriesFirst.objects.get(name = category.section)
products = Product.objects.filter(category = category)
categoryes = return_category()
context = {'category':category, 'products':products,'category_1':categoryes['category_1'], 'category_2':categoryes['category_2'],
'category_3':categoryes['category_3'], 'section':section, 'cart':cart, 'brands':brands, 'popular':popular}
return render(request, "catalog/catalog.html", context)
def brand(request, slug):
brands = Brand.objects.all()[:15]
popular = Product.objects.all().order_by('-views')[:15]
brand = Brand.objects.get(slug = slug)
products = Product.objects.filter(brand = brand)
cart = Cart(request)
categoryes = return_category()
context = {'cart':cart, 'products' : products, 'brand' : brand, 'brands':brands, 'popular':popular}
return render(request, "catalog/catalog.html", context)
def return_category():
woman = CategoriesFirst.objects.get(name = "Женщинам")
man = CategoriesFirst.objects.get(name = "Мужчинам")
kid = CategoriesFirst.objects.get(name = "Детям")
category_1 = CategoriesSecond.objects.filter(section = woman)
category_2 = CategoriesSecond.objects.filter(section = man)
category_3 = CategoriesSecond.objects.filter(section = kid)
categoryes = {'category_1':category_1, 'category_2':category_2, 'category_3':category_3}
return categoryes
def search(request):
brands = Brand.objects.all()[:15]
popular = Product.objects.all().order_by('-views')[:15]
cart = Cart(request)
categoryes = return_category()
if request.method == "POST":
q = request.POST['q']
result = Product.objects.filter(Q(name__icontains=q) | Q(description__icontains=q) | Q(description__iexact=q) | Q(name__icontains=q.title()))
context = {'result':result,'category_1':categoryes['category_1'], 'category_2':categoryes['category_2'],
'category_3':categoryes['category_3'], 'q' : q, 'cart':cart, 'brands':brands, 'popular':popular}
return render(request, "catalog/search.html", context)
else:
context = {'category_1':categoryes['category_1'], 'category_2':categoryes['category_2'],
'category_3':categoryes['category_3'], 'cart':cart, 'brands':brands, 'popular':popular}
return render(request, "catalog/search.html", context)
def order(request):
brands = Brand.objects.all()[:15]
popular = Product.objects.all().order_by('-views')[:15]
products = Product.objects.all()
categoryes = return_category()
cart = Cart(request)
context = {'products':products, 'category_1':categoryes['category_1'], 'category_2':categoryes['category_2'],
'category_3':categoryes['category_3'], 'cart':cart, 'brands':brands, 'popular':popular}
if request.method == "POST":
order = Order()
order.last_name = request.POST['last_name']
order.first_name = request.POST['first_name']
order.two_name = request.POST['two_name']
order.phone = request.POST['phone']
order.stat = request.POST['stat']
order.street = request.POST['street']
order.house = request.POST['house']
order.index = request.POST['index']
order.att = request.POST['att']
order.product = request.POST['product']
order.save()
return render(request, "catalog/thank.html", context)
<file_sep>/catalog/admin.py
from django.contrib import admin
from catalog.models import CategoriesFirst,CategoriesSecond, Product, Brand, Order
admin.site.register(Product)
admin.site.register(CategoriesFirst)
admin.site.register(CategoriesSecond)
admin.site.register(Brand)
admin.site.register(Order)
<file_sep>/catalog/migrations/0006_order.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-27 20:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0005_product_views'),
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('last_name', models.CharField(max_length=256, verbose_name='Фамилия')),
('first_name', models.CharField(max_length=256, verbose_name='Имя')),
('two_name', models.CharField(max_length=256, verbose_name='Отчество')),
('phone', models.CharField(max_length=256, verbose_name='Фамилия')),
('stat', models.CharField(max_length=256, verbose_name='Город')),
('street', models.CharField(max_length=256, verbose_name='Улица')),
('house', models.CharField(max_length=256, verbose_name='Дом')),
('index', models.CharField(max_length=256, verbose_name='Индекс')),
('att', models.TextField(verbose_name='Примечания')),
('product', models.TextField(verbose_name='Товары')),
],
options={
'verbose_name_plural': 'Заказы',
},
),
]
<file_sep>/user/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class User(User):
phone = models.CharField(max_length = 30)
<file_sep>/catalog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^search/$', views.search, name="search"),
url(r'^(?P<id>[0-9]+)/$', views.item, name="item"),
url(r'^category/(?P<slug>[\w-]+)/$', views.category, name="category"),
url(r'^brand/(?P<slug>[\w-]+)/$', views.brand, name="brand"),
url(r'^add_order/$', views.order, name="order"),
]
| e94b24acfe7a48ecba8af9e6784f0c1ee02ff546 | [
"JavaScript",
"Python"
] | 10 | Python | avdeyArtem/my-first-shop | e6ef21b210aece41df58709be4dfd952c50a84bb | 8d7a1a276dc017d0d4d9517e0a5d768ba1675223 | |
refs/heads/master | <file_sep>Click==7.0
Flask==1.0.2
Flask-PyMongo==2.2.0
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.0
pymongo==3.7.2
python-dateutil==2.8.0
six==1.12.0
Werkzeug==0.14.1
<file_sep>RESTful Flask API with MongoDB
__________________________________
This repo is an example of CREATE-READ-UPDATE-DELETE (CRUD) API in Python, based on Flask, and uses MongoDB as a database.
Tech/Framework Used
__________________________________
* Python
* Flask
* MongoDB
Getting Started
__________________________________
These instructions will get a copy of the project up and running on your local machine.
* Clone project onto local machine.
* Activate your environment.
- pip install virtualenv
- virtualenv env
- source env/bin/activate
* Install requirements for project.
- pip install -r requirements.txt
* Start mongoDB.
mongod
* In a second tab, start flask instance.
python3 server.py
* In a third tab, you can use and test the API by trying out the following commands:
* To post (Create a new entry)
- curl -v -XPOST -H "Content-Type: application/json" http://localhost:5000/info -d '{"name":"<string name>"}'
* To get (Read an existing entry)
- curl -v -XGET http://localhost:5000/info/<id # of entry>
* To put (Update an existing entry)
- curl -v -XPUT -H "Content-Type: application/json" http://localhost:5000/info/<id of entry> -d '{"name":"<update value>"}'
* To delete (Delete an existing entry)
- curl -v -XDELETE http://localhost:5000/info/<id # of entry>
* Make sure to end the environment!
- deactivate
Extra Notes
__________________________________
* If there are issues with bson (i.e. "cannot import name 'abc' from 'bson.py3compat'"), follow these directions to resolve:
- Uninstall pymongo and reinstall with command:
- python3 -m pip install pymongo
Misc
__________________________________
Information on CRUD in Python:
https://realpython.com/flask-connexion-rest-api/
<file_sep>from flask import Flask, request, jsonify
from flask_pymongo import MongoClient
from bson import ObjectId, errors
import sys
app = Flask(__name__)
client = MongoClient('mongodb://localhost:27017/') # Have to specify the host & port
db = client.restdb
collection = db.cats
@app.route('/')
def homepage():
return "Homepage", 200
@app.route('/info', methods=['POST'])
def post_info():
if not request.json:
return "Please enter request in JSON", 400
info = request.json
id = collection.insert_one(info).inserted_id
return jsonify(str(id)), 201
@app.route('/info/<id>', methods=['GET'])
def get_info(id):
try:
result = collection.find_one({'_id': ObjectId(id)})
except errors.InvalidId:
return "ID entered invalid, please enter valid ID", 400
if not result:
return "ID not found in database", 404
return jsonify({'name': result['name']}), 200
@app.route('/info/<id>', methods=['DELETE'])
def delete_info(id):
try:
result = collection.find_one({'_id': ObjectId(id)})
except errors.InvalidId:
return "ID entered invalid", 400
if not result:
return "ID not found in database", 404
collection.remove({'_id': ObjectId(id)})
return jsonify(result['name']), 200
@app.route('/info/<id>', methods=['PUT'])
def put_info(id):
try:
result = collection.find_one({'_id': ObjectId(id)})
except errors.InvalidId:
return "ID entered invalid", 400
if not result:
return "ID not found in database", 404
if not request.json:
return "Please enter request in JSON", 400
info = request.json
collection.update({'_id': ObjectId(id)}, {'$set': info})
result = collection.find_one({'_id': ObjectId(id)})
return jsonify(result['name']), 200
if __name__ == '__main__':
app.run(debug=False, host="0.0.0.0")
| 0bb7c9e694dd84c99c48c1dca8b0861fbb12e311 | [
"Markdown",
"Python",
"Text"
] | 3 | Text | tien-han/REST-API-with-MongoDB | 729051791044abe77e4c6d7a44486f08cd090f46 | 7007346f1153897bfd13ac41a8a772244c9f31bf | |
refs/heads/master | <repo_name>weimingtom/learn<file_sep>/sys_program/player/src/inc/process_lrc.h
/* ************************************************************************
* Filename: process_lrc.h
* Description:
* Version: 1.0
* Created: 2015年07月31日 星期五 09時17分38秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __PTHREAD_LRC_H__
#define __PTHREAD_LRC_H__
extern uint src_segment(char *psrc, char *plines[], char *str);
extern uint line_segment(char *pline, char *pbuf[], char *str);
//extern LRC *build_link(char *lrc_pline[], char *ptitle[], int lines);
extern LRC *build_link(MPLAYER *pm,char *plines[],int lines);
extern LRC *dispose_lrc(MPLAYER *pm, char *name);
extern void show_lyric(LRC *pnode, int longest);
extern void mplayer_show_lyric(MPLAYER *pm, LRC *pnode);
//extern void mplayer_show_lyrtitle(MPLAYER *pm, char *title[]);
extern void mplayer_show_lyrtitle(MPLAYER *pm, char *ptitle, int i);
//void mplayer_show_lyric(MPLAYER *pm, int cur_time);
#endif
<file_sep>/network/1st_day/udp.c
/* ************************************************************************
* Filename: udp.c
* Description:
* Version: 1.0
* Created: 2015年08月31日 16时37分21秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
int sockfd = 0;
unsigned short port = 8080;
char *server_ip = "10.221.2.12";
if(argc > 1)
{
server_ip = argv[1];
}
if(argc > 2)
{
port = atoi(argv[2]);
}
//AF_INET : ipv4
//0: 根据
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
//配置服务器地址
struct sockaddr_in server_addr;
//memset(&server_addr, 0, sizeof(server_addr));
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);//服务器的端口
//服务器的IP
inet_pton(AF_INET, server_ip ,&server_addr.sin_addr.s_addr);
//发送数据
while(1)
{
char msg[256] = "";
fgets(msg,sizeof(msg),stdin);
sendto(sockfd, msg, strlen(msg), 0,\
(struct sockaddr *)&server_addr, sizeof(server_addr));
}
printf("fd = %d\n",sockfd);
close(sockfd);
return 0;
}
<file_sep>/work/debug/pc/virtualchar/virtualchar.c
#include <linux/module.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#define DEVICE_NAME "virtualchar"
#define MEM_SIZE 0x400 // 1kb
#define VIRTUALCHAR_MAGIC 0x08
#define MEM_CLEAR _IO(VIRTUALCHAR_MAGIC, 0) // 清零全局内存
static int major = 0;
static struct class *virtualchar_class = NULL;
struct virtualchar_dev
{
struct cdev cdev;
unsigned char mem[MEM_SIZE];
};
static struct virtualchar_dev *virtualchar_pdev = NULL; // 设备结构指针
static loff_t virtualchar_llseek(struct file *filp, loff_t offset, int orig)
{
loff_t ret;
switch(orig)
{
case SEEK_SET: // 从文件开头开始偏移
{
if(offset < 0){
ret = -EINVAL;
break;
}
else if((unsigned int)offset > MEM_SIZE){ // 越界
ret = -EINVAL;
break;
}
filp->f_pos = offset;
ret = filp->f_pos;
break;
}
case SEEK_CUR: // 从当前位置开始偏移
{
if(filp->f_pos + offset < 0){
ret = -EINVAL;
break;
}
else if(filp->f_pos + offset > MEM_SIZE){ // 越界
ret = -EINVAL;
break;
}
filp->f_pos += offset;
ret = filp->f_pos;
break;
}
case SEEK_END:
{
if(offset>0){
ret = -EINVAL;
break;
}
else if(MEM_SIZE + offset <0){
ret = -EINVAL;
break;
}
filp->f_pos = MEM_SIZE + offset;
ret = filp->f_pos;
break;
}
default:
ret = -EINVAL;
}
return ret;
}
static int virtualchar_ioctl(struct inode *pinode, struct file *filp, unsigned int cmd, unsigned long arg)
{
int ret;
struct virtualchar_dev *pdev = filp->private_data; // 获取设备结构指针
switch(cmd)
{
case MEM_CLEAR:
{ // 清空全局内存
memset(pdev->mem, 0, MEM_SIZE);
printk(KERN_INFO "Virtualchar memory is set to zero\n");
break;
}
default:
ret = -EINVAL; // 其他不支持命令
}
return ret;
}
static int virtualchar_open(struct inode *pinode, struct file *filp)
{
struct virtualchar_dev *pdev = NULL;
pdev = container_of(pinode->i_cdev, struct virtualchar_dev, cdev); // 返回设备结构体的首地址
// 将设备结构指针赋值给文件私有数据指针
filp->private_data = pdev;
return 0;
}
static ssize_t virtualchar_read(struct file *filp, char __user *buf, size_t size, loff_t *ppos)
{
int ret;
unsigned long count = size;
unsigned long pos = *ppos;
struct virtualchar_dev *pdev = filp->private_data;// 获取设备结构指针
// 分析和获取有效的读长度
if(pos >= MEM_SIZE){ // 要读的偏移位置越界
return count? -ENXIO : 0;
}
else if(count > MEM_SIZE - pos){ // 要读的字节数过大
count = MEM_SIZE - pos;
}
// 内核空间 -> 用户空间
if(copy_to_user(buf, (void *)(pdev->mem + pos), count)){
ret = -EFAULT;
}
else {
*ppos += count;
ret = count;
printk(KERN_INFO "read %lu bytes from %lu\n", count, pos);
}
return ret;
}
static ssize_t virtualchar_write(struct file *filp, const char __user *buf, size_t size, loff_t *ppos)
{
int ret;
unsigned long count = size;
unsigned long pos = *ppos;
struct virtualchar_dev *pdev = filp->private_data;// 获取设备结构指针
// 分析和获取有效的写长度
if(pos >= MEM_SIZE){ // 要写的偏移位置越界
return count? -ENXIO : 0;
}
else if(count > MEM_SIZE - pos){ // 要写的字节数过大
count = MEM_SIZE - pos;
}
// 用户空间 -> 内核空间
if(copy_from_user((void *)(pdev->mem + pos), buf, count)){
ret = -EFAULT;
}
else {
*ppos += count;
ret = count;
printk(KERN_INFO "written %lu bytes from %lu\n", count, pos);
}
return ret;
}
static struct file_operations virtualchar_fops = {
.owner = THIS_MODULE,
.llseek = virtualchar_llseek,
.ioctl = virtualchar_ioctl,
.open = virtualchar_open,
.read = virtualchar_read,
.write = virtualchar_write,
};
#if 1
void virtualchar_setup_cdev(struct virtualchar_dev *pdev, int minor)
{
int err, devno;
devno = MKDEV(major, minor);
cdev_init(&pdev->cdev, &virtualchar_fops);
pdev->cdev.owner = THIS_MODULE;
pdev->cdev.ops = &virtualchar_fops;
err = cdev_add(&pdev->cdev, devno, 1);
if(err){
printk(KERN_NOTICE "Error %d adding globmem\n", err);
}
}
#else
void virtualchar_setup_cdev(void)
{
int err, devno;
devno = MKDEV(major, 0);
cdev_init(&virtualchar_dev.cdev, &virtualchar_fops);
virtualchar_dev.cdev.owner = THIS_MODULE;
virtualchar_dev.cdev.ops = &virtualchar_fops;
err = cdev_add(&virtualchar_dev.cdev, devno, 1);
if(err){
printk(KERN_NOTICE "Error %d adding globmem\n", err);
}
}
#endif
int __init virtualchar_init(void)
{
int ret ,i;
struct device *virtualchar_device;
dev_t devno = MKDEV(major, 0);
if(major){
ret = register_chrdev_region(devno, 2, DEVICE_NAME);
}
else{ // 动态获取设备号
ret = alloc_chrdev_region(&devno, 0, 2, DEVICE_NAME);
major = MAJOR(devno);
}
if(ret < 0){
printk("register keys_driver failed!\n");
return ret;
}
/* 动态申请两个设备结构体的内存 */
virtualchar_pdev = (struct virtualchar_dev *)kmalloc(2*sizeof(struct virtualchar_dev), GFP_KERNEL);
if(!virtualchar_pdev){ // 申请失败
ret = -ENOMEM;
goto malloc_err;
}
virtualchar_setup_cdev(&virtualchar_pdev[0], 0);
virtualchar_setup_cdev(&virtualchar_pdev[1], 1);
// 注册一个类
virtualchar_class = class_create(THIS_MODULE, DEVICE_NAME);
if(IS_ERR(virtualchar_class)){
printk("Err:failed in create keys class!\n");
ret = PTR_ERR(virtualchar_class);
goto class_err;
}
//创建设备节点
for(i=0;i<2;i++){
virtualchar_device = device_create(virtualchar_class, NULL, MKDEV(major, i), NULL, "virtualchar%d", i);
if(IS_ERR(virtualchar_device)){
printk("Err:failed in create keys device!\n");
ret = PTR_ERR(virtualchar_device);
goto device_err;
}
}
printk("%s:%d\n",__FUNCTION__,__LINE__);
return 0;
device_err:
while(i--){
device_destroy(virtualchar_class, MKDEV(major, i));
}
class_destroy(virtualchar_class);
class_err:
cdev_del(&virtualchar_pdev[0].cdev);
cdev_del(&virtualchar_pdev[1].cdev);
kfree(virtualchar_pdev);
malloc_err:
unregister_chrdev_region(devno, 2);
return ret;
}
void __exit virtualchar_exit(void)
{
int i;
//删除设备节点
for(i=0;i<2;i++)
device_destroy(virtualchar_class,MKDEV(major, i));
//注销类
class_destroy(virtualchar_class);
// 删除cdev结构
cdev_del(&(virtualchar_pdev[0].cdev));
cdev_del(&(virtualchar_pdev[1].cdev));
kfree(virtualchar_pdev); // 释放设备结构体的内存
// 注销设备号
unregister_chrdev_region(MKDEV(major, 0), 2);
printk("%s:%d\n",__FUNCTION__,__LINE__);
}
module_init(virtualchar_init);
module_exit(virtualchar_exit);
MODULE_LICENSE("GPL");
<file_sep>/sys_program/3rd_day/homework/yy/tom.c
/* ************************************************************************
* Filename: jerry.c
* Description:
* Version: 1.0
* Created: 2015年08月17日 16时57分02秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int ret,fr,fw;
char tom[] = "Tom: ";
pid_t pid;
//remove(".rfifo");
//remove(".wfifo");
mkfifo(".rfifo",0777);
mkfifo(".wfifo",0777);
printf("Hello, I am %s\n",tom);
fr = open(".rfifo",O_RDONLY);
if(fr < 0) perror("");
fw = open(".wfifo",O_WRONLY);
pid = fork();
if(pid < 0) perror("");
else if(pid == 0) //子进程
{
int len = 0;
char buf[128] = "";
while(1)
{
printf("%s",tom);
fflush(stdout);
fgets(buf,sizeof(buf),stdin);
len = strlen(buf);
if(len > 1)
{
char msg[128] = "";
strcat(msg,tom);
strcat(msg,buf);
write(fw, msg, strlen(tom)+len - 1);
}
}
}
else
{
char msg[128] = "";
while(1)
{
memset(msg,0,sizeof(msg));
read(fr, msg, sizeof(msg)); //FIFO里没数据read会阻塞,如果通信写进程先退出,read将不阻塞,read返回值为0
if(msg[0] == 0)
{
kill(pid,1);
exit(0);
}
printf("\r%s\n",msg);
printf("%s",tom);
fflush(stdout);
}
}
return 0;
}
<file_sep>/c/practice/get_samechar.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if 0
char *get_samechar(char *str)
{
if(str == NULL)
return NULL;
char *p = NULL, *ret = NULL;
int i = 0, j = 1;
int len = strlen(str) + 1;// 测出传入字符串长度
p = (char *)malloc(len); // 动态分配内存空间,len个字节长度
bzero(p, len); // 清零
while(j<len){
//printf("j = %d\n", j);
if(str[i] == str[j]){ // 出现连续字符有相同
p[i] += 2; // 在出现连续相同字符 对应 在字符串中的位置 记录出现的次数,
j++;
while(j < len && str[i] == str[j]){ // 判断后面还是不是相同字符
p[i] += 1; // 记录加1
j++; // 指向下一个
}
i = j;
j++;
}
else{
i++;
j++;
}
}
for(i=0,j=1; j<len; j++){
if(p[i] < p[j])
i = j;
}
if(p[i] != 0) ret = str + i;
else ret = NULL;
free(p); // 释放动态分配的内存空间,malloc函数分配的空间在不要时要释放掉
return ret;
}
#else
char *get_samechar(char *str)
{
if(str == NULL)
return NULL;
int i = 0, j = 1, len = strlen(str);
int pos = 0, len_new = 0, len_old = 0;
while(j < len){
if(str[i] == str[j]){
len_new += 2;
j++;
while(str[j] != 0 && str[i] == str[j]){
len_new++;
j++;
}
if(len_new > len_old)
len_old = len_new;
pos = i;
i = j + 1;
j++;
}
else{
i++;
j++;
}
}
if(len_old != 0)
return str + pos;
else
return NULL;
}
#endif
int main(int argc, char argv[])
{
char str[64] = "";
int len = 0;
printf("输入字符串:");
// 刷新标准输出,因为在printf函数的缓冲没满,并且打印的
//字符串后面没有 "\n",调用这个函数屏幕马上可以看到”输入字符串:“
fflush(stdout);
fgets(str, sizeof(str), stdin); // 从标准输入获取输入字符串
len = strlen(str); // 求出长度
str[len - 1] = 0; // 去掉字符串后的换行符
char *p = get_samechar(str); // 处理
if(p != NULL){
printf("##:%s\n", p);
}
return 0;
}
<file_sep>/README.md
# learn
echo "# learn" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin <EMAIL>:panddio/learn.git
git push -u origin master
<file_sep>/gtk/4st_week/picture_browse/picture_browse.c
/* ************************************************************************
* Filename: picture_browse.c
* Description:
* Version: 1.0
* Created: 2015年08月11日 14时21分54秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <gtk/gtk.h>
#include "scan_dir.h"
#include "image.h"
gboolean pause_flag = TRUE;
guint timer; // 定时器id
gdouble upstep;
char buf[6];
typedef struct _Window
{
GtkWidget *main_window;
GtkWidget *table;
GtkWidget *image;
GtkWidget *button_previous;
GtkWidget *button_next;
GtkWidget *button_pause;
GtkWidget *progress;
}WINDOW;
void itoc(int number, char buf[])
{
buf[0] = number/1000;
buf[1] = number%1000/100;
buf[2] = number%100/10;
buf[3] = '%';
buf[4] = '\0';
buf[5] = number%10;
if(buf[5] > 5)
{
buf[2] += 1;
if(buf[2] >= 10)
{
buf[2] = 0;
buf[1] += 1;
if(buf[1] >= 10)
{
buf[1] = 0;
if(buf[0] > 0) buf[0] = 1;
else buf[0] += 1;
}
}
}
if (buf[0] == 0) buf[0] = ' ';
else buf[0] +=48;
buf[1] += 48;
buf[2] += 48;
}
// 定时器的回调函数
static void timer_callback(gpointer data)
{
WINDOW *p_temp = (WINDOW *)data;
//upstep = gtk_progress_bar_get_fraction(GTK_PROGRESS_BAR(p_temp->progress));
gs_index++;
upstep += (gdouble)(1.0/(gs_bmp_total));
if(gs_index >= gs_bmp_total)
{
gs_index = 0;
upstep = (gdouble)(1.0/(gs_bmp_total));;
}
printf("gs_index = %d\n", gs_index);
load_image(p_temp->image, gs_bmp_name[gs_index], 500, 450);
// 设置进度条的新值
gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(p_temp->progress), upstep);
itoc((int)(upstep*1000),buf);
gtk_progress_bar_set_text(GTK_PROGRESS_BAR(p_temp->progress), buf);
}
// 按钮的回调函数
void deal_switch_image(GtkWidget *button, gpointer data)
{
WINDOW *p_temp = (WINDOW *)data;
//gdouble upstep = gtk_progress_bar_get_fraction(GTK_PROGRESS_BAR(p_temp->progress));
//创建图片控件(这里加这行会出现只能播放一张图片的错误)
//p_temp->image = gtk_image_new_from_pixbuf(NULL);
if(button == p_temp->button_previous)// 上一张
{
gs_index--;
upstep -= (gdouble)(1.0/(gs_bmp_total));
if(gs_index < 0)
{
gs_index = gs_bmp_total - 1;
upstep = 1;
}
printf("gs_index = %d\n", gs_index);
printf("p_temp->button_previous\n");
load_image(p_temp->image, gs_bmp_name[gs_index], 500, 450);
}
else if(button == p_temp->button_next ) // 下一张
{
gs_index++;
upstep += (gdouble)(1.0/(gs_bmp_total));
if(gs_index >= gs_bmp_total)
{
gs_index = 0;
upstep = (gdouble)(1.0/(gs_bmp_total));
}
printf("gs_index = %d\n", gs_index);
printf("p_temp->button_next\n");
load_image(p_temp->image, gs_bmp_name[gs_index], 500, 450);
}
else if(button == p_temp->button_pause )
{
printf("p_temp->button_pause\n");
if(pause_flag) // 自动播放
{
pause_flag = FALSE;
gtk_widget_set_sensitive(p_temp->button_next, FALSE);
gtk_widget_set_sensitive(p_temp->button_previous, FALSE);
GtkWidget *image = gtk_image_new_from_file("./skin/pause.bmp"); // 图像控件
gtk_button_set_image(GTK_BUTTON(p_temp->button_pause), image);
//创建定时器
timer = g_timeout_add(1000, (GSourceFunc)timer_callback, (gpointer)data);
}
else
{
pause_flag = TRUE;
gtk_widget_set_sensitive(p_temp->button_next, TRUE);
gtk_widget_set_sensitive(p_temp->button_previous, TRUE);
GtkWidget *image = gtk_image_new_from_file("./skin/play.bmp"); // 图像控件
gtk_button_set_image(GTK_BUTTON(p_temp->button_pause), image);
//移除定时器
g_source_remove(timer);
}
}
printf("%f\n",(float)upstep);
gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(p_temp->progress), upstep); //设置进度条的新值
itoc((int)(upstep*1000),buf);
gtk_progress_bar_set_text(GTK_PROGRESS_BAR(p_temp->progress), buf);
//gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->image, 1, 6, 1, 6); // 把图片控件加入布局
//gtk_widget_show_all(p_temp->main_window);
}
void show_window(gpointer data)
{
WINDOW *p_temp = (WINDOW *)data;
upstep = (gdouble)(1.0/(gs_bmp_total));
// 主窗口
p_temp->main_window = gtk_window_new(GTK_WINDOW_TOPLEVEL); // 创建主窗口
gtk_window_set_title(GTK_WINDOW(p_temp->main_window), "picture_browse"); // 设置窗口标题
gtk_window_set_position(GTK_WINDOW(p_temp->main_window), GTK_WIN_POS_CENTER); // 设置窗口在显示器中的位置为居中
gtk_widget_set_size_request(p_temp->main_window, 800, 480); // 设置窗口的最小大小
gtk_window_set_resizable(GTK_WINDOW(p_temp->main_window), FALSE); // 固定窗口的大小
g_signal_connect(p_temp->main_window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
// 表格布局
p_temp->table = gtk_table_new(7, 7, TRUE); // 表格布局容器 7行 7列
gtk_container_add(GTK_CONTAINER(p_temp->main_window), p_temp->table); // 容器加入窗口
// 图片控件
//gs_index = 1;
p_temp->image = gtk_image_new_from_pixbuf(NULL); // 创建图片控件
load_image(p_temp->image, gs_bmp_name[gs_index], 500, 450);
gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->image, 1, 6, 1, 6); // 把图片控件加入布局
// 进度条
GtkWidget *table = gtk_table_new(5, 7, TRUE); // 表格布局容器,用来存放进度条,限制进度条的宽度
gtk_table_attach_defaults(GTK_TABLE(p_temp->table), table, 0, 7, 0, 1);// 把进度条控件加入布局
p_temp->progress = gtk_progress_bar_new();
gtk_table_attach_defaults(GTK_TABLE(table), p_temp->progress, 1, 6, 3, 4);// 把进度条控件加入布局
gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(p_temp->progress), upstep); //设置开始进度为零
itoc((int)(upstep*1000),buf);
gtk_progress_bar_set_text(GTK_PROGRESS_BAR(p_temp->progress), buf);
//gtk_progress_bar_set_bar_style (p_temp->progress,GTK_PROGRESS_CONTINUOUS);
// 按钮
#if 1
p_temp->button_previous = create_button_from_file("./skin/previous.bmp", 70, 60);
gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_previous, 1, 2, 6, 7);
g_signal_connect(p_temp->button_previous, "clicked", G_CALLBACK(deal_switch_image), p_temp);
p_temp->button_next = create_button_from_file("./skin/next.bmp", 70, 60);
gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_next, 5, 6, 6, 7);
g_signal_connect(p_temp->button_next, "clicked", G_CALLBACK(deal_switch_image), p_temp);
p_temp->button_pause = create_button_from_file("./skin/play.bmp", 70, 60);
gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_pause, 3, 4, 6, 7);
g_signal_connect(p_temp->button_pause, "clicked", G_CALLBACK(deal_switch_image), p_temp);
#endif
chang_background(p_temp->main_window, 800, 480, "./skin/background.bmp"); // 设置窗口背景图
gtk_widget_show_all(p_temp->main_window);
}
int main(int argc, char* argv[])
{
WINDOW window;
gtk_init(&argc, &argv);
get_bmp_name(IMAGE_DIR);
order_bmp_name();
//bmp_name_print();//for test
show_window(&window);
gtk_main();
return 0;
}
<file_sep>/c/practice/3rd_week/mylink/link.c
/* ************************************************************************
* Filename: link.c
* Description:
* Version: 1.0
* Created: 2015年07月29日 星期三 04時18分53秒 HKT
* Revision: none
* Compiler: gcc
* Author: 王秋伟
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "link.h"
/**************************************************
*函数:insert_link
*功能:给链表添加新节点,当链表为空时创建链表
*************************************************/
#if 0
//从链表头插入节点
STU *insert_link(STU *head, STU stu)
{
STU *pi = NULL;
pi = (STU *)malloc(sizeof(STU));
if(pi != NULL) //成功申请到空间
{
*pi = stu;
pi->next = NULL;
if(head != NULL)
{
pi->next = head;
}
head = pi;
}
else
{
printf("Can not apply for a STU memeory space!\n");
}
return head;
}
#elif 1
//从链表尾部插入节点
STU *insert_link(STU *head, STU stu)
{
STU *pi = NULL;
pi = (STU *)malloc(sizeof(STU));
if(pi != NULL) //成功申请到空间
{
*pi = stu;
pi->next = NULL;
if(head == NULL)
{
head = pi;
}
else //链表不为空
{
STU *pb = head;
while(pb->next != NULL)
pb = pb->next;
pb->next = pi;
}
}
else
{
printf("Can not apply for a STU memeory space!\n");
}
return head;
}
#elif 0
//按某种顺序插入链表节点
STU *insert_link(STU *head, STU stu)
{
STU *pi = NULL;
pi = (STU *)malloc(sizeof(STU));
if(pi != NULL) //成功申请到空间
{
*pi = stu;
pi->next = NULL;
if(head == NULL)
{
head = pi;
}
else //链表不为空
{
STU *pb = NULL, *pf =NULL;
pb = pf = head;
//按num从小到大插入链表
while((pi->num > pb->num) && (pb->next != NULL))
{
pf = pb;
pb = pb->next;
}
if(pi->num <= pb->num)//链表头插入新节点
{
if(pb == head)
{
pi->next = pb;
head = pi;
}
else //中间插入新节点
{
pi->next = pb;
pf->next = pi;
}
}
else //尾部插入新节点
{
pb->next = pi;
}
}
}
else
{
printf("Can not apply for a STU memeory space!\n");
}
return head;
}
#endif
/**************************************************
*函数:delete_link
*功能:删除链表中指定的节点
*************************************************/
STU *delete_link(STU *head, int num)
{
if(head == NULL)
{
printf("Link is not exist!\n");
}
else
{
STU *pb = NULL, *pf = NULL;
pb = pf =head;
while((pb->num != num) && (pb->next != NULL))
{
pf = pb;
pb = pb->next;
}
if(pb->num == num)
{
if(pb == head) //删除的节点是链表头部
{
head = pb->next;
}
else if(pb->next == NULL) //删除的节点在链表尾部
{
pf->next = NULL;
}
else//删除的节点在中间
{
pf->next = pb->next;
}
free(pb);
}
}
return head;
}
/**************************************************
*函数:delete_head
*功能:删除链表的头节点
*************************************************/
STU *delete_head(STU *head)
{
if(head == NULL)
{
printf("Link is empty!\n");
}
else
{
STU *pb = NULL;
pb = head;
head = pb->next; //删除链表头部
free(pb);
}
return head;
}
/**************************************************
*函数:search_link
*功能:查询链表中指定的节点,找到返回节点地址,否则返回NULL
*************************************************/
STU *search_link(STU *head,char *name)
{
if(head == NULL)
{
printf("Link is not exist!\n");
}
else
{
STU *pb = head;
while((strcmp(pb->name,name) !=0) && (pb->next != NULL))
pb = pb->next;
if(strcmp(pb->name,name) == 0) //找到
{
return pb;
}
}
return NULL; //没找到返回NULL指针
}
/**************************************************
*函数:print_link
*功能:遍历链表中每个节点,并打印节点的内容
*************************************************/
void print_link(STU *head)
{
if(head == NULL)
{
printf("Link is not exist!\n");
}
else
{
STU *pb = head;
while(pb != NULL)
{
printf("num: %-4d name: %-8s score: %-3d\n",pb->num,pb->name,pb->score);
pb = pb->next;
}
}
}
/**************************************************
*函数:free_link
*功能:将整个链表所占的内存空间释放
*************************************************/
STU *free_link(STU *head)
{
if(head == NULL)
{
printf("Link is not exist!\n");
}
else
{
STU *pb = head;
//循环删除链表每个节点的方法:
//1.判断 head 是否为空
//2.让 pb 指向和 head 相同的节点
//3.然后 让 head 指向下个节点
//4.再把 pb 指向的节点释放掉
//5.返回步骤 1
while(head != NULL)
{
pb = head;
head = pb->next;
free(pb);
}
}
return head;
}
/**************************************************
*函数:sort_link
*功能:采用"选择法"将链表按 scort 从大到小排序
*************************************************/
STU *sort_link(STU *head)
{
if(head != NULL)
{
STU *i, *j, *k, buf;
for(i=head;i->next != NULL; i=i->next)
{
k = i;
for(j=i->next;j != NULL;j=j->next)
{
if(k->score < j->score)
{
k = j;
}
}
if(k != i) //不相等,进行交换 i 和 k
{
buf = *i;
buf.next = k->next;
k->next = i->next;
*i = *k;
*k = buf;
}
}
}
return head;
}
/**************************************************
*函数:invert_link
*功能:倒置整个链表
**************************************************/
STU *invert_link(STU *head)
{
if(head == NULL)
{
printf("Link is not exist!\n");
return NULL;
}
if( head->next != NULL) //不等与NULL,说明链表节点大于或等于二
{
STU *pb = NULL, *pf = NULL, *pn = NULL;
#if 0
pf = head; //指向链表头
pb = pn = head->next; //指向链表第二个元素
while(pn != NULL)
{
pn = pn->next;
pb->next = pf;
pf = pb;
pb = pn;
}
head->next = NULL;
head = pf; //
#else
pb = pf = head;
pn = head->next;
printf("akkk\n");
while(pn != NULL)
{
pb = pn;
pn = pn->next;
pb->next = pf;
pf = pb;
}
head->next = NULL;
head = pb;
#endif
}
return head;
}
<file_sep>/c/practice/3rd_week/encrypt/encrypt.c
/* ************************************************************************
* Filename: encrypt.c
* Description:
* Version: 1.0
* Created: 2015年07月30日 星期四 02時04分32秒 HKT
* Revision: none
* Compiler: gcc
* Author: 王秋伟
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "encrypt.h"
/**************************************************************************
*函数功能:获取 目的文件 和 源文件 的名字
*参数:src_file_name 源文件名字字符数组首地址。
* dest_file_name 目的文件的名字字符数组首地址
**************************************************************************/
void get_file_name(char * dest_file_name,char * src_file_name)
{
printf("请输入原文件的名称(30个字符): ");
scanf("%s",src_file_name);
printf("请输入目的文件名(30个字符): ");
scanf("%s",dest_file_name);
}
/**************************************************************************
*函数功能:读出文件内容
*参数:file_length 整型指针,此地址中保存文件字节数。
* src_file_name 文件名字,从此文件中读取内容。
* 返回值:读出字符串的首地址
* 函数中测文件的大小并分配空间,再把文件内容读出到分配的空间中,返回此空间首地址
**************************************************************************/
char * read_src_file(unsigned long int *file_length,char *src_file_name)
{
FILE *fp = NULL;
char *buf = NULL;
fp = fopen(src_file_name,"rb");//以只读方式打开一个二进制文件
if(fp == NULL)
{
printf("Cannot open the flie!\n");
return;
}
fseek(fp,0,SEEK_END);
*file_length = ftell(fp); //获取文件的大小
buf = (char *)malloc(*file_length); //
if(buf == NULL)
{
printf("malloc() cannot apply for memory!\n");
goto out;
}
rewind(fp); //
fread(buf,*file_length,1,fp);
out:
fclose(fp);
return buf;
}
/**************************************************************************
*函数功能:加密字符串
*参数:src_file_text 要加密的字符串。length:字符串的长度
* password <PASSWORD>
*返回值: 加密后的字符串的首地址
*加密原理字符数组中每个元素加上password
**************************************************************************/
char * file_text_encrypt(char * src_file_text,unsigned long int length,unsigned int password)
{
int i;
for(i=0;i<length;i++)
{
*(src_file_text + i) += password;
}
return src_file_text;
}
/**************************************************************************
*函数功能:解密字符串
*参数:src_file_text 要解密的字符串。length:字符串的长度
* password 解密密码
*返回值: 解密后的字符串的首地址
*思想;把数组中的每个元素减去password 给自己赋值。
**************************************************************************/
char * file_text_decrypt(char * src_file_text,unsigned long int length,unsigned int password)
{
int i;
for(i=0;i<length;i++)
{
*(src_file_text + i) -= password;
}
return src_file_text;
}
/**************************************************************************
*函数功能:将字符串保存到目的文件中
*参数:text 要保存的字符串首地址
* file_name 目的文件的名字
* length 字符串的长度
*思想:传入字符数组的首地址和数组的大小及保存后的文件的名字,即可保存数组到文件中
**************************************************************************/
void save_file(char* text,unsigned long int length,char * file_name)
{
FILE *fp = NULL;
fp = fopen(file_name,"wb");
if(fp == NULL)
{
printf("Cannot open the file!\n");
return;
}
fwrite(text,length,1,fp); //保存text中的数据到文件
printf("Data is successfully saved!\n");
fclose(fp);
}
<file_sep>/sys_program/4th_day/msg.c
/* ************************************************************************
* Filename: msg.c
* Description:
* Version: 1.0
* Created: 2015年08月18日 14时53分41秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <sys/types.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <string.h>
typedef struct _msg
{
long type;
char mutex[100];
}MSG;
int main(int argc, char *argv[])
{
key_t key;
int id;
MSG sed;
MSG sed2;
sed.type = 10;
strcpy(sed.mutex, "hello world");
sed2.type = 1;
strcpy(sed2.mutex, "I love you");
key = ftok("./",23);
id = msgget(key, IPC_CREAT | 0666);
msgsnd(id,&sed,sizeof(sed)-4 ,0); //参数0,表示msgsnd调用阻塞直到条件满足为止
msgsnd(id,&sed2,sizeof(sed2)-4 ,0);
return 0;
}
<file_sep>/c/practice/2nd_week/fun_pointer/fun.h
/* ************************************************************************
* Filename: fun.h
* Description:
* Version: 1.0
* Created: 2015年07月24日 星期五 12時12分43秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __FUN_H__
#define __FUN_H__
extern int add(int a, int b);
extern int sub(int a, int b);
extern int mul(int a, int b);
extern int div(int a, int b);
#endif
<file_sep>/sys_program/7th_day/Makefile
CC = arm-linux-gcc
button:gpio_buttons.c
$(CC) gpio_buttons.c -o buttons
<file_sep>/c/practice/3rd_week/gps/gps.c
/* ************************************************************************
* Filename: gps.c
* Description:
* Version: 1.0
* Created: 2015年07月28日 星期二 07時11分10秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <string.h>
typedef struct gpsinfo
{
char id[10];
char time[16];
char sta;
char lat[12];
char ns;
char lon[12];
char ew;
char vel;
char azi[8];
char utct[10];
char mag[6];
char dir;
int crc;
}GPS;
typedef struct date
{
int year;
int mon;
int day;
int hour;
int min;
int sec;
}DATE;
void show_time(char *pinfo[])
{
DATE time;
// printf("%s\n",pinfo);
sscanf(pinfo[1],"%2d%2d%2d",&time.hour,&time.min,&time.sec);
time.hour += 8;
printf("时间:%02d:%02d:%02d\n",time.hour,time.min,time.sec);
sscanf(pinfo[9],"%2d%2d%2d",&time.day,&time.mon,&time.year);
printf("日期:%02d年%02d月%01d日\n",time.year,time.mon,time.day);
}
void show_latitude(char *pinfo[])
{
int du = 0;
char fen[10];
sscanf(pinfo[3],"%2d%s",&du,fen);
printf("纬度:%s纬 %3d度 %s分\n",pinfo[4],du,fen);
}
void show_longitude(char *pinfo[])
{
int du = 0;
char fen[10];
sscanf(pinfo[5],"%3d%s",&du,fen);
printf("经度:%s经 %3d度 %s分\n",pinfo[6],du,fen);
}
char get_status(char *pinfo[])
{
char state;
sscanf(pinfo[2],"%1c",&state);
//printf("state = %c\n",state);
return state;
}
int sep_gpsinfo(char *pinfo[],char info[],char *pch)
{
int i = 0;
pinfo[0] = strtok(info,pch);
while(pinfo[i++] != NULL)
{
pinfo[i] = strtok(NULL,pch);
}
return i;
}
void main()
{
char *pinfo[13] = {NULL};
char info[128]="$GPRMC,024813.640,A,3158.4608,N,11848.3737,E,\
10.05,324.27,150706, , ,A*50";
char state;
sep_gpsinfo(pinfo,info,",");
state = get_status(pinfo);
if(state == 'A')
{
show_time(pinfo);
show_latitude(pinfo);
show_longitude(pinfo);
}
}
<file_sep>/work/test/v4l2/Makefile
TOPDIR := $(shell pwd)
GCC := mips-linux-gnu-gcc
CFLAGS := -Os -Wall -mabi=32 -mhard-float -march=mips32r2 -I$(TOPDIR)/include
LDFLAGS := -Wl,-EL
LDLIBS := -L$(TOPDIR)/lib -ljpeg-hw
SOURCES := $(wildcard *.c)
TARGET = cimcapt
all: $(TARGET)
$(TARGET): $(SOURCES)
$(GCC) $(CFLAGS) $(LDLIBS) $(LDFLAGS) -o $@ $^
INSTALL_DIR = ~/work/sz-halley2/out/product/yak/system/usr/bin
install: all
cp $(TARGET) $(INSTALL_DIR) -a
.PHONY: clean
clean:
rm -rf *.o $(TARGET)
<file_sep>/work/test/cim_test-zmm220/gpio.c
#include <string.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <time.h>
#include <sys/time.h>
#include "arca.h"
#define LEDR 104
#define LEDG 105
#define GPIO_DIR_IN 0
#define GPIO_DIR_OUT 1
#define GPIO_LEVEL_LOW 0
#define GPIO_LEVEL_HIGH 1
/* ioctl command */
#if 1
#define SETDIRECTION 0x01
#define GETDIRECTION 0x02
#define SETLEVEL 0x03
#define GETLEVEL 0x04
#define SETRISINGEDGE 0x05
#define GETRISINGEDGE 0x06
#define SETFALLINGEDGE 0x07
#define GETFALLINGEDGE 0x08
#define GETEDGEDETECTSTATUS 0x09
#define CLEAREDGEDETECTSTATUS 0x0A
#define NANDREADPAGE 0x0B
#define NANDWRITEPAGE 0x0C
#define NANDREADBLOCK 0x0D
#define NANDWRITEBLOCK 0x0E
#define NANDREASEBLOCK 0x0F
#define NANDSAVEMAC 0x10
#else
#define SETDIRECTION _IOW ('N', 0x01, struct _MSG)
#define GETDIRECTION _IOR ('N', 0x02, struct _MSG)
#define SETLEVEL _IOW ('N', 0x03, struct _MSG)
#define GETLEVEL _IOR ('N', 0x04, struct _MSG)
#define SETRISINGEDGE _IOW ('N', 0x05, struct _MSG)
#define GETRISINGEDGE _IOR ('N', 0x06, struct _MSG)
#define SETFALLINGEDGE _IOW ('N', 0x07, struct _MSG)
#define GETFALLINGEDGE _IOR ('N', 0x08, struct _MSG)
#define GETEDGEDETECTSTATUS _IOR ('N', 0x09, struct _MSG)
#define CLEAREDGEDETECTSTATUS _IOW ('N', 0x0A, struct _MSG)
#define NANDREADPAGE _IOR ('N', 0x0B, struct _MSG)
#define NANDWRITEPAGE _IOW ('N', 0x0C, struct _MSG)
#define NANDREADBLOCK _IOR ('N', 0x0D, struct _MSG)
#define NANDWRITEBLOCK _IOW ('N', 0x0E, struct _MSG)
#define NANDREASEBLOCK _IOW ('N', 0x0F, struct _MSG)
#define NANDSAVEMAC _IOW ('N', 0x10, struct _MSG)
#define NANDGETBLOCKSTATUS _IOR ('N', 0x11, struct _MSG)
#define FREEGPIO _IOW ('N', 0x12, struct _MSG)
#define MAPGPIO _IOW ('N', 0x13, struct _MSG)
#endif
static int fd = -1;
struct _MSG
{
int param0;
int param1;
// unsigned char buf[2048];
}Info;
//static int BASELOOPTESTCNT = 30;
/*
void DelayUS(int us)
{
int i, j, k;
if (us <= CNT*1000)
{
for (i=0; i<us; i++)
for(j=0; j<BASELOOPTESTCNT; j++) k++;
}
else
{
usleep(us);
}
}
*/
/*
void DelayMS(int ms)
{
usleep(1000*ms);
}
*/
void __gpio_as_output(int n)
{
if(fd<0)
{
printf("invalid operation!\n");
return;
}
Info.param0 = n;
Info.param1 = GPIO_DIR_OUT;
ioctl(fd, SETDIRECTION,&Info);
// return;
}
void __gpio_as_input(int n)
{
if(fd<0)
{
printf("invalid operation!\n");
return;
}
Info.param0 = n;
Info.param1 = GPIO_DIR_IN;
ioctl(fd, SETDIRECTION,&Info);
// return;
}
void __gpio_set_pin(int n)
{
if(fd<0)
{
printf("invalid operation!\n");
return;
}
Info.param0 = n;
Info.param1 = GPIO_LEVEL_HIGH;
ioctl(fd, SETLEVEL, &Info);
// return;
}
void __gpio_clear_pin(int n)
{
if(fd<0)
{
printf("invalid operation!\n");
return;
}
Info.param0 = n;
Info.param1 = GPIO_LEVEL_LOW;
ioctl(fd, SETLEVEL, &Info);
// return;
}
int __gpio_get_pin(int n)
{
if(fd<0)
{
printf("invalid operation!\n");
return -1;
}
Info.param0 = n;
ioctl(fd, GETLEVEL,&Info);
return Info.param1;
}
int gpio_open(void)
{
fd = open("/dev/jzgpio", O_RDWR);
if(fd<0)
printf("Error: open dev/jzgpio\n");
printf("open gpio control ok!\n");
return fd;
}
int gpio_close(void)
{
close(fd);
}
#if 0
void Nand_read_onePage(U32 page, U8 *buf)
{
if(fd<0)
{
printf("invalid operation!\n");
return;
}
Info.param0 = page;
memset(Info.buf, 0, sizeof(Info.buf));
ioctl(fd, NANDREADPAGE,&Info);
memcpy(buf, Info.buf, sizeof(Info.buf));
return;
}
void Nand_write_onePage(U32 page, U8 *buf)
{
if(fd<0)
{
printf("invalid operation!\n");
return;
}
Info.param0 = page;
memcpy(Info.buf, buf, sizeof(Info.buf));
ioctl(fd, NANDWRITEPAGE,&Info);
return;
}
void Nand_read_oneBlock(U32 page, U8 *buf)
{
if(fd<0)
{
printf("invalid operation!\n");
return;
}
// ioctl(fd, NANDREADBLOCK,&buf);
return;
}
void Nand_write_oneBlock(U32 page, U8 *buf)
{
if(fd<0)
{
printf("invalid operation!\n");
return;
}
// ioctl(fd, NANDWRITEBLOCK,&buf);
return;
}
void Nand_erase_oneBlock(U32 block)
{
if(fd<0)
{
printf("invalid operation!\n");
return;
}
Info.param0 = block;
ioctl(fd, NANDREASEBLOCK,NULL);
return;
}
void Nand_save_MAC(U8 *buf)
{
if(fd<0)
{
printf("invalid operation!\n");
return;
}
memcpy(Info.buf, buf,6);
ioctl(fd, NANDSAVEMAC,&Info);
return;
}
#endif
/*
int swi2c_write(uint8_t i2caddr, uint8_t subaddr, uint8_t data);
int swi2c_blkwrite(uint8_t i2caddr, uint8_t subaddr, uint8_t *data, uint32_t blksize);
int swi2c_read(uint8_t i2caddr, uint8_t subaddr, uint8_t *data);
int swi2c_blkread(uint8_t i2caddr, uint8_t subaddr, uint8_t *data, uint32_t blksize);
*/
int CNT=8;
#if 0
int main(int argc, int **argv)
{
unsigned char buf[100];
int i;
int sw = 0;
// if(argc>=1)
// CNT=strtoul(argv[1], NULL, 0);
// if(argc>=2)
// sw=strtoul(argv[2], NULL, 0);
fd = open("/dev/gpio", O_RDWR);
if(fd<0)
{
printf("Error: open dev/gpio\n");
return 0;
}
__gpio_as_output(LEDR);
__gpio_as_output(LEDG);
while(1)
{
__gpio_set_pin(LEDR);
__gpio_set_pin(LEDG);
printf("set pin\n");
DelayMS(500);
__gpio_clear_pin(LEDR);
__gpio_clear_pin(LEDG);
printf("clear pin\n");
DelayMS(500);
}
#if 0
if(sw==0)
{
#if 0
for(i=0; i<CNT; i++) buf[i]=i+10;
printf("write EEPROM.\n");
swi2c_blkwrite(0xa0,0, buf, CNT);
memset(buf, 0, CNT);
printf("read EEPROM:\n");
if(swi2c_blkread(0xa0, 0, buf, CNT)!=0)
printf("read failed\n");
for(i=0; i<CNT; i++)
printf("%02x ",buf[i]);
printf("\n\n");
#else
printf("write EEPROM.\n");
for(i=0; i<CNT; i++)
swi2c_write(0xa0,i,i);
memset(buf, 0, CNT);
printf("read EEPROM:\n");
for(i=0; i<CNT; i++)
if(swi2c_read(0xa0, i, buf+i)!=0)
printf("read failed\n");
for(i=0; i<CNT; i++)
printf("%02x ",buf[i]);
memset(buf, 0, CNT);
printf("block read EEPROM:\n");
if(swi2c_blkread(0xa0, 0, buf, CNT)!=0)
printf("read failed\n");
for(i=0; i<CNT; i++)
printf("%02x ",buf[i]);
printf("\n\n");
#endif
}
if(sw==1)
{
memset(buf, 0, CNT);
printf("read MI0360:\n");
if(swi2c_blkread(0xBA, 0, buf, CNT)!=0)
printf("read failed\n");
for(i=0; i<CNT; i++)
printf("%02x ",buf[i]);
printf("\n");
}
if(sw==2)
{
memset(buf, 0, CNT);
printf("read RTC:\n");
if(swi2c_blkread(0x65, 0, buf, CNT)!=0)
printf("read failed\n");
for(i=0; i<CNT; i++)
printf("%02x ",buf[i]);
printf("\n\n");
memset(buf, 0, CNT);
if(swi2c_read(0x65, 0, buf)!=0)
printf("read failed\n");
printf("%02x\n",buf[0]);
}
if(sw==3)
{
memset(buf, 0, CNT);
printf("read HVCNT131:\n");
if(swi2c_blkread(0x22, 0, buf, CNT)!=0)
printf("read failed\n");
for(i=0; i<CNT; i++)
printf("%02x ",buf[i]);
printf("\n\n");
}
if(sw==4)
{
memset(buf, 0, CNT);
printf("read GC030CNT:\n");
if(swi2c_blkread(0x42, 0, buf, CNT)!=0)
printf("read failed\n");
for(i=0; i<CNT; i++)
printf("%02x ",buf[i]);
printf("\n\n");
}
if(sw==5)
{
memset(buf, 0, CNT);
printf("read GC0303:\n");
if(swi2c_blkread(0x30, 0x90, buf, CNT)!=0)
printf("read failed\n");
for(i=0; i<CNT; i++)
printf("%02x ",buf[i]);
printf("\n\n");
}
*/
#endif
return 0;
}
#endif
<file_sep>/sys_program/5th_day/mutil_pthread.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
int fd[2];
pid_t pid;
pid_t pid_sec;
char buf[7];
pipe(fd);
if((pid = fork())<0)
{
printf("fork error!");
exit(1);
}
else if(pid == 0)
{
close(fd[0]);
write(fd[1],"first1",7);
close(fd[1]);
exit(0);
}
else
{
wait(NULL);
if((pid_sec = fork())<0)
{
printf("fork second error!");
exit(1);
}
else if(pid_sec==0)
{
close(fd[0]);
write(fd[1],"Child1",7);
close(fd[1]);
exit(0);
}
else
{
wait(0);
close(fd[1]);
read(fd[0],buf,7);
printf("%s\n",buf);
wait(0);
close(fd[1]);
read(fd[0],buf,7);
close(fd[0]);
printf("%s\n",buf);
exit(0);
}
}
return 0;
}
<file_sep>/work/debug/a8/matrix_keys/matrix_keys.c
#include <linux/module.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/ioport.h>
#include <linux/slab.h> // kmalloc() kfree()
#include <linux/delay.h> // mdelya() msleep()
#include <asm/io.h>
#include <asm/uaccess.h>
#include <plat/gpio-cfg.h>
#include <mach/gpio.h>
#define DEVICE_NAME "keys_drv"
static int keys_major = 0;
static struct class *keys_class = NULL;
static struct cdev *pcdev = NULL;
static int keys_drv_open(struct inode *pindo, struct file *filp)
{
printk("%s:%d\n",__FUNCTION__,__LINE__);
// 引脚设置为输出
s3c_gpio_cfgpin(S5PV210_GPH3(0), S3C_GPIO_OUTPUT);
s3c_gpio_cfgpin(S5PV210_GPH3(1), S3C_GPIO_OUTPUT);
//s3c_gpio_setpin(S5PV210_GPH3(0), 0);
gpio_set_value(S5PV210_GPH3(0), 0);
gpio_set_value(S5PV210_GPH3(1), 1);
s3c_gpio_cfgpin(S5PV210_GPH2(3), S3C_GPIO_INPUT);
s3c_gpio_cfgpin(S5PV210_GPH2(4), S3C_GPIO_INPUT);
s3c_gpio_cfgpin(S5PV210_GPH2(5), S3C_GPIO_INPUT);
s3c_gpio_cfgpin(S5PV210_GPH2(6), S3C_GPIO_INPUT);
s3c_gpio_cfgpin(S5PV210_GPH2(7), S3C_GPIO_INPUT);
s3c_gpio_setpull(S5PV210_GPH2(3), S3C_GPIO_PULL_UP);
s3c_gpio_setpull(S5PV210_GPH2(4), S3C_GPIO_PULL_UP);
s3c_gpio_setpull(S5PV210_GPH2(5), S3C_GPIO_PULL_UP);
s3c_gpio_setpull(S5PV210_GPH2(6), S3C_GPIO_PULL_UP);
s3c_gpio_setpull(S5PV210_GPH2(7), S3C_GPIO_PULL_UP);
printk("%s:%d\n",__FUNCTION__,__LINE__);
return 0;
}
static ssize_t keys_drv_read(struct file *filp, char __user *buf, size_t count, loff_t *ppos)
{
char data[] = {0};
int i, keyval;
int len, ret;
volatile unsigned char *gph2dat = NULL;
gph2dat = ioremap(0xe0200c44, 1); // 0xe0200c44 是GPH2DAT 的地址
for(i=0; i<10; i++){ // 键盘扫描
gpio_set_value(S5PV210_GPH3(0), 0);
gpio_set_value(S5PV210_GPH3(1), 1);
keyval = *gph2dat;
keyval &= 0xf8;
if(keyval != 0xf8){ //
msleep(100);
//mdelay(100); // 延时消抖
keyval = *gph2dat;
keyval &= 0xf8;
if(keyval != 0xf8){
switch(keyval){
case 0xf0: // key2
data[0] = 2;
goto out;
break;
case 0xe8: // key3
data[0] = 3;
goto out;
break;
case 0xd8: // key4
data[0] = 4;
goto out;
break;
case 0xb8: // key5
data[0] = 5;
goto out;
break;
case 0x78: // key6
data[0] = 6;
goto out;
break;
}
}
// 等待按键释放
while(keyval != 0xf8){
keyval = *gph2dat;
keyval &= 0xf8;
}
}
// 扫描第二行
gpio_set_value(S5PV210_GPH3(0), 1);
gpio_set_value(S5PV210_GPH3(1), 0);
keyval = *gph2dat;
keyval &= 0xf0;
if(keyval != 0xf0){ //
msleep(100);
//mdelay(100); // 延时消抖
keyval = *gph2dat;
keyval &= 0xf0;
if(keyval != 0xf0){
switch(keyval){
case 0xe0: // key8
data[0] = 8;
goto out;
break;
case 0xd0: // key9
data[0] = 9;
goto out;
break;
case 0xb0: // key10
data[0] = 10;
goto out;
break;
case 0x70: // key11
data[0] = 11;
goto out;
break;
}
}
// 等待按键释放
while(keyval != 0xf0){
keyval = *gph2dat;
keyval &= 0xf0;
}
}
}
out:
len = min(sizeof(data), count);
ret = copy_to_user(buf, data, len); // 返回不能被复制的字节数
return len;
}
static int keys_drv_release(struct inode *pinode, struct file *filp)
{
printk("%s:%d\n",__FUNCTION__,__LINE__);
return 0;
}
static struct file_operations keys_drv_fops = {
.owner = THIS_MODULE,
.open = keys_drv_open,
.read = keys_drv_read,
.release = keys_drv_release,
};
static void keys_setup_cdev(struct cdev *pcdev, int index)
{
int err;
dev_t devno = MKDEV(keys_major, index);
cdev_init(pcdev, &keys_drv_fops);
pcdev->owner = THIS_MODULE;
pcdev->ops = &keys_drv_fops;
err = cdev_add(pcdev, devno, 1);
if(err){
printk(KERN_NOTICE "Error %d adding keys cdev %d",err,index);
}
}
int __init keys_drv_init(void)
{
int ret;
dev_t devno = MKDEV(keys_major, 0);
if(!keys_major){ // 动态获取设备号
ret = alloc_chrdev_region(&devno, 0, 1, DEVICE_NAME);
keys_major = MAJOR(devno);
}
else{
ret = register_chrdev_region(devno, 1, DEVICE_NAME);
}
if(ret < 0){ // 注册失败
printk("register keys_driver failed!\n");
return ret;
}
pcdev = kmalloc(sizeof(struct cdev), GFP_KERNEL);
if(pcdev == NULL){
printk("kmalloc failed!\n");
ret = -ENOMEM;
goto malloc_err;
}
memset(pcdev, 0, sizeof(struct cdev));
keys_setup_cdev(pcdev, 0);
// 注册一个类
keys_class = class_create(THIS_MODULE, DEVICE_NAME);
if(IS_ERR(keys_class)){
printk("Err:failed in create keys class\n");
goto class_err;
}
//创建一个设备节点
device_create(keys_class, NULL, devno, NULL, DEVICE_NAME);
printk("%s:%d\n",__FUNCTION__,__LINE__);
return 0;
class_err:
cdev_del(pcdev);
kfree(pcdev);
malloc_err:
unregister_chrdev_region(devno, 1);
return ret;
}
void __exit keys_drv_exit(void)
{
device_destroy(keys_class, MKDEV(keys_major, 0));// 删除设备节点
class_destroy(keys_class); //注销类
cdev_del(pcdev); // 注销设备
kfree(pcdev); // 回收内存
unregister_chrdev_region(MKDEV(keys_major, 0), 1);// 注销设备号
printk("%s:%d\n",__FUNCTION__,__LINE__);
}
module_init(keys_drv_init);
module_exit(keys_drv_exit);
MODULE_LICENSE("GPL");
<file_sep>/sys_program/player/kill.sh
str=`ps | grep mplayer`
echo "$str"
i=1
for arg in `ps | grep ./mplayer`
do
if [ $i -eq 1 ]
then
kill -9 $arg
echo "mplayer killed!!"
fi
i=$[ $i + 1 ]
done
j=1
for arg2 in `ps | grep mplayer`
do
if [ $j -eq 1 ]
then
kill -9 $arg2
echo "mplayer killed!!"
exit
fi
j=$[ $j + 1 ]
done
<file_sep>/c/practice/3rd_week/gps/Makefile
agps:gps.c
gcc -o agps gps.c
clean:
rm agps
<file_sep>/sys_program/2nd_day/am/execl.c
/* ************************************************************************
* Filename: exec.c
* Description:
* Version: 1.0
* Created: 2015年08月14日 11时07分06秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
execl("/bin/ls","ls","-l","-a","-h",NULL);
return 0;
}
<file_sep>/gtk/1. base/05_list/list.c
#include <gtk/gtk.h>
// 用户点击"Add List"按钮时的回调函数
void button_add_clicked( GtkWidget *widget, gpointer data )
{
char *a[2] = {"Mike", "3 Oz"};
gtk_clist_append( (GtkCList *)data, a );
char *b[2] = { "Water", "6 l" };
gtk_clist_append( (GtkCList *)data, b );
}
//用户点击"Clear List" 按钮时的回调函数
void button_clear_clicked( GtkWidget *widget, gpointer data )
{
/* 用gtk_clist_clear函数清除列表。比用
* gtk_clist_remove函数逐行清除要快
*/
gtk_clist_clear( (GtkCList *)data );
}
// 用户选中某一行时的回调函数
void selection_made( GtkWidget *clist, gint row, gint column,
GdkEventButton *event, gpointer data )
{
gtk_widget_queue_draw(clist); // 人为更新列表,开发板有效
gchar *text;
/* 取得存储在被选中的行和列的单元格上的文本
* 当鼠标点击时,我们用text参数接收一个指针
*/
gtk_clist_get_text(GTK_CLIST(clist), row, column, &text);
//打印一些关于选中了哪一行的信息
g_print("第%d行,第%d列的内容为%s\n", row, column, text);
}
int main( int argc, gchar *argv[] )
{
gtk_init(&argc, &argv); // 初始化
// 主窗口
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL); // 创建窗口
gtk_widget_set_size_request(GTK_WIDGET(window), 300, 300); // 设置最小大小
gtk_window_set_title(GTK_WINDOW(window), "GtkCList Example"); // 设置标题
gtk_window_set_resizable(GTK_WINDOW(window), FALSE); // 固定窗口大小
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
// 表格布局容器
GtkWidget *table = gtk_table_new(5, 2, TRUE);
gtk_container_add(GTK_CONTAINER(window), table);
/* 创建一个滚动窗口构件,将GtkCList组装到里面。
* 这样使得内容超出列表时,可以用滚动条浏览
* 第一个参数是水平方向的调整对象,第二个参数是垂直方向的调整对象。它们总是设置为NULL。
*/
GtkWidget *scrolled_window = gtk_scrolled_window_new(NULL, NULL);
gtk_table_attach_defaults(GTK_TABLE(table), scrolled_window, 0, 2, 0, 4);// 把按钮加入布局
// GTK_POLICY_AUTOMATIC:滚动条根据需要自动出现时
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gchar *titles[2] = { "Ingredients", "Amount" };
// 创建GtkCList构件。本例中,我们使用了两列
GtkWidget *clist = gtk_clist_new_with_titles(2, titles);
// 将GtkCList构件添加到滚动窗口构件中
gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled_window), clist);
/* 设置某列内容显示的对齐方式
* GTK_JUSTIFY_LEFT: 列中的文本左对齐。
* GTK_JUSTIFY_RIGHT: 列中的文本右对齐。
* GTK_JUSTIFY_CENTER:列中的文本居中对齐。
* GTK_JUSTIFY_FILL: 文本使用列中所有可用的空间
*/
gtk_clist_set_column_justification(GTK_CLIST(clist), 1, GTK_JUSTIFY_CENTER);
/* 很重要的一点,我们设置列宽,让文本能容纳在列中。
* 注意,列编号是从0开始的, 本例中是0和1
*/
gtk_clist_set_column_width(GTK_CLIST(clist), 0, 100);
// 选择某一行时触发selection_made回调函数
g_signal_connect(clist, "select-row", G_CALLBACK(selection_made), NULL);
// 按钮的创建,并放进布局容器里
GtkWidget *button_add = gtk_button_new_with_label("Add List");
GtkWidget *button_clear = gtk_button_new_with_label("Clear List");
gtk_table_attach_defaults(GTK_TABLE(table), button_add, 0, 1, 4, 5);// 把按钮加入布局
gtk_table_attach_defaults(GTK_TABLE(table), button_clear, 1, 2, 4, 5);// 把按钮加入布局
// 为按钮的点击设置回调函数
g_signal_connect(button_add, "clicked", G_CALLBACK(button_add_clicked), (gpointer)clist);
g_signal_connect(button_clear, "clicked", G_CALLBACK(button_clear_clicked), (gpointer)clist);
/* 界面已经完全设置好了,下面可以显示窗口,
* 进入gtk_main主循环
*/
gtk_widget_show_all(window);
gtk_main();
return 0;
}<file_sep>/work/camera/bf3703/BF3703_MTK6225_Drv_V3.0/image_sensor.c
/****************************BF3703_BYD_VGA_Sensor***************************
* Copyright Statement:
* --------------------
* This software is protected by Copyright and the information contained
* herein is confidential. The software may not be copied and the information
* contained herein may not be used or disclosed except with the written
* permission of MediaTek Inc. (C) 2010
*
* BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
* NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S
* SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
* BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE
* LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE
* WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF
* LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND
* RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER
* THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC).
*
*****************************************************************************/
/*****************************************************************************
*
* Filename:
* ---------
* image_sensor.c
*
* Version:
* --------
* BF3703 MTK 6225 or 6226 DRV V1.0.0
*
* Release Date:
* ------------
* 2010-07-26
*
* Description:
* ------------
* Image sensor driver function
*
* Author:
* BYD Sensor Group
* -------
*
*============================================================================
* HISTORY
* Below this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
*------------------------------------------------------------------------------
*
*------------------------------------------------------------------------------
* Upper this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
*============================================================================
****************************************************************************/
#include "drv_comm.h"
#include "IntrCtrl.h"
#include "reg_base.h"
#include "gpio_sw.h"
#include "sccb.h"
#include "isp_if.h"
#include "image_sensor.h"
#include "camera_para.h"
#include "upll_ctrl.h"
#include "med_api.h"
#define BF3703_BYD { 128, 0 }
/* Global Valuable */
SensorInfo g_CCT_MainSensor=BF3703_BYD;// must be defined but not referenced by YUV driver
kal_uint8 g_CCT_FirstGrabColor = INPUT_ORDER_CbYCrY1; // must be defined but not referenced by YUV driver
kal_uint8 start_grab_x_offset=0, start_grab_y_offset=0;
kal_bool gVGAmode=KAL_TRUE, sensor_night_mode=KAL_FALSE, MPEG4_encode_mode=KAL_FALSE, g_bMJPEG_mode = KAL_FALSE;
kal_uint8 preview_pclk_division=0, capture_pclk_division=0;
kal_uint16 dummy_pixels=0,pre_dummy_pixels=0,cap_dummy_pixels=0,dummy_lines=0, extra_exposure_lines=0;
kal_uint16 exposure_lines=0;
/* MAX/MIN Explosure Lines Used By AE Algorithm */
kal_uint16 MAX_EXPOSURE_LINES=1000;
kal_uint8 MIN_EXPOSURE_LINES=2;
/* Parameter For Engineer mode function */
kal_uint32 FAC_SENSOR_REG;
/* Image Sensor ID */
kal_uint16 sensor_id=0;
kal_bool sensor_cap_state=KAL_FALSE;
#ifndef HW_SCCB
void SCCB_send_byte(kal_uint8 send_byte)
{
volatile signed char i;
volatile kal_uint32 j;
for (i=7;i>=0;i--)
{ /* data bit 7~0 */
if (send_byte & (1<<i))
{
SET_SCCB_DATA_HIGH;
}
else
{
SET_SCCB_DATA_LOW;
}
for(j=0;j<SENSOR_I2C_DELAY;j++);
SET_SCCB_CLK_HIGH;
for(j=0;j<SENSOR_I2C_DELAY;j++);
SET_SCCB_CLK_LOW;
for(j=0;j<SENSOR_I2C_DELAY;j++);
}
/* don't care bit, 9th bit */
SET_SCCB_DATA_LOW;
SET_SCCB_DATA_INPUT;
SET_SCCB_CLK_HIGH;
for(j=0;j<SENSOR_I2C_DELAY;j++);
SET_SCCB_CLK_LOW;
SET_SCCB_DATA_OUTPUT;
} /* SCCB_send_byte() */
kal_uint8 SCCB_get_byte(void)
{
volatile signed char i;
volatile kal_uint32 j;
kal_uint8 get_byte=0;
SET_SCCB_DATA_INPUT;
for (i=7;i>=0;i--)
{ /* data bit 7~0 */
SET_SCCB_CLK_HIGH;
for(j=0;j<SENSOR_I2C_DELAY;j++);
if (GET_SCCB_DATA_BIT)
get_byte |= (1<<i);
for(j=0;j<SENSOR_I2C_DELAY;j++);
SET_SCCB_CLK_LOW;
for(j=0;j<SENSOR_I2C_DELAY;j++);
}
/* don't care bit, 9th bit */
SET_SCCB_DATA_OUTPUT;
SET_SCCB_DATA_HIGH;
for(j=0;j<SENSOR_I2C_DELAY;j++);
SET_SCCB_CLK_HIGH;
for(j=0;j<SENSOR_I2C_DELAY;j++);
SET_SCCB_CLK_LOW;
return get_byte;
} /* SCCB_get_byte() */
#endif
void write_cmos_sensor(kal_uint32 addr, kal_uint32 para)
{
volatile kal_uint32 j;
#ifdef HW_SCCB
SET_SCCB_DATA_LENGTH(3);
ENABLE_SCCB;
REG_SCCB_DATA = BF3703_WRITE_ID | SCCB_DATA_REG_ID_ADDRESS;
REG_SCCB_DATA = addr;
REG_SCCB_DATA = para;
while (SCCB_IS_WRITTING) {};
#else
I2C_START_TRANSMISSION;
for(j=0;j<SENSOR_I2C_DELAY;j++);
SCCB_send_byte(BF3703_WRITE_ID);
for(j=0;j<SENSOR_I2C_DELAY;j++);
SCCB_send_byte(addr);
for(j=0;j<SENSOR_I2C_DELAY;j++);
SCCB_send_byte(para);
for(j=0;j<SENSOR_I2C_DELAY;j++);
I2C_STOP_TRANSMISSION;
#endif /* HW_SCCB */
} /* write_cmos_sensor() */
kal_uint32 read_cmos_sensor(kal_uint32 addr)
{
volatile kal_uint32 j;
kal_uint8 get_byte=0;
#ifdef HW_SCCB
SET_SCCB_DATA_LENGTH(2);
ENABLE_SCCB;
REG_SCCB_DATA = BF3703_WRITE_ID | SCCB_DATA_REG_ID_ADDRESS;
REG_SCCB_DATA = addr;
while (SCCB_IS_WRITTING) {};
ENABLE_SCCB;
REG_SCCB_DATA = BF3703_READ_ID | SCCB_DATA_REG_ID_ADDRESS;
REG_SCCB_DATA=0;
while (SCCB_IS_READING) {};
get_byte = REG_SCCB_READ_DATA & 0xFF;
#else
I2C_START_TRANSMISSION;
for(j=0;j<SENSOR_I2C_DELAY;j++);
SCCB_send_byte(BF3703_WRITE_ID);
for(j=0;j<SENSOR_I2C_DELAY;j++);
SCCB_send_byte(addr);
for(j=0;j<SENSOR_I2C_DELAY;j++);
I2C_STOP_TRANSMISSION;
for(j=0;j<SENSOR_I2C_DELAY;j++);
I2C_START_TRANSMISSION;
for(j=0;j<SENSOR_I2C_DELAY;j++);
SCCB_send_byte(BF3703_READ_ID);
for(j=0;j<SENSOR_I2C_DELAY;j++);
get_byte=SCCB_get_byte();
for(j=0;j<SENSOR_I2C_DELAY;j++);
I2C_STOP_TRANSMISSION;
#endif
return get_byte;
} /* read_cmos_sensor() */
void write_BF3703_shutter(kal_uint16 shutter)
{
write_cmos_sensor(0x8c,(shutter&0xFF00)>>8);
write_cmos_sensor(0x8D,shutter&0xFF);
} /* write_BF3703_shutter */
kal_uint16 read_BF3703_shutter(void)
{
kal_uint8 temp_reg1, temp_reg2;
kal_uint16 shutter;
temp_reg1=read_cmos_sensor(0x8c);
temp_reg2=read_cmos_sensor(0x8d);
shutter=((temp_reg1&0xff)<<8)|(temp_reg2);
exposure_lines=shutter;
return exposure_lines;
} /* read_BF3703_shutter */
void set_BF3703_dummy(kal_uint16 pixels, kal_uint16 lines)
{
write_cmos_sensor(0x2A,((pixels&0x700)>>4));
write_cmos_sensor(0x2B,(pixels&0xFF));
write_cmos_sensor(0x92,(lines&0xFF));
write_cmos_sensor(0x93,((lines&0xFF00)>>8));
} /* set_BF3703_dummy */
/*************************************************************************
* FUNCTION
* init_BF3703
*
* DESCRIPTION
* This function initialize the registers of CMOS sensor and ISP control register.
*
* PARAMETERS
* None
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_int8 init_BF3703(void)
{
kal_uint8 I;
cis_module_power_on(KAL_TRUE); // Power On CIS Power
kal_sleep_task(2);
PWRDN_PIN_LOW;
/* Sensor Signal Polarity */
/* Note: Set HSync Polarity to Low means High active */
SET_CMOS_CLOCK_POLARITY_LOW;
SET_VSYNC_POLARITY_LOW;
SET_HSYNC_POLARITY_LOW;
kal_sleep_task(2);
/* YUV Sensor Input Format */
ENABLE_CAMERA_INDATA_FORMAT; /* Enable yuv data input */
SET_CAMERA_INPUT_TYPE(INPUT_YUV422);
SET_CAMERA_INPUT_ORDER(INPUT_ORDER_CrYCbY1);
/* Use UPLL to produce 48M clock, then divided by 2 */
ENABLE_CAMERA_TG_CLK_48M;
UPLL_Enable(UPLL_OWNER_ISP);
set_isp_driving_current(camera_para.SENSOR.reg[CMMCLK_CURRENT_INDEX].para);
/* Reset the sensor */
RESET_PIN_HIGH;
RESET_PIN_LOW;
for (I = 0; I < 0x80; I++);
RESET_PIN_HIGH;
kal_sleep_task(10);
sensor_id=(read_cmos_sensor(0xFC)<<8)|read_cmos_sensor(0xFD);
kal_prompt_trace(MOD_MMI,"------->>>> BF3703 sensor_id==%x",sensor_id);
if(sensor_id != BF3703_SENSOR_ID)
return -1;
kal_sleep_task(10);
write_cmos_sensor(0x11,0x80);
write_cmos_sensor(0x09,0x00);
write_cmos_sensor(0x13,0x00);
write_cmos_sensor(0x01,0x13);
write_cmos_sensor(0x02,0x25);
write_cmos_sensor(0x8c,0x02);//01 :devided by 2 02 :devided by 1
write_cmos_sensor(0x8d,0xfd);//cb: devided by 2 fd :devided by 1
write_cmos_sensor(0x87,0x1a);
write_cmos_sensor(0x13,0x07);
//POLARITY of Signal
write_cmos_sensor(0x15,0x40);
write_cmos_sensor(0x3a,0x03);
//black level ,对上电偏绿有改善,如果需要请选择使用
/*
write_cmos_sensor(0x05,0x1f);
write_cmos_sensor(0x06,0x60);
write_cmos_sensor(0x14,0x1f);
write_cmos_sensor(0x27,0x03);
write_cmos_sensor(0x06,0xe0);
*/
//lens shading
write_cmos_sensor(0x35,0x68);
write_cmos_sensor(0x65,0x68);
write_cmos_sensor(0x66,0x62);
write_cmos_sensor(0x36,0x05);
write_cmos_sensor(0x37,0xf6);
write_cmos_sensor(0x38,0x46);
write_cmos_sensor(0x9b,0xf6);
write_cmos_sensor(0x9c,0x46);
write_cmos_sensor(0xbc,0x01);
write_cmos_sensor(0xbd,0xf6);
write_cmos_sensor(0xbe,0x46);
//AE
write_cmos_sensor(0x82,0x14);
write_cmos_sensor(0x83,0x23);
write_cmos_sensor(0x9a,0x23);//the same as 0x83
write_cmos_sensor(0x84,0x1a);
write_cmos_sensor(0x85,0x20);
write_cmos_sensor(0x89,0x04);//02 :devided by 2 04 :devided by 1
write_cmos_sensor(0x8a,0x08);//04: devided by 2 05 :devided by 1
write_cmos_sensor(0x86,0x28);//the same as 0x7b
write_cmos_sensor(0x96,0xa6);//AE speed
write_cmos_sensor(0x97,0x0c);//AE speed
write_cmos_sensor(0x98,0x18);//AE speed
//AE target
write_cmos_sensor(0x24,0x7a);//灯箱测试 0x6a
write_cmos_sensor(0x25,0x8a);//灯箱测试 0x7a
write_cmos_sensor(0x94,0x0a);//INT_OPEN
write_cmos_sensor(0x80,0x55);
//denoise
write_cmos_sensor(0x70,0x6f);//denoise
write_cmos_sensor(0x72,0x4f);//denoise
write_cmos_sensor(0x73,0x2f);//denoise
write_cmos_sensor(0x74,0x27);//denoise
write_cmos_sensor(0x77,0x90);//去除格子噪声
write_cmos_sensor(0x7a,0x4e);//denoise in low light,0x8e\0x4e\0x0e
write_cmos_sensor(0x7b,0x28);//the same as 0x86
//black level
write_cmos_sensor(0X1F,0x20);//G target
write_cmos_sensor(0X22,0x20);//R target
write_cmos_sensor(0X26,0x20);//B target
//模拟部分参数
write_cmos_sensor(0X16,0x00);//如果觉得黑色物体不够黑,有点偏红,将0x16写为0x03会有点改善
write_cmos_sensor(0xbb,0x20); // deglitch 对xclk整形
write_cmos_sensor(0xeb,0x30);
write_cmos_sensor(0xf5,0x21);
write_cmos_sensor(0xe1,0x3c);
write_cmos_sensor(0xbb,0x20);
write_cmos_sensor(0X2f,0X66);
write_cmos_sensor(0x06,0xe0);
//anti black sun spot
write_cmos_sensor(0x61,0xd3);//0x61[3]=0 black sun disable
write_cmos_sensor(0x79,0x48);//0x79[7]=0 black sun disable
//contrast
write_cmos_sensor(0x56,0x40);
//Gamma
write_cmos_sensor(0x3b,0x60);//auto gamma offset adjust in low light
write_cmos_sensor(0x3c,0x20);//auto gamma offset adjust in low light
write_cmos_sensor(0x39,0x80);
/*//gamma1
write_cmos_sensor(0x3f,0xb0);
write_cmos_sensor(0X40,0X88);
write_cmos_sensor(0X41,0X74);
write_cmos_sensor(0X42,0X5E);
write_cmos_sensor(0X43,0X4c);
write_cmos_sensor(0X44,0X44);
write_cmos_sensor(0X45,0X3E);
write_cmos_sensor(0X46,0X39);
write_cmos_sensor(0X47,0X35);
write_cmos_sensor(0X48,0X31);
write_cmos_sensor(0X49,0X2E);
write_cmos_sensor(0X4b,0X2B);
write_cmos_sensor(0X4c,0X29);
write_cmos_sensor(0X4e,0X25);
write_cmos_sensor(0X4f,0X22);
write_cmos_sensor(0X50,0X1F);*/
/*gamma2 过曝过度好,高亮度
write_cmos_sensor(0x3f,0xb0);
write_cmos_sensor(0X40,0X9b);
write_cmos_sensor(0X41,0X88);
write_cmos_sensor(0X42,0X6e);
write_cmos_sensor(0X43,0X59);
write_cmos_sensor(0X44,0X4d);
write_cmos_sensor(0X45,0X45);
write_cmos_sensor(0X46,0X3e);
write_cmos_sensor(0X47,0X39);
write_cmos_sensor(0X48,0X35);
write_cmos_sensor(0X49,0X31);
write_cmos_sensor(0X4b,0X2e);
write_cmos_sensor(0X4c,0X2b);
write_cmos_sensor(0X4e,0X26);
write_cmos_sensor(0X4f,0X23);
write_cmos_sensor(0X50,0X1F);
*/
/*//gamma3 清晰亮丽 灰阶分布好
write_cmos_sensor(0X3f,0Xb0);
write_cmos_sensor(0X40,0X60);
write_cmos_sensor(0X41,0X60);
write_cmos_sensor(0X42,0X66);
write_cmos_sensor(0X43,0X57);
write_cmos_sensor(0X44,0X4c);
write_cmos_sensor(0X45,0X43);
write_cmos_sensor(0X46,0X3c);
write_cmos_sensor(0X47,0X37);
write_cmos_sensor(0X48,0X33);
write_cmos_sensor(0X49,0X2f);
write_cmos_sensor(0X4b,0X2c);
write_cmos_sensor(0X4c,0X29);
write_cmos_sensor(0X4e,0X25);
write_cmos_sensor(0X4f,0X22);
write_cmos_sensor(0X50,0X20);*/
//gamma 4 low noise
write_cmos_sensor(0X3f,0Xa8);
write_cmos_sensor(0X40,0X48);
write_cmos_sensor(0X41,0X54);
write_cmos_sensor(0X42,0X4E);
write_cmos_sensor(0X43,0X44);
write_cmos_sensor(0X44,0X3E);
write_cmos_sensor(0X45,0X39);
write_cmos_sensor(0X46,0X35);
write_cmos_sensor(0X47,0X31);
write_cmos_sensor(0X48,0X2E);
write_cmos_sensor(0X49,0X2B);
write_cmos_sensor(0X4b,0X29);
write_cmos_sensor(0X4c,0X27);
write_cmos_sensor(0X4e,0X23);
write_cmos_sensor(0X4f,0X20);
write_cmos_sensor(0X50,0X20);
//color matrix
write_cmos_sensor(0x51,0x0d);
write_cmos_sensor(0x52,0x21);
write_cmos_sensor(0x53,0x14);
write_cmos_sensor(0x54,0x15);
write_cmos_sensor(0x57,0x8d);
write_cmos_sensor(0x58,0x78);
write_cmos_sensor(0x59,0x5f);
write_cmos_sensor(0x5a,0x84);
write_cmos_sensor(0x5b,0x25);
write_cmos_sensor(0x5D,0x95);
write_cmos_sensor(0x5C,0x0e);
/*
// color 艳丽
write_cmos_sensor(0x51,0x0e);
write_cmos_sensor(0x52,0x16);
write_cmos_sensor(0x53,0x07);
write_cmos_sensor(0x54,0x1a);
write_cmos_sensor(0x57,0x9d);
write_cmos_sensor(0x58,0x82);
write_cmos_sensor(0x59,0x71);
write_cmos_sensor(0x5a,0x8d);
write_cmos_sensor(0x5b,0x1c);
write_cmos_sensor(0x5D,0x95);
write_cmos_sensor(0x5C,0x0e);
//
//适中
write_cmos_sensor(0x51,0x08);
write_cmos_sensor(0x52,0x0E);
write_cmos_sensor(0x53,0x06);
write_cmos_sensor(0x54,0x12);
write_cmos_sensor(0x57,0x82);
write_cmos_sensor(0x58,0x70);
write_cmos_sensor(0x59,0x5C);
write_cmos_sensor(0x5a,0x77);
write_cmos_sensor(0x5b,0x1B);
write_cmos_sensor(0x5c,0x0e);//0x5c[3:0] low light color coefficient,smaller ,lower noise
write_cmos_sensor(0x5d,0x95);
//color 淡
write_cmos_sensor(0x51,0x03);
write_cmos_sensor(0x52,0x0d);
write_cmos_sensor(0x53,0x0b);
write_cmos_sensor(0x54,0x14);
write_cmos_sensor(0x57,0x59);
write_cmos_sensor(0x58,0x45);
write_cmos_sensor(0x59,0x41);
write_cmos_sensor(0x5a,0x5f);
write_cmos_sensor(0x5b,0x1e);
write_cmos_sensor(0x5c,0x0e);//0x5c[3:0] low light color coefficient,smaller ,lower noise
write_cmos_sensor(0x5d,0x95);
*/
write_cmos_sensor(0x60,0x20);//color open in low light
//AWB
write_cmos_sensor(0x6a,0x01);//如果肤色偏色,将0x6a写为0x81.
write_cmos_sensor(0x23,0x66);//Green gain
write_cmos_sensor(0xa0,0x07);//0xa0写0x03,黑色物体更红;0xa0写0x07,黑色物体更黑;
write_cmos_sensor(0xa1,0X41);//
write_cmos_sensor(0xa2,0X0e);
write_cmos_sensor(0xa3,0X26);
write_cmos_sensor(0xa4,0X0d);
//冷色调
write_cmos_sensor(0xa5,0x28);//The upper limit of red gain
/*暖色调
write_cmos_sensor(0xa5,0x2d);
*/
write_cmos_sensor(0xa6,0x04);
write_cmos_sensor(0xa7,0x80);//BLUE Target
write_cmos_sensor(0xa8,0x80);//RED Target
write_cmos_sensor(0xa9,0x28);
write_cmos_sensor(0xaa,0x28);
write_cmos_sensor(0xab,0x28);
write_cmos_sensor(0xac,0x3c);
write_cmos_sensor(0xad,0xf0);
write_cmos_sensor(0xc8,0x18);
write_cmos_sensor(0xc9,0x20);
write_cmos_sensor(0xca,0x17);
write_cmos_sensor(0xcb,0x1f);
write_cmos_sensor(0xaf,0x00);
write_cmos_sensor(0xc5,0x18);
write_cmos_sensor(0xc6,0x00);
write_cmos_sensor(0xc7,0x20);
write_cmos_sensor(0xae,0x83);//如果照户外偏蓝,将此寄存器0xae写为0x81。
write_cmos_sensor(0xcc,0x30);
write_cmos_sensor(0xcd,0x70);
write_cmos_sensor(0xee,0x4c);// P_TH
// color saturation
write_cmos_sensor(0xb0,0xd0);
write_cmos_sensor(0xb1,0xc0);
write_cmos_sensor(0xb2,0xb0);
/* // 饱和度艳丽
write_cmos_sensor(0xb1,0xd0);
write_cmos_sensor(0xb2,0xc0);
*/
write_cmos_sensor(0xb3,0x88);
//anti webcamera banding
write_cmos_sensor(0x9d,0x4c);
//switch direction
write_cmos_sensor(0x1e,0x00);//00:normal 10:IMAGE_V_MIRROR 20:IMAGE_H_MIRROR 30:IMAGE_HV_MIRROR
return 1;
/* init_cmos_sensor() */
}
/*************************************************************************
* FUNCTION
* power_off_BF3703
*
* DESCRIPTION
* This function is to turn off sensor module power.
*
* PARAMETERS
* None
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void power_off_BF3703(void)
{
cis_module_power_on(KAL_FALSE); // Power Off CIS Power
UPLL_Disable(UPLL_OWNER_ISP);
#ifndef HW_SCCB
SET_SCCB_CLK_LOW;
SET_SCCB_DATA_LOW;
#endif
} /* power_off_BF3703 */
/*************************************************************************
* FUNCTION
* get_BF3703_id
*
* DESCRIPTION
* This function return the sensor read/write id of SCCB interface.
*
* PARAMETERS
* *sensor_write_id : address pointer of sensor write id
* *sensor_read_id : address pointer of sensor read id
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void get_BF3703_id(kal_uint8 *sensor_write_id, kal_uint8 *sensor_read_id)
{
*sensor_write_id=BF3703_WRITE_ID;
*sensor_read_id=BF3703_READ_ID;
} /* get_BF3703_id */
/*************************************************************************
* FUNCTION
* get_BF3703_size
*
* DESCRIPTION
* This function return the image width and height of image sensor.
*
* PARAMETERS
* *sensor_width : address pointer of horizontal effect pixels of image sensor
* *sensor_height : address pointer of vertical effect pixels of image sensor
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void get_BF3703_size(kal_uint16 *sensor_width, kal_uint16 *sensor_height)
{
*sensor_width=IMAGE_SENSOR_VGA_WIDTH; /* pixel numbers actually used in one frame */
*sensor_height=IMAGE_SENSOR_VGA_HEIGHT; /* line numbers actually used in one frame */
} /* get_BF3703_size */
/*************************************************************************
* FUNCTION
* get_BF3703_period
*
* DESCRIPTION
* This function return the image width and height of image sensor.
*
* PARAMETERS
* *pixel_number : address pointer of pixel numbers in one period of HSYNC
* *line_number : address pointer of line numbers in one period of VSYNC
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void get_BF3703_period(kal_uint16 *pixel_number, kal_uint16 *line_number)
{
*pixel_number=VGA_PERIOD_PIXEL_NUMS; /* pixel numbers in one period of HSYNC */
*line_number=VGA_PERIOD_LINE_NUMS; /* line numbers in one period of VSYNC */
} /* get_BF3703_period */
void BF3703_preview(image_sensor_exposure_window_struct *image_window, image_sensor_config_struct *sensor_config_data)
{
sensor_cap_state=KAL_FALSE;
g_bMJPEG_mode = KAL_FALSE;
write_cmos_sensor(0x11,0x80); //MCLK = PCLK
if((sensor_config_data->isp_op_mode==ISP_MJPEG_PREVIEW_MODE)||(sensor_config_data->isp_op_mode==ISP_MJPEG_ENCODE_MODE))
{ //MT6225 video mode
MPEG4_encode_mode=KAL_FALSE;
g_bMJPEG_mode = KAL_TRUE;
/* config TG of ISP to match the setting of image sensor*/
SET_TG_OUTPUT_CLK_DIVIDER(3);
SET_CMOS_RISING_EDGE(0);
SET_CMOS_FALLING_EDGE(2);
ENABLE_CAMERA_PIXEL_CLKIN_ENABLE;
SET_TG_PIXEL_CLK_DIVIDER(3);
SET_CMOS_DATA_LATCH(2);
pre_dummy_pixels=32;
dummy_lines=32;//anti_flicker 32:devided by 2 103: devided by 1
}
else
{
if(sensor_config_data->frame_rate==0x0F) // MPEG4 Encode Mode
{
//MT6226 video mode
kal_prompt_trace(MOD_MMI," BF3703 video");
MPEG4_encode_mode=KAL_TRUE;
/* config TG of ISP to match the setting of image sensor*/
SET_TG_OUTPUT_CLK_DIVIDER(3);
SET_CMOS_RISING_EDGE(0);
SET_CMOS_FALLING_EDGE(2);
ENABLE_CAMERA_PIXEL_CLKIN_ENABLE;
SET_TG_PIXEL_CLK_DIVIDER(3);
SET_CMOS_DATA_LATCH(2);
pre_dummy_pixels=32;
dummy_lines=32;//anti_flicker 32:devided by 2 103: devided by 1
}
else
{
kal_prompt_trace(MOD_MMI," BF3703 preview");
MPEG4_encode_mode=KAL_FALSE;
/* config TG of ISP to match the setting of image sensor*/
SET_TG_OUTPUT_CLK_DIVIDER(1);
SET_CMOS_RISING_EDGE(0);
SET_CMOS_FALLING_EDGE(1);
ENABLE_CAMERA_PIXEL_CLKIN_ENABLE;
SET_TG_PIXEL_CLK_DIVIDER(1);
SET_CMOS_DATA_LATCH(1);
pre_dummy_pixels=32;
dummy_lines=64;//anti_flicker 32:devided by 2 64: devided by 1
}
}
preview_pclk_division=((DRV_Reg32(ISP_TG_PHASE_COUNTER_REG)&0xF0)>>4)+1;
image_window->grab_start_x=IMAGE_SENSOR_VGA_INSERTED_PIXELS;
image_window->grab_start_y=IMAGE_SENSOR_VGA_INSERTED_LINES+start_grab_y_offset;
image_window->exposure_window_width=IMAGE_SENSOR_VGA_WIDTH;
image_window->exposure_window_height=IMAGE_SENSOR_VGA_HEIGHT-1;
set_BF3703_dummy(pre_dummy_pixels,dummy_lines);
write_BF3703_shutter(exposure_lines);
if (sensor_config_data->isp_op_mode == ISP_MJPEG_ENCODE_MODE)
{
;
}else
{
// ISP_MJPEG_ENCODE_MODE mode does not invok YUV setting API after preview function
// If turn on AEC/AGC/AWB in ISP_MJPEG_ENCODE_MODE mode, the AWB setting will be overwriten.
write_cmos_sensor(0x13, 0x07); // Turn ON AEC/AGC/AWB
}
kal_sleep_task(30);
}
void BF3703_capture(image_sensor_exposure_window_struct *image_window, image_sensor_config_struct *sensor_config_data)
{
volatile kal_uint32 shutter=exposure_lines;
sensor_cap_state=KAL_TRUE;
if(sensor_config_data->enable_shutter_tansfer==KAL_TRUE)
shutter=sensor_config_data->capture_shutter;
if(!(sensor_config_data->frame_rate==0xF0)) // If not WEBCAM mode.
{
kal_prompt_trace(MOD_MMI,"Not WEBCAM MODE");
write_cmos_sensor(0x13,0xE2); // Turn OffF AGC/AEC
shutter=read_BF3703_shutter();
}
if ((image_window->image_target_width<IMAGE_SENSOR_1M_WIDTH)&&
(image_window->image_target_height<IMAGE_SENSOR_1M_HEIGHT))
{ /* Less than VGA Mode */
if (image_window->digital_zoom_factor>=(ISP_DIGITAL_ZOOM_INTERVAL<<1))
{
kal_prompt_trace(MOD_MMI,"BF3703 ZOOM ");
write_cmos_sensor(0x11,0xB0);
SET_TG_PIXEL_CLK_DIVIDER(7);
SET_CMOS_DATA_LATCH(4);
cap_dummy_pixels=VGA_PERIOD_PIXEL_NUMS/4;
dummy_lines=0;
}
else
{
if(sensor_config_data->frame_rate==0xF0) // WEBCAM Preview mode.
{
write_cmos_sensor(0x11,0x90);
SET_TG_PIXEL_CLK_DIVIDER(1);
SET_CMOS_DATA_LATCH(1);
start_grab_x_offset=0;
start_grab_y_offset=0;
cap_dummy_pixels=0;
dummy_lines=0;
}
else
{
kal_prompt_trace(MOD_MMI,"BF3703 Capture");
write_cmos_sensor(0x11,0x90);
SET_TG_PIXEL_CLK_DIVIDER(3);//3
SET_CMOS_DATA_LATCH(2);
cap_dummy_pixels=0;
}
}
capture_pclk_division=((DRV_Reg32(ISP_TG_PHASE_COUNTER_REG)&0xF0)>>4)+1;
shutter=(shutter*preview_pclk_division)/capture_pclk_division;
shutter=(shutter*(VGA_PERIOD_PIXEL_NUMS+pre_dummy_pixels))/(VGA_PERIOD_PIXEL_NUMS+cap_dummy_pixels);
if(shutter<1)
shutter=1;
}
if ((image_window->image_target_width>=IMAGE_SENSOR_1M_WIDTH)&&
(image_window->image_target_height>=IMAGE_SENSOR_1M_HEIGHT))
{
write_cmos_sensor(0x11,0x90);
SET_TG_PIXEL_CLK_DIVIDER(3);
SET_CMOS_DATA_LATCH(2);
cap_dummy_pixels=1000;
capture_pclk_division=((DRV_Reg32(ISP_TG_PHASE_COUNTER_REG)&0xF0)>>4)+1;
shutter=(shutter*preview_pclk_division)/capture_pclk_division;
shutter=(shutter*(VGA_PERIOD_PIXEL_NUMS+pre_dummy_pixels))/((VGA_PERIOD_PIXEL_NUMS+cap_dummy_pixels));
if(shutter<1)
shutter=1;
}
image_window->grab_start_x=IMAGE_SENSOR_VGA_INSERTED_PIXELS;
image_window->grab_start_y=IMAGE_SENSOR_VGA_INSERTED_LINES;
image_window->exposure_window_width=IMAGE_SENSOR_VGA_WIDTH;
image_window->exposure_window_height=IMAGE_SENSOR_VGA_HEIGHT-1; // minus 1 to avoid the last black line
set_BF3703_dummy(cap_dummy_pixels,dummy_lines);
write_BF3703_shutter(shutter);
} /* BF3703_capture() */
/*************************************************************************
* FUNCTION
* write_BF3703_reg
*
* DESCRIPTION
* This function set the register of BF3703.
*
* PARAMETERS
* addr : the register index of BF3703
* para : setting parameter of the specified register of BF3703
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void write_BF3703_reg(kal_uint32 addr, kal_uint32 para)
{
write_cmos_sensor(addr,para);
} /* write_BF3703_reg() */
/*************************************************************************
* FUNCTION
* read_cmos_sensor
*
* DESCRIPTION
* This function read parameter of specified register from BF3703.
*
* PARAMETERS
* addr : the register index of BF3703
*
* RETURNS
* the data that read from BF3703
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 read_BF3703_reg(kal_uint32 addr)
{
return (read_cmos_sensor(addr));
} /* read_BF3703_reg() */
/*************************************************************************
* FUNCTION
* set_BF3703_shutter
*
* DESCRIPTION
* This function set e-shutter of BF3703 to change exposure time.
*
* PARAMETERS
* shutter : exposured lines
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void set_BF3703_shutter(kal_uint16 shutter)
{
exposure_lines=shutter;
write_BF3703_shutter(shutter);
} /* set_BF3703_shutter */
/*************************************************************************
* FUNCTION
* set_BF3703_gain
*
* DESCRIPTION
* This function is to set global gain to sensor.
*
* PARAMETERS
* gain : sensor global gain(base: 0x40)
*
* RETURNS
* the actually gain set to sensor.
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint16 set_BF3703_gain(kal_uint16 gain)
{
return gain;
}
/*************************************************************************
* FUNCTION
* BF3703_night_mode
*
* DESCRIPTION
* This function night mode of BF3703.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void BF3703_night_mode(kal_bool enable)
{
if (enable)
{
if (g_bMJPEG_mode||MPEG4_encode_mode)
{
// this mode is used by MT6225 or MT6226 video Night mode
write_cmos_sensor(0X85, 0X2a);
write_cmos_sensor(0X86, 0X30);
write_cmos_sensor(0x7b, 0x30);
write_cmos_sensor(0x8e, 0x07);//Min fps =4 07 分频 0e 不分频
write_cmos_sensor(0x8f, 0x79);// 79 分频 F2 不分频
}
else
{
// this mode is used by camera Night mode
write_cmos_sensor(0X85, 0X2a);
write_cmos_sensor(0X86, 0X30);
write_cmos_sensor(0x7b, 0x30);
write_cmos_sensor(0x8e, 0x0E);//Min fps =4 07 分频 0e 不分频
write_cmos_sensor(0x8f, 0xF2);// 79 分频 F2 不分频
}
}
else
{
if (g_bMJPEG_mode||MPEG4_encode_mode)
{
// this mode is used by MT6225 or MT6226 video Normal mode
write_cmos_sensor(0x8e, 0x03);
write_cmos_sensor(0x8f, 0xbc);
}
else
{
// this mode is used by camera Normal mode
write_cmos_sensor(0x8e, 0x07);// MIN FPS=8 03 分频 07 不分频
write_cmos_sensor(0x8f, 0x79);// bc 分频 79 不分频
}
}
}/* BF3703_night_mode */
/*************************************************************************
* FUNCTION
* set_BF3703_flashlight
*
* DESCRIPTION
* turn on/off BF3703 flashlight .
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void set_BF3703_flashlight(kal_bool enable)
{
// Todo
}
/*************************************************************************
* FUNCTION
* set_BF3703_param_zoom
*
* DESCRIPTION
* BF3703 zoom setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_zoom(kal_uint32 para)
{
return KAL_FALSE;
}
/*************************************************************************
* FUNCTION
* set_BF3703_param_contrast
*
* DESCRIPTION
* BF3703 contrast setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_contrast(kal_uint32 para)
{
// Not Support
return KAL_FALSE;
}
/*************************************************************************
* FUNCTION
* set_BF3703_param_brightness
*
* DESCRIPTION
* BF3703 brightness setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_brightness(kal_uint32 para)
{
// Not Support
return KAL_FALSE;
}
/*************************************************************************
* FUNCTION
* set_BF3703_param_hue
*
* DESCRIPTION
* BF3703 hue setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_hue(kal_uint32 para)
{
// Not Support
return KAL_FALSE;
}
/*************************************************************************
* FUNCTION
* set_BF3703_param_gamma
*
* DESCRIPTION
* BF3703 gamma setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_gamma(kal_uint32 para)
{
return KAL_FALSE;
}
/*************************************************************************
* FUNCTION
* set_BF3703_param_wb
*
* DESCRIPTION
* BF3703 wb setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_wb(kal_uint32 para)
{
kal_uint8 temp_reg;
temp_reg=read_cmos_sensor(0x13);
switch (para)
{
case CAM_WB_AUTO:
kal_prompt_trace(MOD_MMI,"------->>>AWB");
write_cmos_sensor(0x01,0x15);
write_cmos_sensor(0x02,0x24);
write_cmos_sensor(0x13,temp_reg|0x2); // Enable AWB
break;
case CAM_WB_CLOUD:
write_cmos_sensor(0x13,temp_reg&~0x2); // Disable AWB
write_cmos_sensor(0x01,0x10);
write_cmos_sensor(0x02,0x28);
break;
case CAM_WB_DAYLIGHT:
write_cmos_sensor(0x13,temp_reg&~0x2); // Disable AWB
write_cmos_sensor(0x01,0x13);
write_cmos_sensor(0x02,0x26);
break;
case CAM_WB_INCANDESCENCE:
write_cmos_sensor(0x13,temp_reg&~0x2); // Disable AWB
write_cmos_sensor(0x01,0x1f);
write_cmos_sensor(0x02,0x15);
break;
case CAM_WB_FLUORESCENT:
write_cmos_sensor(0x13,temp_reg&~0x2); // Disable AWB
write_cmos_sensor(0x01,0x1a);
write_cmos_sensor(0x02,0x1e);
break;
case CAM_WB_TUNGSTEN:
write_cmos_sensor(0x13,temp_reg&~0x2); // Disable AWB
write_cmos_sensor(0x01,0x1a);
write_cmos_sensor(0x02,0x0d);
break;
case CAM_WB_MANUAL:
// TODO
break;
default:
return KAL_FALSE;
}
return KAL_TRUE;
}
/*************************************************************************
* FUNCTION
* set_BF3703_param_exposure
*
* DESCRIPTION
* BF3703 exposure setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_exposure(kal_uint32 para)
{
switch (para)
{
case CAM_EV_NEG_4_3:
write_cmos_sensor(0x55, 0xF8);
break;
case CAM_EV_NEG_3_3:
write_cmos_sensor(0x55, 0xD8);
break;
case CAM_EV_NEG_2_3:
write_cmos_sensor(0x55, 0xB8);
break;
case CAM_EV_NEG_1_3:
write_cmos_sensor(0x55, 0x98);
break;
case CAM_EV_ZERO:
write_cmos_sensor(0x55, 0x00);
break;
case CAM_EV_POS_1_3:
write_cmos_sensor(0x55, 0x18);
break;
case CAM_EV_POS_2_3:
write_cmos_sensor(0x55, 0x38);
break;
case CAM_EV_POS_3_3:
write_cmos_sensor(0x55, 0x58);
break;
case CAM_EV_POS_4_3:
write_cmos_sensor(0x55, 0x78);
break;
default:
return KAL_FALSE;
}
return KAL_TRUE;
}
/*************************************************************************
* FUNCTION
* set_BF3703_param_effect
*
* DESCRIPTION
* BF3703 effect setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_effect(kal_uint32 para)
{
kal_uint32 ret = KAL_TRUE;
kal_prompt_trace(MOD_MMI,"---->>effect");
switch (para)
{
case CAM_EFFECT_ENC_NORMAL:
write_cmos_sensor(0x80,0x45);
write_cmos_sensor(0x76,0x00);
write_cmos_sensor(0x69,0x00);
write_cmos_sensor(0x67,0x80);
write_cmos_sensor(0x68,0x80);
break;
case CAM_EFFECT_ENC_GRAYSCALE:
write_cmos_sensor(0x80,0x45);
write_cmos_sensor(0x76,0x00);
write_cmos_sensor(0x69,0x20);
write_cmos_sensor(0x67,0x80);
write_cmos_sensor(0x68,0x80);
break;
case CAM_EFFECT_ENC_SEPIA:
write_cmos_sensor(0x80,0x45);
write_cmos_sensor(0x76,0x00);
write_cmos_sensor(0x69,0x20);
write_cmos_sensor(0x67,0x60);
write_cmos_sensor(0x68,0x98);
break;
case CAM_EFFECT_ENC_COLORINV:
write_cmos_sensor(0x80,0x45);
write_cmos_sensor(0x76,0x00);
write_cmos_sensor(0x69,0x40);
write_cmos_sensor(0x67,0x80);
write_cmos_sensor(0x68,0x80);
break;
case CAM_EFFECT_ENC_SEPIAGREEN:
write_cmos_sensor(0x80,0x45);
write_cmos_sensor(0x76,0x00);
write_cmos_sensor(0x69,0x20);
write_cmos_sensor(0x67,0x40);
write_cmos_sensor(0x68,0x40);
break;
case CAM_EFFECT_ENC_SEPIABLUE:
write_cmos_sensor(0x80,0x45);
write_cmos_sensor(0x76,0x00);
write_cmos_sensor(0x69,0x20);
write_cmos_sensor(0x67,0xA0);
write_cmos_sensor(0x68,0x40);
break;
case CAM_EFFECT_ENC_GRAYINV:
write_cmos_sensor(0x80,0x45);
write_cmos_sensor(0x76,0x00);
write_cmos_sensor(0x69,0x20);
write_cmos_sensor(0x67,0x80);
write_cmos_sensor(0x68,0x80);
break;
case CAM_EFFECT_ENC_COPPERCARVING:
write_cmos_sensor(0x69,0x00);
write_cmos_sensor(0x80,0xc5);
write_cmos_sensor(0x76,0xc0);
write_cmos_sensor(0x67,0x80);
write_cmos_sensor(0x68,0x80);
break;
case CAM_EFFECT_ENC_BLUECARVING:
write_cmos_sensor(0x69,0x00);
write_cmos_sensor(0x80,0xc5);
write_cmos_sensor(0x76,0xd0);
write_cmos_sensor(0x67,0x80);
write_cmos_sensor(0x68,0x80);
break;
case CAM_EFFECT_ENC_CONTRAST:
write_cmos_sensor(0x80,0x45);
write_cmos_sensor(0x76,0x00);
write_cmos_sensor(0x69,0x00);
write_cmos_sensor(0x67,0x80);
write_cmos_sensor(0x68,0x80);
break;
case CAM_EFFECT_ENC_EMBOSSMENT:
write_cmos_sensor(0x69,0x00);
write_cmos_sensor(0x80,0xc5);
write_cmos_sensor(0x77,0x80);
write_cmos_sensor(0x67,0x80);
write_cmos_sensor(0x68,0x80);
break;
case CAM_EFFECT_ENC_SKETCH:
write_cmos_sensor(0x69,0x00);
write_cmos_sensor(0x80,0xc5);
write_cmos_sensor(0x76,0xb0);
write_cmos_sensor(0x67,0x80);
write_cmos_sensor(0x68,0x80);
break;
case CAM_EFFECT_ENC_BLACKBOARD:
write_cmos_sensor(0x69,0x00);
write_cmos_sensor(0x80,0xc5);
write_cmos_sensor(0x76,0xe0);
write_cmos_sensor(0x67,0x80);
write_cmos_sensor(0x68,0x80);
break;
case CAM_EFFECT_ENC_WHITEBOARD:
write_cmos_sensor(0x69,0x00);
write_cmos_sensor(0x80,0xc5);
write_cmos_sensor(0x76,0xf0);
write_cmos_sensor(0x67,0x80);
write_cmos_sensor(0x68,0x80);
break;
case CAM_EFFECT_ENC_JEAN:
case CAM_EFFECT_ENC_OIL:
default:
ret = KAL_FALSE;
}
return ret;
}
/*************************************************************************
* FUNCTION
* set_BF3703_param_banding
*
* DESCRIPTION
* BF3703 banding setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_banding(kal_uint32 para)
{
kal_uint8 temp_Reg_80,temp_Reg_2a,temp_Reg_2b;
kal_uint16 dummy_pixels_banding;
temp_Reg_80=read_cmos_sensor(0x80);
temp_Reg_2a=read_cmos_sensor(0x2a);
temp_Reg_2b=read_cmos_sensor(0x2b);
dummy_pixels_banding=((temp_Reg_2a&0xF0)<<4)|(temp_Reg_2b);
kal_prompt_trace(MOD_MMI,"------>>Banding");
switch (para)
{
case CAM_BANDING_50HZ:
if(g_bMJPEG_mode||MPEG4_encode_mode) // video , MCLK=12M
{
write_cmos_sensor(0x80,temp_Reg_80);
write_cmos_sensor(0x9d,60000/(784+dummy_pixels_banding));
}
else
{
write_cmos_sensor(0x80,temp_Reg_80);
write_cmos_sensor(0x9d,120000/(784+dummy_pixels_banding));
}
break;
case CAM_BANDING_60HZ:
if(g_bMJPEG_mode||MPEG4_encode_mode) //video , MCLK=12M
{
write_cmos_sensor(0x80,temp_Reg_80&0xFE);
write_cmos_sensor(0x9e,6000000/(784+dummy_pixels_banding)/120);
}
else
{
write_cmos_sensor(0x80,temp_Reg_80&0xFE);
write_cmos_sensor(0x9e,12000000/(784+dummy_pixels_banding)/120);
}
break;
default:
return KAL_FALSE;
}
return KAL_TRUE;
}
/*************************************************************************
* FUNCTION
* set_BF3703_param_saturation
*
* DESCRIPTION
* BF3703 SATURATION setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_saturation(kal_uint32 para)
{
// Not Support
return KAL_FALSE;
}
/*************************************************************************
* FUNCTION
* set_BF3703_param_nightmode
*
* DESCRIPTION
* BF3703 night mode setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_nightmode(kal_uint32 para)
{
BF3703_night_mode((kal_bool)para);
return KAL_TRUE;
}
/*************************************************************************
* FUNCTION
* set_BF3703_param_ev
*
* DESCRIPTION
* BF3703 ev setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_ev(kal_uint32 para)
{
return set_BF3703_param_exposure(para);
}
/*************************************************************************
* FUNCTION
* BF3703_yuv_sensor_setting
*
* DESCRIPTION
* This function send command and parameter to yuv sensor module BF3703
* to configure it
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 BF3703_yuv_sensor_setting(kal_uint32 cmd, kal_uint32 para)
{
kal_uint32 ret = KAL_TRUE;
switch (cmd)
{
case CAM_PARAM_ZOOM_FACTOR:
ret = set_BF3703_param_zoom(para);
break;
case CAM_PARAM_CONTRAST:
ret = set_BF3703_param_contrast(para);
break;
case CAM_PARAM_BRIGHTNESS:
ret = set_BF3703_param_brightness(para);
break;
case CAM_PARAM_HUE:
ret = set_BF3703_param_hue(para);
break;
case CAM_PARAM_GAMMA:
ret = set_BF3703_param_gamma(para);
break;
case CAM_PARAM_WB:
ret = set_BF3703_param_wb(para);
break;
case CAM_PARAM_EXPOSURE:
ret = set_BF3703_param_exposure(para);
break;
case CAM_PARAM_EFFECT:
ret = set_BF3703_param_effect(para);
break;
case CAM_PARAM_BANDING:
ret = set_BF3703_param_banding(para);
break;
case CAM_PARAM_SATURATION:
ret = set_BF3703_param_saturation(para);
break;
case CAM_PARAM_NIGHT_MODE:
ret = set_BF3703_param_nightmode(para);
break;
case CAM_PARAM_EV_VALUE:
ret = set_BF3703_param_ev(para);
break;
default:
ret = KAL_FALSE;
}
return ret;
}
/*************************************************************************
* FUNCTION
* image_sensor_func_BF3703
*
* DESCRIPTION
* BF3703 Image Sensor functions struct.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
image_sensor_func_struct image_sensor_func_BF3703=
{
init_BF3703,
get_BF3703_id,
get_BF3703_size,
get_BF3703_period,
BF3703_preview,
BF3703_capture,
write_BF3703_reg,
read_BF3703_reg,
set_BF3703_shutter,
BF3703_night_mode,
power_off_BF3703,
set_BF3703_gain,
set_BF3703_flashlight,
BF3703_yuv_sensor_setting
}; /* image_sensor_func_BF3703 */
/*************************************************************************
* FUNCTION
* cam_module_func_config
*
* DESCRIPTION
* This function maps the external camera module function API structure.
*
* PARAMETERS
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void image_sensor_func_config(void)
{
image_sensor_func=&image_sensor_func_BF3703;
} /* cam_module_func_config() */
// write camera_para to sensor register
void camera_para_to_sensor(void)
{
}
// update camera_para from sensor register
void sensor_to_camera_para(void)
{
}
//------------------------Engineer mode---------------------------------
void get_sensor_group_count(kal_int32* sensor_count_ptr)
{
}
void get_sensor_group_info(kal_uint16 group_idx, kal_int8* group_name_ptr, kal_int32* item_count_ptr)
{
}
void get_sensor_item_info(kal_uint16 group_idx,kal_uint16 item_idx, ENG_sensor_info* info_ptr)
{
}
kal_bool set_sensor_item_info(kal_uint16 group_idx, kal_uint16 item_idx, kal_int32 item_value)
{
return KAL_TRUE;
}
<file_sep>/work/test/v4l2/yuv2bmp.c
/*************************************************************************
> Filename: capture.c
> Author: Qiuwei.wang
> Email: <EMAIL> / <EMAIL>
> Datatime: Mon 28 Nov 2016 06:05:39 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "yuv2bmp.h"
/*
* Functions
*/
static unsigned int yuv2rgb_pixel(int y, int u, int v)
{
unsigned int rgb_24 = 0;
unsigned char *pixel = (unsigned char *)&rgb_24;
int r, g, b;
r = y + (1.370705 * (v - 128));
g = y - (0.698001 * (v - 128)) - (0.337633 * (u - 128));
b = y + (1.732446 * (u - 128));
if(r > 255) r = 255;
if(g > 255) g = 255;
if(b > 255) b = 255;
if(r < 0) r = 0;
if(g < 0) g = 0;
if(b < 0) b = 0;
pixel[0] = r;
pixel[1] = g;
pixel[2] = b;
return rgb_24;
}
/*
* YUV422 to RGB24
*/
int yuv2rgb(unsigned char *yuv, unsigned char *rgb, unsigned int width, unsigned height)
{
unsigned int in = 0, out = 0;
unsigned int pixel_16;
unsigned char pixel_24[3];
unsigned int rgb_24;
unsigned int y0, u, y1, v;
for(in = 0; in < width * height * 2; in +=4) {
pixel_16 = yuv[in + 3] << 24 |
yuv[in + 2] << 16 |
yuv[in + 1] << 8 |
yuv[in + 0];
#if 1
/* Output data mode:Y U Y V */
y0 = (pixel_16 & 0x000000ff);
u = (pixel_16 & 0x0000ff00) >> 8;
y1 = (pixel_16 & 0x00ff0000) >> 16;
v = (pixel_16 & 0xff000000) >> 24;
#elif 0
/* Output data mode:Y V Y U */
y0 = (pixel_16 & 0x000000ff);
v = (pixel_16 & 0x0000ff00) >> 8;
y1 = (pixel_16 & 0x00ff0000) >> 16;
u = (pixel_16 & 0xff000000) >> 24;
#else
/* Output data mode:U Y V Y */
u = (pixel_16 & 0x000000ff);
y0 = (pixel_16 & 0x0000ff00) >> 8;
v = (pixel_16 & 0x00ff0000) >> 16;
y1 = (pixel_16 & 0xff000000) >> 24;
#endif
rgb_24 = yuv2rgb_pixel(y0, u, v);
pixel_24[0] = (rgb_24 & 0x000000ff);
pixel_24[1] = (rgb_24 & 0x0000ff00) >> 8;
pixel_24[2] = (rgb_24 & 0x00ff0000) >> 16;
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
rgb_24 = yuv2rgb_pixel(y1, u, v);
pixel_24[0] = (rgb_24 & 0x000000ff);
pixel_24[1] = (rgb_24 & 0x0000ff00) >> 8;
pixel_24[2] = (rgb_24 & 0x00ff0000) >> 16;
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
}
return 0;
}
int rgb2bmp(char *filename, unsigned int width, unsigned int height,\
int iBitCount, unsigned char *rgbbuf)
{
unsigned char *dstbuf;
unsigned int i, j;
unsigned long linesize, rgbsize;
printf("sizeof(BITMAPFILEHEADER) = 0x%02x\n", (unsigned int)sizeof(BITMAPFILEHEADER));
printf("sizeof(BITMAPINFOHEADER) = 0x%02x\n", (unsigned int)sizeof(BITMAPINFOHEADER));
if(iBitCount == 24) {
FILE *fp;
long ret;
BITMAPFILEHEADER bmpHeader;
BITMAPINFO bmpInfo;
if((fp = fopen(filename, "wb")) == NULL) {
printf("Can not create BMP file: %s\n", filename);
return -1;
}
rgbsize = width * height * 3;
bmpHeader.bfType = (WORD)(('M' << 8) | 'B');
bmpHeader.bfSize = rgbsize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bmpHeader.bfReserved1 = 0;
bmpHeader.bfReserved2 = 0;
bmpHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmpInfo.bmiHeader.biWidth = width;
bmpInfo.bmiHeader.biHeight = height;
bmpInfo.bmiHeader.biPlanes = 1;
bmpInfo.bmiHeader.biBitCount = iBitCount;
bmpInfo.bmiHeader.biCompression = 0;
bmpInfo.bmiHeader.biSizeImage = rgbsize;
bmpInfo.bmiHeader.biXPelsPerMeter = 0;
bmpInfo.bmiHeader.biYPelsPerMeter = 0;
bmpInfo.bmiHeader.biClrUsed = 0;
bmpInfo.bmiHeader.biClrImportant = 0;
if((ret = fwrite(&bmpHeader, 1, sizeof(BITMAPFILEHEADER), fp))
!= sizeof(BITMAPFILEHEADER))
printf("write BMP file header failed: ret=%ld\n", ret);
if((ret = fwrite(&(bmpInfo.bmiHeader), 1, sizeof(BITMAPINFOHEADER), fp))
!= sizeof(BITMAPINFOHEADER))
printf("write BMP file info failed: ret=%ld\n", ret);
/* convert rgbbuf */
dstbuf = (unsigned char *)malloc(rgbsize);
if(!dstbuf) {
printf("malloc dstbuf failed !!\n");
return -1;
}
linesize = width * 3; //line size
for(i = 0, j = height -1; i < height - 1; i++, j--)
memcpy((dstbuf + (linesize * j)), (rgbbuf + (linesize * i)), linesize);
if((ret = fwrite(dstbuf, 1, rgbsize, fp)) != rgbsize)
printf("write BMP file date failed: ret=%ld\n", ret);
free(dstbuf);
fclose(fp);
return 0;
} else {
printf("%s: error iBitCount != 24\n", __FUNCTION__);
return -1;
}
}
<file_sep>/work/camera/ov7740/ov7740.c
/*
* V4L2 Driver for camera sensor ov7740
*
* Copyright (C) 2012, Ingenic Semiconductor Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* fix by <EMAIL>
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/videodev2.h>
#include <media/v4l2-chip-ident.h>
#include <media/v4l2-subdev.h>
#include <media/soc_camera.h>
#include <media/soc_mediabus.h>
#include <mach/jz_camera.h>
#define REG_CHIP_ID_HIGH 0x0a
#define REG_CHIP_ID_LOW 0x0b
//#define REG_CHIP_REVISION 0x302a
#define CHIP_ID_HIGH 0x77
#define CHIP_ID_LOW 0x42 //0x40
//#define ov7740_DEFAULT_WIDTH 320
//#define ov7740_DEFAULT_HEIGHT 240
/* Private v4l2 controls */
#define V4L2_CID_PRIVATE_BALANCE (V4L2_CID_PRIVATE_BASE + 0)
#define V4L2_CID_PRIVATE_EFFECT (V4L2_CID_PRIVATE_BASE + 1)
/* In flip, the OV7740 does not need additional settings because the ISP block
* will auto-detect whether the pixel is in the red line or blue line and make
* the necessary adjustments.
*/
//#define REG_TC_VFLIP 0x3820
//#define REG_TC_MIRROR 0x3821
//#define OV7740_HFLIP 0x1
//#define OV7740_VFLIP 0x2
//#define OV7740_FLIP_VAL ((unsigned char)0x06)
//#define OV7740_FLIP_MASK ((unsigned char)0x06)
#define REG0C 0x0C /* Register 0C */
#define REG0C_HFLIP_IMG 0x40 /* Horizontal mirror image ON/OFF */
#define REG0C_VFLIP_IMG 0x80 /* Vertical flip image ON/OFF */
/* whether sensor support high resolution (> vga) preview or not */
#define SUPPORT_HIGH_RESOLUTION_PRE 1
/*
* Struct
*/
struct regval_list {
u8 reg_num;
u8 value;
};
struct mode_list {
u8 index;
const struct regval_list *mode_regs;
};
/* Supported resolutions */
enum ov7740_width {
W_VGA = 640,
};
enum ov7740_height {
H_VGA = 480,
};
struct ov7740_win_size {
char *name;
enum ov7740_width width;
enum ov7740_height height;
const struct regval_list *regs;
};
struct ov7740_priv {
struct v4l2_subdev subdev;
struct ov7740_camera_info *info;
enum v4l2_mbus_pixelcode cfmt_code;
struct ov7740_win_size *win;
int model;
u8 balance_value;
u8 effect_value;
u16 flag_vflip:1;
u16 flag_hflip:1;
};
int cam_t_j = 0, cam_t_i = 0;
unsigned long long cam_t0_buf[10];
unsigned long long cam_t1_buf[10];
static int ov7740_s_power(struct v4l2_subdev *sd, int on);
static inline int ov7740_write_reg(struct i2c_client * client, unsigned char addr, unsigned char value)
{
return i2c_smbus_write_byte_data(client, addr, value);
}
static inline char ov7740_read_reg(struct i2c_client *client, unsigned char addr)
{
char ret;
ret = i2c_smbus_read_byte_data(client, addr);
if (ret < 0)
return ret;
return ret;
}
/*
* Registers settings
*/
#define ENDMARKER { 0xff, 0xff }
static const struct regval_list ov7740_init_regs[] = {
//{0x12, 0x80}, //default
//{0x0a, 0x00}, // read id high
//{0x0b, 0x00}, // read id low
{0x13, 0x00},
{0x11, 0x01},
{0x12, 0x00}, // i/o control
//{0x28, 0x02},
{0x0c, 0x12},
{0x0d, 0x34},
{0x17, 0x25},
{0x18, 0xa0},
{0x19, 0x03},
{0x1a, 0xf0}, //
{0x1b, 0x89},
{0x22, 0x03},
{0x33, 0xc4},
{0x35, 0x05},
{0x36, 0x3f}, //
{0xcc, 0x40},
{0x00, 0x00},
{0x10, 0xff},
{0x0f, 0x00},
{0x13, 0x02},
ENDMARKER,
};
static const struct regval_list ov7740_vga_regs[] = {
/* Initial registers is for vga format, no setting needed */
ENDMARKER,
};
static const struct regval_list ov7740_wb_auto_regs[] = {
ENDMARKER,
};
static const struct regval_list ov7740_wb_incandescence_regs[] = {
ENDMARKER,
};
static const struct regval_list ov7740_wb_daylight_regs[] = {
ENDMARKER,
};
static const struct regval_list ov7740_wb_fluorescent_regs[] = {
ENDMARKER,
};
static const struct regval_list ov7740_wb_cloud_regs[] = {
ENDMARKER,
};
static const struct mode_list ov7740_balance[] = {
{0, ov7740_wb_auto_regs}, {1, ov7740_wb_incandescence_regs},
{2, ov7740_wb_daylight_regs}, {3, ov7740_wb_fluorescent_regs},
{4, ov7740_wb_cloud_regs},
};
static const struct regval_list ov7740_effect_normal_regs[] = {
ENDMARKER,
};
static const struct regval_list ov7740_effect_grayscale_regs[] = {
ENDMARKER,
};
static const struct regval_list ov7740_effect_sepia_regs[] = {
ENDMARKER,
};
static const struct regval_list ov7740_effect_colorinv_regs[] = {
ENDMARKER,
};
static const struct regval_list ov7740_effect_sepiabluel_regs[] = {
ENDMARKER,
};
static const struct mode_list ov7740_effect[] = {
{0, ov7740_effect_normal_regs}, {1, ov7740_effect_grayscale_regs},
{2, ov7740_effect_sepia_regs}, {3, ov7740_effect_colorinv_regs},
{4, ov7740_effect_sepiabluel_regs},
};
#define OV7740_SIZE(n, w, h, r) \
{.name = n, .width = w , .height = h, .regs = r }
static struct ov7740_win_size ov7740_supported_win_sizes[] = {
OV7740_SIZE("VGA", W_VGA, H_VGA, ov7740_vga_regs),
};
#define N_WIN_SIZES (ARRAY_SIZE(ov7740_supported_win_sizes))
static const struct regval_list ov7740_yuv422_regs[] = {
ENDMARKER,
};
static const struct regval_list ov7740_rgb565_regs[] = {
ENDMARKER,
};
static enum v4l2_mbus_pixelcode ov7740_codes[] = {
V4L2_MBUS_FMT_YUYV8_2X8,
//V4L2_MBUS_FMT_YUYV8_1_5X8,
//V4L2_MBUS_FMT_JZYUYV8_1_5X8,
};
/*
* Supported balance menus
*/
static const struct v4l2_querymenu ov7740_balance_menus[] = {
{
.id = V4L2_CID_PRIVATE_BALANCE,
.index = 0,
.name = "auto",
}, {
.id = V4L2_CID_PRIVATE_BALANCE,
.index = 1,
.name = "incandescent",
}, {
.id = V4L2_CID_PRIVATE_BALANCE,
.index = 2,
.name = "fluorescent",
}, {
.id = V4L2_CID_PRIVATE_BALANCE,
.index = 3,
.name = "daylight",
}, {
.id = V4L2_CID_PRIVATE_BALANCE,
.index = 4,
.name = "cloudy-daylight",
},
};
/*
* Supported effect menus
*/
static const struct v4l2_querymenu ov7740_effect_menus[] = {
{
.id = V4L2_CID_PRIVATE_EFFECT,
.index = 0,
.name = "none",
}, {
.id = V4L2_CID_PRIVATE_EFFECT,
.index = 1,
.name = "mono",
}, {
.id = V4L2_CID_PRIVATE_EFFECT,
.index = 2,
.name = "sepia",
}, {
.id = V4L2_CID_PRIVATE_EFFECT,
.index = 3,
.name = "negative",
}, {
.id = V4L2_CID_PRIVATE_EFFECT,
.index = 4,
.name = "aqua",
},
};
/*
* General functions
*/
static struct ov7740_priv *to_ov7740(const struct i2c_client *client)
{
return container_of(i2c_get_clientdata(client), struct ov7740_priv,
subdev);
}
static int ov7740_write_array(struct i2c_client *client, const struct regval_list *vals)
{
int ret;
while ((vals->reg_num != 0xff) || (vals->value != 0xff)) {
ret = i2c_smbus_write_byte_data(client, vals->reg_num, vals->value);
dev_vdbg(&client->dev, "array: 0x%02x, 0x%02x", vals->reg_num, vals->value);
if (ret < 0) {
dev_err(&client->dev, "array: 0x%02x, 0x%02x write failed",
vals->reg_num, vals->value);
return ret;
}
vals++;
}
return 0;
}
static int ov7740_mask_set(struct i2c_client *client,
u8 reg, u8 mask, u8 set)
{
s32 val = ov7740_read_reg(client, reg);
if (val < 0)
return val;
val &= ~mask;
val |= set & mask;
dev_vdbg(&client->dev, "masks: 0x%02x, 0x%02x", reg, val);
return ov7740_write_reg(client, reg, val);
}
static int ov7740_reset(struct i2c_client *client)
{
int ret;
const struct regval_list reset_seq[] = {
{0x12 ,0x80},
ENDMARKER,
};
ret = ov7740_write_array(client, reset_seq);
if (ret)
goto err;
msleep(5);
err:
dev_dbg(&client->dev, "%s: (ret %d)", __func__, ret);
return ret;
}
/*
* soc_camera_ops functions
*/
static int ov7740_s_stream(struct v4l2_subdev *sd, int enable)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
#if 0
if (!enable ) {
dev_info(&client->dev, "stream down\n");
//ov7740_write_reg(client, 0x3008, 0x42);
ov7740_write_reg(client, 0x4202, 0x0f);
return 0;
}
dev_info(&client->dev, "stream on\n");
//ov7740_write_reg(client, 0x3008, 0x02);
ov7740_write_reg(client, 0x4202, 0x00);
#endif
dev_info(&client->dev, "-----%s----", __func__);
return 0;
}
static int ov7740_g_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct ov7740_priv *priv = to_ov7740(client);
dev_info(&client->dev, "-----%s----", __func__);
switch (ctrl->id) {
case V4L2_CID_VFLIP:
ctrl->value = priv->flag_vflip;
break;
case V4L2_CID_HFLIP:
ctrl->value = priv->flag_hflip;
break;
case V4L2_CID_PRIVATE_BALANCE:
ctrl->value = priv->balance_value;
break;
case V4L2_CID_PRIVATE_EFFECT:
ctrl->value = priv->effect_value;
break;
default:
break;
}
return 0;
}
/* FIXME: Flip function should be update according to specific sensor */
static int ov7740_s_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct ov7740_priv *priv = to_ov7740(client);
int ret = 0;
int i = 0;
u8 value;
int balance_count = ARRAY_SIZE(ov7740_balance);
int effect_count = ARRAY_SIZE(ov7740_effect);
dev_info(&client->dev, "-----%s----", __func__);
switch (ctrl->id) {
case V4L2_CID_PRIVATE_BALANCE:
if(ctrl->value > balance_count)
return -EINVAL;
for(i = 0; i < balance_count; i++) {
if(ctrl->value == ov7740_balance[i].index) {
ret = ov7740_write_array(client,
ov7740_balance[ctrl->value].mode_regs);
priv->balance_value = ctrl->value;
break;
}
}
break;
case V4L2_CID_PRIVATE_EFFECT:
if(ctrl->value > effect_count)
return -EINVAL;
for(i = 0; i < effect_count; i++) {
if(ctrl->value == ov7740_effect[i].index) {
ret = ov7740_write_array(client,
ov7740_effect[ctrl->value].mode_regs);
priv->effect_value = ctrl->value;
break;
}
}
break;
case V4L2_CID_VFLIP:
value = ctrl->value ? REG0C_VFLIP_IMG : 0x00;
return ov7740_mask_set(client, REG0C, REG0C_VFLIP_IMG, value);
case V4L2_CID_HFLIP:
value = ctrl->value ? REG0C_HFLIP_IMG : 0x00;
return ov7740_mask_set(client, REG0C, REG0C_HFLIP_IMG, value);
default:
dev_err(&client->dev, "no V4L2 CID: 0x%x ", ctrl->id);
return -EINVAL;
}
return ret;
}
static int ov7740_g_chip_ident(struct v4l2_subdev *sd,
struct v4l2_dbg_chip_ident *id)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
dev_info(&client->dev, "-----%s----", __func__);
id->ident = SUPPORT_HIGH_RESOLUTION_PRE;
id->revision = 0;
return 0;
}
static int ov7740_querymenu(struct v4l2_subdev *sd,
struct v4l2_querymenu *qm)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
dev_info(&client->dev, "-----%s----", __func__);
switch (qm->id) {
case V4L2_CID_PRIVATE_BALANCE:
memcpy(qm->name, ov7740_balance_menus[qm->index].name,
sizeof(qm->name));
break;
case V4L2_CID_PRIVATE_EFFECT:
memcpy(qm->name, ov7740_effect_menus[qm->index].name,
sizeof(qm->name));
break;
}
return 0;
}
#ifdef CONFIG_VIDEO_ADV_DEBUG
static int ov7740_g_register(struct v4l2_subdev *sd,
struct v4l2_dbg_register *reg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
int ret;
reg->size = 1;
if (reg->reg > 0xff)
return -EINVAL;
ret = ov7740_read_reg(client, reg->reg);
if (ret < 0)
return ret;
reg->val = ret;
return 0;
}
static int ov7740_s_register(struct v4l2_subdev *sd,
struct v4l2_dbg_register *reg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
if (reg->reg > 0xff ||
reg->val > 0xff)
return -EINVAL;
return ov7740_write_reg(client, reg->reg, reg->val);
}
#endif
/* Select the nearest higher resolution for capture */
static struct ov7740_win_size *ov7740_select_win(u32 *width, u32 *height)
{
int i, default_size = ARRAY_SIZE(ov7740_supported_win_sizes) - 1;
for (i = 0; i < ARRAY_SIZE(ov7740_supported_win_sizes); i++) {
if ((*width >= ov7740_supported_win_sizes[i].width) &&
(*height >= ov7740_supported_win_sizes[i].height)) {
*width = ov7740_supported_win_sizes[i].width;
*height = ov7740_supported_win_sizes[i].height;
return &ov7740_supported_win_sizes[i];
}
}
*width = ov7740_supported_win_sizes[default_size].width;
*height = ov7740_supported_win_sizes[default_size].height;
return &ov7740_supported_win_sizes[default_size];
}
static int ov7740_init(struct v4l2_subdev *sd, u32 val)
{
int ret;
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct ov7740_priv *priv = to_ov7740(client);
int bala_index = priv->balance_value;
int effe_index = priv->effect_value;
ov7740_reset(client);
/* initialize the sensor with default data */
ret = ov7740_write_array(client, ov7740_init_regs);
ret = ov7740_write_array(client, ov7740_balance[bala_index].mode_regs);
ret = ov7740_write_array(client, ov7740_effect[effe_index].mode_regs);
if (ret < 0)
goto err;
dev_info(&client->dev, "%s: Init default", __func__);
return 0;
err:
dev_err(&client->dev, "%s: Error %d", __func__, ret);
return ret;
}
static int ov7740_g_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct ov7740_priv *priv = to_ov7740(client);
dev_info(&client->dev, "-----%s----", __func__);
mf->width = priv->win->width;
mf->height = priv->win->height;
mf->code = priv->cfmt_code;
mf->colorspace = V4L2_COLORSPACE_JPEG;
mf->field = V4L2_FIELD_NONE;
return 0;
}
static int ov7740_s_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
/* current do not support set format, use unify format yuv422i */
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct ov7740_priv *priv = to_ov7740(client);
int ret;
dev_info(&client->dev, "-----%s----", __func__);
ov7740_init(sd, 1);
priv->win = ov7740_select_win(&mf->width, &mf->height);
/* set size win */
ret = ov7740_write_array(client, priv->win->regs);
if (ret < 0) {
dev_err(&client->dev, "%s: Error\n", __func__);
return ret;
}
return 0;
}
static int ov7740_try_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
const struct ov7740_win_size *win;
struct i2c_client *client = v4l2_get_subdevdata(sd);
/*
* select suitable win
*/
dev_info(&client->dev, "-----%s----", __func__);
win = ov7740_select_win(&mf->width, &mf->height);
if(mf->field == V4L2_FIELD_ANY) {
mf->field = V4L2_FIELD_NONE;
} else if (mf->field != V4L2_FIELD_NONE) {
dev_err(&client->dev, "Field type invalid.\n");
return -ENODEV;
}
switch (mf->code) {
case V4L2_MBUS_FMT_YUYV8_2X8:
//case V4L2_MBUS_FMT_YUYV8_1_5X8:
//case V4L2_MBUS_FMT_JZYUYV8_1_5X8:
mf->colorspace = V4L2_COLORSPACE_JPEG;
break;
default:
mf->code = V4L2_MBUS_FMT_YUYV8_2X8;
mf->colorspace = V4L2_COLORSPACE_JPEG;
break;
}
return 0;
}
static int ov7740_enum_fmt(struct v4l2_subdev *sd, unsigned int index,
enum v4l2_mbus_pixelcode *code)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
dev_info(&client->dev, "-----%s----", __func__);
if (index >= ARRAY_SIZE(ov7740_codes))
return -EINVAL;
*code = ov7740_codes[index];
return 0;
}
static int ov7740_g_crop(struct v4l2_subdev *sd, struct v4l2_crop *a)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
dev_info(&client->dev, "-----%s----", __func__);
return 0;
}
static int ov7740_cropcap(struct v4l2_subdev *sd, struct v4l2_cropcap *a)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
dev_info(&client->dev, "-----%s----", __func__);
return 0;
}
/*
* Frame intervals. Since frame rates are controlled with the clock
* divider, we can only do 30/n for integer n values. So no continuous
* or stepwise options. Here we just pick a handful of logical values.
*/
static int ov7740_frame_rates[] = { 30, 15, 10, 5, 1 };
static int ov7740_enum_frameintervals(struct v4l2_subdev *sd,
struct v4l2_frmivalenum *interval)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
dev_info(&client->dev, "-----%s----", __func__);
if (interval->index >= ARRAY_SIZE(ov7740_frame_rates))
return -EINVAL;
interval->type = V4L2_FRMIVAL_TYPE_DISCRETE;
interval->discrete.numerator = 1;
interval->discrete.denominator = ov7740_frame_rates[interval->index];
return 0;
}
/*
* Frame size enumeration
*/
static int ov7740_enum_framesizes(struct v4l2_subdev *sd,
struct v4l2_frmsizeenum *fsize)
{
int i;
int num_valid = -1;
__u32 index = fsize->index;
struct i2c_client *client = v4l2_get_subdevdata(sd);
dev_info(&client->dev, "-----%s----", __func__);
for (i = 0; i < N_WIN_SIZES; i++) {
struct ov7740_win_size *win = &ov7740_supported_win_sizes[index];
if (index == ++num_valid) {
fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
fsize->discrete.width = win->width;
fsize->discrete.height = win->height;
return 0;
}
}
return -EINVAL;
}
static int ov7740_video_probe(struct i2c_client *client)
{
unsigned char retval = 0, retval_high = 0, retval_low = 0;
struct v4l2_subdev *subdev = i2c_get_clientdata(client);
int ret = 0;
struct soc_camera_subdev_desc *ssdd = soc_camera_i2c_to_desc(client);
dev_info(&client->dev, "-----%s----", __func__);
ret = soc_camera_power_on(&client->dev, ssdd);
if (ret < 0)
return ret;
/*
* check and show product ID and manufacturer ID
*/
#if 0
retval = ov7740_write_reg(client, 0x3008, 0x80);
if(retval) {
dev_err(&client->dev, "i2c write failed!\n");
return -1;
}
#endif
retval_high = ov7740_read_reg(client, REG_CHIP_ID_HIGH);
if (retval_high != CHIP_ID_HIGH) {
dev_err(&client->dev, "read sensor %s chip_id high %x is error\n",
client->name, retval_high);
return -1;
}
retval_low = ov7740_read_reg(client, REG_CHIP_ID_LOW);
if (retval_low != CHIP_ID_LOW) {
dev_err(&client->dev, "read sensor %s chip_id low %x is error\n",
client->name, retval_low);
return -1;
}
dev_info(&client->dev, "read sensor %s id high:0x%x,low:%x successed!\n",
client->name, retval_high, retval_low);
ret = soc_camera_power_off(&client->dev, ssdd);
return 0;
}
static int ov7740_s_power(struct v4l2_subdev *sd, int on)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct soc_camera_subdev_desc *ssdd = soc_camera_i2c_to_desc(client);
struct ov7740_priv *priv = to_ov7740(client);
int ret;
int bala_index = priv->balance_value;
int effe_index = priv->effect_value;
dev_info(&client->dev, "-----%s----", __func__);
if (!on)
return soc_camera_power_off(&client->dev, ssdd);
ret = soc_camera_power_on(&client->dev, ssdd);
#if 1
return ret;
#else
if (ret < 0)
return ret;
ov7740_reset(client);
///* initialize the sensor with default data */
ret = ov7740_write_array(client, ov7740_init_regs);
ret = ov7740_write_array(client, ov7740_balance[bala_index].mode_regs);
ret = ov7740_write_array(client, ov7740_effect[effe_index].mode_regs);
if (ret < 0)
goto err;
dev_info(&client->dev, "%s: Init default", __func__);
return 0;
err:
dev_err(&client->dev, "%s: Error %d", __func__, ret);
ov7740_reset(client);
return ret;
#endif
}
#if 0
static int ov7740_g_mbus_config(struct v4l2_subdev *sd,struct v4l2_mbus_config *cfg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct soc_camera_subdev_desc *ssdd = soc_camera_i2c_to_desc(client);
cfg->flags = V4L2_MBUS_PCLK_SAMPLE_RISING | V4L2_MBUS_MASTER |
V4L2_MBUS_VSYNC_ACTIVE_HIGH | V4L2_MBUS_HSYNC_ACTIVE_HIGH |
V4L2_MBUS_VSYNC_ACTIVE_LOW |
V4L2_MBUS_DATA_ACTIVE_HIGH;
cfg->type = V4L2_MBUS_PARALLEL;
cfg->flags = soc_camera_apply_board_flags(ssdd, cfg);
return 0;
}
#else
static int ov7740_g_mbus_config(struct v4l2_subdev *sd,
struct v4l2_mbus_config *cfg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct soc_camera_subdev_desc *ssdd = soc_camera_i2c_to_desc(client);
dev_info(&client->dev, "-----%s----", __func__);
cfg->flags = V4L2_MBUS_PCLK_SAMPLE_RISING | V4L2_MBUS_MASTER |
V4L2_MBUS_VSYNC_ACTIVE_HIGH| V4L2_MBUS_HSYNC_ACTIVE_HIGH |
V4L2_MBUS_DATA_ACTIVE_HIGH;
cfg->type = V4L2_MBUS_PARALLEL;
cfg->flags = soc_camera_apply_board_flags(ssdd, cfg);
return 0;
}
#endif
static struct v4l2_subdev_core_ops ov7740_subdev_core_ops = {
.s_power = ov7740_s_power,
.g_ctrl = ov7740_g_ctrl,
.s_ctrl = ov7740_s_ctrl,
.g_chip_ident = ov7740_g_chip_ident,
.querymenu = ov7740_querymenu,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.g_register = ov7740_g_register,
.s_register = ov7740_s_register,
#endif
};
static struct v4l2_subdev_video_ops ov7740_subdev_video_ops = {
.s_stream = ov7740_s_stream,
.g_mbus_fmt = ov7740_g_fmt,
.s_mbus_fmt = ov7740_s_fmt,
.try_mbus_fmt = ov7740_try_fmt,
.cropcap = ov7740_cropcap,
.g_crop = ov7740_g_crop,
.enum_mbus_fmt = ov7740_enum_fmt,
// .enum_framesizes = ov7740_enum_framesizes,
// .enum_frameintervals = ov7740_enum_frameintervals,
.g_mbus_config = ov7740_g_mbus_config,
};
static struct v4l2_subdev_ops ov7740_subdev_ops = {
.core = &ov7740_subdev_core_ops,
.video = &ov7740_subdev_video_ops,
};
/*
* i2c_driver functions
*/
static int ov7740_probe(struct i2c_client *client,
const struct i2c_device_id *did)
{
struct ov7740_priv *priv;
struct soc_camera_subdev_desc *ssdd = soc_camera_i2c_to_desc(client);
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
int ret = 0,default_wight = 640,default_height = 480;
if (!ssdd) {
dev_err(&client->dev, "ov7740: missing platform data!\n");
return -EINVAL;
}
if(!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE
| I2C_FUNC_SMBUS_BYTE_DATA)) {
dev_err(&client->dev, "client not i2c capable\n");
return -ENODEV;
}
priv = kzalloc(sizeof(struct ov7740_priv), GFP_KERNEL);
if (!priv) {
dev_err(&adapter->dev,
"Failed to allocate memory for private data!\n");
return -ENOMEM;
}
v4l2_i2c_subdev_init(&priv->subdev, client, &ov7740_subdev_ops);
priv->win = ov7740_select_win(&default_wight, &default_height);
priv->cfmt_code = V4L2_MBUS_FMT_YUYV8_2X8;
ret = ov7740_video_probe(client);
if (ret) {
kfree(priv);
}
return ret;
}
static int ov7740_remove(struct i2c_client *client)
{
struct ov7740_priv *priv = to_ov7740(client);
kfree(priv);
return 0;
}
static const struct i2c_device_id ov7740_id[] = {
{ "ov7740", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, ov7740_id);
static struct i2c_driver ov7740_i2c_driver = {
.driver = {
.name = "ov7740",
},
.probe = ov7740_probe,
.remove = ov7740_remove,
.id_table = ov7740_id,
};
/*
* Module functions
*/
static int __init ov7740_module_init(void)
{
return i2c_add_driver(&ov7740_i2c_driver);
}
static void __exit ov7740_module_exit(void)
{
i2c_del_driver(&ov7740_i2c_driver);
}
module_init(ov7740_module_init);
module_exit(ov7740_module_exit);
MODULE_DESCRIPTION("camera sensor ov7740 driver");
MODULE_AUTHOR("<NAME>");
MODULE_LICENSE("GPL");
<file_sep>/work/test/cim_test-zmm220/cimsh
#!/bin/sh
make clean
make
cp -f cimtest /mnt/hgfs/wlshare/linuxdevelop/tmp
<file_sep>/network/6th_day/pcap_test.c
/* ************************************************************************
* Filename: pcap_test.c
* Description:
* Version: 1.0
* Created: 2015年09月09日 16时13分09秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <pcap.h>
#if 0
void my_callback(u_char *user, const struct pcap_pkthdr *hdr, const u_char *msg)
{
printf("user=%s\n", user);
printf("%02x:%02x:%02x:%02x:%02x:%02x\n",\
msg[6],msg[7],msg[8],msg[9],msg[10],msg[11]);
printf("%02x:%02x:%02x:%02x:%02x:%02x\n",\
msg[0],msg[1],msg[2],msg[3],msg[4],msg[5]);
}
int main(int argc, char *argv[])
{
char err_buf[100] = "";
//1.打开网络句柄
pcap_t *p_fd = pcap_open_live("eth0",2048,0,0,err_buf);
//2.过滤网络数据
//2.1编译过滤规则
//struct bpf_program bpf_p;
//pcap_compile(p_fd,&bpf_p,"udp port 8000", 0, 0xffffff00);
//2.2设置过滤规则
//pcap_setfilter(p_fd, &bpf_p);
struct pcap_pkthdr p_hdr;
const u_char *msg = NULL;
pcap_loop(p_fd, -1, my_callback, (u_char *)"haha");
pcap_close(p_fd);
return 0;
}
#elif 0
void my_callback(u_char *msg, const struct pcap_pkthdr *hdr, const u_char *user)
{
printf("user=%s\n", user);
printf("%02x:%02x:%02x:%02x:%02x:%02x\n",\
msg[6],msg[7],msg[8],msg[9],msg[10],msg[11]);
printf("%02x:%02x:%02x:%02x:%02x:%02x\n",\
msg[0],msg[1],msg[2],msg[3],msg[4],msg[5]);
}
int main(int argc, char *argv[])
{
char err_buf[100] = "";
//打开网络句柄
pcap_t *p_fd = pcap_open_live("eth0",2048,0,0,err_buf);
struct pcap_pkthdr p_hdr;
const u_char *msg = NULL;
pcap_loop(p_fd, -1, my_callback, (u_char *)"haha");
pcap_close(p_fd);
return 0;
}
#elif 1
int main(int argc, char *argv[])
{
char err_buf[100] = "";
pcap_t *p_fd = pcap_open_live("eth0",2048,0,0,err_buf);
struct pcap_pkthdr p_hdr;
const u_char *msg = NULL;
msg = pcap_next(p_fd, &p_hdr);
printf("%02x:%02x:%02x:%02x:%02x:%02x\n",\
msg[6],msg[7],msg[8],msg[9],msg[10],msg[11]);
printf("%02x:%02x:%02x:%02x:%02x:%02x\n",\
msg[0],msg[1],msg[2],msg[3],msg[4],msg[5]);
pcap_close(p_fd);
return 0;
}
#elif 0
int main(int argc, char *argv[])
{
char err_buf[100] = "";
char *dev = NULL;
dev = pcap_lookupdev(err_buf);
printf("dev=%s\n",dev);
return 0;
}
#endif
<file_sep>/work/camera/bf3703/BF3703_MTK6225_Drv_V3.0/image_sensor.h
/****************************BF3403_BYD_VGA_Sensor***************************
* Copyright Statement:
* --------------------
* This software is protected by Copyright and the information contained
* herein is confidential. The software may not be copied and the information
* contained herein may not be used or disclosed except with the written
* permission of MediaTek Inc. (C) 2005
*
* BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
* NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S
* SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
* BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE
* LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE
* WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF
* LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND
* RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER
* THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC).
*
*****************************************************************************/
/*****************************************************************************
*
* Filename:
* ---------
* image_sensor.h
*
* Version:
* --------
* BF3703 MTK 6225 or 6226 DRV V1.0.0
*
* Release Date:
* ------------
* 2010-07-08
*
* Description:
* ------------
* CMOS sensor header file
*
* Author:
* -------
* -------
*
*============================================================================
* HISTORY
* Below this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
*------------------------------------------------------------------------------
*
*------------------------------------------------------------------------------
* Upper this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
*============================================================================
****************************************************************************/
#ifndef _IMAGE_SENSOR_H
#define _IMAGE_SENSOR_H
#include "isp_if.h"
//------------------------Engineer mode---------------------------------
#define FACTORY_START_ADDR 70
typedef enum group_enum {
AWB_GAIN=0,
PRE_GAIN,
SENSOR_DBLC,
GAMMA_ENABLE,
CMMCLK_CURRENT,
FRAME_RATE_LIMITATION,
REGISTER_EDITOR,
GROUP_TOTAL_NUMS
} FACTORY_CCT_GROUP_ENUM;
typedef enum register_index {
AWB_GAIN_R_INDEX=FACTORY_START_ADDR,
AWB_GAIN_B_INDEX,
SENSOR_DBLC_INDEX,
GAMMA_ENABLE_INDEX,
CMMCLK_CURRENT_INDEX,
FACTORY_END_ADDR
} FACTORY_REGISTER_INDEX;
typedef enum cct_register_index {
GLOBAL_GAIN_INDEX=0,
PRE_GAIN_R_INDEX,
PRE_GAIN_B_INDEX,
CCT_END_ADDR
} CCT_REGISTER_INDEX;
typedef struct
{
kal_uint8 item_name_ptr[50]; // item name
kal_int32 item_value; // item value
kal_bool is_true_false; // is this item for enable/disable functions
kal_bool is_read_only; // is this item read only
kal_bool is_need_restart; // after set this item need restart
kal_int32 min; // min value of item value
kal_int32 max; // max value of item value
} ENG_sensor_info;
// API FOR ENGINEER FACTORY MODE
void get_sensor_group_count(kal_int32* sensor_count_ptr);
void get_sensor_group_info(kal_uint16 group_idx, kal_int8* group_name_ptr, kal_int32* item_count_ptr);
void get_sensor_item_info(kal_uint16 group_idx,kal_uint16 item_idx, ENG_sensor_info* info_ptr);
kal_bool set_sensor_item_info(kal_uint16 group_idx, kal_uint16 item_idx, kal_int32 item_value);
//------------------------Engineer mode---------------------------------
typedef struct {
kal_uint32 addr;
kal_uint32 para;
} sensor_reg_struct;
typedef struct {
sensor_reg_struct reg[FACTORY_END_ADDR];
sensor_reg_struct cct[CCT_END_ADDR];
} sensor_data_struct;
// write camera_para to sensor register
void camera_para_to_sensor(void);
// update camera_para from sensor register
void sensor_to_camera_para(void);
// config sensor callback function
void image_sensor_func_config(void);
// Compact Image Sensor Module Power ON/OFF
void cis_module_power_on(kal_bool on);
/* HW PRODUCE I2C SIGNAL TO CONTROL SENSOR REGISTER */
//#define HW_SCCB
/* OUTPUT DEBUG INFO. BY UART */
//#define OUTPUT_DEBUG_INFO
typedef enum _SENSOR_TYPE {
CMOS_SENSOR=0,
CCD_SENSOR
} SENSOR_TYPE;
typedef struct {
kal_uint16 id;
SENSOR_TYPE type;
} SensorInfo;
/* MAXIMUM EXPLOSURE LINES USED BY AE */
extern kal_uint16 MAX_EXPOSURE_LINES;
extern kal_uint8 MIN_EXPOSURE_LINES;
/* AE CONTROL CRITERION */
extern kal_uint8 AE_AWB_CAL_PERIOD;
extern kal_uint8 AE_GAIN_DELAY_PERIOD;
extern kal_uint8 AE_SHUTTER_DELAY_PERIOD;
/* DEFINITION USED BY CCT */
extern SensorInfo g_CCT_MainSensor;
extern kal_uint8 g_CCT_FirstGrabColor;
/* CAMERA PREVIEW FRAME RATE DEFINITION */
#define CAM_PREVIEW_15FPS
// #define CAM_PREVIEW_22FPS
// #define CAM_PREVIEW_30FPS
#define SYSTEM_CLK (48*1000*1000)
/* PIXEL CLOCK USED BY BANDING FILTER CACULATION*/
#if defined(CAM_PREVIEW_15FPS)
#define PIXEL_CLK (SYSTEM_CLK/8) // 52/8 MHz
#elif defined(CAM_PREVIEW_22FPS)
#define PIXEL_CLK (SYSTEM_CLK/6) // 52/6 MHz
#elif defined(CAM_PREVIEW_30FPS)
#define PIXEL_CLK (SYSTEM_CLK/4) // 52/4 MHz
#endif
/* MAX/MIN FRAME RATE (FRAMES PER SEC.) */
#define MAX_FRAME_RATE 15 // Limitation for MPEG4 Encode Only
#define MIN_FRAME_RATE 12
/* LINE NUMBERS IN MAX_FRAME_RATE */
#define MIN_LINES_PER_FRAME ((SYSTEM_CLK/8/MAX_FRAME_RATE)/VGA_PERIOD_PIXEL_NUMS)
/* SENSOR GLOBAL GAIN AT NIGHT MODE */
#define SENSOR_NIGHT_MODE_GAIN 0x08
/* SENSOR PIXEL/LINE NUMBERS IN ONE PERIOD */
#define VGA_PERIOD_PIXEL_NUMS 784
#define VGA_PERIOD_LINE_NUMS 510
/* SENSOR EXPOSURE LINE LIMITATION */
#define VGA_EXPOSURE_LIMITATION 510
/* 1M RESOLUTION SIZE */
#define IMAGE_SENSOR_1M_WIDTH 1280
#define IMAGE_SENSOR_1M_HEIGHT 960
/* SENSOR VGA SIZE */
#define IMAGE_SENSOR_VGA_WIDTH 640
#define IMAGE_SENSOR_VGA_HEIGHT 480
/* SETUP TIME NEED TO BE INSERTED */
#define IMAGE_SENSOR_VGA_INSERTED_PIXELS 133
#define IMAGE_SENSOR_VGA_INSERTED_LINES 16
/* SENSOR READ/WRITE ID */
#define BF3703_WRITE_ID 0xdc
#define BF3703_READ_ID 0xdd
/* SENSOR CHIP VERSION */
#define BF3703_SENSOR_ID 0x3703
// BB's reset pin high low control MACROs
#define RESET_PIN_LOW (REG_ISP_CMOS_SENSOR_MODE_CONFIG &= ~REG_CMOS_SENSOR_RESET_BIT)
#define RESET_PIN_HIGH (REG_ISP_CMOS_SENSOR_MODE_CONFIG |= REG_CMOS_SENSOR_RESET_BIT)
#define PWRDN_PIN_LOW (REG_ISP_CMOS_SENSOR_MODE_CONFIG &= ~REG_CMOS_SENSOR_POWER_ON_BIT)
#define PWRDN_PIN_HIGH (REG_ISP_CMOS_SENSOR_MODE_CONFIG |= REG_CMOS_SENSOR_POWER_ON_BIT)
#ifdef MCU_104M
#define SENSOR_I2C_DELAY 0xFF
#else
#define SENSOR_I2C_DELAY 0x10
#endif
#define I2C_START_TRANSMISSION \
{ \
volatile kal_uint32 j; \
SET_SCCB_CLK_OUTPUT; \
SET_SCCB_DATA_OUTPUT; \
SET_SCCB_CLK_HIGH; \
SET_SCCB_DATA_HIGH; \
for(j=0;j<SENSOR_I2C_DELAY;j++);\
SET_SCCB_DATA_LOW; \
for(j=0;j<SENSOR_I2C_DELAY;j++);\
SET_SCCB_CLK_LOW; \
}
#define I2C_STOP_TRANSMISSION \
{ \
volatile kal_uint32 j; \
SET_SCCB_CLK_OUTPUT; \
SET_SCCB_DATA_OUTPUT; \
SET_SCCB_CLK_LOW; \
SET_SCCB_DATA_LOW; \
for(j=0;j<SENSOR_I2C_DELAY;j++);\
SET_SCCB_CLK_HIGH; \
for(j=0;j<SENSOR_I2C_DELAY;j++);\
SET_SCCB_DATA_HIGH; \
}
#endif /* _IMAGE_SENSOR_H */
<file_sep>/network/route/src/inc/common.h
/******************************************************************************
文 件 名 : common.h
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月11日
最近修改 :
功能描述 : 通用 的头文件
******************************************************************************/
#ifndef __COMMON_H__
#define __COMMON_H__
/*----------------------------------------------*
* 标准库头文件 *
*----------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <termios.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <netinet/ether.h>
#include <netinet/udp.h>
#include <netinet/tcp.h>
#include <netinet/ip.h>
#include <net/if.h>
#include <net/ethernet.h>
#include <netpacket/packet.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <semaphore.h>
/*----------------------------------------------*
* 宏定义 *
*----------------------------------------------*/
#define uint unsigned int
#define uint16 unsigned short
#define ulint unsigned long
#define uchar unsigned char
#define TRUE (1)
#define FALSE (0)
#define MS (1000)
#define MAX_PORT 16
#define RULE_LEN 32
#define PASSWD_LEN 9 // 密码最长 8 位 最后以为用于保存 \0
#define ENCRYPT_KEY (23)
#define ROOT_PASSWD "<PASSWORD>"
/*----------------------------------------------*
* 枚举类型定义 *
*----------------------------------------------*/
#undef TRUE
#undef FALSE
typedef enum _boolean
{
FALSE = 0,
TRUE = 1,
}Boolean;
typedef enum _type
{
MAC = 0,
IP = 1,
PORT = 2,
PRO = 3,
}TYPE_Rule;
typedef enum _status
{
DOWN = 0,
UP = 1,
}STATUS;
/*----------------------------------------------*
* 结构体类型定义 *
*----------------------------------------------*/
typedef struct _firewall
{
char rule[RULE_LEN];
struct _firewall *next;
}FIRE_Wall;
typedef struct _arphdr
{
uint16 ar_hrd;
uint16 ar_pro;
uint16 ar_hln;
uint16 ar_pln;
uint16 ar_op;
uchar src_mac[6];
uchar src_ip[4];
uchar dst_mac[6];
uchar dst_ip[4];
}ARP_Hdr;
typedef struct _msg
{
uchar dst_mac[6];
uchar src_mac[6];
uchar dst_ip[4];
uchar src_ip[4];
uint16 frame_type;
uchar pro_type;
uint16 s_port;
uint16 d_port;
int len;
int port;
}MSG_Info;
typedef struct _eth_port
{
char name[20]; //接口名称
uchar ip[4]; //ip地址
uchar mac[6]; //mac地址
uchar netmask[4];//子网掩码
uchar bc_ip[4]; //广播地址
STATUS status;
}ETH_Port;
typedef struct _arp_table
{
unsigned char ip[4];
unsigned char mac[6];
struct _arp_table *next;
}ARP_Table;
typedef struct _route
{
uchar recv[2048];
char passwd[PASSWD_LEN];
int raw_fd; // 原始套接字
int sockfd; // 监听套接字
int connfd; // 连接套接字
int port_num; // 接口总数
STATUS fire_status;
pthread_t pth_getmsg;
pthread_t pth_keyeve;
pthread_mutex_t mutex;
struct _arp_table *arp_head;
struct _firewall *ip_head;
struct _firewall *mac_head;
struct _firewall *port_head;
struct _firewall *pro_head;
struct _eth_port eth_port[MAX_PORT];
struct ether_header *eth_hdr;
struct _arphdr *arp_hdr;
struct iphdr *ip_hdr;
struct tcphdr *tcp_hdr;
struct udphdr *udp_hdr;
struct sockaddr_in s_addr;
struct sockaddr_ll sll;
struct ifreq ethreq;
}TYPE_Route;
#endif
<file_sep>/network/5th_day/arp.c
/* ************************************************************************
* Filename: arp.c
* Description:
* Version: 1.0
* Created: 2015年09月08日 15时05分02秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netpacket/packet.h>
#include <net/if.h>
#include <netinet/ether.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
int i = 0;
//创建原始套接字
int sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
unsigned char send_msg[1024] = {
//-----组MAC----14----
0xff,0xff,0xff,0xff,0xff,0xff,//dst_mac: ff:ff:ff:ff:ff:ff
0x00,0x0c,0x29,0xe4,0xd3,0xd6,//src_mac: 00:0c:29:e4:d3:d6
0x08,0x06, //类型: 0x0806 ARP协议
//-----组ARP----28----
0x00,0x01,0x08,0x00, //硬件类型1(以太网地址),协议类型0x0800(IP)
0x06,0x04,0x00,0x01, //硬件、协议的地址长度分别为6和4,ARP请求
0x00,0x0c,0x29,0xe4,0xd3,0xd6,//发送端的mac
10, 221, 2, 221, //发送端的IP
0x00,0x00,0x00,0x00,0x00,0x00,//目的mac(获取对方的mac,设置为0)
10, 221, 2, 255, //目的IP
};
//数据初始化
struct sockaddr_ll sll;
struct ifreq ethreq;
bzero(&sll, sizeof(sll));
strncpy(ethreq.ifr_name,"eth0", IFNAMSIZ); //指定网卡名称
ioctl(sockfd, SIOCGIFINDEX, (char *)ðreq); //获取网络接口
sll.sll_ifindex = ethreq.ifr_ifindex; //将网络接口赋值给原始套接字地址结构
for(i=1;i<50;i++)
{
send_msg[41] = i;
sendto(sockfd, send_msg, 42, 0, (struct sockaddr *)&sll, sizeof(sll));
//接收对方的ARP应答
unsigned char recv_msg[1024] = "";
recvfrom(sockfd, recv_msg, sizeof(recv_msg), 0, NULL, NULL);
if(recv_msg[21] == 2) //ARP应答
{
unsigned char resp_mac[18] = "";
unsigned char resp_ip[16] = "";
//提取mac地址
sprintf(resp_mac, "%02x:%02x:%02x:%02x:%02x:%02x", \
recv_msg[22],recv_msg[23],recv_msg[24],recv_msg[25],recv_msg[26],recv_msg[27]);
//提取ip
sprintf(resp_ip,"%d.%d.%d.%d",\
recv_msg[28],recv_msg[29],recv_msg[30],recv_msg[31]);
printf("IP:%s -- %s\n",resp_ip,resp_mac);
}
}
close(sockfd);
return 0;
}
<file_sep>/work/test/cim_test-zmm220/cim.h
#ifndef __CIM_H__
#define __CIM_H__
/*
typedef unsigned int u32;
typedef unsigned char BYTE;
typedef unsigned char u8;
*/
/* timing parameters */
typedef struct
{
unsigned long mclk_freq;
unsigned int pclk_active_direction;//o for rising edge, 1 for falling edge
unsigned int hsync_active_level;
unsigned int vsync_active_level;
} TIMING_PARAM;
/* image parameters */
typedef struct
{
unsigned int width; /* width */
unsigned int height; /* height */
unsigned int bpp; /* bits per pixel: 8/16/32 */
} IMG_PARAM;
/* image format */
typedef enum {
NO_FORMAT = 0,
YUV422_SEP,
YUV422_PACK,
RGB565,
RGB888,
RAW
} img_format_t;
int cim_open(int id,int width, int height, int bpp);
void cim_close(int id);
int cim_read(unsigned char id,unsigned char *buf, int frame_size);
int set_timing_param(int id,TIMING_PARAM *timing);
void *cim_mmap(int id, unsigned int size);
#endif /* __CIM_H__ */
<file_sep>/c/lrc/process_lrc.c
/* ************************************************************************
* Filename: process_lrc.c
* Description:
* Version: 1.0
* Created: 2015年07月31日 星期五 09時17分27秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include "common.h"
#include "console.h"
#include "link.h"
#include "file.h"
int src_segment(char *lrc_src, char *plines[], char *str)
{
int i = 0;
plines[0] = strtok(lrc_src, str);
while(plines[i++] != NULL)
{
plines[i] = strtok(NULL, str);
}
//printf("i=%d\n",i);
return (i-1);
}
int line_segment(char *pline, char *pbuf[], char *str)
{
int i = 0;
pbuf[0] = strtok(pline, str);
while(pbuf[i++] != NULL)
{
pbuf[i] = strtok(NULL, str);
//printf("%s\n",pbuf[i]);
}
//printf("i=%d\n",i);
return (i-1);
}
LRC *build_link(char *plines[], char *pheader[], int lines)
{
int i, j;
int part = 0;
LRC lyric, *lrc_head = NULL;
for(i=0;plines[i] != NULL && i<lines;i++)
{
#if 0
char *pbuf[10] = {NULL};
part = line_segment(plines[i],pbuf, "]"); //切割一行
for(j=0;j<part;j++)
{
int min = 0,sec = 0, msec = 0;
printf("%s\n",pbuf[j]);
}
#elif 1
if(i<4) //
{
char *trash = NULL;
//char msg[100]; sscanf 按给定格式输出内容放到一个足够大的空间
//sscanf(plines[i],"%*[^:]%*1s%[^]]",msg[0]);
trash = strtok(plines[i],":]");
if(trash != NULL) pheader[i] = strtok(NULL,":]");
}
else
{
char *pbuf[10] = {NULL};
char tbuf[10] = {0};
int min = 0, sec = 0, msec = 0;
//float sec;
part = line_segment(plines[i],pbuf, "]"); //切割一行
for(j=0;j<part-1;j++)
{
if(pbuf[part-1][0] != '[')
{
sscanf(pbuf[j],"[%2d:%2d.%2d",&min,&sec,&msec);
//printf("%2d:%2d.%2d\n",min,sec,msec);
lyric.time = (min * 60 + sec)*1000 + msec*10; //毫秒
lyric.psrc = pbuf[part-1];
lrc_head = insert_link(lrc_head,lyric);
//printf("%4d %s\n",lyric.time, lyric.psrc);
}
}
}
#endif
}
return lrc_head;
}
void show_lyric(LRC *pnode, int longest)
{
char *empty = " ";
char *pbuf[12];
int i = 0, offset = 0;
LRC *pb = NULL, *pf = NULL;
pb = pnode;
pf = pnode->next;
for(i=4;i>=0;i--)
{
if(pb != NULL)
{
pbuf[i] = pb->psrc;
pb = pb->prev;
}
else
{
pbuf[i] = empty;
}
}
for(i=5;i<12;i++)
{
if(pf != NULL)
{
pbuf[i] = pf->psrc;
pf = pf->next;
}
else
{
pbuf[i] = empty;
}
}
for(i = 0;i < 12;i++) //
{
cusor_moveto(60, 17+i); //光标移到 第4+i行,第20列
printf("%-36s",empty); //清除上次的显示
fflush(stdout);
}
for(i = 0;i < 12;i++)
{
offset = get_showoffset(pbuf[i],longest);
cusor_moveto(60+offset, 17+i); //光标移到 第10+i行,第50列
set_fg_color(COLOR_WHITE);
if(i == 4)
{
set_fg_color(COLOR_MAGENTA);
}
printf("%-36s",pbuf[i]);
}
//cusor_moveto(9, 33);
fflush(stdout);
}
int get_maxtime(LRC *head)
{
int maxtime = 0;
LRC *pb = head;
while(pb->next != NULL) pb = pb->next;
maxtime = pb->time;
return (maxtime + 12 * 1000); //ms
}
int get_timelag(LRC *head)
{
int maxtime = 0;
LRC *pb = head;
while(pb->next != NULL) pb = pb->next;
maxtime = pb->time;
return (maxtime + 12 * 1000)/60; //ms
}
<file_sep>/shell/2nd_week/sh
#!/bin/bash
echo $1
if [ $1 -lt 60 ]
then
echo "E"
elif [ $1 -lt 69 -a $1 -gt 60 ]
then
echo "D"
elif [ $1 -lt 79 -a $1 -gt 69 ]
then
echo "C"
fi
<file_sep>/c/practice/binary_search.c
/*=========================================================================
工程名称: 练习
组成文件: main.c
功能描述: 在一个排好序的数据中用二分查找法,找出需要的数据
程序分析: 首先得从小到大排好序,二分再比较,不等则继续二分,直到高低碰头遍历结束
维护记录: 2010-09-11 v1.1
=========================================================================*/
#include <stdio.h>
//二分法对以排好序的数据进行查找
int binary_search(int array[],int value,int size)
{
int low=0,high=size-1,mid;
while(low<=high) //只要高低不碰头就继续二分查找
{
mid=(low+high)/2;
if(value==array[mid]) //比较是不是与中间元素相等
return mid;
else if(value > array[mid]) //每查找一次,就判断一次所要查找变量所在范围,并继续二分
low=mid + 1; //如果大小中间值,下限移到中间的后一个位,上限不变,往高方向二分
else
high=mid - 1; //上限移到中间的前一个位,往低方向二分
}
return -1;
}
int main(void)
{
int value;
int a[10]={0,1,2,3,4,5,6,7,8,9};
int n;
while(1)
{
printf("\n请输入你要查找的数字:\n");
scanf("%d",&value);
n = binary_search(a,value,10);
if(n==-1)
printf("数字没找到!\n");
else
printf("查找数据的下标是:%d\n",n);
}
}
<file_sep>/c/homework/3rd_week/message/msg.h
/* ************************************************************************
* Filename: msg.h
* Description:
* Version: 1.0
* Created: 2015年07月27日 星期一 02時29分22秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __MSG_H__
#define __MSG_H__
extern void show_number(const char *src);
extern void show_time( char *src1,char *src2);
extern void show_content(const char *src);
extern void show_message(char **src);
extern int msg_deal(char *msg_src, char *msg_done[],char *str);
#endif
<file_sep>/work/test/netlink/netlink_test.c
/*************************************************************************
> File Name: netlink_test.c
> Author:
> Mail:
> Created Time: Thu 01 Sep 2016 12:24:14 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/socket.h>
#define NETLINK_TEST 17
#define MAX_PAYLOAD 1024
struct sockaddr_nl src_addr, dest_addr;
struct nlmsghdr *nlh = NULL;
struct iovec iov;
struct msghdr msg;
int sock_fd;
int main(int argc, const char *argv[])
{
sock_fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_TEST);
memset(&msg, 0, sizeof(struct msghdr));
memset(&src_addr, 0, sizeof(struct sockaddr_nl));
src_addr.nl_family = AF_NETLINK;
src_addr.nl_pid = getpid(); // self pid
src_addr.nl_groups = 0;
bind(sock_fd, (struct sockaddr *)&src_addr, sizeof(src_addr));
memset(&dest_addr, 0, sizeof(struct sockaddr_nl));
dest_addr.nl_family = AF_NETLINK;
dest_addr.nl_pid = 0; // for linux kernel
dest_addr.nl_groups = 0; // unicast
nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD));
// fill the netlink message header
nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
nlh->nlmsg_pid = getpid();
nlh->nlmsg_flags = 0;
// fill in the netlink message payload
strcpy(NLMSG_DATA(nlh), "This is a test!");
iov.iov_base = (void *)nlh;
iov.iov_len = nlh->nlmsg_len;
msg.msg_name = (void *)&dest_addr;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
sendmsg(sock_fd, &msg, 0);
// read messsage from kernel
memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));
recvmsg(sock_fd, &msg, 0);
printf("Received message payload: %s\n", NLMSG_DATA(nlh));
// close netlink socket
close(sock_fd);
return 0;
}
<file_sep>/c/mkheader/loader.c
/*************************************************************************
> Filename: loader.c
> Author:
> Email:
> Datatime: 2017年02月24日 星期五 22时34分02秒
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char *argv[])
{
if (argc > 1) {
FILE *fp;
FILE *fp_n;
char *app_buf;
uint32_t length;
fp = fopen("./app", "rb");
if (fp == NULL) {
printf("Cannot open file!\n");
return -1;
}
fseek(fp, 0, SEEK_SET);
fread(&length, sizeof(length), 1, fp);
printf("read length=%d\n", length);
app_buf = (char *)malloc(length);
if (app_buf == NULL) {
printf("Failed to malloc mem\n");
return -1;
}
bzero(app_buf, length);
fp_n = fopen("./n_app", "ab+");
if (fp_n == NULL) {
printf("Cannot open new file!\n");
return -1;
}
fread(app_buf, length, 1, fp);
fwrite(app_buf, length, 1, fp_n);
fclose(fp);
fclose(fp_n);
free(app_buf);
} else {
int fd;
int fd_n;
uint32_t length;
char *app_buf;
fd = open("./app", O_RDONLY);
if (fd < 0) {
printf("Cannot open app file\n");
return -1;
}
read(fd, (void *)&length, sizeof(length));
printf("read length=%d\n", length);
app_buf = (char *)malloc(length);
if (app_buf == NULL) {
printf("Failed to malloc mem\n");
return -1;
}
bzero(app_buf, length);
read(fd, app_buf, length);
fd_n = open("./n_app", O_RDWR | O_CREAT);
if (fd_n < 0) {
printf("Cannot open n_app file\n");
return -1;
}
write(fd_n, app_buf, length);
fsync(fd_n);
fchmod(fd_n, 0775);
close(fd);
close(fd_n);
free(app_buf);
}
return 0;
}
<file_sep>/sys_program/7th_day/leds.c
/* ************************************************************************
* Filename: leds.c
* Description:
* Version: 1.0
* Created: 2015年08月21日 11时59分31秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "s5pv210-gpio.h"
int main(int argc, char *argv[])
{
return 0;
}
<file_sep>/sys_program/6th_day/sem.c
/* ************************************************************************
* Filename: sem.c
* Description:
* Version: 1.0
* Created: 2015年08月20日 12时00分54秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t sem1;
void print(char *str)
{
sem_wait(&sem1);
while(*str != '\0')
{
putchar(*str++);
fflush(stdout);
sleep(1);
}
putchar('\n');
sem_post(&sem1);
}
void *fun1(void *arg)
{
char *buf = "world";
print(buf);
}
void *fun2(void *arg)
{
char *buf = "hello";
print(buf);
}
int main(int argc, char *argv[])
{
int val = 0;
pthread_t pth1,pth2;
sem_init(&sem1,0,1);
sem_getvalue(&sem1,&val);
printf("sem_val = %d\n",val);
pthread_create(&pth1,NULL,fun1,NULL);
pthread_create(&pth2,NULL,fun2,NULL);
pthread_join(pth1,NULL);
pthread_join(pth2,NULL);
val = sem_destroy(&sem1);
if(val==0)
{
printf("delete sem succeed\n");
}
return 0;
}
<file_sep>/c/homework/1st_week/petrol.c
/* ************************************************************************
* Filename: petrol.c
* Description:
* Version: 1.0
* Created: 2015年07月20日 星期一 09時36分43秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#define APRICE (1.50f)
#define BPRICE (1.35f)
#define CPRICE (1.18f)
typedef enum
{
agas = 'a',
bgas = 'b',
cgas = 'c',
}GAS;
typedef enum
{
ato = 'f',
own = 'm',
ass = 'e',
}SERVER;
float get_gasoline(char service, char gasoline, float kg)
{
float gas_price;
float discount;
switch(service)
{
case ato: discount = 0.00f; break;
case own: discount = 0.05f; break;
case ass: discount = 0.10f; break;
}
switch(gasoline)
{
case agas:
{
gas_price = (APRICE * (1-discount)) * kg;
break;
}
case bgas:
{
gas_price = (BPRICE * (1-discount)) * kg;
break;
}
case cgas:
{
gas_price = (CPRICE * (1-discount)) * kg;
break;
}
}
return gas_price;
}
int main(int argc, char *argv[])
{
float price;
float kg;
char service,gasoline,temp;
printf("请选择服务类型,输入:f | m | e\n");
printf("f--自动服务,无优惠!\n");
printf("m--自助服务,优惠%5!\n");
printf("e--协助服务,优惠%10!\n");
scanf("%c%c",&service,&temp);
// service = getchar();
printf("请选择汽油类型,输入:a | b | c\n");
scanf("%c",&gasoline);
// gasoline = getchar();
printf("请输入本次加油量,单位:KG\n");
scanf("%f",&kg);
price = get_gasoline(service,gasoline,kg);
printf("本次加油总价为 %.2f 元\n",price);
return 0;
}
<file_sep>/work/test/mplay/tcp_server.c
/*************************************************************************
> File Name: tcp_server.c
> Author:
> Mail:
> Created Time: Mon 17 Oct 2016 10:53:42 AM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int create_tcp_server(unsigned short port)
{
int listen_sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in s_addr;
bzero(&s_addr, sizeof(s_addr));
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(port);
s_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(listen_sock, (struct sockaddr *)&s_addr, sizeof(s_addr));
if(ret != 0) {
perror("bind():");
return -1;
}
listen(listen_sock, 10);
return listen_sock;
}
int recv_client_data(int listen_sock)
{
fd_set rfds;
struct timeval tv = {0, 100*1000};
static int client = -1;
int max, ret, index = -1;
FD_ZERO(&rfds);
FD_SET(listen_sock, &rfds);
if(client != -1)
FD_SET(client, &rfds);
max = listen_sock > client ? listen_sock : client;
ret = select(max+1, &rfds, NULL, NULL, &tv);
if(ret > 0) {
if(FD_ISSET(listen_sock, &rfds)) {
struct sockaddr_in c_addr;
socklen_t addr_len = sizeof(c_addr);
bzero(&c_addr, addr_len);
if(client != -1)
close(client);
client = accept(listen_sock, (struct sockaddr *)&c_addr, &addr_len);
}
if(client != -1 && FD_ISSET(client, &rfds)) {
ret = read(client, &index, sizeof(index));
if(ret != sizeof(index)) {
close(client);
client = -1;
index = -1;
}
}
}
return index;
}
<file_sep>/sys_program/4th_day/rcv.c
/* ************************************************************************
* Filename: rcv.c
* Description:
* Version: 1.0
* Created: 2015年08月18日 15时44分30秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <string.h>
#include <unistd.h>
typedef struct _msg
{
long type;
char mutex[100];
}MSG;
int main(int argc, char *argv[])
{
key_t key;
int id;
MSG rcv1, rcv2;
key = ftok("./", 23);
id = msgget(key, IPC_CREAT | 0666);
msgrcv(id, &rcv1,sizeof(rcv1)-4, 10, 0); //0:msgrcv调用阻塞直到接收消息成功为止;成功返回消息长度
printf("rcv1 = %s\n",rcv1.mutex);
msgrcv(id, &rcv2,sizeof(rcv2)-4, 1, 0);
printf("rcv2 = %s\n",rcv2.mutex);
#ifdef P
printf("this is a test\n");
#endif
return 0;
}
<file_sep>/gtk/1. base/08_key_event/key_event.c
#include <gtk/gtk.h> // 头文件
#include <gdk/gdkkeysyms.h> //键盘头文件
// 键盘按下事件处理函数
gboolean deal_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
{
switch(event->keyval){ // 键盘键值类型
case GDK_Up:
g_print("Up\n");
break;
case GDK_Left:
g_print("Left\n");
break;
case GDK_Right:
g_print("Right\n");
break;
case GDK_Down:
g_print("Down\n");
break;
}
int key = event->keyval; // 获取键盘键值类型
g_print("keyval = %d\n", key);
return TRUE;
}
int main( int argc, char *argv[] )
{
gtk_init(&argc, &argv); // 初始化
// 创建顶层窗口
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
// 设置窗口的标题
gtk_window_set_title(GTK_WINDOW(window), "mouse_event");
// 设置窗口在显示器中的位置为居中
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
// 设置窗口的最小大小
gtk_widget_set_size_request(window, 400, 300);
// "destroy" 和 gtk_main_quit 连接
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
// "key-press-event" 与 deal_key_press 连接
g_signal_connect(window, "key-press-event", G_CALLBACK(deal_key_press), NULL);
gtk_widget_show_all(window); // 显示窗口全部控件
gtk_main(); // 主事件循环
return 0;
}<file_sep>/sys_program/4th_day/homework/mplayer/image.c
/* ************************************************************************
* Filename: image.c
* Description:
* Version: 1.0
* Created: 2015年08月11日 14时47分17秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <gtk/gtk.h>
// 给创建好的image重新设计一张图片
void load_image(GtkWidget *image, const char *file_path, const int w, const int h )
{
gtk_image_clear( GTK_IMAGE(image) ); // 清除图像
GdkPixbuf *src_pixbuf = gdk_pixbuf_new_from_file(file_path, NULL); // 创建图片资源
GdkPixbuf *dest_pixbuf = gdk_pixbuf_scale_simple(src_pixbuf, w, h, GDK_INTERP_BILINEAR); // 指定大小
gtk_image_set_from_pixbuf(GTK_IMAGE(image), dest_pixbuf); // 图片控件重新设置一张图片(pixbuf)
g_object_unref(src_pixbuf); // 释放资源
g_object_unref(dest_pixbuf); // 释放资源
}
// 根据图片路径创建一个新按钮,同时指定图片大小
GtkWidget *create_button_from_file(const char *file_path, const int w, const int h)
{
GtkWidget *temp_image = gtk_image_new_from_pixbuf(NULL);
load_image(temp_image, file_path, w, h);
GtkWidget *button = gtk_button_new(); // 先创建空按钮
gtk_button_set_image(GTK_BUTTON(button), temp_image); // 给按钮设置图标
gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE); // 按钮背景色透明
return button;
}
/* 功能: 设置背景图
* widget: 主窗口
* w, h: 图片的大小
* path: 图片路径
*/
void chang_background(GtkWidget *widget, int w, int h, const gchar *path)
{
gtk_widget_set_app_paintable(widget, TRUE); //允许窗口可以绘图
gtk_widget_realize(widget);
/* 更改背景图时,图片会重叠
* 这时要手动调用下面的函数,让窗口绘图区域失效,产生窗口重绘制事件(即 expose 事件)。
*/
gtk_widget_queue_draw(widget);
GdkPixbuf *src_pixbuf = gdk_pixbuf_new_from_file(path, NULL); // 创建图片资源对象
// w, h是指定图片的宽度和高度
GdkPixbuf *dst_pixbuf = gdk_pixbuf_scale_simple(src_pixbuf, w, h, GDK_INTERP_BILINEAR);
GdkPixmap *pixmap = NULL;
/* 创建pixmap图像;
* NULL:不需要蒙版;
* 123: 0~255,透明到不透明
*/
gdk_pixbuf_render_pixmap_and_mask(dst_pixbuf, &pixmap, NULL, 50);
// 通过pixmap给widget设置一张背景图,最后一个参数必须为: FASLE
gdk_window_set_back_pixmap(widget->window, pixmap, FALSE);
// 释放资源
g_object_unref(src_pixbuf);
g_object_unref(dst_pixbuf);
g_object_unref(pixmap);
}
<file_sep>/shell/2nd_week/b.sh
#!/bin/bash
str=" I love linux.I love UNIX too."
str2="$str"
#str2=${str/love/like}
echo "str =$str"
echo "str2=$str2"
exit
str="I love linux, I love GNU too."
echo ${str%,*.}
exit
echo -n "input a string:"
#read -s -p "input a string:" str
read str
echo "$str"
unset color
echo "the shy is ${color:-grey} today"
echo "$color"
echo "the sky is ${color:=grey} today"
echo "$color"
color=yellow
echo "the shy is ${color:?error} today"
echo "$color"
echo "the shy is ${color:+blue} today"
echo "$color"
<file_sep>/c/practice/3rd_week/time/main.c
/* ************************************************************************
* Filename: main.c
* Description:
* Version: 1.0
* Created: 2015年07月28日 星期二 05時13分34秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "show_time.h"
void main()
{
show_time();
}
<file_sep>/work/debug/pc/sync/sync_drv.c
/* ************************************************************************
* Filename: sync_drv.c
* Description:
* Version: 1.0
* Created: 2015年11月11日 10时57分49秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <linux/miscdevice.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/moduleparam.h>
#include <linux/errno.h>
#include <linux/ioctl.h>
#include <linux/cdev.h>
#include <linux/string.h>
#include <linux/list.h>
#include <linux/poll.h>
#include <linux/fcntl.h>
#include <linux/signal.h> //for SIGIO,POLL_IN
#include <linux/timer.h>
#include <linux/jiffies.h>
#define DEVICE_NAME "sync"
static struct timer_list sync_timer;
static struct fasync_struct *sync_queue;
static void sync_timerhandler(unsigned long arg)
{
//发送信号到用户空间,通知相关进程
kill_fasync(&sync_queue, SIGIO, POLL_IN);
mod_timer(&sync_timer,jiffies + HZ); //更新定时器,不更新的话,定时器处理函数只执行一次
}
static int sync_open(struct inode *pinode, struct file *filp)
{
init_timer(&sync_timer); // 初始化定时器
sync_timer.data = 0; // 传递给定时器处理函数的参数
sync_timer.function = sync_timerhandler; // 定时器处理函数
sync_timer.expires = jiffies + HZ;
add_timer(&sync_timer); // 启动定时器
return 0;
}
static int sync_fasync(int fd, struct file *filp, int mode)
{
//根据用户空间的需要,获取或设置相应的属性
return fasync_helper(fd, filp, mode, &sync_queue);
}
static int sync_close(struct inode *pinode, struct file *filp)
{
del_timer_sync(&sync_timer); // 删除定时器,在定时器时间到前停止一个已注册的定时器
sync_fasync(-1, filp, 0); // 将文件从异步通知列表中删除
return 0;
}
static struct file_operations sync_fops = {
.owner = THIS_MODULE,
.open = sync_open,
.fasync = sync_fasync,
.release = sync_close,
};
static struct miscdevice sync_misc = { /*杂项字符设备结构体*/
.minor = MISC_DYNAMIC_MINOR, /*次设备号 表示自动分配*/
.name = DEVICE_NAME, /*设备名*/
.fops = &sync_fops, /*设备操作*/
};
static __init int sync_init(void)
{
int ret;
ret = misc_register(&sync_misc);
if(ret < 0)
printk(DEVICE_NAME "can't register\n");
else
printk(DEVICE_NAME "register successful\n");
return ret;
}
static __exit void sync_exit(void)
{
misc_deregister(&sync_misc);
printk("unregister success \n");
}
module_init(sync_init);
module_exit(sync_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/test/yuv2bmp/conver.c
/*
##############################################################################
# Raw Image Player [ImPlayer] #
# Copyright 2000 <NAME> and <NAME> #
# Video Signal Processing Lab, Dept.EE, NTHU #
# Version 1.5 Created 2/1/2000 #
##############################################################################
# COPYRIGHT NOTICE #
# Copyright 2000 <NAME> and <NAME>, All Rights Reserved. #
# #
# [ImPlayer] may be used and modified free of charge by anyone so long as #
# this copyright notice and the comments above remain intact. By using this #
# code you agree to indemnify Yao-Jen Chang from any liability that might #
# arise from it's use. #
# #
# Comments, feedback, bug reports, improvements are encouraged. Please sent #
# them to <EMAIL>. #
##############################################################################
*/
/************************************************************************
*
* yuvrgb24.c, colour space conversion for tmndecode (H.263 decoder)
* Copyright (C) 1995, 1996 Telenor R&D, Norway
* <NAME> <<EMAIL>>
*
* Contacts:
* <NAME> <<EMAIL>>, or
* <NAME> <<EMAIL>>
*
* Telenor Research and Development http://www.nta.no/brukere/DVC/
* P.O.Box 83 tel.: +47 63 84 84 00
* N-2007 Kjeller, Norway fax.: +47 63 81 00 76
*
************************************************************************/
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any
* license fee or royalty on an "as is" basis. Telenor Research and
* Development disclaims any and all warranties, whether express,
* implied, or statuary, including any implied warranties or
* merchantability or of fitness for a particular purpose. In no
* event shall the copyright-holder be liable for any incidental,
* punitive, or consequential damages of any kind whatsoever arising
* from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs
* and user's customers, employees, agents, transferees, successors,
* and assigns.
*
* Telenor Research and Development does not represent or warrant that
* the programs furnished hereunder are free of infringement of any
* third-party patents.
*
* Commercial implementations of H.263, including shareware, are
* subject to royalty fees to patent holders. Many of these patents
* are general enough such that they are unavoidable regardless of
* implementation design.
* */
#include "futil.h"
static unsigned char* clp = NULL;
static int crv_tab[256]={0};
static int cbu_tab[256]={0};
static int cgu_tab[256]={0};
static int cgv_tab[256]={0};
static int tab_76309[256]={0};
static int bilevel_tab_76309[256]={0};
BITMAPINFO bmi;
static int inited = 0;
static int init_clp()
{
int i;
if(clp == NULL)
{
clp = (unsigned char*)malloc(1024);
if(clp == NULL)
{
printf("init_clp malloc failed \r\n");
return -1;
}
}else
{
printf("init_clp always inited \r\n");
return 0;
}
clp += 384;
for (i=-384; i<640; i++)
{
clp[i] = (i<0) ? 0 : ((i>255) ? 255 : i);
}
return 0;
}
static void init_dither_tab()
{
long int crv,cbu,cgu,cgv;
int i;
crv = 104597; cbu = 132201; /* fra matrise i global.h */
cgu = 25675; cgv = 53279;
for (i = 0; i < 256; i++) {
crv_tab[i] = (i-128) * crv;
cbu_tab[i] = (i-128) * cbu;
cgu_tab[i] = (i-128) * cgu;
cgv_tab[i] = (i-128) * cgv;
tab_76309[i] = 76309*(i-16);
}
bilevel_tab_76309[0] = tab_76309[0];
for (i = 1; i < 256; i++) {
bilevel_tab_76309[i] = tab_76309[255];
}
}
int init_conver()
{
init_dither_tab();
if(init_clp() < 0)
{
return -1;
}
bmi.bmiHeader.biSize = (LONG)sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biCompression = 0l;
bmi.bmiHeader.biSizeImage = 0l;
bmi.bmiHeader.biXPelsPerMeter = 0l;
bmi.bmiHeader.biYPelsPerMeter = 0l;
bmi.bmiHeader.biBitCount = 24;
inited = 1;
return 0;
}
/**********************************************************************
*
* Name: ConvertYUVtoRGB
* Description: Converts YUV image to RGB (packed mode)
*
* Input: pointer to source luma, Cr, Cb, destination,
* image width and height
* Returns:
* Side effects:
*
* Date: 951208 Author: <EMAIL>
*
***********************************************************************/
void rgb5652rgb888(unsigned short* rgb565,unsigned int* rgb888,unsigned int framesize)
{
unsigned int i;
unsigned char r,g,b;
r=g=b=0;
for(i=0;i<framesize;i++)
{
r=((*((unsigned short*)rgb565 + i))>>11)&0x1f;
g=((*((unsigned short*)rgb565 + i))>>5)&0x3f;
b=(*((unsigned short*)rgb565 + i))&0x1f;
*((unsigned int*)rgb888 + i)=(r<<19)|(g<<10)|(b<<3);
}
}
/*
yuv422转换RGB565并缩小一半图像的函数
yuv422buf: input width*height picture buffer
rgb565: output width/2*height/2 picture RGB565 buffer
width: input picture width
height: input picture height
*/
int yuv422rgb565_scale(unsigned char *yuv422buf,unsigned short *rgb565,int width,int height)
{
int i, j, k, u, v, u2g, u2b, v2g, v2r, y11, y12;
int width4 = width + (4 - (width%4))%4;
unsigned short R,G,B;
unsigned char *pucy,* pucu, * pucv;
char crgbtmp;
if((yuv422buf==NULL)||(rgb565==NULL)){
return -1;
}
if(inited == 0){
if(init_conver() < 0){
return -1;
}
}
pucy = yuv422buf;
pucu = yuv422buf + width * height;
pucv = yuv422buf + width * height * 3/2;
width = width/2;
height = height/2;
k = width * (height-1); //Point to the last width_line of rgb565buf,why?
for (i = 0; i < height; i++){
for (j = 0; j < width; j+=4)
{
y11 = tab_76309[*pucy++];
y12 = tab_76309[*pucy++];
u = *pucu++;
v = *pucv++;
u2g = cgu_tab[u];
u2b = cbu_tab[u];
v2g = cgv_tab[v];
v2r = crv_tab[v];
crgbtmp = clp[(y11 + v2r)>>16];
R = ((crgbtmp >> 3)) & 0x001F;
crgbtmp = clp[(y11 - u2g - v2g)>>16];
G = ((crgbtmp >> 2)<<5) & 0x07E0;
crgbtmp = clp[(y11 + u2b)>>16];
B = ((crgbtmp >> 3)<<11) & 0xF800;
// printf(" === R = 0x%04x, G = 0x%04x B =0x%04x \n",R,G,B);
rgb565[k++] = (R | G | B);
//printf("%d rgb565[%d] = 0x%04x \n",__LINE__,k,rgb565[k]);
crgbtmp = clp[(y12 + v2r)>>16];
R = ((crgbtmp >> 3)) & 0x001F;
crgbtmp = clp[(y12 - u2g - v2g)>>16];
G = ((crgbtmp >> 2)<<5) & 0x07E0;
crgbtmp = clp[(y12 + u2b)>>16];
B = ((crgbtmp >> 3)<<11) & 0xF800;
rgb565[k++] = (R | G | B);
//Skip two pixels,because two pixels as a unit.
pucy+=2;
pucu++;
pucv++;
// Let two ALU work at the same time
y11 = tab_76309[*pucy++];
y12 = tab_76309[*pucy++];
u = *pucu++;
v = *pucv++;
u2g = cgu_tab[u];
u2b = cbu_tab[u];
v2g = cgv_tab[v];
v2r = crv_tab[v];
crgbtmp = clp[(y11 + v2r)>>16];
R = ((crgbtmp >> 3)) & 0x001F;
crgbtmp = clp[(y11 - u2g - v2g)>>16];
G = ((crgbtmp >> 2)<<5) & 0x07E0;
crgbtmp = clp[(y11 + u2b)>>16];
B = ((crgbtmp >> 3)<<11) & 0xF800;
rgb565[k++] = (R | G | B);
crgbtmp = clp[(y12 + v2r)>>16];
R = ((crgbtmp >> 3)) & 0x001F;
crgbtmp = clp[(y12 - u2g - v2g)>>16];
G = ((crgbtmp >> 2)<<5) & 0x07E0;
crgbtmp = clp[(y12 + u2b)>>16];
B = ((crgbtmp >> 3)<<11) & 0xF800;
rgb565[k++] = (R | G | B);
//Skip two pixels,because two pixels as a unit.
pucy+=2;
pucu++;
pucv++;
}
k=k - width*2;
pucy+=width4; //Skip one width_line Y,U,V
pucu+=width4/2;
pucv+=width4/2;
}
return 0;
}
/*
yuv422转换RGB565图像的函数
yuv422buf: input width*height picture buffer
rgb565: output width*height picture RGB565 buffer
width: input picture width
height: input picture height
*/
int yuv422rgb565(unsigned char *yuv422buf,unsigned short *rgb565,int width,int height)
{
int i, j, k, u, v, u2g, u2b, v2g, v2r, y11, y12;
int width4 = width + (4 - (width%4))%4;
unsigned short R,G,B;
unsigned char *pucy,* pucu, * pucv;
char crgbtmp;
if((yuv422buf==NULL)||(rgb565==NULL)){
return -1;
}
if(inited == 0){
if(init_conver() < 0){
return -1;
}
}
pucy = yuv422buf;
pucu = yuv422buf + width * height;
pucv = yuv422buf + width * height * 3/2;
k = width * (height-1); //Point to the last width_line of rgb565buf,why?
for (i = 0; i < height; i++){
for (j = 0; j < width; j+=4)
{
y11 = tab_76309[*pucy++];
y12 = tab_76309[*pucy++];
u = *pucu++;
v = *pucv++;
u2g = cgu_tab[u];
u2b = cbu_tab[u];
v2g = cgv_tab[v];
v2r = crv_tab[v];
crgbtmp = clp[(y11 + v2r)>>16];
R = ((crgbtmp >> 3)) & 0x001F;
crgbtmp = clp[(y11 - u2g - v2g)>>16];
G = ((crgbtmp >> 2)<<5) & 0x07E0;
crgbtmp = clp[(y11 + u2b)>>16];
B = ((crgbtmp >> 3)<<11) & 0xF800;
rgb565[k++] = (R | G | B);
crgbtmp = clp[(y12 + v2r)>>16];
R = ((crgbtmp >> 3)) & 0x001F;
crgbtmp = clp[(y12 - u2g - v2g)>>16];
G = ((crgbtmp >> 2)<<5) & 0x07E0;
crgbtmp = clp[(y12 + u2b)>>16];
B = ((crgbtmp >> 3)<<11) & 0xF800;
rgb565[k++] = (R | G | B);
y11 = tab_76309[*pucy++];
y12 = tab_76309[*pucy++];
u = *pucu++;
v = *pucv++;
u2g = cgu_tab[u];
u2b = cbu_tab[u];
v2g = cgv_tab[v];
v2r = crv_tab[v];
crgbtmp = clp[(y11 + v2r)>>16];
R = ((crgbtmp >> 3)) & 0x001F;
crgbtmp = clp[(y11 - u2g - v2g)>>16];
G = ((crgbtmp >> 2)<<5) & 0x07E0;
crgbtmp = clp[(y11 + u2b)>>16];
B = ((crgbtmp >> 3)<<11) & 0xF800;
rgb565[k++] = (R | G | B);
crgbtmp = clp[(y12 + v2r)>>16];
R = ((crgbtmp >> 3)) & 0x001F;
crgbtmp = clp[(y12 - u2g - v2g)>>16];
G = ((crgbtmp >> 2)<<5) & 0x07E0;
crgbtmp = clp[(y12 + u2b)>>16];
B = ((crgbtmp >> 3)<<11) & 0xF800;
rgb565[k++] = (R | G | B);
}
k=k - width*2;
}
return 0;
}
#define YCbCrtoR(Y,Cb,Cr) (1000*Y + 1371*(Cr-128))/1000
#define YCbCrtoG(Y,Cb,Cr) (1000*Y - 336*(Cb-128) - 698*(Cr-128))/1000
#define YCbCrtoB(Y,Cb,Cr) (1000*Y + 1732*(Cb-128))/1000
#define min(x1, x2) (((x1)<(x2))?(x1):(x2))
typedef unsigned char __u8;
typedef unsigned short __u16;
typedef unsigned int __u32;
__u32 Conv_YCbCr_Rgb(__u8 y0, __u8 y1, __u8 cb0, __u8 cr0)
{
// bit order is
// YCbCr = [Cr0 Y1 Cb0 Y0], RGB=[R1,G1,B1,R0,G0,B0].
int r0, g0, b0, r1, g1, b1;
__u16 rgb0, rgb1;
__u32 rgb;
#if 1 // 4 frames/s @192MHz, 12MHz ; 6 frames/s @450MHz, 12MHz
r0 = YCbCrtoR(y0, cb0, cr0);
g0 = YCbCrtoG(y0, cb0, cr0);
b0 = YCbCrtoB(y0, cb0, cr0);
r1 = YCbCrtoR(y1, cb0, cr0);
g1 = YCbCrtoG(y1, cb0, cr0);
b1 = YCbCrtoB(y1, cb0, cr0);
#endif
if (r0>255 ) r0 = 255;
if (r0<0) r0 = 0;
if (g0>255 ) g0 = 255;
if (g0<0) g0 = 0;
if (b0>255 ) b0 = 255;
if (b0<0) b0 = 0;
if (r1>255 ) r1 = 255;
if (r1<0) r1 = 0;
if (g1>255 ) g1 = 255;
if (g1<0) g1 = 0;
if (b1>255 ) b1 = 255;
if (b1<0) b1 = 0;
// 5:6:5 16bit format
rgb0 = (((__u16)r0>>3)<<11) | (((__u16)g0>>2)<<5) | (((__u16)b0>>3)<<0); //RGB565.
rgb1 = (((__u16)r1>>3)<<11) | (((__u16)g1>>2)<<5) | (((__u16)b1>>3)<<0); //RGB565.
rgb = (rgb1<<16) | rgb0;
return(rgb);
}
/*
yuv422转换RGB888并缩小一半图像的函数
yuv422buf: input width*height picture buffer
rgb888: output width/2*height/2 picture RGB888 buffer
width: input picture width
height: input picture height
*/
int yuv422rgb888_scale(unsigned char *yuv422buf,unsigned int *rgb888,int width,int height)
{
int i, j, k, u, v, u2g, u2b, v2g, v2r, y11, y12;
int width4 = width + (4 - (width%4))%4;
unsigned int R,G,B;
unsigned char *pucy,* pucu, * pucv;//, * pucraster0;
char crgbtmp;
if((yuv422buf==NULL)||(rgb888==NULL))
{
return -1;
}
if(inited == 0)
{
if(init_conver() < 0)
{
return -1;
}
}
pucy = yuv422buf;
pucu = yuv422buf + width * height;
pucv = yuv422buf + width * height * 3/2;
width = width/2;
height = height/2;
k = width * (height-1); //Point to the last width_line of rgb565buf,why?
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j+=4)
{
y11 = tab_76309[*pucy++];
y12 = tab_76309[*pucy++];
u = *pucu++;
v = *pucv++;
u2g = cgu_tab[u];
u2b = cbu_tab[u];
v2g = cgv_tab[v];
v2r = crv_tab[v];
crgbtmp = clp[(y11 + v2r)>>16];
R = crgbtmp ;
crgbtmp = clp[(y11 - u2g - v2g)>>16];
G = crgbtmp ;
crgbtmp = clp[(y11 + u2b)>>16];
B = crgbtmp;
rgb888[k++] = ((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));
crgbtmp = clp[(y12 + v2r)>>16];
R = crgbtmp ;
crgbtmp = clp[(y12 - u2g - v2g)>>16];
G = crgbtmp ;
crgbtmp = clp[(y12 + u2b)>>16];
B = crgbtmp;
rgb888[k++] = ((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));
//Skip two pixels,because two pixels as a unit.
pucy+=2;
pucu++;
pucv++;
// Let two ALU work at the same time
y11 = tab_76309[*pucy++];
y12 = tab_76309[*pucy++];
u = *pucu++;
v = *pucv++;
u2g = cgu_tab[u];
u2b = cbu_tab[u];
v2g = cgv_tab[v];
v2r = crv_tab[v];
crgbtmp = clp[(y11 + v2r)>>16];
R = crgbtmp ;
crgbtmp = clp[(y11 - u2g - v2g)>>16];
G = crgbtmp;
crgbtmp = clp[(y11 + u2b)>>16];
B = crgbtmp;
rgb888[k++] = ((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));
crgbtmp = clp[(y12 + v2r)>>16];
R = crgbtmp ;
crgbtmp = clp[(y12 - u2g - v2g)>>16];
G = crgbtmp ;
crgbtmp = clp[(y12 + u2b)>>16];
B = crgbtmp ;
rgb888[k++] = ((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));
//Skip two pixels,because two pixels as a unit.
pucy+=2;
pucu++;
pucv++;
}
k=k - width*2;
pucy+=width4; //Skip one width_line Y,U,V
pucu+=width4/2;
pucv+=width4/2;
}
return 0;
}
/*
yuv422转换RGB888图像的函数
yuv422buf: input width*height picture buffer
rgb888: output width*height picture RGB888 buffer
width: input picture width
height: input picture height
*/
int yuv422rgb888(unsigned char *yuv422buf,unsigned int *rgb888,int width,int height)
{
int i, j, k, u, v, u2g, u2b, v2g, v2r, y11, y12;
int width4 = width + (4 - (width%4))%4;
unsigned int R,G,B;
unsigned char *pucy,* pucu, * pucv;//, * pucraster0;
char crgbtmp;
if((yuv422buf==NULL)||(rgb888==NULL))
{
return -1;
}
if(inited == 0)
{
if(init_conver() < 0)
{
return -1;
}
}
pucy = yuv422buf;
pucu = yuv422buf + width * height;
pucv = yuv422buf + width * height * 3/2;
k = width * (height-1); //Point to the last width_line of rgb565buf,why?
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j+=4)
{
y11 = tab_76309[*pucy++];
y12 = tab_76309[*pucy++];
u = *pucu++;
v = *pucv++;
u2g = cgu_tab[u];
u2b = cbu_tab[u];
v2g = cgv_tab[v];
v2r = crv_tab[v];
crgbtmp = clp[(y11 + v2r)>>16];
R = crgbtmp ;
crgbtmp = clp[(y11 - u2g - v2g)>>16];
G = crgbtmp ;
crgbtmp = clp[(y11 + u2b)>>16];
B = crgbtmp;
rgb888[k++] = ((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));
crgbtmp = clp[(y12 + v2r)>>16];
R = crgbtmp ;
crgbtmp = clp[(y12 - u2g - v2g)>>16];
G = crgbtmp ;
crgbtmp = clp[(y12 + u2b)>>16];
B = crgbtmp;
rgb888[k++] = ((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));
// Let two ALU work at the same time
y11 = tab_76309[*pucy++];
y12 = tab_76309[*pucy++];
u = *pucu++;
v = *pucv++;
u2g = cgu_tab[u];
u2b = cbu_tab[u];
v2g = cgv_tab[v];
v2r = crv_tab[v];
crgbtmp = clp[(y11 + v2r)>>16];
R = crgbtmp ;
crgbtmp = clp[(y11 - u2g - v2g)>>16];
G = crgbtmp;
crgbtmp = clp[(y11 + u2b)>>16];
B = crgbtmp;
rgb888[k++] = ((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));
crgbtmp = clp[(y12 + v2r)>>16];
R = crgbtmp ;
crgbtmp = clp[(y12 - u2g - v2g)>>16];
G = crgbtmp ;
crgbtmp = clp[(y12 + u2b)>>16];
B = crgbtmp ;
rgb888[k++] = ((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));
}
k=k - width;
}
return 0;
}
void FilterRGB(unsigned char *PixelsBuffer, int Width, int Height) {
int i, j;
unsigned char p, *p1, *p2, *p3, *p4;
p1 = (unsigned char *) PixelsBuffer;
p2 = p1 + 1;
p3 = p1 + Width;
p4 = p3 + 1;
for (i = 0; i < Height - 1; i++) {
for (j = 0; j < Width - 1; j++) {
p = (*p1 + *p2++ + *p3++ + *p4++ + 2) / 4;
*p1++ = p;
}
p1++;
p2++;
p3++;
p4++;
}
}
// convert 24bit rgb888 to 16bit rgb565 color format
static inline unsigned short rgb888torgb565(unsigned char red,unsigned char green, unsigned char blue)
{
unsigned short B = (blue >> 3) & 0x001F;
unsigned short G = ((green >> 2) << 5) & 0x07E0;
unsigned short R = ((red >> 3) << 11) & 0xF800;
return (unsigned short) (R | G | B);
}
int rgb8882rgb565(unsigned short *rgb565,unsigned char *rgb888,unsigned int imagesize)
{
unsigned int i,j;
unsigned short R,G,B;
for(i = 0; i < imagesize; ++i)
{
j = i * 3;
R = ((rgb888[j++] >> 3)<<11) & 0xF800; //
G = ((rgb888[j++] >> 2)<<5) & 0x07E0; //
B = ((rgb888[j] >> 3)) & 0x001F;
rgb565[i] = R | G | B;
}
return 0;
}
/*
把rgb565src的图像宽度截取width
rgb565src:输入图像源
rgb565cut:截取后的输出图像数据
width:需要截取的宽度
imagesize:输入图像源的图像大小(这个数据是原始没有缩放的图像长度)
*/
int cut_rgb565(unsigned short *rgb565cut,unsigned short *rgb565src,unsigned int width,unsigned int imagesize)
{
int i=0,j=0,n=-1,length=0;
length = imagesize>>2;
unsigned short *p_input = rgb565src;
unsigned short *p_output = rgb565cut;
while(i < length)
{
if(0==(j%width))
p_input += width;
*p_output++ = *p_input++;
p_input++;
j+=2;
i++;
}
return 0;
}
void rgb565_rotate90(const unsigned short *input, int width_in, int height_in,unsigned short *output)//, int *width_out, int *height_out)
{
unsigned short *pIn=(unsigned short *)input;
unsigned short *pOut=(unsigned short *)output;
int i,j;
for(i=0; i<height_in; i++)
{
for(j=0; j<width_in; j++)
{
*pOut = *pIn++;
pOut = output+height_in*j + i;
}
}
// *width_out = height_in;
// *height_out = width_in;
}
/*************************
*Translate the picture Right_Left.
* ***********************/
void rgb565_folio(unsigned short *rgb565,int width,int height)
{
printf("rgb565_folio\n");
unsigned short *p;
unsigned short *q;
p = rgb565;
q = p + width - 1;
unsigned short ustmp;
int x,y;
for(y=1; y <= height; ++y)
{
for(x=0; x < width; ++x)
{
ustmp = *q;
*q = *p;
*p = ustmp;
q--;
p++;
}
p++;
q=q+width;
}
}
int close_conver()
{
if(clp != NULL)
{
clp -= 384;
free(clp);
clp=NULL;
}
inited = 0;
return 0;
}
<file_sep>/work/debug/a8/driver.c
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <asm/uaccess.h>
#include <plat/gpio-cfg.h>
#include <mach/gpio.h>
#define LED_INPUT _IO('i',1)
#define LED_OUTPUT _IO('o',2)
static int demo_major = 0;
static struct class *my_class;
static int demo_open(struct inode *pinode, struct file *pfile)
{
printk("%s:%d\n",__FUNCTION__,__LINE__);
printk("major:%d,minor:%d\n",imajor(pinode),iminor(pinode));
return 0;
}
static ssize_t demo_read(struct file *pfile, char __user *buffer, size_t count, loff_t *offset)
{
char data[] = "this is driver!";
int ret;
int len = min(strlen(data),count);
printk("%s:%d\n",__FUNCTION__,__LINE__);
ret = copy_to_user(buffer,data,len);
return len;
}
static ssize_t demo_write(struct file *pfile, const char __user *buffer, size_t count, loff_t *offset)
{
char data[20];
int ret;
int len = min(strlen(data),count);
printk("%s:%d\n",__FUNCTION__,__LINE__);
ret = copy_from_user(data,buffer,len);
printk("%s\n",data);
if(data[0] == '1'){
gpio_set_value(S5PV210_GPH0(0), 1); // ΆΤΣ¦Ί―Κύ: gpio_get_value(S5PV210_GPH0(0));
gpio_set_value(S5PV210_GPH0(1), 1);
gpio_set_value(S5PV210_GPH0(2), 1);
gpio_set_value(S5PV210_GPH0(3), 1);
}
else{
gpio_set_value(S5PV210_GPH0(0), 0);
gpio_set_value(S5PV210_GPH0(1), 0);
gpio_set_value(S5PV210_GPH0(2), 0);
gpio_set_value(S5PV210_GPH0(3), 0);
}
return len;
}
static int demo_release(struct inode *pinode, struct file *pfile)
{
printk("%s:%d\n",__FUNCTION__,__LINE__);
return 0;
}
static long demo_ioctl(struct file *pfile, unsigned int cmd, unsigned long arg)
{
switch(cmd){
case LED_INPUT:
s3c_gpio_cfgpin(S5PV210_GPH0(arg),S3C_GPIO_INPUT);
break;
case LED_OUTPUT:
s3c_gpio_cfgpin(S5PV210_GPH0(arg),S3C_GPIO_OUTPUT);
break;
default:
break;
}
return 0;
}
static struct file_operations demo_fops = {
.owner = THIS_MODULE,
.open = demo_open,
.read = demo_read,
.write = demo_write,
.release = demo_release,
.unlocked_ioctl = demo_ioctl,
};
int __init demo_module_init(void)
{
int i;
printk("%s:%d\n",__FUNCTION__,__LINE__);
demo_major = register_chrdev(demo_major,"char_dev",&demo_fops);
my_class = class_create(THIS_MODULE,"demo_class");
for(i=0;i<6;i++)
device_create(my_class,NULL,MKDEV(demo_major,i),NULL,"demo_char%d",i);
return 0;
}
void __exit demo_module_exit(void)
{
int i;
printk("%s:%d\n",__FUNCTION__,__LINE__);
for(i=0;i<6;i++)
device_destroy(my_class,MKDEV(demo_major,i));
class_destroy(my_class);
unregister_chrdev(demo_major,"char_dev");
}
module_init(demo_module_init);
module_exit(demo_module_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/debug/pc/sync/test_sync.c
/* ************************************************************************
* Filename: test_sync.c
* Description:
* Version: 1.0
* Created: 2015年11月11日 10时58分08秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <signal.h>
int flag = 0;
void sync_handler(int signo)
{
if(signo == SIGIO){
printf("receive successful!!!\n");
flag++;
}
}
#if 0
int main(int argc, char *argv[])
{
int fd, oflags;
fd = open("/dev/sync", O_RDWR, 766);
if(fd < 0){
printf("cannot' open /dev/sync\n");
return -1;
}
signal(SIGIO, sync_handler);
fcntl(fd, F_SETOWN, getpid());
oflags = fcntl(fd, F_GETFL);
fcntl(fd, F_SETFL, oflags | FASYNC);
while(1){
if(flag > 5)
break;
usleep(600*1000);
}
close(fd);
return 0;
}
#else
int main()
{
struct sigaction action;
int async_fd;
memset(&action, 0, sizeof(action));
//信号处理函数
action.sa_handler = sync_handler;
action.sa_flags = 0;
//注册信号类型
sigaction(SIGIO, &action, NULL);
async_fd = open("/dev/sync", O_RDONLY);
if(async_fd < 0)
{
printf("can not open /dev/sync \n");
return -1;
}
//告诉驱动当前进程的PID
fcntl(async_fd, F_SETOWN, getpid());
//设置驱动的FASYNC属性,支持异步通知
fcntl(async_fd, F_SETFL, fcntl(async_fd, F_GETFL) | FASYNC);
printf("waiting for receive...\n");
while(1){
if(flag > 5) break;
usleep(600*1000);
}
close(async_fd);
return 0;
}
#endif<file_sep>/c/practice/1st_week/area_circle/Makefile
area:area_circle.o
gcc -o area area_circle.o
area_circle.o:area_circle.c
gcc -c area_circle.c
.PHONY:clean
clean:
rm *.o area
<file_sep>/network/3rd_day/tcp_server.c
/* ************************************************************************
* Filename: tcp_server.c
* Description:
* Version: 1.0
* Created: 2015年09月02日 15时19分34秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
void *fun(void *arg)
{
int confd = (int )arg;
send(confd, "connect successful!\n", strlen("connect successful!\n"), 0);
while(1)
{
char buf[512]="";
int recv_len = recv(confd, buf, sizeof(buf),0);
if(recv_len == 0) break;
strcat(buf, "\n");
send(confd, buf, strlen(buf), 0);
}
close(confd);
}
int main(int argc, char *argv[])
{
//1.创建一个用于通信的tcp 监听 套接字
unsigned short port = 8080;
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
// if(argc < 2)
// {
// printf("parameter too little\n");
// exit(-1);
// }
// port = atoi(argv[1]);
//2.让服务器绑定IP和端口
struct sockaddr_in s_addr;
bzero(&s_addr, sizeof(s_addr));
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(port);
s_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(sockfd, (struct sockaddr *)&s_addr, sizeof(s_addr));
if(ret != 0)
{
perror("bind:");
exit(-1);
}
//3.listen创建连接队列
listen(sockfd, 10);
while(1)
{
struct sockaddr_in c_addr;
socklen_t c_addr_len = sizeof(c_addr);
int confd = accept(sockfd, (struct sockaddr *)&c_addr, &c_addr_len);
pthread_t pthid;
pthread_create(&pthid, NULL, (void *)fun, (void *)confd);
pthread_detach(pthid); //线程分离
}
close(sockfd);
return 0;
}
#if 0
int main(int argc, char *argv[])
{
//1.创建一个用于通信的tcp 监听 套接字
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
//2.让服务器绑定IP和端口
struct sockaddr_in s_addr;
bzero(&s_addr, sizeof(s_addr));
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(8080);
s_addr.sin_addr.s_addr = htons(INADDR_ANY);
int ret = bind(sockfd, (struct sockaddr *)&s_addr, sizeof(s_addr));
if(ret != 0)
{
perror("bind:");
exit(-1);
}
//3.listen创建连接队列
listen(sockfd, 10);
while(1)
{
char ip[16] = "";
struct sockaddr_in c_addr;
socklen_t c_addr_len= sizeof(c_addr);
//4.提取客户端的连接
int confd = accept(sockfd, (struct sockaddr *)&c_addr, &c_addr_len);
inet_ntop(AF_INET, &c_addr.sin_addr.s_addr, ip,16);
while(confd != 0)
{
send(confd, "hongbao", strlen("hongbao"), 0);
//printf("ip:%s port:%d\n",ip, ntohs(c_addr.sin_port));
//4.接收
char buf[128]="";
int recv_len = recv(confd, buf, sizeof(buf),0);
if(recv_len == 0) break;
printf("ip:%s port:%d recv = %s\n",ip, ntohs(c_addr.sin_port),buf);
}
break;
}
close(sockfd);
return 0;
}
#endif
<file_sep>/work/test/cim_test-zmm220/arca.h
/********************************************************************
ZEM 200
jz4730.h defines all the constants and others for Jz4730 CPU
Copyright (C) 2003-2006, ZKSoftware Inc.
********************************************************************/
#ifndef _JZ4730_H_
#define _JZ4730_H_
#include <unistd.h>
#define TRUE 1
#define FALSE 0
#define U8 unsigned char
#define U16 unsigned short
#define U32 unsigned int
#define BOOL int
#define BYTE unsigned char
#define WORD unsigned short
#define DWORD unsigned long
#define LONG long
#define CONFIG_DEBUG
#ifdef CONFIG_DEBUG
#define DBPRINTF(format, arg...) do { printf(format, ## arg); } while (0)
#else
#define DBPRINTF(format, arg...)
#endif
#define AC97_CTL 53
#define I2S_CTL AC97_CTL
#define RS485_SEND 102
#define LCDBACkLIGHT 20
#define IO_GREEN_LED 104
#define IO_RED_LED 105
#define IO_LOCK 103
#define IO_WIEGAND_OUT_D0 100
#define IO_WIEGAND_OUT_D1 101
#define WEI_DN 104
#define WEI_DP 105
#define USB_SEL 120
#define REG8 volatile unsigned char
#define REG16 volatile unsigned short
#define REG32 volatile unsigned int
#define VPchar *(REG8 *)
#define VPshort *(REG16 *)
#define VPint *(REG32 *)
#define Pchar (REG8 *)
#define Pshort (REG16 *)
#define Pint (REG32 *)
void CalibrationTimeBaseValue(void);
void DelayUS(int us);
void DelayMS(int ms);
void DelayNS(long ns);
BOOL GPIO_IO_Init(void);
void GPIO_IO_Free(void);
void GPIO_PIN_CTL_SET(int IsWiegandKeyPad, int IsNetSwitch);
void GPIO_AC97_Mute(BOOL Switch);
void GPIO_HY7131_Power(BOOL Switch);
void GPIO_LCD_USB0_Power(BOOL Switch);
void GPIO_RS485_Status(U32 SendMode);
void GPIO_SYS_POWER(void);
void GPIO_WIEGAND_LED(BYTE GPIOPIN, BOOL Light);
void GPIO_KEY_SET(BYTE Value);
int GPIO_KEY_GET(void);
void GPIOSetLevel(BYTE IOPIN, int High);
BOOL GPIOGetLevel(BYTE IOPIN);
BOOL ExCheckGPI(BYTE GPIOPIN);
#endif /* _JZ4730_H_ */
<file_sep>/c/practice/sort/shellsort.c
#include "stdio.h"
void swap(int *a,int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void display(int k[],int n)
{
int i;
for(i=0;i<n;i++) /*显示原序列之中的元素*/
printf("%d ",k[i]);
printf("\n");
}
void shellsort(int k[],int n)
{
int i, j, flag ,gap = n;
while(gap > 1)
{
gap = gap/2; /*增量缩小,每次减半*/
do
{ /*子序列应用冒泡排序*/
flag = 0;
for(i=0;i<n-gap;i++) //n-gap 是控制上限不让越界
{
j = i + gap; //相邻间隔的前后值进行比较
if(k[i]>k[j])
{
swap(&k[i],&k[j]);
flag = 1;
}
}
printf("gap = %d:\n",gap);
display(k,10);
}while(flag !=0);
}
}
void shellsort_1(int k[],int n)
{
int i,flag;
do
{ /*子序列应用冒泡排序*/
flag = 0;
for(i=0;i<n-1;i++)
{
if(k[i]>k[i+1]) //相邻的前后值进行比较
{
swap(&k[i],&k[i+1]);
flag = 1;
}
}
printf("gap=1:\n");
display(k,10);
}while(flag !=0);
}
int main()
{
int i,a[10] = {2,5,6,3,7,8,0,9,12,1}; /*初始化序列,a[0]可任意置数*/
printf("The data array is:\n") ;
for(i=0;i<10;i++) /*显示原序列之中的元素*/
printf("%d ",a[i]);
printf("\n\n");
shellsort(a,10); /*执行希尔排序*/
//shellsort_1(a,10); /*执行希尔排序*/
printf("\nThe result of Shell's sorting for the array is:\n");
for(i=0;i<10;i++)
printf("%d ",a[i]); /*输出排序后的结果*/
printf("\n");
return 0;
}
<file_sep>/c/lrc/common.h
#ifndef __COMMON_H__
#define __COMMON_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#define uint unsigned int
#define ulint unsigned long int
#define uchar unsigned char
typedef struct lrc
{
//float time;
int time;
char *psrc;
struct lrc *prev;
struct lrc *next;
}LRC;
#endif<file_sep>/network/route/src/main.c
/******************************************************************************
文 件 名 : main.c
版 本 号 : 初稿
作 者 : 呵呵
生成日期 : 2015年9月11日
功能描述 : 主函数
******************************************************************************/
#include "common.h"
#include "route_control.h"
#include "route_pthread.h"
int main(int argc, char *argv[])
{
TYPE_Route route; // 定义路由器结构体变量
route_init(&route); // 路由器初始化
create_pthread(&route); // 创建线程
return 0;
}
<file_sep>/network/route/src/route_firewall.c
/******************************************************************************
文 件 名 : route_firewall.c
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月15日
最近修改 :
功能描述 : 防火墙规则创建和过滤
函数列表 :
delete_firewall_rule
firewall_build_rule
firewall_filt
firewall_filt_ip
firewall_filt_mac
firewall_filt_port
firewall_filt_protocol
修改历史 :
1.日 期 : 2015年9月15日
作 者 : if
修改内容 : 创建文件
******************************************************************************/
#include "common.h"
#include "firewall_link.h"
const char *rules[] = {
"ip",
"mac",
"port",
"arp",
"tcp",
"udp",
"icmp",
"igmp",
"http",
"tftp",
};
#if 0
/*****************************************************************************
函 数 名 : firewall_rule_set_help()
功能描述 : 防火墙规则规则设置帮助
输入参数 : NULL
返 回 值 : NULL
修改日期 : 2015年9月14日
*****************************************************************************/
void firewall_rule_set_help(void)
{
printf("*************************************************************************\n");
printf("- >>> 温馨提示: ()是可选选项 <<< *\n");
printf("-设置 ip 过滤规则,格式: ip (opt) <ip> -> ip (src) 192.168.1.1 *\n");
printf("-设置 mac过滤规则,格式: mac (opt) <mac> -> mac (dst) 192.168.1.1 *\n");
printf("-设置端口过滤规则,格式: port (opt) <port> -> port (host) 8000 *\n");
printf("-设置协议过滤规则,格式: <pro> (type) (opt) (type_val) -> udp port 8000 *\n");
printf("-删除已设置的规则,输入: -d <要删除的规则> *\n");
printf("-查看设置规则帮助,输入: -h *\n");
printf("-查看已设置的规则,输入: ls *\n");
printf("-退出防火墙设置, 输入: esc *\n");
printf("*************************************************************************\n");
}
#endif
/*****************************************************************************
函 数 名 : firewall_build_rule()
功能描述 : 建立防火墙规则表
输入参数 : rt TYPE_Route 类型结构指针
rule 待插入的规则
flag 是否保存到文件标准 1: 保存
返 回 值 : NULL
修改日期 : 2015年9月13日
*****************************************************************************/
void firewall_build_rule(TYPE_Route *rt, const char *rule, char flag)
{
struct _firewall node;
bzero(node.rule, sizeof(node.rule));
strcpy(node.rule, rule);
if(strncmp(rules[0], rule, strlen(rules[0])) == 0){
rt->ip_head = (FIRE_Wall *)insert_firewall_node(rt->ip_head, node);
}
else if(strncmp(rules[1], rule, strlen(rules[1])) == 0){
rt->mac_head = (FIRE_Wall *)insert_firewall_node(rt->mac_head, node);
}
else if(strncmp(rules[2], rule, strlen(rules[2])) == 0){
rt->port_head = (FIRE_Wall *)insert_firewall_node(rt->port_head, node);
}
else{
int i = 0;
for(i = 3; i < sizeof(rules)/sizeof(rules[0]); i++)
{
if(strncmp(rules[i], rule, strlen(rules[i])) == 0){
rt->pro_head = (FIRE_Wall *)insert_firewall_node(rt->pro_head, node);
break;
}
}
}
if(flag == 1){
filrewall_save_rule(rule); //保存规则到文件
}
}
/*****************************************************************************
函 数 名 : delete_firewall_rule()
功能描述 : 删除防火墙规则表
输入参数 : rt TYPE_Route 类型结构指针
rule 待删除的规则
返 回 值 : NULL
修改日期 : 2015年9月15日
*****************************************************************************/
void delete_firewall_rule(TYPE_Route *rt, const char *rule)
{
if(strncmp(rules[0], rule, strlen(rules[0])) == 0){
rt->ip_head = (FIRE_Wall *)delete_firewall_node(rt->ip_head, rule);
}
else if(strncmp(rules[1], rule, strlen(rules[1])) == 0){
rt->mac_head = (FIRE_Wall *)delete_firewall_node(rt->ip_head, rule);
}
else if(strncmp(rules[2], rule, strlen(rules[2])) == 0){
rt->port_head = (FIRE_Wall *)delete_firewall_node(rt->ip_head, rule);
}
else{
int i = 0;
for(i = 3; i < sizeof(rules)/sizeof(rules[0]); i++)
{
if(strncmp(rules[i], rule, strlen(rules[i])) == 0){
rt->pro_head = (FIRE_Wall *)delete_firewall_node(rt->ip_head, rule);
break;
}
}
}
}
/*****************************************************************************
函 数 名 : firewall_filt_ip()
功能描述 : 防火墙过滤ip
输入参数 : rt TYPE_Route 类型结构指针
pinfo MSG_Info 类型结构指针
返 回 值 : 返回0,说明可以通过ip过滤,返回-1,说明不能通过ip过滤
修改日期 : 2015年9月13日
*****************************************************************************/
static int firewall_filt_ip(TYPE_Route *rt, MSG_Info *pinfo)
{
if(rt->ip_head != NULL){
uchar type[16];
uchar ip[16];
uchar src_ip[16] = "";
uchar dst_ip[16] = "";
struct _firewall *pnode = NULL;
pnode = rt->ip_head;
//提取目的ip
sprintf(dst_ip,"%d.%d.%d.%d",\
pinfo->dst_ip[0],pinfo->dst_ip[1],pinfo->dst_ip[2],pinfo->dst_ip[3]);
//提取源ip
sprintf(src_ip,"%d.%d.%d.%d",\
pinfo->src_ip[0],pinfo->src_ip[1],pinfo->src_ip[2],pinfo->src_ip[3]);
while(pnode != NULL)
{
bzero(type, sizeof(type));
bzero(ip, sizeof(ip));
sscanf(pnode->rule, "%*s %s %s", type, ip);
if(strcmp(type, "host") == 0 || strlen(ip) == 0) {
if(strlen(ip) != 0){
if(strcmp(src_ip, ip) == 0 || \
strcmp(dst_ip, ip) == 0){
return -1;
}
}
else {
if(strcmp(src_ip, type) == 0 || \
strcmp(dst_ip, type) == 0){
return -1;
}
}
}
else if(strcmp(type, "src") == 0) {
if(strcmp(src_ip, ip) == 0){
return -1;
}
}
else if(strcmp(type, "dst") == 0) {
if(strcmp(dst_ip, ip) == 0) {
return -1;
}
}
else {
rt->mac_head = (FIRE_Wall *)delete_firewall_node(rt->ip_head, pnode->rule);
}
pnode = pnode->next;
}
}
return 0;
}
/*****************************************************************************
函 数 名 : firewall_filt_mac()
功能描述 : 防火墙过滤mac
输入参数 : rt TYPE_Route 类型结构指针
pinfo MSG_Info 类型结构指针
返 回 值 : 返回0,说明可以通过mac过滤,返回-1,说明不能通过mac过滤
修改日期 : 2015年9月13日
*****************************************************************************/
static int firewall_filt_mac(TYPE_Route *rt, MSG_Info *pinfo)
{
if(rt->mac_head != NULL){
uchar type[18];
uchar mac[18];
uchar dst_mac[18] = "";
uchar src_mac[18] = "";
struct _firewall *pnode = NULL;
pnode = rt->mac_head;
//提取目的mac
sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
pinfo->dst_mac[0],pinfo->dst_mac[1],pinfo->dst_mac[2],\
pinfo->dst_mac[3],pinfo->dst_mac[4],pinfo->dst_mac[5]);
//提取源mac
sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
pinfo->src_mac[0],pinfo->src_mac[1],pinfo->src_mac[2],\
pinfo->src_mac[3],pinfo->src_mac[4],pinfo->src_mac[5]);
while(pnode != NULL)
{
bzero(type, sizeof(type));
bzero(mac, sizeof(mac));
sscanf(pnode->rule, "%*s %s %s", type, mac);
if(strcmp(type, "host") == 0 || strlen(mac) == 0) {
if(strlen(mac) != 0){
if(strcmp(src_mac, mac) == 0 || \
strcmp(src_mac, mac) == 0){
return -1;
}
}
else {
if(strcmp(src_mac, type) == 0 || \
strcmp(src_mac, type) == 0){
return -1;
}
}
}
else if(strcmp(type, "src") == 0) {
if(strcmp(src_mac, mac) == 0){
return -1;
}
}
else if(strcmp(type, "dst") == 0) {
if(strcmp(dst_mac, mac) == 0) {
return -1;
}
}
else {
rt->mac_head = (FIRE_Wall *)delete_firewall_node(rt->mac_head, pnode->rule);
}
pnode = pnode->next;
}
}
return 0;
}
/*****************************************************************************
函 数 名 : firewall_filt_port()
功能描述 : 防火墙过滤端口
输入参数 : rt TYPE_Route 类型结构指针
pinfo MSG_Info 类型结构指针
返 回 值 : 返回0,说明可以通过端口过滤,返回-1,说明不能通过端口过滤
修改日期 : 2015年9月13日
*****************************************************************************/
static int firewall_filt_port(TYPE_Route *rt, MSG_Info *pinfo)
{
if(rt->port_head != NULL){
uchar type[6];
uchar port[6];
uint16 port_val = 0;
struct _firewall *pnode = NULL;
pnode = rt->port_head;
while(pnode != NULL)
{
bzero(type, sizeof(type));
bzero(port, sizeof(port));
sscanf(pnode->rule, "%*s %s %s", type, port);
if(strlen(port) != 0)
port_val = (uint16)atoi(port);
else
port_val = (uint16)atoi(type);
if(strcmp(type, "host") == 0 || strlen(port) == 0) {
if(port_val == pinfo->s_port || \
port_val == pinfo->d_port){
return -1;
}
}
else if(strcmp(type, "src") == 0) {
if(port_val == pinfo->s_port){
return -1;
}
}
else if(strcmp(type, "dst") == 0) {
if(port_val == pinfo->d_port) {
return -1;
}
}
else {
rt->mac_head = (FIRE_Wall *)delete_firewall_node(rt->port_head, pnode->rule);
}
pnode = pnode->next;
}
}
return 0;
}
/*****************************************************************************
函 数 名 : firewall_filt_protocol()
功能描述 : 防火墙过滤协议类型
输入参数 : rt TYPE_Route 类型结构指针
pinfo MSG_Info 类型结构指针
返 回 值 : 返回0,说明可以通过协议过滤,返回-1,说明不能通过协议过滤
修改日期 : 2015年9月13日
*****************************************************************************/
static int firewall_filt_protocol(TYPE_Route *rt, MSG_Info *pinfo)
{
if(rt->pro_head != NULL){
uchar part[4][18];
struct _firewall *pnode = NULL;
pnode = rt->pro_head;
while(pnode != NULL)
{
sscanf(pnode->rule, "%s %s %s %s", *(part+0), *(part+1), *(part+2), *(part+3));
if(strlen(*(part+1)) == 0){
if(strcmp(*(part+0), "arp") == 0){
if(pinfo->frame_type == 0x0806){
return -1;
}
}
else if(strcmp(*(part+0), "icmp") == 0){
if(pinfo->pro_type == 1){
return -1;
}
}
else if(strcmp(*(part+0), "igmp") == 0){
if(pinfo->pro_type == 2){
return -1;
}
}
else if(strcmp(*(part+0), "tcp") == 0){
if(pinfo->pro_type == 6){
return -1;
}
}
else if(strcmp(*(part+0), "udp") == 0){
if(pinfo->pro_type == 17){
return -1;
}
}
else if(strcmp(*(part+0), "ftp") == 0){
if(pinfo->d_port == 21){
return -1;
}
}
else if(strcmp(*(part+0), "http") == 0){
if(pinfo->d_port == 80){
return -1;
}
}
else if(strcmp(*(part+0), "tftp") == 0){
if(pinfo->d_port == 69){
return -1;
}
}
else{
rt->pro_head = (FIRE_Wall *)delete_firewall_node(rt->pro_head, pnode->rule);
}
}
else {
if(strcmp(*(part+1), "mac")) {
uchar dst_mac[18] = "";
uchar src_mac[18] = "";
//提取目的mac
sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
pinfo->dst_mac[0],pinfo->dst_mac[1],pinfo->dst_mac[2],\
pinfo->dst_mac[3],pinfo->dst_mac[4],pinfo->dst_mac[5]);
//提取源mac
sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
pinfo->src_mac[0],pinfo->src_mac[1],pinfo->src_mac[2],\
pinfo->src_mac[3],pinfo->src_mac[4],pinfo->src_mac[5]);
if(strcmp(*(part+2), "host") == 0 || strlen(*(part+3)) == 0) {
if(strlen(*(part+3)) != 0){
if(strcmp(src_mac, *(part+3)) == 0 || \
strcmp(src_mac, *(part+3)) == 0){
return -1;
}
}
else {
if(strcmp(src_mac, *(part+2)) == 0 || \
strcmp(src_mac, *(part+2)) == 0){
return -1;
}
}
}
else if(strcmp(*(part+2), "src") == 0) {
if(strcmp(src_mac, *(part+3)) == 0){
return -1;
}
}
else if(strcmp(*(part+2), "dst") == 0) {
if(strcmp(dst_mac, *(part+3)) == 0) {
return -1;
}
}
else {
rt->pro_head = (FIRE_Wall *)delete_firewall_node(rt->pro_head, pnode->rule);
}
}
else if(strcmp(*(part+1), "ip")) {
uchar src_ip[16] = "";
uchar dst_ip[16] = "";
//提取目的ip
sprintf(dst_ip,"%d.%d.%d.%d",\
pinfo->dst_ip[0],pinfo->dst_ip[1],pinfo->dst_ip[2],pinfo->dst_ip[3]);
//提取源ip
sprintf(src_ip,"%d.%d.%d.%d",\
pinfo->src_ip[0],pinfo->src_ip[1],pinfo->src_ip[2],pinfo->src_ip[3]);
if(strcmp(*(part+2), "host") == 0 || strlen(*(part+3)) == 0) {
if(strlen(*(part+3)) != 0){
if(strcmp(src_ip, *(part+3)) == 0 || \
strcmp(dst_ip, *(part+3)) == 0){
return -1;
}
}
else {
if(strcmp(src_ip, *(part+2)) == 0 || \
strcmp(dst_ip, *(part+2)) == 0){
return -1;
}
}
}
else if(strcmp(*(part+2), "src") == 0) {
if(strcmp(src_ip, *(part+3)) == 0){
return -1;
}
}
else if(strcmp(*(part+2), "dst") == 0) {
if(strcmp(dst_ip, *(part+3)) == 0) {
return -1;
}
}
else {
rt->pro_head = (FIRE_Wall *)delete_firewall_node(rt->pro_head, pnode->rule);
}
}
else if(strcmp(*(part+1), "port")) {
uint16 port_val = 0;
if(strlen(*(part+3)) != 0)
port_val = (uint16)atoi(*(part+3));
else
port_val = (uint16)atoi(*(part+2));
if(strcmp(*(part+2), "host") == 0 || strlen(*(part+3)) == 0) {
if(port_val == pinfo->s_port || \
port_val == pinfo->d_port){
return -1;
}
}
else if(strcmp(*(part+2), "src") == 0) {
if(port_val == pinfo->s_port){
return -1;
}
}
else if(strcmp(*(part+2), "dst") == 0) {
if(port_val == pinfo->d_port) {
return -1;
}
}
else {
rt->pro_head = (FIRE_Wall *)delete_firewall_node(rt->pro_head, pnode->rule);
}
}
else {
rt->pro_head = (FIRE_Wall *)delete_firewall_node(rt->pro_head, pnode->rule);
}
}
pnode = pnode->next;
}
}
}
/*****************************************************************************
函 数 名 : firewall_filt()
功能描述 : 防火墙过滤
输入参数 : rt TYPE_Route 类型结构指针
pinfo MSG_Info 类型结构指针
返 回 值 : 返回0,说明可以通过ip过滤,返回-1,说明不能通过ip过滤
修改日期 : 2015年9月13日
*****************************************************************************/
int firewall_filt(TYPE_Route *rt, MSG_Info *pinfo)
{
int ret = 0;
rt->eth_hdr = (struct ether_header *)rt->recv;
memcpy(pinfo->dst_mac, rt->eth_hdr->ether_dhost, ETH_ALEN);
memcpy(pinfo->src_mac, rt->eth_hdr->ether_shost, ETH_ALEN);
if(rt->fire_status == UP){
ret = firewall_filt_mac(rt, pinfo);
if(ret < 0) return -1;
}
pinfo->frame_type = ntohs(rt->eth_hdr->ether_type);
if(pinfo->frame_type == 0x0800) {
//recv+14 跳过mac头
rt->ip_hdr = (struct iphdr *)(rt->recv + 14);
memcpy(pinfo->src_ip, (uchar *)&rt->ip_hdr->saddr, 4);
memcpy(pinfo->dst_ip, (uchar *)&rt->ip_hdr->daddr, 4);
pinfo->pro_type = rt->ip_hdr->protocol;
switch(pinfo->pro_type)
{
case 6:
{ // rt->ip_hdr->ihl * 4 跳过ip头部
rt->udp_hdr = (struct udphdr *)(rt->recv + 14 + rt->ip_hdr->ihl * 4);
pinfo->s_port = ntohs(rt->udp_hdr->source);
pinfo->d_port = ntohs(rt->udp_hdr->dest);
break;
}
case 17:
{
rt->tcp_hdr = (struct tcphdr *)(rt->recv + 14 + rt->ip_hdr->ihl * 4);
pinfo->s_port = ntohs(rt->tcp_hdr->source);
pinfo->d_port = ntohs(rt->tcp_hdr->dest);
break;
}
}
if(rt->fire_status == UP){
ret = firewall_filt_port(rt, pinfo);
if(ret < 0) return -1;
}
}
else if(pinfo->frame_type == 0x0806) {
rt->arp_hdr = (struct _arphdr *)(rt->recv + 14);
memcpy(pinfo->src_ip, rt->arp_hdr->src_ip, 4);
memcpy(pinfo->dst_ip, rt->arp_hdr->dst_ip, 4);
}
if(rt->fire_status == UP){
ret = firewall_filt_ip(rt, pinfo);
if(ret < 0) return -1;
ret = firewall_filt_protocol(rt, pinfo);
if(ret < 0) return -1;
}
return 0;
}
<file_sep>/work/debug/ingenic/wiegand/wiegand_out.c
/*
* Copyright (C) 2012 Ingenic Semiconductor Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/miscdevice.h>
#include <linux/spinlock.h>
#include <linux/wakelock.h>
#include <linux/clk.h>
#include <linux/syscalls.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/gpio.h>
#include <linux/spinlock.h>
#include <linux/poll.h>
#include <linux/hrtimer.h>
#include <linux/wait.h>
#include <linux/time.h>
#include <linux/kernel.h>
#include <linux/wiegand.h>
#ifdef CONFIG_BOARD_4775_ZMM220
#define WIEGANDOUTDRV_LIB_VERSION "1.0.1 ZMM220"__DATE__ /* DRV LIB VERSION */
#endif
#ifdef CONFIG_BOARD_4775_ZMM210
#define WIEGANDOUTDRV_LIB_VERSION "1.0.1 ZMM210"__DATE__ /* DRV LIB VERSION */
#endif
#ifdef CONFIG_BOARD_4775_ZMM200
#define WIEGANDOUTDRV_LIB_VERSION "1.0.1 ZMM200"__DATE__ /* DRV LIB VERSION */
#endif
#ifdef CONFIG_BOARD_X1000_ZLM60
#define WIEGANDOUTDRV_LIB_VERSION "1.0.1 ZLM60"__DATE__ /* DRV LIB VERSION */
#endif
#define WIEGAND_OUT0_DATA '0'
#define WIEGAND_OUT1_DATA '1'
#define PLUSE_WIDTH_STATE 0
#define PLUSE_INTVAL_STATE 1
#define MAX_WIEGAND_DATA_LEN 128
#define DEF_PULSE_WIDTH 100 //us
#define DEF_PULSE_INTERVAL 1000 //us
#define DEF_DATA_LENGTH 26 //bit
struct wiegand_out_dev {
struct device *dev;
struct miscdevice mdev;
unsigned int data0_pin;
unsigned int data1_pin;
unsigned char wiegand_out_data[MAX_WIEGAND_DATA_LEN];
int pos;
int data_length;
int pulse_width; //us
int pulse_intval; //us
int state;
spinlock_t lock;
int use_count;
struct hrtimer timer;
wait_queue_head_t wq;
};
static void wiegand_out_data_reset(struct wiegand_out_dev *wiegand_out)
{
gpio_direction_output(wiegand_out->data0_pin, 1);
gpio_direction_output(wiegand_out->data1_pin, 1);
}
static void wiegand_out_set_start_state(struct wiegand_out_dev *wiegand_out)
{
wiegand_out->state = PLUSE_INTVAL_STATE;
}
static void wiegand_out_set_current_state(struct wiegand_out_dev *wiegand_out)
{
wiegand_out->state = (wiegand_out->state == PLUSE_WIDTH_STATE) ? PLUSE_INTVAL_STATE : PLUSE_WIDTH_STATE;
}
static void wiegand_out_start_pulse_width_timer(struct wiegand_out_dev *wiegand_out)
{
int us = wiegand_out->pulse_width;
int s = us / 1000000;
ktime_t time = ktime_set(s, (us % 1000000) * 1000);
hrtimer_start(&wiegand_out->timer, time, HRTIMER_MODE_REL);
}
static void wiegand_out_start_pulse_intval_timer(struct wiegand_out_dev *wiegand_out)
{
int us = wiegand_out->pulse_intval;
int s = us / 1000000;
ktime_t time = ktime_set(s, (us % 1000000) * 1000);
hrtimer_start(&wiegand_out->timer, time, HRTIMER_MODE_REL);
}
static void wiegand_out_start_write(struct wiegand_out_dev *wiegand_out)
{
wiegand_out->pos = 0;
wiegand_out_set_start_state(wiegand_out);
wiegand_out_data_reset(wiegand_out);
hrtimer_start(&wiegand_out->timer, ktime_set(0, 0), HRTIMER_MODE_REL);
}
static int wiegand_out_check_data(struct wiegand_out_dev *wiegand_out)
{
int i;
for (i = 0; i < wiegand_out->data_length; i++) {
if (wiegand_out->wiegand_out_data[i] != WIEGAND_OUT0_DATA &&
wiegand_out->wiegand_out_data[i] != WIEGAND_OUT1_DATA)
return -1;
}
return 0;
}
static enum hrtimer_restart wiegand_out_timeout(struct hrtimer *timer)
{
struct wiegand_out_dev *wiegand_out = container_of(timer, struct wiegand_out_dev, timer);
wiegand_out_set_current_state(wiegand_out);
if (wiegand_out->state == PLUSE_WIDTH_STATE) {
if (wiegand_out->pos == wiegand_out->data_length) {
if(waitqueue_active(&wiegand_out->wq))
wake_up_interruptible(&wiegand_out->wq);
return HRTIMER_NORESTART;
}
if (wiegand_out->wiegand_out_data[wiegand_out->pos] == WIEGAND_OUT0_DATA)
gpio_direction_output(wiegand_out->data0_pin, 0);
else
gpio_direction_output(wiegand_out->data1_pin, 0);
wiegand_out->pos++;
wiegand_out_start_pulse_width_timer(wiegand_out);
}
else {
gpio_direction_output(wiegand_out->data0_pin, 1);
gpio_direction_output(wiegand_out->data1_pin, 1);
wiegand_out_start_pulse_intval_timer(wiegand_out);
}
return HRTIMER_NORESTART;
}
static int wiegand_out_open(struct inode *inode, struct file *filp)
{
struct miscdevice *dev = filp->private_data;
struct wiegand_out_dev *wiegand_out = container_of(dev, struct wiegand_out_dev, mdev);
spin_lock(&wiegand_out->lock);
if (wiegand_out->use_count > 0) {
spin_unlock(&wiegand_out->lock);
return -EBUSY;
}
wiegand_out->use_count++;
spin_unlock(&wiegand_out->lock);
wiegand_out_data_reset(wiegand_out);
return 0;
}
static int wiegand_out_release(struct inode *inode, struct file *filp)
{
struct miscdevice *dev = filp->private_data;
struct wiegand_out_dev *wiegand_out = container_of(dev, struct wiegand_out_dev, mdev);
spin_lock(&wiegand_out->lock);
wiegand_out->use_count--;
spin_unlock(&wiegand_out->lock);
return 0;
}
static ssize_t wiegand_out_write(struct file *filp, const char __user *buf, size_t size, loff_t *l)
{
int ret;
int us;
int s;
struct miscdevice *dev = filp->private_data;
struct wiegand_out_dev *wiegand_out = container_of(dev, struct wiegand_out_dev, mdev);
if (filp->f_flags & O_NONBLOCK)
return -EAGAIN;
if (size > MAX_WIEGAND_DATA_LEN) {
printk("ERROR: wiegand out data length error, max is %d, please check.\n", MAX_WIEGAND_DATA_LEN);
return -EFAULT;
}
if (copy_from_user(wiegand_out->wiegand_out_data, buf, size))
return -EFAULT;
wiegand_out->data_length = size;
ret = wiegand_out_check_data(wiegand_out);
if (ret) {
printk("ERROR: wiegand out data format error, must be '0' or '1', please check.\n");
return -EFAULT;
}
wiegand_out_start_write(wiegand_out);
us = (wiegand_out->pulse_width + wiegand_out->pulse_intval)
* wiegand_out->data_length;
s = us / 1000000;
ret = interruptible_sleep_on_timeout(&wiegand_out->wq, (s + 2) * HZ);
if (!ret) {
printk("wiegand write timeout\n");
return -EIO;
}
return 0;
}
static long wiegand_out_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct miscdevice *dev = filp->private_data;
struct wiegand_out_dev *wiegand_out = container_of(dev, struct wiegand_out_dev, mdev);
int cs;
switch (cmd) {
case WIEGAND_PULSE_WIDTH:
{
if(get_user(cs, (unsigned int *)arg))
return -EINVAL;
wiegand_out->pulse_width = cs;
break;
}
case WIEGAND_PULSE_INTERVAL:
{
if(get_user(cs, (unsigned int *)arg))
return -EINVAL;
wiegand_out->pulse_intval = cs;
break;
}
default:
return -EINVAL;
}
return 0;
}
static struct file_operations wiegand_out_misc_fops = {
.open = wiegand_out_open,
.release = wiegand_out_release,
.write = wiegand_out_write,
.unlocked_ioctl = wiegand_out_ioctl,
};
static int wiegand_out_probe(struct platform_device *pdev)
{
int ret = -1;
struct wiegand_out_dev *wiegand_out;
struct wiegand_platform_data *pdata;
printk(" WIEGAND OUT VERSION = %s \n",WIEGANDOUTDRV_LIB_VERSION);
pdata = dev_get_platdata(&pdev->dev);
if (!pdata) {
dev_err(&pdev->dev, "Failed to get platform_data %s %d.\n", __FUNCTION__, __LINE__);
return -ENXIO;
}
wiegand_out = kzalloc(sizeof(struct wiegand_out_dev), GFP_KERNEL);
if (!wiegand_out) {
printk("%s: alloc mem failed.\n", __FUNCTION__);
ret = -ENOMEM;
}
wiegand_out->data0_pin = pdata->data0_pin;
wiegand_out->data1_pin = pdata->data1_pin;
if (gpio_is_valid(wiegand_out->data0_pin)) {
ret = gpio_request(wiegand_out->data0_pin, "WIEGAND_OUT_DATA0");
if (ret < 0) {
printk("ERROR: request wiegand_out_data0 gpio failed.\n");
goto err_gpio_request0;
}
}
else {
printk("ERROR: wiegand_out_data0 gpio is invalid.\n");
goto err_gpio_request0;
}
if (gpio_is_valid(wiegand_out->data1_pin)) {
ret = gpio_request(wiegand_out->data1_pin, "WIEGAND_OUT_DATA1");
if (ret < 0) {
printk("ERROR: request wiegand_out_data1 gpio failed.\n");
goto err_gpio_request1;
}
}
else {
printk("ERROR: wiegand_out_data1 gpio is invalid.\n");
goto err_gpio_request1;
}
wiegand_out->dev = &pdev->dev;
wiegand_out->mdev.minor = MISC_DYNAMIC_MINOR;
wiegand_out->mdev.name = "dummy";
wiegand_out->mdev.fops = &wiegand_out_misc_fops;
wiegand_out_data_reset(wiegand_out);
wiegand_out->pulse_width = DEF_PULSE_WIDTH;
wiegand_out->pulse_intval = DEF_PULSE_INTERVAL;
wiegand_out->data_length = DEF_DATA_LENGTH;
spin_lock_init(&wiegand_out->lock);
init_waitqueue_head(&wiegand_out->wq);
hrtimer_init(&wiegand_out->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
wiegand_out->timer.function = wiegand_out_timeout;
ret = misc_register(&wiegand_out->mdev);
if (ret < 0) {
dev_err(&pdev->dev, "misc_register failed %s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
goto err_registe_misc;
}
platform_set_drvdata(pdev, wiegand_out);
printk("Weigand out driver register success.\n");
return 0;
err_registe_misc:
gpio_free(wiegand_out->data1_pin);
err_gpio_request1:
gpio_free(wiegand_out->data0_pin);
err_gpio_request0:
kfree(wiegand_out);
return ret;
}
static int wiegand_out_remove(struct platform_device *dev)
{
struct wiegand_out_dev *wiegand_out = platform_get_drvdata(dev);
misc_deregister(&wiegand_out->mdev);
gpio_free(wiegand_out->data0_pin);
gpio_free(wiegand_out->data1_pin);
kfree(wiegand_out);
return 0;
}
static struct platform_driver wiegand_out_driver = {
.probe = wiegand_out_probe,
.remove = wiegand_out_remove,
.driver = {
.name = "dummy",
},
};
static int __init wiegand_out_init(void)
{
return platform_driver_register(&wiegand_out_driver);
}
static void __exit wiegand_out_exit(void)
{
platform_driver_unregister(&wiegand_out_driver);
}
module_init(wiegand_out_init);
module_exit(wiegand_out_exit);
<file_sep>/sys_program/4th_day/shm.c
/* ************************************************************************
* Filename: shm.c
* Description:
* Version: 1.0
* Created: 2015年08月18日 17时01分32秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <sys/ipc.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <string.h>
int main(int argc, char *argv[])
{
key_t key;
char *buf;
key = ftok("./",66);
int id = shmget(key,2048,IPC_CREAT | 0666);
printf("id = %d\n",id);
buf = (char *)shmat(id,NULL,0);
bzero(buf,2048);
strcpy(buf,"I love programming");
return 0;
}
<file_sep>/work/test/mplay/mplay.c
/*************************************************************************
> File Name: mplay.c
> Author:
> Mail:
> Created Time: Thu 13 Oct 2016 11:29:59 AM CST
************************************************************************/
#include <tinyalsa/asoundlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <linux/input.h>
#define PARENT SIGUSR1
#define CHILD SIGUSR2
int exit_flag = 1;
int close_flag = 1;
void play_sample(char *filename, unsigned int device);
/*
* Functions
*/
void signal_handler(int signo)
{
switch(signo) {
case SIGINT:
printf("recv SIGINT\n");
close_flag = 1;
break;
case SIGCHLD:
printf("recv SIGCHLD\n");
waitpid(-1, NULL, WNOHANG); // recycling child process
exit_flag = 1;
break;
}
}
int main(int argc, char *argv[])
{
pid_t pid = -1;
int ret = 0;
int keyfd = 0;
char *filename = NULL;
struct input_event event;
keyfd = open("/dev/input/event0", O_RDONLY);
if(keyfd < 0) {
printf("open /dev/input/event0 device failed\n");
return -1;
}
if(argc == 2)
filename = argv[1];
else
filename = "/tmp/paomo.wav";
//注册父进程 SIGCHLD 信号处理函数,用于非阻塞回收子进程
//SIGCHLD 将在子进程exit()时发给父进程
signal(SIGCHLD, signal_handler);
while(1) {
bzero(&event, sizeof(struct input_event));
ret = read(keyfd, &event, sizeof(struct input_event));
if(ret == sizeof(struct input_event)) {
if(event.type == EV_KEY) {
printf("key %d -- %s\n", event.code, !event.value? "Pressed" : "Released");
if(event.code == KEY_POWER) {
if(event.value == 0) {
if(pid != -1) {
kill(pid, SIGINT);
pid = -1;
}
if(exit_flag) {
pid = fork();
if(pid < 0) {
perror("fork()");
break;
}
exit_flag = 0; // fork() succeed
if(pid == 0) {
//close_flag = 0;
//注册子进程 SIGINT 信号处理函数
//SIGINT 在父进程收到新命令时调用kill(pid, SIGINT)时发出
//signal(SIGINT, signal_handler);
play_sample(filename, 0);
#if 0
while(!close_flag) {
printf("child process: wait a common!\n");
sleep(1);
}
#endif
printf("child process %d: exit\n", getpid());
exit(0); // child process exit
}
}
}
}
}
}
}
close(keyfd);
return 0;
}
<file_sep>/c/homework/test_typewriting.c
/* ************************************************************************
* Filename: test_typewriting.c
* Description:
* Version: 1.0
* Created: 2015年07月22日 星期三 11時59分14秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <termios.h>
#include <unistd.h>
//#include <windows.h>
#define uint unsigned int
#define LENGHT 40
char mygetch()
{
struct termios oldt, newt;
char ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
void show_rule()
{
printf("\n---------------------\n");
printf(" 1.按任键开始测试\n");
printf(" 3.输入屏幕显示字符\n");
printf(" 4.输入首字母后计时\n");
printf(" 2.输入过程按Esc退出\n");
printf(" 5.输入出错以 _ 表示\n");
printf("----------------------\n");
}
void get_string(char *buf, int n)
{
char i,ch;
i = 0;
srand((uint)time(NULL));
do
{
ch = (char)rand()%128;
if((ch >= 'a' && ch <= 'z')
||(ch >= 'A' && ch <= 'Z'))
{
buf[i] = ch;
i++;
}
}while(i<n);
}
int main()
{
char i,ch;
char src[LENGHT],buf[LENGHT];
int start_time,end_time;
int count = 0;
//show_rule();
//mygetch();
system("clear");
while(1)
{
show_rule();
mygetch();
get_string(src,LENGHT);
//printf("%s\n",src);
for(i=0;i<LENGHT;i++)
{
printf("%c",src[i]);
}
putchar('\n');
for(i=0;i<LENGHT;i++)
{
ch = mygetch();
if(i == 0)
{
start_time = time(NULL);
}
if(ch == src[i])
{
putchar(ch);
count++;
}
else
{
if(ch == 27)
{
putchar('\n');
exit(0);
}
putchar('_');
}
}
end_time = time(NULL);
printf("\n输出完成!\n用时 %ds\n",end_time-start_time);
printf("正确率%.2f%\n",count/(LENGHT+0.0)*100);
printf("按Esc键退出,按空格键继续\n");
getch:
ch = mygetch();
switch(ch)
{
case ' ': system("clear"); break;
case 27: exit(0);
default: goto getch;
}
}
return 0;
}
<file_sep>/sys_program/2nd_day/pm/sighandler.c
/* ************************************************************************
* Filename: sighandler.c
* Description:
* Version: 1.0
* Created: 2015年08月14日 15时48分36秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
typedef void (* sighandler_t)(int);
void fun1(int signum)
{
printf("fun1 signal = %d\n",signum);
}
void fun2(int signum)
{
printf("fun2 signal = %d\n",signum);
}
int main(int argc, char *argv[])
{
sighandler_t p = NULL;
p = signal(2,fun1);
if(p == NULL)
printf("fun1\n");
p = signal(2,fun2);
if(p == fun1)
printf("fun2\n");
pause();
return 0;
}
<file_sep>/network/route/src/print.c
/******************************************************************************
文 件 名 : print.c
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月15日
最近修改 :
功能描述 : 帮助输出
函数列表 :
firewall_rule_set_help
show_help
修改历史 :
1.日 期 : 2015年9月15日
作 者 : if
修改内容 : 创建文件
******************************************************************************/
#include "common.h"
void show_help(void)
{
printf("*****************************************************\n");
printf("- arp: 查看 ARP 表 *\n");
printf("- clear: 清空屏幕 *\n");
printf("- exit: 关闭路由器 *\n");
printf("- help: 查看帮助信息 *\n");
printf("- ifconfig: 查看网卡信息 *\n");
printf("- reset: 恢复出厂设置 *\n");
printf("- fire on: 开启防火墙 *\n");
printf("- fire off: 关闭防火墙 *\n");
printf("- lsfire: 查看防火墙规则 *\n");
printf("- setfire: 设置防火墙规则 *\n");
printf("*****************************************************\n");
}
void firewall_rule_set_help(void)
{
printf("****************************************************************************\n");
printf("- >>> 温馨提示: ()是可选选项 <<< *\n");
printf("-设置 ip 过滤规则,格式: ip (opt) <ip> -> ip (src) 192.168.1.1 *\n");
printf("-设置 mac过滤规则,格式: mac (opt) <mac> -> mac (dst) 11:22:33:aa:bb:cc *\n");
printf("-设置端口过滤规则,格式: port (opt) <port> -> port (host) 8000 *\n");
printf("-设置协议过滤规则,格式: <pro> (type) (opt) (type_val) -> udp port 8000 *\n");
printf("-删除已设置的规则,输入: -d <要删除的规则> *\n");
printf("-查看设置规则帮助,输入: -h *\n");
printf("-查看已设置的规则,输入: ls *\n");
printf("-退出防火墙设置, 输入: esc *\n");
printf("****************************************************************************\n");
}
<file_sep>/work/shell/envsetup.sh
#!/bin/bash
export WORKPATH=`pwd`
TOP=$WORKPATH
while true;do
if [ -d $TOP/toolchains ];then
#echo $TOP
break
fi
if [ x$TOP == x ];then #这里x的作用用于判断$TOP是否为空, if [ X$str = Xabc ], 谨防$str 为空
echo "no"
break
else
echo "yes"
fi
TOP=${TOP%/*}
done
#if [ `uname -m`x = "i686"x ]; then
# TOOLCHAIN=$TOP/toolchains/mips-gcc472-glibc216-32bit/bin
#else
# TOOLCHAIN=$TOP/toolchains/mips-gcc472-glibc216/bin
#fi
TOOLCHAIN=$TOP/toolchains/mipsel-gcc472-glibc216-mips32/bin
PATH=$TOOLCHAIN:$PATH
echo "setup PATH=$TOOLCHAIN:\$PATH"
export CROSS_COMPILE='mips-linux-gnu-'
<file_sep>/shell/2nd_week/passwd.sh
#!/bin/bash
IFS.OLD=$IFS
IFS=$'\n'
for entry in `cat /etc/passwd`
do
echo "value in $entry"
IFS=:
for value in $entry
do
echo "$value"
done
done
IFS=$IFS.OLD
<file_sep>/network/route/src/inc/tcp_server.h
/******************************************************************************
文 件 名 : tcp_server.h
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月16日
最近修改 :
功能描述 : tcp_server.c 的头文件
******************************************************************************/
#ifndef __TCP_SERVER_H__
#define __TCP_SERVER_H__
#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */
/*----------------------------------------------*
* 外部函数原型说明 *
*----------------------------------------------*/
extern void tcp_send_arp_table(TYPE_Route *rt, int connfd);
extern void tcp_send_firewall_rules(TYPE_Route *rt, int connfd);
extern void tcp_send_port_info(TYPE_Route *rt, int connfd);
extern void dispose_tcp_cmd(TYPE_Route *rt, int connfd, char cmd[]);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
#endif /* __TCP_SERVER_H__ */
<file_sep>/work/test/yuv2bmp/yuv2bmp.c
/*************************************************************************
> Filename: main.c
> Author: Qiuwei.wang
> Email: <EMAIL> / <EMAIL>
> Datatime: Time: Tue 27 Sep 2016 11:09:02 AM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "bmp.h"
#include "srcBuf.h"
/*
* Macro
*/
#define DEFAULT_WIDTH 640
#define DEFAULT_HEIGHT 480
#define DEFAULT_BPP 16
static const char short_options[] = "b:hx:y:";
static const struct option long_options[] = {
{ "help", 0, NULL, 'h' },
{ "bpp", 1, NULL, 'b' },
{ "width", 1, NULL, 'x' },
{ "height", 1, NULL, 'y' },
{ 0, 0, 0, 0 }
};
/*
* Functions
*/
static void usage(FILE *fp, int argc, char *argv[])
{
fprintf(fp,
"\nUsage: %s [options]\n"
"Options:\n"
"-h | --help Print this message\n"
"-b | --bpp Set image bpp\n"
"-x | --width Set image width\n"
"-y | --height set image height\n"
"\n", argv[0]);
}
/*
* Functions
*/
unsigned int yuv2rgb_pixel(int y, int u, int v)
{
unsigned int rgb_24 = 0;
unsigned char *pixel = (unsigned char *)&rgb_24;
int r, g, b;
r = y + (1.370705 * (v - 128));
g = y - (0.698001 * (v - 128)) - (0.337633 * (u - 128));
b = y + (1.732446 * (u - 128));
if(r > 255) r = 255;
if(g > 255) g = 255;
if(b > 255) b = 255;
if(r < 0) r = 0;
if(g < 0) g = 0;
if(b < 0) b = 0;
/*
* BMP文件内部不压缩图片的格式是BGR
*/
pixel[0] = b;
pixel[1] = g;
pixel[2] = r;
return rgb_24;
}
/*
* YUV422 to RGB
*/
int yuv2rgb(unsigned char *yuv, unsigned char *rgb, unsigned int width, unsigned height)
{
unsigned int in = 0, out = 0;
unsigned int pixel_16;
unsigned char pixel_24[3];
unsigned int rgb_24;
unsigned int y0, u, y1, v;
for(in = 0; in < width * height * 2; in +=4) {
pixel_16 = yuv[in + 3] << 24 |
yuv[in + 2] << 16 |
yuv[in + 1] << 8 |
yuv[in + 0];
#if 0
u = (pixel_16 & 0x000000ff);
y0 = (pixel_16 & 0x0000ff00) >> 8;
v = (pixel_16 & 0x00ff0000) >> 16;
y1 = (pixel_16 & 0xff000000) >> 24;
#else
y0 = (pixel_16 & 0x000000ff);
v = (pixel_16 & 0x0000ff00) >> 8;
y1 = (pixel_16 & 0x00ff0000) >> 16;
u = (pixel_16 & 0xff000000) >> 24;
#endif
rgb_24 = yuv2rgb_pixel(y0, u, v);
pixel_24[0] = (rgb_24 & 0x000000ff);
pixel_24[1] = (rgb_24 & 0x0000ff00) >> 8;
pixel_24[2] = (rgb_24 & 0x00ff0000) >> 16;
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
rgb_24 = yuv2rgb_pixel(y1, u, v);
pixel_24[0] = (rgb_24 & 0x000000ff);
pixel_24[1] = (rgb_24 & 0x0000ff00) >> 8;
pixel_24[2] = (rgb_24 & 0x00ff0000) >> 16;
rgb[out++] = pixel_24[0];
rgb[out++] = pixel_24[1];
rgb[out++] = pixel_24[2];
}
return 0;
}
int writBMPFile(char *filename, unsigned int width, unsigned int height,\
int iBitCount, unsigned long rgbSize, unsigned char *rgbBuf)
{
unsigned char *dstBuf = NULL;
unsigned int i, j, size;
printf("width = %d, height = %d, rgbSize = %ld\n", width, height, rgbSize);
printf("sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) = 0x%0x\n", \
(unsigned int)(sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)));
printf("sizeof(BITMAPFILEHEADER) = 0x%02x\n", \
(unsigned int)sizeof(BITMAPFILEHEADER));
printf("sizeof(BITMAPINFOHEADER) = 0x%02x\n", \
(unsigned int)sizeof(BITMAPINFOHEADER));
if(iBitCount == 24) {
FILE *fp;
long count = 0;
BITMAPFILEHEADER bmpHeader;
BITMAPINFO bmpInfo;
if((fp = fopen(filename, "wb")) == NULL) {
printf("Can not create BMP file: %s\n", filename);
return -1;
}
bmpHeader.bfType = (WORD)(('M' << 8) | 'B');
bmpHeader.bfSize = rgbSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bmpHeader.bfReserved1 = 0;
bmpHeader.bfReserved2 = 0;
bmpHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmpInfo.bmiHeader.biWidth = width;
bmpInfo.bmiHeader.biHeight = height;
bmpInfo.bmiHeader.biPlanes = 1;
bmpInfo.bmiHeader.biBitCount = iBitCount;
bmpInfo.bmiHeader.biCompression = 0;
bmpInfo.bmiHeader.biSizeImage = rgbSize;
bmpInfo.bmiHeader.biXPelsPerMeter = 0;
bmpInfo.bmiHeader.biYPelsPerMeter = 0;
bmpInfo.bmiHeader.biClrUsed = 0;
bmpInfo.bmiHeader.biClrImportant = 0;
if((count = fwrite(&bmpHeader, 1, sizeof(BITMAPFILEHEADER), fp))
!= sizeof(BITMAPFILEHEADER))
printf("write BMP file header failed: count=%ld\n", count);
if((count = fwrite(&(bmpInfo.bmiHeader), 1, sizeof(BITMAPINFOHEADER), fp))
!= sizeof(BITMAPINFOHEADER))
printf("write BMP file info failed: count=%ld\n", count);
/* convert rgbbuf */
dstBuf = (unsigned char *)malloc(rgbSize);
if(!dstBuf) {
printf("malloc dstBuf failed !!\n");
return -1;
}
size = width * 3; // line size
for(i = 0, j = height -1; i < height - 1; i++, j--)
memcpy((dstBuf + (size * j)), (rgbBuf + (size * i)), size);
if((count = fwrite(dstBuf, 1, rgbSize, fp)) != rgbSize)
printf("write BMP file date failed: count=%ld\n", count);
free(dstBuf);
fclose(fp);
return 0;
} else {
printf("Err: iBitCount != 24\n");
return -1;
}
}
int main(int argc, char *argv[])
{
unsigned char *rgbBuf = NULL;
unsigned long rgbSize;
unsigned int bpp = DEFAULT_BPP;
unsigned int width = DEFAULT_WIDTH;
unsigned int height = DEFAULT_HEIGHT;
while(1) {
int oc;
oc = getopt_long(argc, argv, \
short_options, long_options, \
NULL);
if(-1 == oc)
break;
switch(oc) {
case 0:
break;
case 'h':
usage(stdout, argc, argv);
exit(EXIT_SUCCESS);
break;
case 'b':
bpp = atoi(optarg);
break;
case 'x':
width = atoi(optarg);
break;
case 'y':
height = atoi(optarg);
break;
default:
usage(stderr, argc, argv);
exit(EXIT_FAILURE);
break;
}
}
#if 0
printf("sizeof(unsigned long) = %ld\n", sizeof(unsigned long));
printf("sizeof(long) = %ld\n", sizeof(long));
printf("sizeof(int) = %ld\n", sizeof(int));
printf("sizeof(unsigned short) = %ld\n", sizeof(unsigned short));
#endif
rgbSize = width * height * 3;
rgbBuf = (unsigned char *)malloc(rgbSize);
if(!rgbBuf) {
printf("malloc rgbBuf failed !!\n");
return -1;
}
yuv2rgb(srcBuf, rgbBuf, width, height);
writBMPFile("./image/test.bmp", width, height, 24, rgbSize, rgbBuf);
free(rgbBuf);
return 0;
}
<file_sep>/c/homework/3rd_week/message/msg.c
#include <stdio.h>
#include <string.h>
#include "msg.h"
void show_number(const char *src)
{
printf("from: %s\n",src+3);
}
void show_time( char *src1,char *src2)
{
int i = 0;
char *pbuf[3] = {NULL};
char *p = NULL;
int time[3];
pbuf[0] = strtok(src1,"/");
while(pbuf[i++] != NULL)
{
pbuf[i] = strtok(NULL,"/");
}
if(atoi(pbuf[0])>15)
{
time[0] = 1900+ atoi(pbuf[0]);
}
else
{
time[0] = 2000+ atoi(pbuf[0]);
}
time[1] = atoi(pbuf[1]);
time[2] = atoi(pbuf[2]);
printf("date: %d年%d月%d日 ",time[0],time[1],time[2]);
p = strchr(src2,'+');
*p = '\0';
printf("%s\n",src2);
}
void show_content(const char *src)
{
printf("content: %s\n",src);
}
void show_message(char **src)
{
show_number(src[1]);
show_time(src[2],src[3]);
show_content(src[4]);
}
int msg_deal(char *msg_src, char *msg_done[],char *str)
{
int i = 0;
msg_done[0] = strtok(msg_src,str);
while(msg_done[i++] != NULL)
{
msg_done[i] = strtok(NULL,str);
}
return i;
}
<file_sep>/work/shell/smk.sh
#!/bin/bash
#
# Copyright (C) 2016 Ingenic Semiconductor, Inc.
# <NAME> <<EMAIL>, <EMAIL>>
#
# Build config seting
if [ "nand" = "$1" ]; then
UBOOT_BUILD_CONFIG=halley2_v20_zImage_sfc_nand
KERNEL_BUILD_CONFIG=halley2_v20_sfc_nand_defconfig
MOZART_BUILD_CONFIG=halley2_v2.0_43438_ubifs_config
MOZART_TARGET_FILE="appfs.img updater.img nv.img"
else
UBOOT_BUILD_CONFIG=halley2_v10_zImage_sfc_nor_config
KERNEL_BUILD_CONFIG=halley2_v10_nor_oss_defconfig
MOZART_BUILD_CONFIG=halley2_v2.0_43438_cramfs_config
MOZART_TARGET_FILE="appfs.cramfs updater.cramfs usrdata.jffs2 nv.img"
fi
UBOOT_TARGET_FILE=u-boot-with-spl.bin
KERNEL_IMAGE_PATH=arch/mips/boot/compressed
KERNEL_TARGET_FILE=zImage
MOZART_IMAGE_PATH=output/target
#
# Multithread compiling
MP=8
echoc()
{
echo -e "\e[0;91m$1\e[0m"
}
usage()
{
echoc "---------------------------------------------------------------------------"
echo "\
usage:
smk [OPTIONS]
used to quickly compile the mozart
support invoke from any location
image output directory: $OUTPUT_DIR
OPTIONS:
-a | --all ---> make all
-u | --uboot ---> make uboot
-k | --kernel ---> make kernel
-m | --mozart ---> make mozart
-c | --clean ---> distclean uboot、kernel、mozart, or all
-j | --jobs ---> set multithread compiling
-s | --setupinfo ---> get setup informations
-h | --help ---> get help message
eg:
smk -m ---> will make mozart
smk -u -k ---> will make uboot and kernel
smk -j 8 ---> will set number of jobs to -j8
smk -c k ---> will distclean kernel
smk -c ---> will distclean all, include the \$OUTPUT_DIR"
echoc "---------------------------------------------------------------------------"
return 0
}
setupinfo()
{
echoc "---------- smk envsetup ---------------------------------------------------"
echo " SOURCE_DIR = $SOURCE_DIR"
echo " TOOLCHAINS = $TOOLCHAINS"
echo "MKIMAGE_DIR = $MKIMAGE_DIR"
echo " OUTPUT_DIR = $OUTPUT_DIR"
echo "export PATH = \$TOOLCHAINS:\$MKIMAGE_DIR:\$PATH"
echo ""
echo " UBOOT_BUILD_CONFIG = $UBOOT_BUILD_CONFIG"
echo "KERNEL_BUILD_CONFIG = $KERNEL_BUILD_CONFIG"
echo "MOZART_BUILD_CONFIG = $MOZART_BUILD_CONFIG"
echo ""
echo " UBOOT_TARGET_FILE = $UBOOT_TARGET_FILE"
echo "KERNEL_TARGET_FILE = $KERNEL_TARGET_FILE"
echo "MOZART_TARGET_FILE = $MOZART_TARGET_FILE"
echoc "---------- If need help: smk -h -------------------------------------------"
}
envsetup()
{
local dir=$(pwd)
SOURCE_DIR=$dir
while true; do
if [ -d $SOURCE_DIR/mozart -a \
-d $SOURCE_DIR/u-boot -a \
-d $SOURCE_DIR/kernel* ]; then
break
fi
if [ x$SOURCE_DIR == x ]; then
echoc "Error, please read tools/README"
return -1;
fi
SOURCE_DIR=${SOURCE_DIR%/*}
done
OUTPUT_DIR=$SOURCE_DIR/out
MKIMAGE_DIR=$SOURCE_DIR/u-boot/tools
TOOLCHAINS=$SOURCE_DIR/tools/toolchains/mipsel-gcc472-glibc216-mips32/bin
if [ -d $TOOLCHAINS ]; then
export PATH=$TOOLCHAINS:$PATH;
else
echoc "TOOLCHAINS is not exist! Please read tools/README"
return -1
fi
if [ -d $MKIMAGE_DIR ]; then
export PATH=$MKIMAGE_DIR:$PATH
fi
if [ ! -d $OUTPUT_DIR ]; then
mkdir -p $OUTPUT_DIR
if [ $? -ne 0 ]; then
echoc "Create $OUTPUT_DIR failed, set OUTPUT_DIR=\$SOURCE_DIR"
OUTPUT_DIR=$SOURCE_DIR
fi
fi
setupinfo
}
declare -f croot > /dev/null || envsetup
make_uboot()
{
echoc "\nsmk: compiling u-boot ..."
cd $SOURCE_DIR/u-boot
make $UBOOT_BUILD_CONFIG && make -j$MP
if [ $? -eq 0 ]; then
cp $UBOOT_TARGET_FILE $OUTPUT_DIR
else
echoc "Failed to compile uboot, try 'smk -c u', then 'smk -u'"
return -1
fi
return 0
}
make_kernel()
{
echoc "\nsmk: compiling kernel ..."
cd $SOURCE_DIR/kernel*
make $KERNEL_BUILD_CONFIG && make $KERNEL_TARGET_FILE -j$MP
if [ $? -eq 0 ]; then
cp $KERNEL_IMAGE_PATH/$KERNEL_TARGET_FILE $OUTPUT_DIR
else
echoc "Failed to compile kernel, try 'smk -c k', then 'smk -k'"
return -1
fi
return 0;
}
make_mozart()
{
echoc "\nsmk: compiling mozart ..."
cd $SOURCE_DIR/mozart
make $MOZART_BUILD_CONFIG && make
if [ $? -eq 0 ]; then
cd $MOZART_IMAGE_PATH
cp $MOZART_TARGET_FILE $OUTPUT_DIR
else
echoc "Failed to compile mozart, try 'smk -c m', then 'smk -m'"
return -1
fi
return 0
}
make_clean()
{
case "$1" in
u | uboot)
echoc "smk: clean uboot ..."
cd $SOURCE_DIR/u-boot && make distclean
;;
k | kernel)
echoc "smk: clean kernel ..."
cd $SOURCE_DIR/kernel* && make distclean
;;
m | mozart)
echoc "smk: clean mozart ..."
cd $SOURCE_DIR/mozart && make distclean
;;
all|*)
echoc "smk: clean all ..."
if [ -d $OUTPUT_DIR -a $OUTPUT_DIR != $SOURCE_DIR ]; then
rm $OUTPUT_DIR -rf
fi
cd $SOURCE_DIR/u-boot && make distclean
cd $SOURCE_DIR/kernel* && make distclean
cd $SOURCE_DIR/mozart && make distclean
break
;;
esac
return 0
}
set_jobs()
{
case "$1" in
[1-9][0-9] | [1-9])
MP=$1
echoc "smk: set MP=$MP"
;;
*)
echoc "Invalid param, eg: smk -j 8"
return -1
;;
esac
return 0
}
smk()
{
local dir=$(pwd)
if [ $# -eq 0 ]; then
usage
return $?
fi
if [ ! -d $OUTPUT_DIR ]; then
mkdir -p $OUTPUT_DIR
if [ $? -ne 0 ]; then
echoc "Create $OUTPUT_DIR failed, set OUTPUT_DIR=\$SOURCE_DIR"
OUTPUT_DIR=$SOURCE_DIR
fi
fi
while [ $# -gt 0 ]
do
case $1 in
-a | --all)
echoc "smk: compiling all ..."
make_uboot && make_kernel && make_mozart
break
;;
-k | --kernel)
make_kernel || break
;;
-u | --uboot)
make_uboot || break
;;
-m | --mozart)
make_mozart || break
;;
-c | --clean)
shift
make_clean $1
break
;;
-j | --jobs)
shift
set_jobs $1
return $?
;;
-s | --setupinfo)
setupinfo
return $?
;;
-h | --help)
usage
return $?
;;
*)
echoc "Invalid option '$1', if need help: smk -h"
return -1
;;
esac
shift
done
cd $dir
echoc "smk: done !!!"
return 0
}
# auto complete
_smk()
{
local cur=${COMP_WORDS[COMP_CWORD]}
local prev=${COMP_WORDS[COMP_CWORD-1]}
local penult=${COMP_WORDS[COMP_CWORD-2]}
[[ "$cur" == "" && "$prev" == "=" ]] && return 0
local flag_preset="no"
local flag_separate="no"
local full_args="--jobs --all --uboot --kernel --mozart --clean --setupinfo --help"
if [[ "$cur" == * ]]; then
if (( $COMP_CWORD == 1 )); then
COMPREPLY=( $( compgen -W "$full_args" -- $cur ) )
else
for i in "${COMP_WORDS[@]}"
do
[ "$i" == "$cur" ] && break
case "$i" in
--all|--clean|--help|--setupinfo|-j) return ;;
--uboot) flag_separate="yes"; full_args=`echo "$full_args" | sed "s/--uboot//g"` ;;
--kernel) flag_separate="yes"; full_args=`echo "$full_args" | sed "s/--kernel//g"` ;;
--mozart) flag_separate="yes"; full_args=`echo "$full_args" | sed "s/--mozart//g"` ;;
esac
done
COMPREPLY=( $( compgen -W "$full_args" -- $cur ) )
fi
fi
return 0
}
complete -F _smk smk
<file_sep>/network/2nd_day/tftp_server.c
/* ************************************************************************
* Filename: tftp_server.c
* Description:
* Version: 1.0
* Created: 2015年09月02日 10时09分55秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
int main(int argc, char *argv[])
{
return 0;
}
<file_sep>/c/practice/3rd_week/mylink/main.c
#include <stdio.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include "link.h"
#define MAX 6 //队列大小
char mygetch()
{
struct termios oldt, newt;
char ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
void help()
{
system("clear");
printf("-----------------------------------\n");
printf("->help : 帮助信息 -\n");
printf("->insert: 插入一个新节点 -\n");
printf("->print : 遍历整个链表 -\n");
printf("->search: 查询某个节点 -\n");
printf("->delete: 查删除某个节点 -\n");
printf("->free : 释放整个节点 -\n");
printf("->sort : 将链表排序 -\n");
printf("->invert: 倒置整个链表 -\n");
printf("->exit : 退出 -\n");
printf("-----------------------------------\n");
}
int main(int argc,char *argv[])
{
char cmd[128] = "";
int count = 0;
STU *head = NULL;
system("clear");
help();
while(1)
{
printf("cmd: ");
fflush(stdout);
scanf("%s",cmd);
if(strcmp(cmd,"help")==0)
{
help();
}
else if(strcmp(cmd,"insert")==0)
{
int num;
char ch, temp[48];
STU new;
while(1)
{
printf("please input the num, name, score: ");
//scanf("%d %s %d",&new.num,new.name,&new.score);
fscanf(stdin,"%d %s %d",&new.num,new.name,&new.score);
gets(temp);
if(new.num != num)
{
if(count < MAX)
{
head = insert_link(head, new);
count++;
}
else
{
head = delete_head(head);
head = insert_link(head, new);
}
num = new.num;
if(head != NULL) //成功插入新节点
{
printf("按任意键继续,按‘Esc'结束\n");
ch = mygetch();
if(ch == 27)//Esc 键的ASCII 码为27
{
printf("结束插入!\n");
break;
}
}
}
else
{
printf("\n输入无效!\n");
}
}
}
else if(strcmp(cmd,"print")==0)
{
printf("-----print-----\n");
print_link(head);
}
else if(strcmp(cmd,"search")==0)
{
char name[64] = "";
STU *ret;
printf("please input search name\n");
scanf("%s",name);
ret = search_link(head, name);
if(ret == NULL)
{
printf("not found\n");
}
else
{
printf("num: %-4d name:%-8s score: %-3d\n",ret->num,ret->name,ret->score);
}
}
else if(strcmp(cmd,"delete")==0)
{
int num = 0;
printf("Please input delete num\n");
scanf("%d",&num);
head = delete_link(head,num);
count--;
if(count < 0) count = 0;
}
else if(strcmp(cmd,"free")==0)
{
printf("-----free link-----\n");
head = free_link(head);
}
else if(strcmp(cmd,"sort")==0)
{
printf("-----sort link from score-----\n");
sort_link(head);
print_link(head);
}
else if(strcmp(cmd,"invert")==0)
{
printf("-----invert link-----\n");
head = invert_link(head);
print_link(head);
}
else if(strcmp(cmd,"exit")==0)
{
printf("----- exit -----\n");
if(head != NULL)
{
head = free_link(head);
}
break;
}
else
{
printf("命令不存在!需要帮助,请输入“help”\n");
}
}
return 0;
}
<file_sep>/work/debug/2440/leds/Makefile
ifneq ($(KERNELRELEASE),)
obj-m := leds_drv.o
else
# KERNELDIR ?= /lib/modules/$(shell uname -r)/build
KERNELDIR ?= ~/micro2440/linux/linux-2.6.32.2
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
rm -rf *.o *.mod.c *.order *.symvers .*.cmd .tmp*
clean:
rm -f *.o *~ *.ko *.mod.c *.mod.o *.symvers *.order
endif
mod:
sudo insmod ./leds_dev.ko
mt:
gcc -o test test_leds.c
.PHONY:clc
clc:
rm test
<file_sep>/work/test/cim_test-zmm220/camera.c
#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <time.h>
#include <sys/time.h>
#include <signal.h>
#include "arca.h"
#include "sensor.h"
#include "cim.h"
#include "futil.h"
#include "mt9v136.h"
//#include "mt9v136old62.h"
#define IMAGESIZE (640*480)
#define RGB565CUT (640*480)
#define YUVSIZE (640*480*2)
#define RGB24 (640*480)//(320*240*3)
#define YUVCUT (640*240*3)
#define PIN (1*32+29) //(3*32+2)
#define TEST 1
#define GC0308 1
#define MT367 2
#if TEST
#define LCD_DEV "/dev/fb0"
static int lcd_fd = -1;
static unsigned int fb_width;
static unsigned int fb_height;
static unsigned int fb_depth;
static unsigned int screensize;
static unsigned char *fbmem;
#endif
extern void*fb_mmap(int fd, unsigned int screensize);
int init_camera_gc0308(int width,int height,int bpp)
{
int ret=0;
TIMING_PARAM t;
ret=cim_open(GC0308,width, height, bpp);
if(ret<0){
printf(" cim open fail \n ");
return -1;
}
ret = sensor_open_0308();
if(ret < 0) {
printf("Open sensor fail!!\n");
return -1;
}
gc0308_init();
t.mclk_freq = 24000000;
t.pclk_active_direction = 1;
t.hsync_active_level = 1;
t.vsync_active_level = 1;
ret = set_timing_param(GC0308,&t);
if(ret == 0) {
printf("set_timing_param fail!!\n");
return -1;
}
printf("Set mclk to %dHz.\n", t.mclk_freq);
sensor_close_0308();
printf("GC0308 Init finish!\n");
return 0;
}
int init_camera_mi367(int width,int height,int bpp)
{
int ret = -1;
TIMING_PARAM t;
ret=cim_open(MT367,width, height, 16);
if(ret<0){
printf(" %s fail \n ",__func__);
return -1;
}
ret = sensor_open_mi367();
if(ret < 0) {
printf("Open sensor fail!!\n");
return -1;
}
InitMT9V136(width,height,mt9v117regs1);
InitMT9V136(width,height,wieght_table);
t.mclk_freq = 48000000;
t.pclk_active_direction = 0;
t.hsync_active_level = 1;
t.vsync_active_level = 0;
set_timing_param(MT367,&t);
if(ret == 0) {
printf("set_timing_param fail!!\n");
return -1;
}
printf("Set mclk to %dHz.\n", t.mclk_freq);
sensor_close_mi367();
printf("MI367 Init finish!\n");
return 0;
}
int initcamera(unsigned char sensor,int width,int height,int bpp)
{
int ret = -1 ;
switch(sensor)
{
case GC0308:
ret = init_camera_gc0308(width,height,bpp);
break;
case MT367:
ret = init_camera_mi367(width,height,bpp);
break;
default:
printf(" NOT SUPPORT SENSOR \n");
ret = -1;
break;
}
return ret;
}
void close_camera(int id)
{
cim_close(id);
}
int saveImage(int quality,int width,int height,const char *path, unsigned char *yuv422buf)
{
int i;
unsigned char *pframebuf;
unsigned char *yuv_data[3];
#if TEST
pframebuf = (unsigned char *)yuv422buf;
yuv_data[0] = pframebuf;
yuv_data[2] = pframebuf + width*height;
yuv_data[1] = pframebuf + width*height*3/2;
write_JPEG_file(path,quality,width,height,yuv_data);
#endif
return 0;
}
int grab_image(unsigned int id,int width,int height,unsigned char *buf)
{
return cim_read(id,buf, width * height * 2);
}
#if TEST
int openlcd(void)
{
lcd_fd = fb_open(LCD_DEV);
if(lcd_fd<0)
{
printf("open /dev/fb0 fail!!\n");
return -1;
}
printf("openlcd ok lcd_fd =%d\n",lcd_fd);
fb_stat(lcd_fd,&fb_width,&fb_height,&fb_depth);
printf("fb: w = %d h = %d depth = %d\n", fb_width, fb_height, fb_depth);
screensize = fb_width * fb_height *fb_depth/8;
fbmem = fb_mmap(lcd_fd,screensize);
if (!fbmem)
{
printf("fb_mmap failed!\n");
return -1;
}
return 0;
}
int closelcd(void)
{
//fb_munmap(fbmem,screensize);
fb_close(LCD_DEV);
return 0;
}
#if 0
int fb_pixelAsRow(void *fbmem, int width_cut, int height_cut, int x, int y, unsigned int *rowbuf, int bufsize)
{
unsigned int *dst = ((unsigned int *) fbmem + y * width_cut + x);
memcpy(dst, rowbuf, bufsize);
return (0);
}
int displayx(int width, int height,unsigned int width_cut,unsigned int height_cut,unsigned int *rgb888)
{
unsigned int x,y,k=0;
for(y = 0; y < height_cut; y++)
{
fb_pixelAsRow(fbmem,width_cut,height_cut,0,y,rgb888+y*width,width *4);
}
}
#endif
#if 1
int displayx(int ox, int oy,unsigned int width_cut,unsigned int height_cut,unsigned short *rgb565cut)
{
unsigned int x,y,k=0;
for(y = 0; y < height_cut; y++)
{
fb_pixelAsRow(fbmem,fb_width,fb_height,0,y,rgb565cut+y*width_cut,width_cut *2);
}
}
#endif
#endif
#if TEST
/****************************************************************************************
flag = 0 save bmp
flag = 1 save jpeg
flag = 2 display to lcd
*******************************************************************************************/
int sensor_0308_handle(int width, int higth, unsigned char *yuv422buf,unsigned short *rgb565,int flag)
{
grab_image(GC0308,width,higth,(unsigned char *)rgb565);
}
/****
flag = 0 save bmp
flag = 1 save jpeg
flag = 2 display to lcd
****/
int sensor_367_handle(int width, int higth, unsigned char *yuv422buf,unsigned short *rgb565,int flag)
{
if(grab_image(MT367,width,higth,yuv422buf)>0)
yuv422rgb565(yuv422buf,rgb565,width,higth);
}
#define USEGV0308 1
#define USEMI367 0
#define ROTATE 1
int main(int argc,char *argv[])
{
int ret;
int width_out, height_out;
unsigned short *rgb565_0308buf = NULL;
unsigned char *yuv422_367buf =NULL;
unsigned short *rgb565_out=NULL;
unsigned short *rgb565_367buf=NULL;
openlcd();
int flag=2;
#if USEGV0308
ret = init_camera_gc0308(640,480,16);
if (ret) {
printf("init_camera_gc0308 failed!\n");
return -1;
}
//rgb565_0308buf = cim_mmap(GC0308,640*480*2);
rgb565_0308buf = malloc(640*480*2);
if (!rgb565_0308buf) {
printf("cim_mmap 0308 failed!\n");
return -1;
}
#endif
#if USEMI367
ret = init_camera_mi367(640,480,16);
if (ret) {
printf("init_camera_mi367!\n");
return -1;
}
//yuv422_367buf = cim_mmap(MT367,640*480*2);
yuv422_367buf = malloc(640*480*2);
if (!yuv422_367buf) {
printf("cim_mmap 367 buf failed!\n");
return -1;
}
rgb565_367buf = (unsigned short *)malloc(RGB565CUT);
if (!rgb565_367buf) {
printf("malloc failed %s %d\n", __func__, __LINE__);
return -1;
}
#endif
#if ROTATE
rgb565_out = (unsigned short *)malloc(2 * RGB565CUT);
if (!rgb565_out) {
printf("malloc failed %s %d\n", __func__, __LINE__);
return -1;
}
#endif
while(1)
{
#if USEGV0308
sensor_0308_handle(640,480,NULL,rgb565_0308buf,flag);
#endif
#if USEMI367
sensor_367_handle(640,480,yuv422_367buf,rgb565_367buf,flag);
#endif
#if ROTATE
rgb565_rotate90(rgb565_0308buf, 640, 480, rgb565_out, &width_out, &height_out);
displayx(0, 0, width_out, height_out, rgb565_out);
#else
displayx(0, 0, 640, 480, rgb565_0308buf);
#endif
}
#if USEGV0308
close_camera(GC0308);
#endif
#if USEMI367
close_camera(MT367);
#endif
closelcd();
if (rgb565_out)
free(rgb565_out);
if (rgb565_367buf)
free(rgb565_367buf);
return 0;
}
#endif //endif test
<file_sep>/gtk/4st_week/gtk_vbox.c
/* ************************************************************************
* Filename: gtk_hbox.c
* Description:
* Version: 1.0
* Created: 2015年08月10日 11时34分43秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <gtk/gtk.h>
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(window,"destroy", G_CALLBACK(gtk_main_quit),NULL);
//创建一个垂直容器
GtkWidget *vbox = gtk_vbox_new(TRUE,10);
//添加到window
gtk_container_add(GTK_CONTAINER(window),vbox);
GtkWidget *button1 = gtk_button_new_with_label("button1");
//添加button1到hbox
gtk_container_add(GTK_CONTAINER(vbox),button1);
GtkWidget *button2 = gtk_button_new_with_label("button2");
//添加button1到hbox
gtk_container_add(GTK_CONTAINER(vbox),button2);
GtkWidget *button3 = gtk_button_new_with_label("button3");
//添加button1到hbox
gtk_container_add(GTK_CONTAINER(vbox),button3);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
<file_sep>/network/sockets/TCPEchoClient.c
/*************************************************************************
> File Name: TCPEchoClient.c
> Author:
> Mail:
> Created Time: Fri 06 May 2016 11:12:30 AM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include "Practical.h"
int main(int argc, char *argv[])
{
if(argc < 3 || argc > 4) //Test for correct number of arguments
DieWithUserMessage("Paramter(s)", "<Server Address/Name> <Echo Word> [<Server Port/Service]");
char *server = argv[1]; //First arg: server address/name
char *echoString = argv[2]; //Second arg: string to echo
char *service = (argc == 4)?argv[3]:"echo"; //Third arg (optional): server port/service
//Create a connected TCP socket
int sock = SetupTCPClientSocket(server, service);
if(sock < 0)
DieWithUserMessage("SetupTCPClientSocket() failed","unable to connect");
size_t echoStringLen = strlen(echoString);
//Send the string to the server
ssize_t numBytes = send(sock, echoString, echoStringLen, 0);
if(numBytes < 0)
DieWithSystemMessage("send() failed");
else if(numBytes != echoStringLen)
DieWithUserMessage("send()", "sent unexpected number of bytes");
//Recevice the same string back from the server
unsigned int totalBytesRcvd = 0; //Count of total bytes receviced
fputs("Receviced: ", stdout);
while(totalBytesRcvd < echoStringLen) {
char buffer[BUFSIZE];
numBytes = recv(sock, buffer, BUFSIZE - 1, 0);
if(numBytes < 0)
DieWithSystemMessage("recv() failed");
else if(numBytes == 0)
DieWithUserMessage("recv()", "connection closed prematurely");
totalBytesRcvd += numBytes; //Keep tally of total bytes
buffer[numBytes] = 0; //Terminate the string
fputs(buffer, stdout); //Print the buffer
}
fputc('\n',stdout);
close(sock);
exit(0);
}
<file_sep>/work/test/v4l2/main.c
/*************************************************************************
> Filename: main.c
> Author: Qiuwei.wang
> Email: <EMAIL> / <EMAIL>
> Datatime: Fri 02 Dec 2016 10:54:24 AM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <getopt.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include "common.h"
#include "capture.h"
/*
* Macro
*/
#define DEFAULT_DEVICE "/dev/video0"
#define DEFAULT_WIDTH 640
#define DEFAULT_HEIGHT 480
#define DEFAULT_BPP 16
#define DEFAULT_NBUF 1
static const char short_options[] = "d:hmn:rux:y:";
static const struct option long_options[] = {
{ "device", 1, NULL, 'd' },
{ "help", 0, NULL, 'h' },
{ "mmap", 0, NULL, 'm' },
{ "nbuf", 1, NULL, 'n' },
{ "read", 0, NULL, 'r' },
{ "userp", 0, NULL, 'u' },
{ "width", 1, NULL, 'x' },
{ "height", 1, NULL, 'y' },
{ 0, 0, 0, 0 }
};
/*
* Functions
*/
static void usage(FILE *fp, int argc, char *argv[])
{
fprintf(fp,
"\nUsage: %s [options]\n"
"Options:\n"
"-d | --device name Video device name [/dev/video]\n"
"-h | --help Print this message\n"
"-m | --mmap Use memory mapped buffers\n"
"-n | --nbuf Request buffer numbers\n"
"-r | --read Use read() calls\n"
"-u | --userp Use application allocated buffers\n"
"-x | --width Capture width\n"
"-y | --height Capture height\n"
"\n", argv[0]);
}
int main(int argc, char *argv[])
{
struct capture_t capt;
capt.dev_name = DEFAULT_DEVICE;
capt.width = DEFAULT_WIDTH;
capt.height = DEFAULT_HEIGHT;
capt.bpp = DEFAULT_BPP;
capt.nbuf = DEFAULT_NBUF;
capt.io = IO_METHOD_MMAP;
while(1) {
int oc;
oc = getopt_long(argc, argv, \
short_options, long_options, \
NULL);
if(-1 == oc)
break;
switch(oc) {
case 0:
break;
case 'd':
capt.dev_name = optarg;
break;
case 'h':
usage(stdout, argc, argv);
exit(EXIT_SUCCESS);
break;
case 'm':
capt.io = IO_METHOD_MMAP;
break;
case 'r':
capt.io = IO_METHOD_READ;
break;
case 'u':
capt.io = IO_METHOD_USERPTR;
break;
case 'n':
capt.nbuf = atoi(optarg);
break;
case 'x':
capt.width = atoi(optarg);
break;
case 'y':
capt.height = atoi(optarg);
break;
default:
usage(stderr, argc, argv);
exit(EXIT_FAILURE);
break;
}
}
open_device(&capt);
init_device(&capt);
test_framerate(&capt);
start_capturing(&capt);
main_loop(&capt);
stop_capturing(&capt);
free_device(&capt);
close_device(&capt);
return 0;
}
<file_sep>/network/5th_day/checksum.c
unsigned short checksum(unsigned short *buf, int nword)
{
unsigned long sum;
for(sum = 0; nword > 0; nword--)
{
sum += htons(*buf);
buf++;
}
sum = (sum>>16) + (sum&0xffff);
sum += (sum>>16);
return ~sum;
}
<file_sep>/sys_program/4th_day/homework/mplayer/mplayer.c
/* ************************************************************************
* Filename: mplayer.c
* Description:
* Version: 1.0
* Created: 2015年08月18日 12时25分03秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include "interface.h"
void *fun(void *arg)
{
int i = (int)arg;
printf("pid = %d\n",i);
sleep(6);
kill((int)arg,2);
}
int main(int argc, char* argv[])
{
WINDOW window;
pid_t pid;
pthread_t pth;
mkfifo("cmd_fifo",0777);
fd = open("cmd_fifo",O_RDWR);
pid = fork();
if(pid < 0)
{
perror("");
exit(-1);
}
else if(pid == 0) //
{
printf("start mplayer now!\n");
//write(fd, "pause\n", strlen("pause\n")); //
//启动mplayer
execlp("mplayer",
"mplayer",
"-slave", "-quiet","-idle",
"-input", "file=./cmd_fifo",
"./media/sad_or_happy.mp3", NULL);
}
else
{
//pthread_create(&pth,NULL,fun,(void *)pid); //创建一个新进程
write(fd, "pause\n", strlen("pause\n")); //
gtk_init(&argc, &argv);
show_window(&window);
gtk_main();
}
return 0;
}
<file_sep>/work/test/gpioset/gpioset.c
/*************************************************************************
> File Name: gpioset.c
> Author:
> Mail:
> Created Time: Tue 24 May 2016 04:36:11 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
/*#define DEBUG*/
#define GPIO_SET_OUTPUT 1
#define GPIO_SET_INPUT 0
#define GPIO_SET_LOW 0
#define GPIO_SET_HIGH 1
// Functions declaration
static void print_help(void);
static int gpio_export(int pin);
static int gpio_unexport(int pin);
static int gpio_direction(int pin, int dir);
static int gpio_read(int pin);
static void print_help(void)
{
printf("Usage: gpioset gpionum I/O/H/L/R\n");
printf("Usage:\n");
printf(" I -> set gpio input\n");
printf(" O -> set gpio output\n");
printf(" H -> set gpio output 1\n");
printf(" L -> set gpio output 0\n");
printf(" R -> read gpio value\n");
printf(" eg: gpioset 52 I\n");
}
static int gpio_export(int gpionum)
{
char buffer[64];
int len, fd;
fd = open("/sys/class/gpio/export", O_WRONLY);
if(fd < 0) {
printf("Failed to open export for writing!\n");
return -1;
}
len = snprintf(buffer, sizeof(buffer),"%d", gpionum);
if(write(fd, buffer, len) < 0) {
printf("Failed to export gpio%d!\n", gpionum);
return -1;
}
close(fd);
return 0;
}
static int gpio_unexport(int gpionum)
{
char buffer[64];
int len, fd;
fd = open("/sys/class/gpio/unexport", O_WRONLY);
if(fd < 0) {
printf("Failed to open upexport for writing!\n");
return -1;
}
len = snprintf(buffer, sizeof(buffer),"%d", gpionum);
if(write(fd, buffer, len) < 0) {
printf("Failed to upexport gpio%d!\n", gpionum);
return -1;
}
close(fd);
return 0;
}
//dir: 0 -> in, 1-> out
static int gpio_direction(int gpionum, int dir)
{
static const char dir_str[] = "in\0out";
char path[64];
int fd;
snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/direction", gpionum);
fd = open(path, O_WRONLY);
if(fd < 0) {
printf("Failed to open gpio direction for writing!\n");
return -1;
}
if(write(fd, &dir_str[dir == 0?0:3], dir == 0?2:3) < 0) {
printf("Failed to set gpio%d direction!\n", gpionum);
return -1;
}
close(fd);
return 0;
}
//value: 0 -> LOW, 1 -> HIGH
static int gpio_write(int gpionum, int value)
{
char path[64];
char value_str[3] = "01";
int fd;
snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value", gpionum);
fd = open(path, O_WRONLY);
if(fd < 0) {
printf("Failed to open gpio value for reading!\n");
return -1;
}
if(write(fd, &value_str[value == 0?0:1], 1) < 0) {
printf("Failed to write gpio%d value!\n", gpionum);
return -1;
}
close(fd);
return 0;
}
static int gpio_read(int gpionum)
{
char path[64];
char value_str[3] = {0};
int fd, i;
snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value", gpionum);
printf("path: %s\n",path);
fd = open(path, O_RDONLY);
if(fd < 0) {
printf("Failed to open gpio value for reading!\n");
return -1;
}
for(i = 0; i < 2; i++) {
if(read(fd, value_str, sizeof(value_str)) < 0) {
printf("Failed to read gpio%d value!\n", gpionum);
return -1;
}
}
#ifdef DEBUG
printf("### read value = %s\n", value_str);
for(i = 0; i < 3; i++) {
printf("value_str[%d] = %d\t",i, value_str[i]);
}
printf("\n");
#endif
close(fd);
return atoi(value_str);
}
int main(int argc, char *argv[])
{
// Test for correct number of arguments
if(argc != 3) {
print_help();
return -1;
}
int gpionum = atoi(argv[1]);
if(gpionum < 0 || gpionum > 101) { // For Ingenic x1000 soc
printf("### gpionum: %d is invalid ###\n", gpionum);
return -1;
}
int ret = gpio_export(gpionum);
if(ret < 0)
return -1;
char opt;
memcpy(&opt, argv[2], 1);
switch(opt) {
case 'I': // Set gpio direction as input
gpio_direction(gpionum, GPIO_SET_INPUT);
break;
case 'O': // Set gpio dirextion as output
gpio_direction(gpionum, GPIO_SET_OUTPUT);
break;
case 'H': // Set gpio output 1
ret = gpio_direction(gpionum, GPIO_SET_OUTPUT);
if(ret != -1)
gpio_write(gpionum, GPIO_SET_HIGH);
break;
case 'L': // Set gpio output 0
ret = gpio_direction(gpionum, GPIO_SET_OUTPUT);
if(ret != -1)
gpio_write(gpionum, GPIO_SET_LOW);
break;
case 'R': // Read gpio value
ret = gpio_read(gpionum);
if(ret != -1)
printf("### read gpio%d ret = %d ###\n", gpionum, ret);
break;
default:
print_help(); // Show help when entry a wrong argument
}
printf("### Successful opetation! ###\n");
gpio_unexport(gpionum);
return 0;
}
<file_sep>/work/shell/s11mount
#!/bin/sh
# mount rootfs
#mount -t jffs2 /dev/mtdblock3 /mnt/rootfs
#if [ $? -ne 0 ]; then
if [ ! -d "rootfs" ]; then
exit 1
fi
libs="ld-2.16.so
ld.so.1
libc-2.16.so
libcrypto.so
libcrypto.so.1.0.0
libc.so.6
libdl-2.16.so
libdl.so.2
libm-2.16.so
libm.so.6
libnss_dns-2.16.so
libnss_dns.so.2
libnss_files-2.16.so
libnss_files.so.2
libpthread-2.16.so
libpthread.so.0
libresolv-2.16.so
libresolv.so.2
librt-2.16.so
librt.so.1
libnl-3.so
libnl-3.so.200
libnl-3.so.200.19.0
libnl-genl-3.so
libnl-genl-3.so.200
libnl-genl-3.so.200.19.0
libssl.so
libssl.so.1.0.0"
# copy libs
ROOTFS=./rootfs
mkdir lib usr/lib sbin -p
for lib in $libs
do
if [ -f $ROOTFS/lib/$lib ]; then
cp $ROOTFS/lib/$lib lib/ -a
elif [ -f $ROOTFS/usr/lib/$lib ]; then
cp $ROOTFS/usr/lib/$lib usr/lib/ -a
else
echo "$lib dose not exist ..."
fi
done
cp $ROOTFS/sbin/wifi_connect.sh sbin/
cp $ROOTFS/usr/sbin/wpa_supplicant sbin/
<file_sep>/network/route/src/inc/route_firewall.h
/******************************************************************************
文 件 名 : route_firewall.h
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月14日
最近修改 :
功能描述 : route_firewall.c 的头文件
******************************************************************************/
#ifndef __ROUTE_FIREWALL_H__
#define __ROUTE_FIREWALL_H__
#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */
/*----------------------------------------------*
* 内部函数原型说明 *
*----------------------------------------------*/
//static Boolean check_input_rules();
static int firewall_filt_ip(TYPE_Route *rt, MSG_Info *pinfo);
static int firewall_filt_mac(TYPE_Route *rt, MSG_Info *pinfo);
static int firewall_filt_port(TYPE_Route *rt, MSG_Info *pinfo);
static int firewall_filt_protocol(TYPE_Route *rt, MSG_Info *pinfo);
/*----------------------------------------------*
* 外部函数原型说明 *
*----------------------------------------------*/
extern void firewall_rule_set_help(void);
extern void firewall_build_rule(TYPE_Route *rt, const char *rule, char flag);
extern void delete_firewall_rule(TYPE_Route *rt, const char *rule);
extern int firewall_filt(TYPE_Route *rt, MSG_Info *pinfo);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
/*****************************************************************************
>>> 防火墙规则输入格式 <<<
ip src 10.221.2.1
ip dst 10.221.2.1
ip host 10.221.2.1
mac src 01:02:03:04:05:06
mac dst 01:02:03:04:05:06
mac host 01:02:03:04:05:06
port src 8000
port dst 8000
port 8000
tcp ip src 10.221.2.1
tcp port dst 8000
tcp port 8000
arp
tcp
udp
icmp
igmp
http
tftp
*****************************************************************************/
#endif /* __ROUTE_FIREWALL_H__ */
<file_sep>/work/debug/a8/buttons/buttons_dev.c
#include <linux/module.h>
#include <linux/ioport.h> /* resource */
#include <linux/irq.h> /* IRQ_EINT(23) */
#include <linux/gpio.h> /* S5PV210_GPH3(0) */
#include <linux/platform_device.h> /* platform_device_register() */
#include <linux/gpio_keys.h> /* gpio_keys_button */
#include <linux/input.h>
static struct gpio_keys_button s5pv210_gpio_buttons[] = {
// KEY2
{
.code = KEY_UP,
.gpio = S5PV210_GPH2(3),
.desc = "key-up",
.type = EV_KEY,
},
// KEY4
{
.code = KEY_DOWN,
.gpio = S5PV210_GPH2(5),
.desc = "key-down",
.type = EV_KEY,
},
// KEY6
{
.code = KEY_LEFT,
.gpio = S5PV210_GPH2(7),
.desc = "key-left",
.type = EV_KEY,
},
// KEY5
{
.code = KEY_RIGHT,
.gpio = S5PV210_GPH2(6),
.desc = "key-right",
.type = EV_KEY,
},
};
static struct resource s5pv210_gpio_resource[] = {
[0] = {
.start = S5PV210_GPH3(0),
.end = S5PV210_GPH3(0),
.name = "GPH3_0",
.flags = IORESOURCE_IO,
},
[1] = {
.start = S5PV210_GPH0(3),
.end = S5PV210_GPH0(3),
.name = "GPH0_3",
.flags = IORESOURCE_IO,
}
};
static struct gpio_keys_platform_data s5pv210_buttons_info = {
.buttons = s5pv210_gpio_buttons,
.nbuttons = ARRAY_SIZE(s5pv210_gpio_buttons),
};
static void s5pv210_buttons_device_release(struct device *pdev)
{
printk(KERN_WARNING "%s\n",__FUNCTION__);
return;
}
static struct platform_device s5pv210_buttons_dev = {
.name = "s5pv210_buttons",
.id = -1,
.num_resources = ARRAY_SIZE(s5pv210_gpio_resource),
.resource = s5pv210_gpio_resource,
.dev = {
.platform_data = &s5pv210_buttons_info,
.release = s5pv210_buttons_device_release,
},
};
static int __init s5pv210_buttons_device_init(void)
{
return platform_device_register(&s5pv210_buttons_dev);
}
static void __exit s5pv210_buttons_device_exit(void)
{
platform_device_unregister(&s5pv210_buttons_dev);
return;
}
module_init(s5pv210_buttons_device_init);
module_exit(s5pv210_buttons_device_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/test/v4l2/capture.c
/*************************************************************************
> Filename: capture.c
> Author: Qiuwei.wang
> Email: <EMAIL> / <EMAIL>
> Datatime: Mon 28 Nov 2016 06:05:39 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <getopt.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <asm/types.h> /* for videodev2.h */
#include <linux/videodev2.h>
#include "common.h"
#include "yuv2bmp.h"
#include "capture.h"
/*
* Functions
*/
static void init_read(struct capture_t *capt)
{
capt->pbuf = calloc(1, sizeof(struct buffer));
if(capt->pbuf) {
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
capt->pbuf[0].length = capt->sizeimage;
capt->pbuf[0].start = malloc(capt->sizeimage);
if(!capt->pbuf[0].start) {
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
}
static void init_mmap(struct capture_t *capt)
{
int i;
struct v4l2_requestbuffers req;
CLEAR(req);
req.count = capt->nbuf;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
/* Request buffer */
if(-1 == xioctl(capt->fd, VIDIOC_REQBUFS, &req)) {
if(EINVAL == errno) {
fprintf(stderr, "%s does not support "
"memory mapping\n", capt->dev_name);
exit(EXIT_FAILURE);
} else
errno_exit("VIDIOC_REQBUFS");
}
if (req.count < 1) {
fprintf(stderr, "Insufficient buffer memory on %s\n",
capt->dev_name);
exit(EXIT_FAILURE);
}
capt->pbuf = calloc(req.count, sizeof(struct buffer));
if(!capt->pbuf) {
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
/* Update the value of nbuf */
capt->nbuf = req.count;
for(i = 0; i < req.count; i++) {
struct v4l2_buffer buf;
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
/* Get address and length of the frame buffer */
if(-1 == xioctl(capt->fd, VIDIOC_QUERYBUF, &buf))
errno_exit("VIDIOC_QUERYBUF");
/* memory map */
capt->pbuf[i].length = buf.length;
capt->pbuf[i].start = mmap(NULL,
buf.length,
PROT_READ | PROT_WRITE,
MAP_SHARED,
capt->fd, buf.m.offset);
if(MAP_FAILED == capt->pbuf[i].start)
errno_exit("mmap");
}
}
static void init_userp(struct capture_t *capt)
{
int i;
unsigned int page_size;
unsigned int buffer_size;
struct v4l2_requestbuffers req;
page_size = getpagesize();
buffer_size = (capt->sizeimage + page_size - 1) & ~(page_size - 1);
CLEAR(req);
req.count = capt->nbuf;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_USERPTR;
/* Request buffer */
if(-1 == xioctl(capt->fd, VIDIOC_REQBUFS, &req)) {
if(EINVAL == errno) {
fprintf(stderr, "%s does not support "
"user pointer i/o\n", capt->dev_name);
exit(EXIT_FAILURE);
} else
errno_exit("VIDIOC_REQBUFS");
}
if (req.count < 1) {
fprintf(stderr, "Insufficient buffer memory on %s\n",
capt->dev_name);
exit(EXIT_FAILURE);
}
capt->pbuf = calloc(req.count, sizeof(struct buffer));
if(!capt->pbuf) {
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
/* Update the value of nbuf */
capt->nbuf = req.count;
for(i = 0; i < capt->nbuf; i++) {
capt->pbuf[i].length = buffer_size;
capt->pbuf[i].start = JZMalloc(128, buffer_size);
if(!capt->pbuf[i].start) {
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
}
}
void process_image(struct capture_t *capt, int index)
{
unsigned char *rgbbuf = NULL;
unsigned char *yuvbuf = NULL;
yuvbuf = (unsigned char *)capt->pbuf[index].start;
rgbbuf = (unsigned char *)malloc(capt->width * capt->height * 3);
if(!rgbbuf) {
fprintf(stderr, "malloc rgbbuf failed!!\n");
errno_exit("malloc");
}
yuv2rgb(yuvbuf, rgbbuf, capt->width, capt->height);
rgb2bmp("test.bmp", capt->width, capt->height, 24, rgbbuf);
free(rgbbuf);
}
int read_frame(struct capture_t *capt)
{
struct v4l2_buffer buf;
unsigned int i;
switch(capt->io) {
case IO_METHOD_READ:
if(-1 == read(capt->fd, capt->pbuf[0].start, capt->pbuf[0].length)) {
switch(errno) {
case EAGAIN:
fprintf(stderr, "Read frame error: %d, %s\n", \
errno, strerror(errno));
return FALSE;
case EIO:
default:
errno_exit("read");
}
}
process_image(capt, 0);
break;
case IO_METHOD_MMAP:
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
if(-1 == xioctl(capt->fd, VIDIOC_DQBUF, &buf)) {
switch(errno) {
case EAGAIN:
fprintf(stderr, "Read frame error: %d, %s\n", \
errno, strerror(errno));
return FALSE;
case EIO:
default:
errno_exit("VIDIOC_DQBUF");
}
}
assert(buf.index < capt->nbuf);
process_image(capt, buf.index);
if(-1 == xioctl(capt->fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
break;
case IO_METHOD_USERPTR:
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_USERPTR;
if(-1 == xioctl(capt->fd, VIDIOC_DQBUF, &buf)) {
switch(errno) {
case EAGAIN:
fprintf(stderr, "Read frame error: %d, %s\n", \
errno, strerror(errno));
return FALSE;
case EIO:
default:
errno_exit("VIDIOC_DQBUF");
}
}
unsigned int page_size = getpagesize();
unsigned int buffer_size = (buf.length + page_size - 1) & ~(page_size - 1);
for(i = 0; i < capt->nbuf; i++) {
if((unsigned long)(capt->pbuf[i].start) == buf.m.userptr && \
(unsigned long)(capt->pbuf[i].length) == buffer_size)
break;
}
assert(i < capt->nbuf);
process_image(capt, i);
if(-1 == xioctl(capt->fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
break;
}
return TRUE;
}
void start_capturing(struct capture_t *capt)
{
int i;
enum v4l2_buf_type type;
switch(capt->io) {
case IO_METHOD_READ:
/* Nothing to do */
break;
case IO_METHOD_MMAP:
/* Add to buffer queue */
for(i = 0; i < capt->nbuf; i++) {
struct v4l2_buffer buf;
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
if(-1 == xioctl(capt->fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if(-1 == xioctl(capt->fd, VIDIOC_STREAMON, &type))
errno_exit("VIDIOC_STREAMON");
break;
case IO_METHOD_USERPTR:
/* Add to buffer queue */
for(i = 0; i < capt->nbuf; i++) {
struct v4l2_buffer buf;
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_USERPTR;
buf.index = i;
buf.length = capt->pbuf[i].length;
buf.m.userptr = (unsigned long)capt->pbuf[i].start;
if(-1 == xioctl(capt->fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if(-1 == xioctl(capt->fd, VIDIOC_STREAMON, &type))
errno_exit("VIDIOC_STREAMON");
break;
}
}
void stop_capturing(struct capture_t *capt)
{
enum v4l2_buf_type type;
switch(capt->io) {
case IO_METHOD_READ:
/* Nothing to do */
break;
case IO_METHOD_MMAP:
case IO_METHOD_USERPTR:
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if(-1 == xioctl(capt->fd, VIDIOC_STREAMOFF, &type))
errno_exit("VIDIOC_STREAMOFF");
break;
}
}
void test_framerate(struct capture_t *capt)
{
fd_set fds;
struct timeval tv;
struct timeval start_tv;
struct timeval end_tv;
struct v4l2_buffer buf;
int ret = 0;
int count = 0;
int costtime = 0;
fprintf(stdout, "Start to test frame rate ...\n");
start_capturing(capt);
gettimeofday(&start_tv, NULL);
while(1) {
FD_ZERO(&fds);
FD_SET(capt->fd, &fds);
/* Select time */
tv.tv_sec = 2;
tv.tv_usec = 0;
ret = select(capt->fd + 1, &fds, NULL, NULL, &tv);
if(ret < 0) {
if(EINTR == errno)
continue;
errno_exit("select");
} else if(0 == ret) {
fprintf(stderr, "Select timeout\n");
exit(EXIT_FAILURE);
}
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
if(-1 == xioctl(capt->fd, VIDIOC_DQBUF, &buf)) {
switch(errno) {
case EAGAIN:
case EIO:
default:
errno_exit("VIDIOC_DQBUF");
}
}
assert(buf.index < capt->nbuf);
if(-1 == xioctl(capt->fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
count++;
if(count == 60)
break;
}
gettimeofday(&end_tv, NULL);
costtime = (end_tv.tv_sec - start_tv.tv_sec) * 1000000 + \
(end_tv.tv_usec - start_tv.tv_usec);
fprintf(stdout, "%s: get %d frame = %dus, fps = %f\n", \
capt->dev_name, count, costtime, 1000000.0 * count/costtime);
stop_capturing(capt);
}
void open_device(struct capture_t *capt)
{
struct stat st;
if(-1 == stat(capt->dev_name, &st)) {
fprintf(stderr, "Cannot identify '%s': %d, %s\n",
capt->dev_name, errno, strerror(errno));
exit(EXIT_FAILURE);
}
if(!S_ISCHR(st.st_mode)) {
fprintf(stderr, "%s is no device\n", capt->dev_name);
exit(EXIT_FAILURE);
}
capt->fd = open(capt->dev_name, O_RDWR | O_NONBLOCK, 0);
if(capt->fd < 0) {
fprintf(stderr, "Cannot open '%s': %d, %s\n",
capt->dev_name, errno, strerror(errno));
exit(EXIT_FAILURE);
}
}
void close_device(struct capture_t *capt)
{
if(-1 == close(capt->fd))
errno_exit("close");
capt->fd = -1;
free(capt->pbuf);
}
void init_device(struct capture_t *capt)
{
unsigned int min;
struct v4l2_capability cap;
struct v4l2_cropcap cropcap;
struct v4l2_crop crop;
struct v4l2_format fmt;
if(-1 == xioctl(capt->fd, VIDIOC_QUERYCAP, &cap)) {
if(EINVAL == errno) {
fprintf(stderr, "%s is no V4L2 device\n",
capt->dev_name);
exit(EXIT_FAILURE);
} else
errno_exit("VIDIOC_QUERYCAP");
}
if(!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
fprintf(stderr, "%s is no video capture device\n",
capt->dev_name);
exit(EXIT_FAILURE);
}
switch(capt->io) {
case IO_METHOD_READ:
if(!(cap.capabilities & V4L2_CAP_READWRITE)) {
fprintf(stderr, "%s does not support read i/o\n",
capt->dev_name);
exit(EXIT_FAILURE);
}
break;
case IO_METHOD_MMAP:
case IO_METHOD_USERPTR:
if(!(cap.capabilities & V4L2_CAP_STREAMING)) {
fprintf(stderr, "%s does not support streaming i/o\n",
capt->dev_name);
exit(EXIT_FAILURE);
}
break;
}
/* Select video input, video standard and tune here */
CLEAR(cropcap);
cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if(0 == xioctl(capt->fd, VIDIOC_CROPCAP, &cropcap)) {
crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
crop.c = cropcap.defrect; /* reset to default */
if(-1 == xioctl(capt->fd, VIDIOC_S_CROP, &crop)) {
switch(errno) {
case EINVAL:
/* Cropping not supported. */
break;
default:
/* Errors ignored. */
break;
}
}
} else {
/* Errors ignored */
}
CLEAR(fmt);
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = capt->width;
fmt.fmt.pix.height = capt->height;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
fmt.fmt.pix.field = V4L2_FIELD_NONE; //V4L2_FIELD_INTERLACED;
if(-1 == xioctl(capt->fd, VIDIOC_S_FMT, &fmt))
errno_exit ("VIDIOC_S_FMT");
/* Note VIDIOC_S_FMT may change width and height */
min = fmt.fmt.pix.width * 2;
if(fmt.fmt.pix.bytesperline < min)
fmt.fmt.pix.bytesperline = min;
min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
if(fmt.fmt.pix.sizeimage < min)
fmt.fmt.pix.sizeimage = min;
/* Save image size */
capt->sizeimage = min;
capt->width = fmt.fmt.pix.width;
capt->height = fmt.fmt.pix.height;
fprintf(stdout, "==> %s L%d: sizeimage = 0x%x, width = %d, height = %d\n", \
__FUNCTION__, __LINE__, capt->sizeimage, capt->width, capt->height);
switch(capt->io) {
case IO_METHOD_READ:
init_read(capt);
break;
case IO_METHOD_MMAP:
init_mmap(capt);
break;
case IO_METHOD_USERPTR:
init_userp(capt);
break;
}
}
void free_device(struct capture_t *capt)
{
int i;
switch(capt->io) {
case IO_METHOD_READ:
free(capt->pbuf[0].start);
break;
case IO_METHOD_MMAP:
for(i = 0; i < capt->nbuf; i++) {
if(-1 == munmap(capt->pbuf[i].start, \
capt->pbuf[i].length))
errno_exit("munmap");
}
break;
case IO_METHOD_USERPTR:
jz47_free_alloc_mem();
break;
}
}
void main_loop(struct capture_t *capt)
{
fd_set fds;
struct timeval tv;
int ret;
int count = 5;
while(count--) {
FD_ZERO(&fds);
FD_SET(capt->fd, &fds);
/* Select time */
tv.tv_sec = 2;
tv.tv_usec = 0;
ret = select(capt->fd + 1, &fds, NULL, NULL, &tv);
if(ret < 0) {
if(EINTR == errno)
continue;
errno_exit("select");
} else if(0 == ret) {
fprintf(stderr, "Select timeout\n");
exit(EXIT_FAILURE);
}
if(read_frame(capt))
break;
}
}
<file_sep>/work/debug/a8/touchscreen/Makefile
# If KERNELRELEASE is 2.6.35.7, we've been invoked from the
# kernel build system and can use its language.
ifeq ($(KERNELRELEASE),2.6.35.7)
#if you want use param to make,as follow:
#use£şmake t=XXX
TARGET=$(t)
ifneq ($(TARGET),)
obj-m := $(TARGET).o
else
#if have only one *.c file and get one *.ko file
#obj-m := virtualchar.o
#if have many *.c file and get many *.ko
obj-m := goodix_dev.o goodix_touch_v2.1.o
#if have many *.c file and get one *.ko
#note: The object file name of the next two line must be consistent
#obj-m := ZZZ.o
#ZZZ-objs := XXX.o YYY.o ...
endif
else
#if not define KERNELDIR in enviroment,you need define KERNELDIR by yourself
ifeq ($(KERNELDIR),)
KERNELDIR = /home/edu/a8/2.6.35.7_tools/unsp210_linux_2.6.35/
endif
$(PWD) := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
rm -rf *.o *.mod.c *.order *.symvers .*.cmd .tmp*
clean:
rm -rf *.ko
# app test need
test:
arm-linux-gcc -o $@ test.c
testclean:
rm -fr test
endif
<file_sep>/work/debug/pc/sync/Makefile
ifneq ($(KERNELRELEASE),)
obj-m := sync_drv.o
else
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
# KERNELDIR ?= /work/linux/linux-2.6.32.2
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
rm -rf *.o *.mod.c *.order *.symvers .*.cmd .tmp*
clean:
rm -f *.o *~ *.ko *.mod.c *.mod.o *.symvers *.order
endif
ins:
sudo insmod ./sync_drv.ko
del:
sudo rmmod sync_drv
CC := gcc
mt:
$(CC) -o test test_sync.c
.PHONY:clc
clc:
rm test
<file_sep>/work/test/pwm-beeper/Makefile
GCC := mips-linux-gnu-gcc
CFLAGS := -EL -mabi=32 -mhard-float -march=mips32r2 -Os
LDFLAGS:= -Wl,-EL
LDLIBS :=
SOURCES := $(wildcard *.c)
TARGET = beeper
all: $(TARGET)
$(TARGET): $(SOURCES)
$(GCC) $(CFLAGS) $(LDFLAGS) -o $@ $^
INSTALL_DIR = ~/work/sz-halley2/out/product/yak/system/usr/bin
install:
cp $(TARGET) $(INSTALL_DIR) -a
.PHONY: clean
clean:
rm -rf *.o $(TARGET)
<file_sep>/gtk/1. base/01_button/button.c
#include <gtk/gtk.h> // 头文件
// 回调函数
void callback(GtkButton *button, gpointer data)
{
const char *str = gtk_button_get_label( button ); // 获得按钮的文本内容
printf("str = %s\n", str);
}
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv); // 初始化
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL); // 创建窗口
gtk_window_set_title(GTK_WINDOW(window), "button");// 设置标题
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
gtk_container_set_border_width(GTK_CONTAINER(window), 10); // 设置窗口边框的宽度
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); // 窗口居中
GtkWidget *hbox = gtk_hbox_new(TRUE, 10); // 水平布局容器
gtk_container_add(GTK_CONTAINER(window), hbox); // 把横向盒状容器放入窗口
// 普通按钮
GtkWidget *normal_button = gtk_button_new_with_label("normal button");
gtk_button_set_label(GTK_BUTTON(normal_button), "change"); // 设置按钮的文本内容
g_signal_connect(normal_button, "pressed", G_CALLBACK(callback), NULL);
gtk_container_add(GTK_CONTAINER(hbox), normal_button); // 把按钮放入横向容器里
// 带图标按钮
GtkWidget *button = gtk_button_new(); // 先创建空按钮
GtkWidget *image = gtk_image_new_from_file("1.png"); // 图像控件
gtk_button_set_image(GTK_BUTTON(button), image);
gtk_container_add(GTK_CONTAINER(hbox), button); // 把按钮放入横向容器里
gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_HALF); // 按钮背景色透明
// 按钮使能设置,默认为使能TRUE,非使能FALSE
//gtk_widget_set_sensitive(button, FALSE);
gtk_widget_show_all(window); // 显示窗口控件
gtk_main(); // 主事件循环
return 0;
}
<file_sep>/c/practice/3rd_week/encrypt/main.c
/* ************************************************************************
* Filename: encrypt.c
* Description:
* Version: 1.0
* Created: 2015年07月30日 星期四 01時59分46秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include "encrypt.h"
char mygetch()
{
struct termios oldt, newt;
char ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
void print_help()
{
printf("输入 1:加密文件\n");
printf("输入 2:解密文件\n");
printf("输入 3:退出程序\n");
}
void main()
{
char ch, *buf = NULL;
char dest_file_name[30] = "";
char src_file_name[30] = "";
long unsigned int length = 0,password = 0;;
while(1)
{
print_help(); //显示提示
do
{
ch = mygetch();
}while(ch != '1' && ch != '2' && ch != '3');
switch(ch)
{
#if 0
case '1':
{
get_file_name(dest_file_name,src_file_name); //获取加密文件名和目的文件名
buf = read_src_file(&length,src_file_name); //读取待加密文件内容
printf("Please input your poassword: ");
scanf("%lu",&password); //获取加密密码
buf = file_text_encrypt(buf,length,password); //进行加密
save_file(buf,length,dest_file_name);
break;
}
case '2':
{
get_file_name(dest_file_name,src_file_name); //获取解密文件名和目的文件名
buf = read_src_file(&length,src_file_name); //读取待解密文件内容
printf("Please input your poassword: ");
scanf("%lu",&password); //获取解密密码
buf = file_text_decrypt(buf,length,password); //进行解密
save_file(buf,length,dest_file_name);
break;
}
case '3': free(buf); exit(0);
#elif 1
case '3': free(buf); exit(0);
case '1':
case '2':
{
get_file_name(dest_file_name,src_file_name); //获取源文件名和目的文件名
buf = read_src_file(&length,src_file_name); //读取待操作的文件内容
printf("Please input your poassword: ");
scanf("%lu",&password); //获取密码
if(ch == '1')
{
buf = file_text_encrypt(buf,length,password); //进行加密
save_file(buf,length,dest_file_name);
break;
}
else
{
buf = file_text_decrypt(buf,length,password); //进行解密
save_file(buf,length,dest_file_name);
break;
}
}
#endif
}
}
}
<file_sep>/c/practice/3rd_week/link/Makefile
link: main.c link.c
gcc -o link main.c link.c -Wall
clean:
rm link
<file_sep>/network/6th_day/Makefile
all:pcap libnet
pcap:
gcc -o pcap pcap_test.c -lpcap
libnet:
gcc -o libnet libnet_test.c -lnet
.PHONY:clean
clean:
rm pcap libnet
<file_sep>/gtk/4st_week/picture_browse/scan_dir.h
/* ************************************************************************
* Filename: scan_dir.h
* Description:
* Version: 1.0
* Created: 2015年08月11日 14时38分20秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __SCAN_DIR_H__
#define __SCAN_DIR_H__
#define IMAGE_WIDTH 400
#define IMAGE_HEIGTH 300
#define IMAGE_DIR "./image/"
extern int gs_index;
extern int gs_bmp_total; //图片总数
extern char *gs_bmp_name[50];//存放图片目录和文件名地址的指针数组
void save_bmp_name(char *path, char *bmp);
void get_bmp_name(char *path);
int conver_bmp_name(char *bmp_pathname);
void order_bmp_name(void);
void bmp_name_print(void);
#endif
<file_sep>/c/homework/3rd_week/mystring.c
/* ************************************************************************
* Filename: mystring.c
* Description:
* Version: 1.0
* Created: 2015年07月24日 星期五 03時39分01秒 HKT
* Revision: none
* Compiler: gcc
* Author: 王秋伟
* Company:
* ************************************************************************/
#include<math.h>
#include<string.h>
#include"mystring.h"
void mystrinv(char *src)
{
char *head = NULL;
char *trail= NULL;
char ch;
int i = 0;
while(src[i++]);
head = src;
trail= head + i -2;
while(trail > head)
{
ch = *head;
*head = *trail;
*trail= ch;
head++;
trail--;
}
}
int mystrlen(char *src)
{
int i= 0;
while(src[i++]);
return i-1;
}
int mystrcpy(char *obj, char *src)
{
int i = 0;
while(src[i])
{
obj[i] = src[i];
i++;
}
obj[i] = '\0';
return i;
}
int mystrcmp(char *src1, char *src2)
{
int i = 0;
while(src1[i++])
{
if(src1[i]>src2[i])
{
return 1;
}
else if(src1[i]<src2[i])
{
return -1;
}
}
return 0;
}
int strchange(char *src)
{
int i = 0;
int len = 0, res = 0;
len = strlen(src);
for(i=0;i<len;i++)
{
res += pow(10,len-i-1) * (src[i]-48);
}
return res;
}
<file_sep>/work/test/cim_test-zmm220/futil.c
#include "futil.h"
#ifndef WIN32
DWORD GetTickCount(void)
{
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
return (tv.tv_sec*1000 + tv.tv_usec/1000);
}
#endif
int WriteBitmap(const BYTE *buffer, int Width, int Height, const char *file)
{
char Buffer[0x500];
BITMAPFILEHEADER *bmpfheader=(BITMAPFILEHEADER *)Buffer;
BITMAPINFO *bmpinfo=(BITMAPINFO *)(((char*)bmpfheader)+14);
int i,w;
FILE *f;
memset(bmpfheader,0,0x500);
bmpfheader->bfType =19778;
w = ((Width+3)/4)*4*Height+sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFO)+255*sizeof(RGBQUAD);
memcpy((void*)(((char*)bmpfheader)+2), &w, 4);
//bmpfheader->bfOffBits;
w= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFO)+255*sizeof(RGBQUAD);
memcpy((void*)(((char*)bmpfheader)+10), &w, 4);
bmpinfo->bmiHeader.biWidth=Width;
bmpinfo->bmiHeader.biHeight=Height;
bmpinfo->bmiHeader.biBitCount=8;
bmpinfo->bmiHeader.biClrUsed=0;
bmpinfo->bmiHeader.biSize=sizeof(bmpinfo->bmiHeader);
bmpinfo->bmiHeader.biPlanes=1;
bmpinfo->bmiHeader.biSizeImage=((Width+3)/4)*4*Height;
f=fopen(file, "wb");
if(f)
{
for(i=1;i<256;i++)
{
bmpinfo->bmiColors[i].rgbBlue=i;
bmpinfo->bmiColors[i].rgbGreen=i;
bmpinfo->bmiColors[i].rgbRed=i;
}
fwrite(Buffer, sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+256*sizeof(RGBQUAD), 1, f);
w = ((Width+3)/4)*4;
buffer+=Width*(Height-1);
for(i=0; i<Height; i++)
{
fwrite(buffer, Width, 1, f);
if(w-Width)
fwrite(buffer, w-Width, 1, f);
buffer-=Width;
}
fclose(f);
return Width*Height;
}
return 0;
}
BYTE *LoadFile(const char *FileName)
{
BYTE *data=NULL;
FILE *f=fopen(FileName, "rb");
long s;
if(!f) return 0;
fseek(f,0,SEEK_END);
s=ftell(f);
if(s>0)
{
fseek(f,0,SEEK_SET);
data=(BYTE*)malloc(s);
if (1>(long)fread(data, s, 1, f))
{
free(data);
data=NULL;
}
}
fclose(f);
return data;
}
int SaveToFile(const char *fileName, void *buffer, int size)
{
FILE *f=fopen(fileName, "wb");
if(f==NULL)
{
logMsg("Open file %s to write fail.\n", fileName);
return 0;
}
fwrite(buffer, size, 1, f);
fclose(f);
return 1;
}
static FILE *logf=NULL;
static unsigned int startTick=0;
int logClose()
{
if(logf)
{
fprintf(logf, "%ld:\tEnd Log.\n", GetTickCount()-startTick);
fclose(logf);
logf=NULL;
}
return 0;
}
int logMsg(char *fmt, ...)
{
static int lastEnd=0;
unsigned int theTick=GetTickCount();
va_list argptr;
va_start(argptr, fmt);
// return 0;
if(logf==NULL)
{
logf=fopen("log.txt", "w");
}
if(logf==NULL) return 0;
if(startTick==0)
{
startTick=theTick;
fprintf(logf, "%d:\tStart Log.\n", startTick);
lastEnd=1;
}
if(lastEnd)
fprintf(logf, "%d:\t",theTick-startTick);
lastEnd=(fmt[strlen(fmt)-1]=='\n')?1:0;
vfprintf(logf, fmt, argptr);
vprintf(fmt, argptr);
return 1;
}
int ReadBitmap(BYTE *p, BYTE *buffer, int *Width, int *Height)
{
BITMAPFILEHEADER *bmpfheader=(BITMAPFILEHEADER *)p;
BITMAPINFO *bmpinfo=(BITMAPINFO *)(p+14);
int i,w;
if(!p) return 0;
*Width = bmpinfo->bmiHeader.biWidth;
*Height=bmpinfo->bmiHeader.biHeight;
if((bmpfheader->bfType ==19778) && (bmpinfo->bmiHeader.biCompression==0) &&
(bmpinfo->bmiHeader.biBitCount==8))
{
if(bmpinfo->bmiHeader.biClrUsed==0) bmpinfo->bmiHeader.biClrUsed=256;
if(bmpinfo->bmiHeader.biClrUsed!=256) return 0;
p+=0x436;
w = ((*Width+3)/4)*4;
p+=w*(*Height-1);
if(buffer)
for(i=0; i<(int)*Height; i++)
{
memcpy(buffer, p, *Width);
buffer+=*Width;
p-=w;
}
}
return *Width**Height;
}
int LoadBitmapFile(const char *FileName, BYTE *buffer, int *Width, int *Height)
{
unsigned char *p=LoadFile(FileName);
int res=ReadBitmap(p, buffer, Width, Height);
free(p);
return res;
}
void msleep(int msec)
{
struct timeval delay;
delay.tv_sec =msec /1000;
delay.tv_usec =(msec%1000)*1000;
select(0, NULL, NULL, NULL, &delay);
}
int dumpData(const unsigned char *data, int dataSize, const char *title)
{
static char Hex[17]="0123456789ABCDEF";
int i, linec=0;
char line[20];
printf("Dump %s: Size=%d\n", title? title: "Data", dataSize);
for(i=0; i<dataSize;i++)
{
char HexData[3];
HexData[0]=Hex[data[i]>>4]; HexData[1]=Hex[data[i]&0x0F]; HexData[2]=0;
if(linec==0) printf(" ");
printf("%s ", HexData);
if(data[i]>=0x20 && data[i]<0x7F)
line[linec]=data[i];
else
line[linec]='.';
if(++linec>=16)
{
line[linec]=0;
printf(" %s\n", line);
linec=0;
}
}
if(linec)
{
for(i=0;i<16-linec;i++) printf(" ");
line[linec]=0;
printf(" %s\n",line);
}
return 0;
}
<file_sep>/c/mkheader/mkheader.c
/*************************************************************************
> Filename: god.c
> Author:
> Email:
> Datatime: 2017年02月24日 星期五 22时23分04秒
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
FILE *fp;
uint32_t length;
char *buf;
//fp = fopen("./app", "rb+");
fp = fopen(argv[1], "rb+");
if (fp == NULL) {
printf("Cannot open the file!\n");
return -1;
}
fseek(fp, 0, SEEK_END);
length = ftell(fp);
printf("write length=%d\n", length);
buf = (char *)malloc(length + 4);
if (buf == NULL) {
printf("Failed to malloc mem\n");
return 0;
}
bzero(buf, length + 4);
*(uint32_t *)buf = length;
fseek(fp, 0, SEEK_SET);
fread(buf+4, length, 1, fp);
fseek(fp, 0, SEEK_SET);
fwrite(buf, length + 4, 1, fp);
fclose(fp);
return 0;
}
<file_sep>/work/shell/timer.sh
#!/bin/sh
for i in $(seq 1 2)
do
sleep 20s
echo "20s later..."
done
echo "reboot system now..."
reboot
<file_sep>/sys_program/4th_day/homework/mplayer/interface.c
/* ************************************************************************
* Filename: interface.c
* Description:
* Version: 1.0
* Created: 2015年08月18日 20时42分13秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <string.h>
#include "interface.h"
#include "image.h"
int fd; //保存管道文件描述符
int playing = FALSE;
// 按钮的回调函数
void deal_switch_image(GtkWidget *button, gpointer data)
{
WINDOW *p_temp = (WINDOW *)data;
if(button == p_temp->button_previous) // 快退
{
write(fd, "seek -10\n", strlen("seek -10\n"));
}
else if(button == p_temp->button_next ) // 快进
{
write(fd, "seek -10\n", strlen("seek 10\n"));
}
else if(button == p_temp->button_pause ) // 赞同或播放
{
printf("p_temp->button_pause\n");
if(playing) // 正在播放,则暂停
{
write(fd, "pause\n", strlen("pause\n"));
playing = FALSE;
GtkWidget *image = gtk_image_new_from_file("./skin/pause.bmp"); // 图像控件
gtk_button_set_image(GTK_BUTTON(p_temp->button_pause), image);
}
else //否则,开启播放
{
write(fd, "pause\n", strlen("pause\n"));
playing = TRUE;
GtkWidget *image = gtk_image_new_from_file("./skin/play.bmp"); // 图像控件
gtk_button_set_image(GTK_BUTTON(p_temp->button_pause), image);
}
}
}
void show_window(gpointer data)
{
WINDOW *p_temp = (WINDOW *)data;
// 主窗口
p_temp->main_window = gtk_window_new(GTK_WINDOW_TOPLEVEL); // 创建主窗口
gtk_window_set_title(GTK_WINDOW(p_temp->main_window), "picture_browse"); // 设置窗口标题
gtk_window_set_position(GTK_WINDOW(p_temp->main_window), GTK_WIN_POS_CENTER); // 设置窗口在显示器中的位置为居中
gtk_widget_set_size_request(p_temp->main_window, 500, 250); // 设置窗口的最小大小
gtk_window_set_resizable(GTK_WINDOW(p_temp->main_window), FALSE); // 固定窗口的大小
g_signal_connect(p_temp->main_window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
// 表格布局
p_temp->table = gtk_table_new(5, 7, TRUE); // 表格布局容器 5行 7列
gtk_container_add(GTK_CONTAINER(p_temp->main_window), p_temp->table); // 容器加入窗口
// 按钮
#if 1
p_temp->button_previous = create_button_from_file("./skin/previous.bmp", 70, 60);
gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_previous, 1, 2, 2, 3);
g_signal_connect(p_temp->button_previous, "clicked", G_CALLBACK(deal_switch_image), p_temp);
p_temp->button_next = create_button_from_file("./skin/next.bmp", 70, 60);
gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_next, 5, 6, 2, 3);
g_signal_connect(p_temp->button_next, "clicked", G_CALLBACK(deal_switch_image), p_temp);
p_temp->button_pause = create_button_from_file("./skin/play.bmp", 70, 60);
gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_pause, 3, 4, 2, 3);
g_signal_connect(p_temp->button_pause, "clicked", G_CALLBACK(deal_switch_image), p_temp);
#endif
chang_background(p_temp->main_window, 500, 250, "./skin/background.bmp"); // 设置窗口背景图
gtk_widget_show_all(p_temp->main_window);
}
<file_sep>/work/shell/abc.sh
#!/bin/sh
/usr/fs/etc/init.d/S04bsa.sh stop
iwconfig wlan0 txpower off
ifconfig wlan0 down
<file_sep>/sys_program/player/src/gtk_callback.c
#include <gtk/gtk.h>
#include <glade/glade.h>
#include <string.h>
#include "common.h"
#include "mplayer_control.h"
#include "mplayer_pthread.h"
#include "mplayer_ui.h"
#include "gtk_callback.h"
// 鼠标移动事件(点击鼠标任何键)的处理函数
gboolean motion_event_callback(GtkWidget *widget, GdkEventMotion *event, gpointer data)
{
// 获得移动鼠标的坐标值
gint x = event->x;
gint seek_sec = 0;
char cmd[32] = "seek ";
char buf[8] = {0};
MPLAYER *pm = (MPLAYER*)data;
if(pm->playflag == playing) pm->playflag = stop;
seek_sec = x * song.end_time/400; //毫秒
seek_sec = (seek_sec - song.cur_time)/1000;//秒
printf("seek_sec = %d\n",seek_sec);
gcvt(seek_sec,5,buf);
strcat(cmd, buf);
strcat(cmd,"\n");
printf("cmd = %s\n",cmd);
send_cmd(cmd,pm);
pm->playflag == playing;
//gint j = event->y;
//printf("motion_x = %d, motion_y = %d\n", i, j);
return TRUE;
}
void search_entry_callback(GtkWidget *widget, gpointer entry)
{
MPLAYER *pm = (MPLAYER*)entry;
const gchar *text;
int i = 0;
char *p = NULL;
text = (gchar *)gtk_entry_get_text(GTK_ENTRY(pm->ui.hbox_left.entry_search));
//printf("Entry contents: %s\n",text);
for(i=0; i<song.count; i++)
{
if((p=strstr(song.psong_list[i],text)) != NULL)
{
printf("entry >> song_name = %s\n",song.psong_list[i]);
sungtk_clist_set_row_color(musiclist, i, "green");
song.search[i] = 1;
song.search_flag = 1;
p = NULL;
}
}
}
void keys_board_callback(GtkWidget *widget, GdkEventKey *event, gpointer data)
{
printf("Entry keys_board_callback!!!!\n");
if(event->keyval == 65288) //backspace
{
MPLAYER *pm = (MPLAYER*)data;
const gchar *text;
char *p = NULL;
int i = 0;
text = (gchar *)gtk_entry_get_text(GTK_ENTRY(pm->ui.hbox_left.entry_search));
//printf("Entry contents: %s\n",text);
if(text != NULL)
{
for(i=0; i<song.count; i++)
{
if((p=strstr(song.psong_list[i],text)) != NULL)
{
printf("entry >> song_name = %s\n",song.psong_list[i]);
//gdk_threads_enter();
sungtk_clist_set_row_color(musiclist, i, "green");
//gdk_threads_leave();
song.search[i] = 1;
song.search_flag = 1;
p = NULL;
}
}
}
}
}
void playmode_button_callback(GtkButton *button, gpointer data)
{
MPLAYER *pm = (MPLAYER*)data;
switch(pm->playmode)
{
case list_loop:
{
pm->playmode = sequence;
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_playmode), "./image/style/playmode_sequence.png",20,20);
break;
}
case sequence:
{
pm->playmode = loop;
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_playmode), "./image/style/playmode_loop.png",20,20);
break;
}
case loop:
{
pm->playmode = randm;
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_playmode), "./image/style/playmode_random.png",20,20);
break;
}
case randm:
{
pm->playmode = list_loop;
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_playmode), "./image/style/playmode_list_loop.png",20,20);
break;
}
}
}
void musiclist_buttons_callback(GtkButton *button, gpointer data)
{
MPLAYER *pm = (MPLAYER*)data;
if(button == pm->ui.hbox_left.bmusic_list)
{
//int i = 0;
//for(i=0;song.psong_list[i] != NULL && i< song.count;i++)
//{
//sungtk_clist_append(musiclist, song.psong_list[i]);
//printf("%s\n",ps->psong_list[i]);
//}
gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_list), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_collect), TRUE);
gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_recently), TRUE);
}
else if(button == pm->ui.hbox_left.bmusic_collect)
{
//gtk_clist_clear();
gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_list), TRUE);
gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_collect), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_recently), TRUE);
}
else if(button == pm->ui.hbox_left.bmusic_recently)
{
gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_list), TRUE);
gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_collect), TRUE);
gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_recently), FALSE);
}
}
void music_buttons_callback(GtkButton *button, gpointer data)
{
MPLAYER *pm = (MPLAYER*)data;
if(button == pm->ui.hbox_right.button_pause)
{
if(pm->playflag == playing)// 正在播放,则暂停
{
//printf("pause\n");
pm->playflag = stop;
send_cmd("pause\n", pm);
gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_right.button_backward), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_right.button_forward), FALSE);
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_pause), "./image/style/play.png",70,70);
}
else //否则,开启播放
{
//printf("playing\n");
pm->playflag = playing;
send_cmd("pause\n", pm);
gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_right.button_backward), TRUE);
gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_right.button_forward), TRUE);
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_pause), "./image/style/pause.png",70,70);
}
}
else if(button == pm->ui.hbox_right.button_forward)
{
//printf("button_forward\n");
send_cmd("seek 10\n", pm);
}
else if(button == pm->ui.hbox_right.button_backward)
{
//printf("button_backward\n");
send_cmd("seek -10\n", pm);
}
else if(button == pm->ui.hbox_right.button_next)
{
//printf("button_next\n");
set_keyflag(next);
set_playing_song(pm, 1);
#if 0
song.old= song.now;
song.now++;
if(song.now >= song.count)
{
song.now = 0;
}
#endif
//set_songname(song.now);
//strcpy(song.name, song.psong_list[song.now]);
//playing_song(pm, song.now);
}
else if(button == pm->ui.hbox_right.button_back)
{
//printf("button_back\n");
set_keyflag(back);
set_playing_song(pm, -1);
#if 0
song.old= song.now;
song.now--;
if(song.now < 0)
{
song.now = song.count - 1;
}
#endif
//set_songname(song.now);
//playing_song(pm, song.now);
}
else if(button == pm->ui.hbox_right.button_volume)
{
if(pm->soundflag == beam)//判断如果不是静音状态 则设置成静音状态
{
//printf("mute\n");
pm->soundflag = mute;
send_cmd("mute 1\n", pm);
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_volume), "./image/style/mute.png",50,50);
}
else
{
//printf("beam\n");
pm->soundflag = beam;
send_cmd("mute 0\n", pm);
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_volume), "./image/style/beam.png",50,50);
}
}
}
gboolean callback_list_release(GtkWidget *widget, GdkEventButton *event, gpointer data)
{
int i;
int row = (int)data;
printf("row = %d\n", row);
printf(">>list 111---song.old = %d\n",song.old);
song.old = song.now;
song.now = row;
printf(">>list 222---song.old = %d\n",song.old);
if(song.search_flag == 1)
{
song.search_flag = 0;
for(i=0;i< song.count;i++)
{
if(song.search[i] == 1)
{
song.search[i] = 0;
//gdk_threads_enter();
sungtk_clist_set_row_color(musiclist, i, "black");
//gdk_threads_leave();
}
}
}
set_keyflag(clist);
set_songname(song.now);
#if 0
const char *text = sungtk_clist_get_row_data(musiclist, row);
printf("text = %s\n", text);
song.now = row;
printf("new = %d\n",song.now);
strcpy(song.name,text);
printf("song_name= %s\n",song.name);
#endif
return TRUE;
}
<file_sep>/c/homework/2nd_week/typewriting.c
/* ************************************************************************
* Filename: test_typewriting.c
* Description:
* Version: 1.0
* Created: 2015年07月22日 星期三 11時59分14秒 HKT
* Revision: none
* Compiler: gcc
* Author: 王秋伟
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <termios.h>
#include <unistd.h>
//#include <windows.h>
#define uint unsigned int
#define LENGHT 40
char mygetch()
{
struct termios oldt, newt;
char ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
void show_rule()
{
printf("\n---------------------\n");
printf(" 1.按任键开始测试\n");
printf(" 3.输入屏幕显示字符\n");
printf(" 4.输入首字母后计时\n");
printf(" 2.输入过程按Esc退出\n");
printf(" 5.输入出错以 _ 表示\n");
printf("----------------------\n");
}
void get_string(char *buf, int n, int mode)
{
char i,ch;
i = 0;
srand((uint)time(NULL));
do
{
ch = (char)rand()%128;
if((mode & 0x01 && ch >= 'a' && ch <= 'z')
||(mode & 0x02 && ch >= 'A' && ch <= 'Z'))
{
buf[i] = ch;
printf("%c",ch);
i++;
}
}while(i<n);
putchar('\n');
}
void typewriting(char *src,int num)
{
char i,ch;
int count = 0;
int start_time,end_time;
putchar('\n');
for(i=0;i<num;i++)
{
ch = mygetch();
if(i == 0)
{
start_time = time(NULL);
}
if(ch == src[i])
{
putchar(ch);
count++;
}
else
{
if(ch == 27)//判断是不是按下Esc键
{
putchar('\n');
exit(0);
}
putchar('_');
}
}
end_time = time(NULL);
printf("\n输出完成!\n用时 %ds\n",end_time-start_time);
printf("正确率%.2f%\n",count/(num+0.0)*100);
printf("按Esc键退出,按空格键继续\n");
getch:
ch = mygetch();
switch(ch)
{
case ' ': system("clear"); break;
case 27: exit(0);
default: goto getch;
}
}
int main()
{
char src[LENGHT];
int mode;
//show_rule();
//mygetch();
system("clear");
while(1)
{
show_rule();
mygetch();
printf(">>>>请选择打字测试模式,输入:1 | 2 | 3\n");
printf("1---全小写字符串\n");
printf("2---全大写字符串\n");
printf("3---大小写字符串\n");
//scanf("%d",&mode);
do
{
mode = mygetch();
}while(mode != '1' && mode != '2' && mode !='3');
get_string(src,LENGHT,mode-48);
typewriting(src,LENGHT);
}
return 0;
}
<file_sep>/gtk/4st_week/gtk_hbox.c
/* ************************************************************************
* Filename: gtk_hbox.c
* Description:
* Version: 1.0
* Created: 2015年08月10日 11时34分43秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <gtk/gtk.h>
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(window,"destroy", G_CALLBACK(gtk_main_quit),NULL);
//创建一个水平容器
GtkWidget *hbox = gtk_hbox_new(TRUE,10);
//添加到window
gtk_container_add(GTK_CONTAINER(window),hbox);
GtkWidget *button1 = gtk_button_new_with_label("button1");
//添加button1到hbox
gtk_container_add(GTK_CONTAINER(hbox),button1);
GtkWidget *button2 = gtk_button_new_with_label("button2");
//添加button1到hbox
gtk_container_add(GTK_CONTAINER(hbox),button2);
GtkWidget *button3 = gtk_button_new_with_label("button3");
//添加button1到hbox
gtk_container_add(GTK_CONTAINER(hbox),button3);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
<file_sep>/c/practice/1st_week/area_circle/area_circle.c
/* ************************************************************************
* Filename: area_circle.c
* Description:
* Version: 1.0
* Created: 2015年07月16日 星期四 11時46分42秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#define PI 3.14
int main(int argc, char *argv[])
{
float r = 0;
float area = 0;
printf("please input circle's radius\n");
scanf("%f",&r);
area = PI * r * r;
printf("area=%8.3f\n",area);
return 0;
}
<file_sep>/c/practice/3rd_week/struct/Makefile
sort:sort.c
.POHONY:clean
clean:
rm sort
<file_sep>/network/3rd_day/broadcast.c
/* ************************************************************************
* Filename: broadcast.c
* Description:
* Version: 1.0
* Created: 2015年09月02日 10时39分25秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int sockfd = 0;
char buf[1024] ="";
unsigned short port = 8080;
struct sockaddr_in send_addr;
bzero(&send_addr, sizeof(send_addr));
send_addr.sin_family = AF_INET;
send_addr.sin_port = htons(port);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0)
{
perror("socket failed!\n");
close(sockfd);
exit(-1);
}
if(argc > 1)
{
send_addr.sin_addr.s_addr = inet_addr(argv[1]);
}
else
{
printf("hava not a server IP\n");
exit(-1);
}
int yes = 1;
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &yes, sizeof(yes));
strcpy(buf, "boardcast sucess, Dawei");
int len = sendto(sockfd, buf, strlen(buf), 0,\
(struct sockaddr *)&send_addr, sizeof(send_addr));
if(len < 0)
{
printf("send error\n");
}
close(sockfd);
return 0;
}
<file_sep>/work/test/cim_test-zmm220/mt9v136725.h
#ifndef _MT9V136_H
#define _MT9V136_H
#define END_ 0xff
unsigned char mt9v136regs0[]=
{
//0xC8,0x16,0x00,0x83,
//0xC8,0x18,0x00,0x9D,
0xC8,0x1A,0x00,0x03,//0x18,
0xC8,0x1C,0x00,0x03,//0x14,
0x00,0x40,0x80,0x02,
//delay = 30
0xC8,0x1E,0x00,0x04,
0xC8,0x20,0x00,0x03,
0xC9,0x16,0x01,0x09,
0xC9,0x18,0x06,0x2C,
0xC8,0x50,0x03,0x42,
0xC8,0xF4,0x00,0x04,
0xC8,0xF8,0x00,0x82,
//delay = 30
0x00,0x30,0x04,0x04,
0x00,0x30,0x04,0x04,
0x30,0x1A,0x10,0xD0,
0x31,0xC0,0x14,0x04,
0x3E,0xD8,0x87,0x9C,
0x30,0x42,0x20,0xE1,
0x30,0xD4,0x80,0x20,
0x30,0xC0,0x00,0x26,
0x30,0x1A,0x10,0xD4,
0xA8,0x02,0x00,0xD3,
0xC8,0x78,0x00,0xA0,
0xC8,0x76,0x01,0x40,
0xBC,0x04,0x00,0xFC,
0xBC,0x38,0x00,0x7f,
0xBC,0x3A,0x00,0xbf,
0xBC,0x3C,0x00,0xbf,
0xBC,0x04,0x00,0xFc,
0xC9,0x1A,0x00,0x0F,
0xC9,0x1C,0x00,0x06,
0xC8,0xFC,0x00,0x0C,
0xC8,0xFE,0x00,0x30,
0xC9,0x12,0x00,0x0C,
0xC9,0x14,0x00,0x4B,
0xC9,0x16,0x01,0x09,
0xC9,0x18,0x06,0x2C,
0xC9,0x07,0xA8,0x01,
0xC9,0x0A,0x14,0x14,
0xC9,0x0C,0x14,0x14,
0xC9,0x0E,0x32,0x32,
0xC9,0x10,0x32,0x32,
0xC9,0x1E,0x01,0xF4,
0xC9,0x20,0x27,0x10,
0xC9,0x00,0x80,0x4a,
0xC9,0x04,0x08,0x02,
0xC9,0x06,0x02,0xa8,
0xC9,0x08,0x07,0x7f,
0xBC,0x06,0x01,0x5E,
0xC8,0xE6,0x80,0x80,
0xC8,0x3E,0x00,0x01,
0x32,0x80,0x00,0xAA,
0xC9,0x16,0x01,0x09,
0xC9,0x18,0x06,0x2C,
0xC8,0xCE,0x33,0xA1,
0xC8,0xD0,0xEC,0x08,
0xC8,0xD2,0xFF,0xC0,
0xC8,0xDE,0x00,0x33,
0x00,0x40,0x80,0x02,
//delay = 30
0x09,0x82,0x00,0x01,
0x09,0x8A,0x70,0x00,
0xF0,0x00,0x72,0xCF,
0xF0,0x02,0xFF,0x00,
0xF0,0x04,0x3E,0xD0,
0xF0,0x06,0x92,0x00,
0xF0,0x08,0x71,0xCF,
0xF0,0x0A,0xFF,0xFF,
0xF0,0x0C,0xF2,0x18,
0xF0,0x0E,0xB1,0x10,
0xF0,0x10,0x92,0x05,
0xF0,0x12,0xB1,0x11,
0xF0,0x14,0x92,0x04,
0xF0,0x16,0xB1,0x12,
0xF0,0x18,0x70,0xCF,
0xF0,0x1A,0xFF,0x00,
0xF0,0x1C,0x30,0xC0,
0xF0,0x1E,0x90,0x00,
0xF0,0x20,0x7F,0xE0,
0xF0,0x22,0xB1,0x13,
0xF0,0x24,0x70,0xCF,
0xF0,0x26,0xFF,0xFF,
0xF0,0x28,0xE7,0x1C,
0xF0,0x2A,0x88,0x36,
0xF0,0x2C,0x09,0x0F,
0xF0,0x2E,0x00,0xB3,
0xF0,0x30,0x69,0x13,
0xF0,0x32,0xE1,0x80,
0xF0,0x34,0xD8,0x08,
0xF0,0x36,0x20,0xCA,
0xF0,0x38,0x03,0x22,
0xF0,0x3A,0x71,0xCF,
0xF0,0x3C,0xFF,0xFF,
0xF0,0x3E,0xE5,0x68,
0xF0,0x40,0x91,0x35,
0xF0,0x42,0x22,0x0A,
0xF0,0x44,0x1F,0x80,
0xF0,0x46,0xFF,0xFF,
0xF0,0x48,0xF2,0x18,
0xF0,0x4A,0x29,0x05,
0xF0,0x4C,0x00,0x3E,
0xF0,0x4E,0x12,0x22,
0xF0,0x50,0x11,0x01,
0xF0,0x52,0x21,0x04,
0xF0,0x54,0x0F,0x81,
0xF0,0x56,0x00,0x00,
0xF0,0x58,0xFF,0xF0,
0xF0,0x5A,0x21,0x8C,
0xF0,0x5C,0xF0,0x10,
0xF0,0x5E,0x1A,0x22,
0xF0,0x60,0x10,0x44,
0xF0,0x62,0x12,0x20,
0xF0,0x64,0x11,0x02,
0xF0,0x66,0xF7,0x87,
0xF0,0x68,0x22,0x4F,
0xF0,0x6A,0x03,0x83,
0xF0,0x6C,0x1A,0x20,
0xF0,0x6E,0x10,0xC4,
0xF0,0x70,0xF0,0x09,
0xF0,0x72,0xBA,0xAE,
0xF0,0x74,0x7B,0x50,
0xF0,0x76,0x1A,0x20,
0xF0,0x78,0x10,0x84,
0xF0,0x7A,0x21,0x45,
0xF0,0x7C,0x01,0xC1,
0xF0,0x7E,0x1A,0x22,
0xF0,0x80,0x10,0x44,
0xF0,0x82,0x70,0xCF,
0xF0,0x84,0xFF,0x00,
0xF0,0x86,0x3E,0xD0,
0xF0,0x88,0xB0,0x60,
0xF0,0x8A,0xB0,0x25,
0xF0,0x8C,0x7E,0xE0,
0xF0,0x8E,0x78,0xE0,
0xF0,0x90,0x71,0xCF,
0xF0,0x92,0xFF,0xFF,
0xF0,0x94,0xF2,0x18,
0xF0,0x96,0x91,0x12,
0xF0,0x98,0x72,0xCF,
0xF0,0x9A,0xFF,0xFF,
0xF0,0x9C,0xE7,0x1C,
0xF0,0x9E,0x8A,0x57,
0xF0,0xA0,0x20,0x04,
0xF0,0xA2,0x0F,0x80,
0xF0,0xA4,0x00,0x00,
0xF0,0xA6,0xFF,0xF0,
0xF0,0xA8,0xE2,0x80,
0xF0,0xAA,0x20,0xC5,
0xF0,0xAC,0x01,0x61,
0xF0,0xAE,0x20,0xC5,
0xF0,0xB0,0x03,0x22,
0xF0,0xB2,0xB1,0x12,
0xF0,0xB4,0x71,0xCF,
0xF0,0xB6,0xFF,0x00,
0xF0,0xB8,0x3E,0xD0,
0xF0,0xBA,0xB1,0x04,
0xF0,0xBC,0x7E,0xE0,
0xF0,0xBE,0x78,0xE0,
0xF0,0xC0,0x70,0xCF,
0xF0,0xC2,0xFF,0xFF,
0xF0,0xC4,0xE7,0x1C,
0xF0,0xC6,0x88,0x57,
0xF0,0xC8,0x71,0xCF,
0xF0,0xCA,0xFF,0xFF,
0xF0,0xCC,0xF2,0x18,
0xF0,0xCE,0x91,0x13,
0xF0,0xD0,0xEA,0x84,
0xF0,0xD2,0xB8,0xA9,
0xF0,0xD4,0x78,0x10,
0xF0,0xD6,0xF0,0x03,
0xF0,0xD8,0xB8,0x89,
0xF0,0xDA,0xB8,0x8C,
0xF0,0xDC,0xB1,0x13,
0xF0,0xDE,0x71,0xCF,
0xF0,0xE0,0xFF,0x00,
0xF0,0xE2,0x30,0xC0,
0xF0,0xE4,0xB1,0x00,
0xF0,0xE6,0x7E,0xE0,
0xF0,0xE8,0xC0,0xF1,
0xF0,0xEA,0x09,0x1E,
0xF0,0xEC,0x03,0xC0,
0xF0,0xEE,0xC1,0xA1,
0xF0,0xF0,0x75,0x08,
0xF0,0xF2,0x76,0x28,
0xF0,0xF4,0x77,0x48,
0xF0,0xF6,0xC2,0x40,
0xF0,0xF8,0xD8,0x20,
0xF0,0xFA,0x71,0xCF,
0xF0,0xFC,0x00,0x03,
0xF0,0xFE,0x20,0x67,
0xF1,0x00,0xDA,0x02,
0xF1,0x02,0x08,0xAE,
0xF1,0x04,0x03,0xA0,
0xF1,0x06,0x73,0xC9,
0xF1,0x08,0x0E,0x25,
0xF1,0x0A,0x13,0xC0,
0xF1,0x0C,0x0B,0x5E,
0xF1,0x0E,0x01,0x60,
0xF1,0x10,0xD8,0x06,
0xF1,0x12,0xFF,0xBC,
0xF1,0x14,0x0C,0xCE,
0xF1,0x16,0x01,0x00,
0xF1,0x18,0xD8,0x00,
0xF1,0x1A,0xB8,0x9E,
0xF1,0x1C,0x0E,0x5A,
0xF1,0x1E,0x03,0x20,
0xF1,0x20,0xD9,0x01,
0xF1,0x22,0xD8,0x00,
0xF1,0x24,0xB8,0x9E,
0xF1,0x26,0x0E,0xB6,
0xF1,0x28,0x03,0x20,
0xF1,0x2A,0xD9,0x01,
0xF1,0x2C,0x8D,0x14,
0xF1,0x2E,0x08,0x17,
0xF1,0x30,0x01,0x91,
0xF1,0x32,0x8D,0x16,
0xF1,0x34,0xE8,0x07,
0xF1,0x36,0x0B,0x36,
0xF1,0x38,0x01,0x60,
0xF1,0x3A,0xD8,0x07,
0xF1,0x3C,0x0B,0x52,
0xF1,0x3E,0x01,0x60,
0xF1,0x40,0xD8,0x11,
0xF1,0x42,0x8D,0x14,
0xF1,0x44,0xE0,0x87,
0xF1,0x46,0xD8,0x00,
0xF1,0x48,0x20,0xCA,
0xF1,0x4A,0x02,0x62,
0xF1,0x4C,0x00,0xC9,
0xF1,0x4E,0x03,0xE0,
0xF1,0x50,0xC0,0xA1,
0xF1,0x52,0x78,0xE0,
0xF1,0x54,0xC0,0xF1,
0xF1,0x56,0x08,0xB2,
0xF1,0x58,0x03,0xC0,
0xF1,0x5A,0x76,0xCF,
0xF1,0x5C,0xFF,0xFF,
0xF1,0x5E,0xE5,0x40,
0xF1,0x60,0x75,0xCF,
0xF1,0x62,0xFF,0xFF,
0xF1,0x64,0xE5,0x68,
0xF1,0x66,0x95,0x17,
0xF1,0x68,0x96,0x40,
0xF1,0x6A,0x77,0xCF,
0xF1,0x6C,0xFF,0xFF,
0xF1,0x6E,0xE5,0x42,
0xF1,0x70,0x95,0x38,
0xF1,0x72,0x0A,0x0D,
0xF1,0x74,0x00,0x01,
0xF1,0x76,0x97,0x40,
0xF1,0x78,0x0A,0x11,
0xF1,0x7A,0x00,0x40,
0xF1,0x7C,0x0B,0x0A,
0xF1,0x7E,0x01,0x00,
0xF1,0x80,0x95,0x17,
0xF1,0x82,0xB6,0x00,
0xF1,0x84,0x95,0x18,
0xF1,0x86,0xB7,0x00,
0xF1,0x88,0x76,0xCF,
0xF1,0x8A,0xFF,0xFF,
0xF1,0x8C,0xE5,0x44,
0xF1,0x8E,0x96,0x20,
0xF1,0x90,0x95,0x15,
0xF1,0x92,0x08,0x13,
0xF1,0x94,0x00,0x40,
0xF1,0x96,0x0E,0x1E,
0xF1,0x98,0x01,0x20,
0xF1,0x9A,0xD9,0x00,
0xF1,0x9C,0x95,0x15,
0xF1,0x9E,0xB6,0x00,
0xF1,0xA0,0xFF,0xA1,
0xF1,0xA2,0x75,0xCF,
0xF1,0xA4,0xFF,0xFF,
0xF1,0xA6,0xE7,0x1C,
0xF1,0xA8,0x77,0xCF,
0xF1,0xAA,0xFF,0xFF,
0xF1,0xAC,0xE5,0x46,
0xF1,0xAE,0x97,0x40,
0xF1,0xB0,0x8D,0x16,
0xF1,0xB2,0x76,0xCF,
0xF1,0xB4,0xFF,0xFF,
0xF1,0xB6,0xE5,0x48,
0xF1,0xB8,0x8D,0x37,
0xF1,0xBA,0x08,0x0D,
0xF1,0xBC,0x00,0x81,
0xF1,0xBE,0x96,0x40,
0xF1,0xC0,0x09,0x15,
0xF1,0xC2,0x00,0x80,
0xF1,0xC4,0x0F,0xD6,
0xF1,0xC6,0x01,0x00,
0xF1,0xC8,0x8D,0x16,
0xF1,0xCA,0xB7,0x00,
0xF1,0xCC,0x8D,0x17,
0xF1,0xCE,0xB6,0x00,
0xF1,0xD0,0xFF,0xB0,
0xF1,0xD2,0xFF,0xBC,
0xF1,0xD4,0x00,0x41,
0xF1,0xD6,0x03,0xC0,
0xF1,0xD8,0xC0,0xF1,
0xF1,0xDA,0x0D,0x9E,
0xF1,0xDC,0x01,0x00,
0xF1,0xDE,0xE8,0x04,
0xF1,0xE0,0xFF,0x88,
0xF1,0xE2,0xF0,0x0A,
0xF1,0xE4,0x0D,0x6A,
0xF1,0xE6,0x01,0x00,
0xF1,0xE8,0x0D,0x8E,
0xF1,0xEA,0x01,0x00,
0xF1,0xEC,0xE8,0x7E,
0xF1,0xEE,0xFF,0x85,
0xF1,0xF0,0x0D,0x72,
0xF1,0xF2,0x01,0x00,
0xF1,0xF4,0xFF,0x8C,
0xF1,0xF6,0xFF,0xA7,
0xF1,0xF8,0xFF,0xB2,
0xF1,0xFA,0xD8,0x00,
0xF1,0xFC,0x73,0xCF,
0xF1,0xFE,0xFF,0xFF,
0xF2,0x00,0xF2,0x40,
0xF2,0x02,0x23,0x15,
0xF2,0x04,0x00,0x01,
0xF2,0x06,0x81,0x41,
0xF2,0x08,0xE0,0x02,
0xF2,0x0A,0x81,0x20,
0xF2,0x0C,0x08,0xF7,
0xF2,0x0E,0x81,0x34,
0xF2,0x10,0xA1,0x40,
0xF2,0x12,0xD8,0x00,
0xF2,0x14,0xC0,0xD1,
0xF2,0x16,0x7E,0xE0,
0xF2,0x18,0x53,0x51,
0xF2,0x1A,0x30,0x34,
0xF2,0x1C,0x20,0x6F,
0xF2,0x1E,0x6E,0x5F,
0xF2,0x20,0x73,0x74,
0xF2,0x22,0x61,0x72,
0xF2,0x24,0x74,0x5F,
0xF2,0x26,0x73,0x74,
0xF2,0x28,0x72,0x65,
0xF2,0x2A,0x61,0x6D,
0xF2,0x2C,0x69,0x6E,
0xF2,0x2E,0x67,0x20,
0xF2,0x30,0x25,0x64,
0xF2,0x32,0x20,0x25,
0xF2,0x34,0x64,0x0A,
0xF2,0x36,0x00,0x00,
0xF2,0x38,0x00,0x00,
0xF2,0x3A,0x00,0x00,
0xF2,0x3C,0x00,0x00,
0xF2,0x3E,0x00,0x00,
0xF2,0x40,0xFF,0xFF,
0xF2,0x42,0xE8,0x28,
0xF2,0x44,0xFF,0xFF,
0xF2,0x46,0xF0,0xE8,
0xF2,0x48,0xFF,0xFF,
0xF2,0x4A,0xE8,0x08,
0xF2,0x4C,0xFF,0xFF,
0xF2,0x4E,0xF1,0x54,
0x09,0x8E,0x00,0x00,
0xE0,0x00,0x05,0xD8,
0xE0,0x02,0x04,0x03,
0x00,0x40,0xFF,0xF8,
//delay = 30
0x00,0x40,0xFF,0xF9,
//delay = 30
0x32,0x10,0x00,0xB0,
0x09,0x8e,0x48,0x26,
0xc8,0x26,0x01,0x00,
0xc8,0x6c,0x00,0x80,
0xc8,0x6e,0x00,0x80,
0xc8,0x70,0x00,0x20,
0xc8,0x72,0x28,/*0x01*/0x80,
0xa8,0x0e,0xa8,0x08,
0x30,0x32,0x01,0x00,
0x30,0x34,0x01,0x00,
0x30,0x36,0x01,0x00,
0x30,0x38,0x01,0x00,
0xc8,0x22,0x00,0xe0,
0x00,0x40,0x80,0x02,
0x00,0x40,0x80,0x04,
0xc8,0x68,0x02,0x38,
0xa8,0x0e,0x2a,0x06,
0xa8,0x12,0x04,0x00,
0xa4,0x04,0x01,0x01,
0xC8,0xF4,0x00,0x04,
0xC8,0xF6,0x00,0x00,
0xC8,0xF8,0x00,0x82,
0xC8,0xFA,0x00,0x5E,
0x00,0x40,0x80,0x04,
0x32,0x6c,0x10,0x03,
0x09,0x8E,0x48,0x8A,
0xC8,0x8A,0x02,0x14,
0xC8,0x8C,0xFE,0xDE,
0xC8,0x8E,0x00,0x0D,
0xC8,0x90,0xFF,0xCB,
0xC8,0x92,0x01,0x4D,
0xC8,0x94,0xFF,0xE8,
0xC8,0x96,0xFF,0xC6,
0xC8,0x98,0xFF,0x2B,
0xC8,0x9A,0x02,0x0F,
0xC8,0x9C,0x00,0x1E,
0xC8,0x9E,0x00,0x44,
0xC8,0xA0,0xFF,0xB7,
0xC8,0xA2,0x00,0x9F,
0xC8,0xA4,0xFF,0xAA,
0xC8,0xA6,0x00,0x05,
0xC8,0xA8,0xFF,0xD3,
0xC8,0xAA,0x00,0x28,
0xC8,0xAC,0x00,0x36,
0xC8,0xAE,0x00,0x67,
0xC8,0xB0,0xFF,0x63,
0xC8,0xB2,0x00,0x12,
0xC8,0xB4,0xFF,0xD9,
0xC8,0xCA,0x03,0x01,
0xC8,0xCC,0x00,0x00,
0xC8,0xCE,0x00,0x00,
0xC8,0xD0,0x00,0x80,
0xC8,0xD2,0x1B,0x80,
0xC8,0xD4,0x16,0x80,
0xC8,0xD6,0x01,0xAC,
0xC8,0xD8,0x00,0x3C,
0xC8,0xDA,0x00,0x00,
0xC8,0xDC,0x00,0x3C,
0xC8,0xDE,0x00,0x57,
0xAC,0x32,0x2E,0x7f,
0xAC,0x34,0x1B,0x83,
0x09,0x8E,0xBC,0x0C,
0xBC,0x02,0x00,0x07,
0xBC,0x0C,0x00,0x03,
0xBC,0x08,0x02,0x01,
0xBC,0x0E,0x0a,0x20,
0xBC,0x10,0x4f,0x71,
0xBC,0x12,0x8d,0xa3,
0xBC,0x14,0xb3,0xc0,
0xBC,0x16,0xcc,0xd5,
0xBC,0x18,0xdd,0xe4,
0xBC,0x1A,0xeb,0xf0,
0xBC,0x1C,0xf6,0xfb,
0xBC,0x1E,0xFf,0x00,
//0xc8,0x1c,0x00,0x14,
0x00,0x40,0x80,0x02,
0x36,0x40,0x03,0x70,
0x36,0x42,0x30,0xE8,
0x36,0x44,0x0A,0xCF,
0x36,0x46,0x62,0xCC,
0x36,0x48,0xA4,0x2F,
0x36,0x4A,0x02,0xD0,
0x36,0x4C,0xB9,0xAB,
0x36,0x4E,0x1B,0x0F,
0x36,0x50,0x1F,0x2B,
0x36,0x52,0x99,0x0F,
0x36,0x54,0x02,0xD0,
0x36,0x56,0xBD,0x89,
0x36,0x58,0x4F,0x2E,
0x36,0x5A,0x81,0x2A,
0x36,0x5C,0xAF,0xCE,
0x36,0x5E,0x03,0x90,
0x36,0x60,0x9E,0xC9,
0x36,0x62,0x16,0xCF,
0x36,0x64,0x11,0x0D,
0x36,0x66,0xBF,0xCF,
0x36,0x80,0x0B,0x8C,
0x36,0x82,0x94,0x6E,
0x36,0x84,0xB1,0x4D,
0x36,0x86,0x51,0xCE,
0x36,0x88,0x0E,0xEF,
0x36,0x8A,0x51,0x0A,
0x36,0x8C,0x85,0x2E,
0x36,0x8E,0x13,0xAB,
0x36,0x90,0x20,0xEE,
0x36,0x92,0x5F,0x6D,
0x36,0x94,0x07,0xEC,
0x36,0x96,0xDB,0x4D,
0x36,0x98,0x03,0xAE,
0x36,0x9A,0x1F,0xAE,
0x36,0x9C,0xE3,0xCD,
0x36,0x9E,0x00,0xED,
0x36,0xA0,0xC4,0x0D,
0x36,0xA2,0x46,0xCB,
0x36,0xA4,0x1F,0x4E,
0x36,0xA6,0x28,0xAB,
0x36,0xC0,0x7E,0xED,
0x36,0xC2,0x09,0x8D,
0x36,0xC4,0x89,0xF1,
0x36,0xC6,0x95,0xEE,
0x36,0xC8,0x47,0xCF,
0x36,0xCA,0x2B,0xCE,
0x36,0xCC,0xC7,0x08,
0x36,0xCE,0x8E,0xD1,
0x36,0xD0,0x06,0x0D,
0x36,0xD2,0x21,0xF0,
0x36,0xD4,0x6D,0x0D,
0x36,0xD6,0xC7,0x2E,
0x36,0xD8,0x93,0x71,
0x36,0xDA,0x05,0xF0,
0x36,0xDC,0x73,0xD0,
0x36,0xDE,0x3D,0x8D,
0x36,0xE0,0x12,0x0D,
0x36,0xE2,0x89,0xD1,
0x36,0xE4,0xEB,0xCD,
0x36,0xE6,0x29,0xD0,
0x37,0x00,0xA6,0x6E,
0x37,0x02,0x65,0xCF,
0x37,0x04,0x02,0x51,
0x37,0x06,0xC2,0x6F,
0x37,0x08,0xC2,0xB1,
0x37,0x0A,0xD9,0x2C,
0x37,0x0C,0x39,0x8F,
0x37,0x0E,0x64,0x0E,
0x37,0x10,0xC3,0xCF,
0x37,0x12,0x20,0x0E,
0x37,0x14,0x22,0x4B,
0x37,0x16,0x1E,0x8F,
0x37,0x18,0x97,0x30,
0x37,0x1A,0xA1,0x6F,
0x37,0x1C,0x33,0x11,
0x37,0x1E,0xB8,0xAD,
0x37,0x20,0x4B,0x8F,
0x37,0x22,0x57,0x8F,
0x37,0x24,0xCE,0x6F,
0x37,0x26,0xF4,0xCF,
0x37,0x40,0x95,0xAE,
0x37,0x42,0x97,0xAF,
0x37,0x44,0x71,0xAC,
0x37,0x46,0x15,0x8D,
0x37,0x48,0x1F,0x72,
0x37,0x4A,0x9A,0x4F,
0x37,0x4C,0xCA,0x6D,
0x37,0x4E,0x02,0xD1,
0x37,0x50,0x17,0x8F,
0x37,0x52,0xF1,0x2F,
0x37,0x54,0xDC,0xCE,
0x37,0x56,0x07,0x10,
0x37,0x58,0x05,0xB2,
0x37,0x5A,0xDB,0x11,
0x37,0x5C,0xC6,0x32,
0x37,0x5E,0x8B,0xCE,
0x37,0x60,0x99,0x2F,
0x37,0x62,0x07,0x90,
0x37,0x64,0x63,0xCD,
0x37,0x66,0x39,0xD0,
0x37,0x82,0x00,0xD8,
0x37,0x84,0x01,0x3C,
0x32,0x10,0x02,0xb8,
0x09,0x8E,0x48,0x60,
0xc8,0x60,0x01,0x00,
0xc8,0x61,0x00,0x00,
0x09,0x8E,0x48,0x61,
0x00,0x40,0x80,0x02,
0x09,0x8E,0x48,0x02,
0xc8,0x02,0x00,0x10,
0xc8,0x06,0x02,0x97,
0xc8,0x04,0x01,0xf3,
0xc8,0x14,0x01,0xe3,
0xc8,0x0e,0x02,0x0d,
0xc8,0x48,0x00,0x00,
0xc8,0x4a,0x00,0x00,
0xc8,0x4c,0x02,0x80,
0xc8,0x4e,0x01,0xe0,
0xc8,0x54,0x02,0x80,
0xc8,0x56,0x01,0xe0,
0xc8,0x50,0x03,0x42,
0xc8,0xf0,0x02,0x7f,
0xc8,0xf2,0x01,0xdf,
0xc8,0xf4,0x00,0x04,
0xc8,0xf6,0x00,0x04,
0xc8,0xf8,0x00,0x7e,
0xc8,0xfa,0x00,0x5e,
0xdc,0x00,0x28,0x00,
0xc8,0x28,0x00,0x02,
//delay = 10
0xc9,0x05,0x02,0x00,
0xc9,0x08,0x03,0x00,
//delay = 10
//0x09,0x8e,0x48,0x18,
//0x09,0x90,0x00,0x9b, //open streaming
0x09,0x8E,0x48,0x48, //VGA streaming
0x09,0x90,0x00,0x00,
0x09,0x8E,0x48,0x4A,
0x09,0x90,0x00,0x00,
0x09,0x8E,0x48,0x4C,
0x09,0x90,0x02,0x80,
0x09,0x8E,0x48,0x4E,
0x09,0x90,0x01,0xE0,
0x09,0x8E,0x48,0x54,
0x09,0x90,0x02,0x80,
0x09,0x8E,0x48,0x56,
0x09,0x90,0x01,0xe0,
0x09,0x8E,0xC8,0x50,
0x09,0x90,0x03,0x00,
0x09,0x8E,0x48,0xF0,
0x09,0x90,0x02,0x7F,
0x09,0x8E,0x48,0xF2,
0x09,0x90,0x01,0xdF,
0x09,0x8E,0x48,0xF4,
0x09,0x90,0x00,0x04,
0x09,0x8E,0x48,0xF6,
0x09,0x90,0x00,0x04,
0x09,0x8E,0x48,0xF8,
0x09,0x90,0x00,0x7e,
0x09,0x8E,0x48,0xFA,
0x09,0x90,0x00,0x5e,
0x09,0x8E,0xDC,0x00,
0x09,0x90,0x28,0x00,
0x09,0x8e,0x48,0x16,
0x09,0x90,0x00,0x83,
0xdc,0x00,0x28,0x31,
0x00,0x40,0x80,0x02,
//delay = 10 //VGA streaming
0x09,0x8E,0x48,0x28,
0xc8,0x28,0x00,0x02, //mirror
0xdc,0x00,0x28,0x31,
0x00,0x40,0x80,0x02,
//delay = 30 //normal[flip section]
0x09,0x8E,0x48,0x69, //brightness
0x09,0x90,0x38,0x00,
0x09,0x8E,0x48,0x60, //Hue
0x09,0x90,0x01,0x00,
0x09,0x8E,0x48,0x61,
0x09,0x90,0x00,0x00,
0x00,0x40,0x80,0x02,
0x09,0x8E,0x49,0x05, //sharpness
0x09,0x90,0x02,0x00,
0x09,0x8E,0x49,0x08,
0x09,0x90,0x02,0x00,
//modify by seven 2011-6-7
//Disable auto exposure
#if 0
0x09,0x8E,0x28,0x04,
0xA8,0x04,0x00,0x00,
0xDC,0x00,0x00,0x28,
0x00,0x40,0x80,0x02,
0x30,0x12,0x01,0x2C,
#endif
//Enable auto exposure
#if 1
0x09,0x8E,0x28,0x04,
0xA8,0x04,0x00,0x1F,
0xDC,0x00,0x00,0x28,
0x00,0x40,0x80,0x02,
#endif
0xC8,0x16,0x00,0xBD,
0xC8,0x18,0x00,0xE3,
0xDC,0x00,0x00,0x28,
0x00,0x40,0x80,0x02,
END_,END_,END_,END_
};
unsigned char mt9v136regs1[]=
{
0xC8,0x16,0x00,0xBD,
0xC8,0x18,0x00,0xE3,
0xC8,0x1A,0x00,0x06,//0x18,
0xC8,0x1C,0x00,0x05,//0x14,
0x00,0x40,0x80,0x02,
//delay = 30
0xC8,0x1E,0x00,0x04,
0xC8,0x20,0x00,0x03,
0xC9,0x16,0x01,0x09,
0xC9,0x18,0x06,0x2C,
0xC8,0x50,0x03,0x42,
0xC8,0xF4,0x00,0x04,
0xC8,0xF8,0x00,0x82,
//delay = 30
0x00,0x30,0x04,0x04,
0x00,0x30,0x04,0x04,
0x30,0x1A,0x10,0xD0,
0x31,0xC0,0x14,0x04,
0x3E,0xD8,0x87,0x9C,
0x30,0x42,0x20,0xE1,
0x30,0xD4,0x80,0x20,
0x30,0xC0,0x00,0x26,
0x30,0x1A,0x10,0xD4,
0xA8,0x02,0x00,0xD3,
0xC8,0x78,0x00,0xA0,
0xC8,0x76,0x01,0x40,
0xBC,0x04,0x00,0xFC,
0xBC,0x38,0x00,0x7f,
0xBC,0x3A,0x00,0xbf,
0xBC,0x3C,0x00,0xbf,
0xBC,0x04,0x00,0xFc,
0xC9,0x1A,0x00,0x0F,
0xC9,0x1C,0x00,0x06,
0xC8,0xFC,0x00,0x0C,
0xC8,0xFE,0x00,0x30,
0xC9,0x12,0x00,0x0C,
0xC9,0x14,0x00,0x4B,
0xC9,0x16,0x01,0x09,
0xC9,0x18,0x06,0x2C,
0xC9,0x07,0xA8,0x01,
0xC9,0x0A,0x14,0x14,
0xC9,0x0C,0x14,0x14,
0xC9,0x0E,0x32,0x32,
0xC9,0x10,0x32,0x32,
0xC9,0x1E,0x01,0xF4,
0xC9,0x20,0x27,0x10,
0xC9,0x00,0x80,0x4a,
0xC9,0x04,0x08,0x02,
0xC9,0x06,0x02,0xa8,
0xC9,0x08,0x07,0x7f,
0xBC,0x06,0x01,0x5E,
0xC8,0xE6,0x80,0x80,
0xC8,0x3E,0x00,0x01,
0x32,0x80,0x00,0xAA,
0xC9,0x16,0x01,0x09,
0xC9,0x18,0x06,0x2C,
0xC8,0xCE,0x33,0xA1,
0xC8,0xD0,0xEC,0x08,
0xC8,0xD2,0xFF,0xC0,
0xC8,0xDE,0x00,0x33,
0x00,0x40,0x80,0x02,
//delay = 30
0x09,0x82,0x00,0x01,
0x09,0x8A,0x70,0x00,
0xF0,0x00,0x72,0xCF,
0xF0,0x02,0xFF,0x00,
0xF0,0x04,0x3E,0xD0,
0xF0,0x06,0x92,0x00,
0xF0,0x08,0x71,0xCF,
0xF0,0x0A,0xFF,0xFF,
0xF0,0x0C,0xF2,0x18,
0xF0,0x0E,0xB1,0x10,
0xF0,0x10,0x92,0x05,
0xF0,0x12,0xB1,0x11,
0xF0,0x14,0x92,0x04,
0xF0,0x16,0xB1,0x12,
0xF0,0x18,0x70,0xCF,
0xF0,0x1A,0xFF,0x00,
0xF0,0x1C,0x30,0xC0,
0xF0,0x1E,0x90,0x00,
0xF0,0x20,0x7F,0xE0,
0xF0,0x22,0xB1,0x13,
0xF0,0x24,0x70,0xCF,
0xF0,0x26,0xFF,0xFF,
0xF0,0x28,0xE7,0x1C,
0xF0,0x2A,0x88,0x36,
0xF0,0x2C,0x09,0x0F,
0xF0,0x2E,0x00,0xB3,
0xF0,0x30,0x69,0x13,
0xF0,0x32,0xE1,0x80,
0xF0,0x34,0xD8,0x08,
0xF0,0x36,0x20,0xCA,
0xF0,0x38,0x03,0x22,
0xF0,0x3A,0x71,0xCF,
0xF0,0x3C,0xFF,0xFF,
0xF0,0x3E,0xE5,0x68,
0xF0,0x40,0x91,0x35,
0xF0,0x42,0x22,0x0A,
0xF0,0x44,0x1F,0x80,
0xF0,0x46,0xFF,0xFF,
0xF0,0x48,0xF2,0x18,
0xF0,0x4A,0x29,0x05,
0xF0,0x4C,0x00,0x3E,
0xF0,0x4E,0x12,0x22,
0xF0,0x50,0x11,0x01,
0xF0,0x52,0x21,0x04,
0xF0,0x54,0x0F,0x81,
0xF0,0x56,0x00,0x00,
0xF0,0x58,0xFF,0xF0,
0xF0,0x5A,0x21,0x8C,
0xF0,0x5C,0xF0,0x10,
0xF0,0x5E,0x1A,0x22,
0xF0,0x60,0x10,0x44,
0xF0,0x62,0x12,0x20,
0xF0,0x64,0x11,0x02,
0xF0,0x66,0xF7,0x87,
0xF0,0x68,0x22,0x4F,
0xF0,0x6A,0x03,0x83,
0xF0,0x6C,0x1A,0x20,
0xF0,0x6E,0x10,0xC4,
0xF0,0x70,0xF0,0x09,
0xF0,0x72,0xBA,0xAE,
0xF0,0x74,0x7B,0x50,
0xF0,0x76,0x1A,0x20,
0xF0,0x78,0x10,0x84,
0xF0,0x7A,0x21,0x45,
0xF0,0x7C,0x01,0xC1,
0xF0,0x7E,0x1A,0x22,
0xF0,0x80,0x10,0x44,
0xF0,0x82,0x70,0xCF,
0xF0,0x84,0xFF,0x00,
0xF0,0x86,0x3E,0xD0,
0xF0,0x88,0xB0,0x60,
0xF0,0x8A,0xB0,0x25,
0xF0,0x8C,0x7E,0xE0,
0xF0,0x8E,0x78,0xE0,
0xF0,0x90,0x71,0xCF,
0xF0,0x92,0xFF,0xFF,
0xF0,0x94,0xF2,0x18,
0xF0,0x96,0x91,0x12,
0xF0,0x98,0x72,0xCF,
0xF0,0x9A,0xFF,0xFF,
0xF0,0x9C,0xE7,0x1C,
0xF0,0x9E,0x8A,0x57,
0xF0,0xA0,0x20,0x04,
0xF0,0xA2,0x0F,0x80,
0xF0,0xA4,0x00,0x00,
0xF0,0xA6,0xFF,0xF0,
0xF0,0xA8,0xE2,0x80,
0xF0,0xAA,0x20,0xC5,
0xF0,0xAC,0x01,0x61,
0xF0,0xAE,0x20,0xC5,
0xF0,0xB0,0x03,0x22,
0xF0,0xB2,0xB1,0x12,
0xF0,0xB4,0x71,0xCF,
0xF0,0xB6,0xFF,0x00,
0xF0,0xB8,0x3E,0xD0,
0xF0,0xBA,0xB1,0x04,
0xF0,0xBC,0x7E,0xE0,
0xF0,0xBE,0x78,0xE0,
0xF0,0xC0,0x70,0xCF,
0xF0,0xC2,0xFF,0xFF,
0xF0,0xC4,0xE7,0x1C,
0xF0,0xC6,0x88,0x57,
0xF0,0xC8,0x71,0xCF,
0xF0,0xCA,0xFF,0xFF,
0xF0,0xCC,0xF2,0x18,
0xF0,0xCE,0x91,0x13,
0xF0,0xD0,0xEA,0x84,
0xF0,0xD2,0xB8,0xA9,
0xF0,0xD4,0x78,0x10,
0xF0,0xD6,0xF0,0x03,
0xF0,0xD8,0xB8,0x89,
0xF0,0xDA,0xB8,0x8C,
0xF0,0xDC,0xB1,0x13,
0xF0,0xDE,0x71,0xCF,
0xF0,0xE0,0xFF,0x00,
0xF0,0xE2,0x30,0xC0,
0xF0,0xE4,0xB1,0x00,
0xF0,0xE6,0x7E,0xE0,
0xF0,0xE8,0xC0,0xF1,
0xF0,0xEA,0x09,0x1E,
0xF0,0xEC,0x03,0xC0,
0xF0,0xEE,0xC1,0xA1,
0xF0,0xF0,0x75,0x08,
0xF0,0xF2,0x76,0x28,
0xF0,0xF4,0x77,0x48,
0xF0,0xF6,0xC2,0x40,
0xF0,0xF8,0xD8,0x20,
0xF0,0xFA,0x71,0xCF,
0xF0,0xFC,0x00,0x03,
0xF0,0xFE,0x20,0x67,
0xF1,0x00,0xDA,0x02,
0xF1,0x02,0x08,0xAE,
0xF1,0x04,0x03,0xA0,
0xF1,0x06,0x73,0xC9,
0xF1,0x08,0x0E,0x25,
0xF1,0x0A,0x13,0xC0,
0xF1,0x0C,0x0B,0x5E,
0xF1,0x0E,0x01,0x60,
0xF1,0x10,0xD8,0x06,
0xF1,0x12,0xFF,0xBC,
0xF1,0x14,0x0C,0xCE,
0xF1,0x16,0x01,0x00,
0xF1,0x18,0xD8,0x00,
0xF1,0x1A,0xB8,0x9E,
0xF1,0x1C,0x0E,0x5A,
0xF1,0x1E,0x03,0x20,
0xF1,0x20,0xD9,0x01,
0xF1,0x22,0xD8,0x00,
0xF1,0x24,0xB8,0x9E,
0xF1,0x26,0x0E,0xB6,
0xF1,0x28,0x03,0x20,
0xF1,0x2A,0xD9,0x01,
0xF1,0x2C,0x8D,0x14,
0xF1,0x2E,0x08,0x17,
0xF1,0x30,0x01,0x91,
0xF1,0x32,0x8D,0x16,
0xF1,0x34,0xE8,0x07,
0xF1,0x36,0x0B,0x36,
0xF1,0x38,0x01,0x60,
0xF1,0x3A,0xD8,0x07,
0xF1,0x3C,0x0B,0x52,
0xF1,0x3E,0x01,0x60,
0xF1,0x40,0xD8,0x11,
0xF1,0x42,0x8D,0x14,
0xF1,0x44,0xE0,0x87,
0xF1,0x46,0xD8,0x00,
0xF1,0x48,0x20,0xCA,
0xF1,0x4A,0x02,0x62,
0xF1,0x4C,0x00,0xC9,
0xF1,0x4E,0x03,0xE0,
0xF1,0x50,0xC0,0xA1,
0xF1,0x52,0x78,0xE0,
0xF1,0x54,0xC0,0xF1,
0xF1,0x56,0x08,0xB2,
0xF1,0x58,0x03,0xC0,
0xF1,0x5A,0x76,0xCF,
0xF1,0x5C,0xFF,0xFF,
0xF1,0x5E,0xE5,0x40,
0xF1,0x60,0x75,0xCF,
0xF1,0x62,0xFF,0xFF,
0xF1,0x64,0xE5,0x68,
0xF1,0x66,0x95,0x17,
0xF1,0x68,0x96,0x40,
0xF1,0x6A,0x77,0xCF,
0xF1,0x6C,0xFF,0xFF,
0xF1,0x6E,0xE5,0x42,
0xF1,0x70,0x95,0x38,
0xF1,0x72,0x0A,0x0D,
0xF1,0x74,0x00,0x01,
0xF1,0x76,0x97,0x40,
0xF1,0x78,0x0A,0x11,
0xF1,0x7A,0x00,0x40,
0xF1,0x7C,0x0B,0x0A,
0xF1,0x7E,0x01,0x00,
0xF1,0x80,0x95,0x17,
0xF1,0x82,0xB6,0x00,
0xF1,0x84,0x95,0x18,
0xF1,0x86,0xB7,0x00,
0xF1,0x88,0x76,0xCF,
0xF1,0x8A,0xFF,0xFF,
0xF1,0x8C,0xE5,0x44,
0xF1,0x8E,0x96,0x20,
0xF1,0x90,0x95,0x15,
0xF1,0x92,0x08,0x13,
0xF1,0x94,0x00,0x40,
0xF1,0x96,0x0E,0x1E,
0xF1,0x98,0x01,0x20,
0xF1,0x9A,0xD9,0x00,
0xF1,0x9C,0x95,0x15,
0xF1,0x9E,0xB6,0x00,
0xF1,0xA0,0xFF,0xA1,
0xF1,0xA2,0x75,0xCF,
0xF1,0xA4,0xFF,0xFF,
0xF1,0xA6,0xE7,0x1C,
0xF1,0xA8,0x77,0xCF,
0xF1,0xAA,0xFF,0xFF,
0xF1,0xAC,0xE5,0x46,
0xF1,0xAE,0x97,0x40,
0xF1,0xB0,0x8D,0x16,
0xF1,0xB2,0x76,0xCF,
0xF1,0xB4,0xFF,0xFF,
0xF1,0xB6,0xE5,0x48,
0xF1,0xB8,0x8D,0x37,
0xF1,0xBA,0x08,0x0D,
0xF1,0xBC,0x00,0x81,
0xF1,0xBE,0x96,0x40,
0xF1,0xC0,0x09,0x15,
0xF1,0xC2,0x00,0x80,
0xF1,0xC4,0x0F,0xD6,
0xF1,0xC6,0x01,0x00,
0xF1,0xC8,0x8D,0x16,
0xF1,0xCA,0xB7,0x00,
0xF1,0xCC,0x8D,0x17,
0xF1,0xCE,0xB6,0x00,
0xF1,0xD0,0xFF,0xB0,
0xF1,0xD2,0xFF,0xBC,
0xF1,0xD4,0x00,0x41,
0xF1,0xD6,0x03,0xC0,
0xF1,0xD8,0xC0,0xF1,
0xF1,0xDA,0x0D,0x9E,
0xF1,0xDC,0x01,0x00,
0xF1,0xDE,0xE8,0x04,
0xF1,0xE0,0xFF,0x88,
0xF1,0xE2,0xF0,0x0A,
0xF1,0xE4,0x0D,0x6A,
0xF1,0xE6,0x01,0x00,
0xF1,0xE8,0x0D,0x8E,
0xF1,0xEA,0x01,0x00,
0xF1,0xEC,0xE8,0x7E,
0xF1,0xEE,0xFF,0x85,
0xF1,0xF0,0x0D,0x72,
0xF1,0xF2,0x01,0x00,
0xF1,0xF4,0xFF,0x8C,
0xF1,0xF6,0xFF,0xA7,
0xF1,0xF8,0xFF,0xB2,
0xF1,0xFA,0xD8,0x00,
0xF1,0xFC,0x73,0xCF,
0xF1,0xFE,0xFF,0xFF,
0xF2,0x00,0xF2,0x40,
0xF2,0x02,0x23,0x15,
0xF2,0x04,0x00,0x01,
0xF2,0x06,0x81,0x41,
0xF2,0x08,0xE0,0x02,
0xF2,0x0A,0x81,0x20,
0xF2,0x0C,0x08,0xF7,
0xF2,0x0E,0x81,0x34,
0xF2,0x10,0xA1,0x40,
0xF2,0x12,0xD8,0x00,
0xF2,0x14,0xC0,0xD1,
0xF2,0x16,0x7E,0xE0,
0xF2,0x18,0x53,0x51,
0xF2,0x1A,0x30,0x34,
0xF2,0x1C,0x20,0x6F,
0xF2,0x1E,0x6E,0x5F,
0xF2,0x20,0x73,0x74,
0xF2,0x22,0x61,0x72,
0xF2,0x24,0x74,0x5F,
0xF2,0x26,0x73,0x74,
0xF2,0x28,0x72,0x65,
0xF2,0x2A,0x61,0x6D,
0xF2,0x2C,0x69,0x6E,
0xF2,0x2E,0x67,0x20,
0xF2,0x30,0x25,0x64,
0xF2,0x32,0x20,0x25,
0xF2,0x34,0x64,0x0A,
0xF2,0x36,0x00,0x00,
0xF2,0x38,0x00,0x00,
0xF2,0x3A,0x00,0x00,
0xF2,0x3C,0x00,0x00,
0xF2,0x3E,0x00,0x00,
0xF2,0x40,0xFF,0xFF,
0xF2,0x42,0xE8,0x28,
0xF2,0x44,0xFF,0xFF,
0xF2,0x46,0xF0,0xE8,
0xF2,0x48,0xFF,0xFF,
0xF2,0x4A,0xE8,0x08,
0xF2,0x4C,0xFF,0xFF,
0xF2,0x4E,0xF1,0x54,
0x09,0x8E,0x00,0x00,
0xE0,0x00,0x05,0xD8,
0xE0,0x02,0x04,0x03,
0x00,0x40,0xFF,0xF8,
//delay = 30
0x00,0x40,0xFF,0xF9,
//delay = 30
0x32,0x10,0x00,0xB0,
0x09,0x8e,0x48,0x26,
0xc8,0x26,0x01,0x00,
0xc8,0x6c,0x00,0x80,
0xc8,0x6e,0x00,0x80,
0xc8,0x70,0x00,0x20,
0xc8,0x72,0x08,/*0x01*/0x00,
0xa8,0x0e,0xa8,0x08,
0x30,0x32,0x01,0x00,
0x30,0x34,0x01,0x00,
0x30,0x36,0x01,0x00,
0x30,0x38,0x01,0x00,
0xc8,0x22,0x00,0xe0,
0x00,0x40,0x80,0x02,
0x00,0x40,0x80,0x04,
0xc8,0x68,0x02,0x38,
0xa8,0x0e,0x2a,0x06,
0xa8,0x12,0x04,0x00,
0xa4,0x04,0x01,0x01,
#if 0
0xC8,0xF4,0x00,0x04,//0x00,0x04, //AE
0xC8,0xF6,0x00,0x00,//0x00,0x00,
0xC8,0xF8,0x00,0x82,//0x00,0x82,
0xC8,0xFA,0x00,0x5E,//0x00,0x5E,
#else
0xC8,0xF4,0x00,0x00, //AE
0xC8,0xF6,0x00,0x00,
0xC8,0xF8,0x02,0x80,
0xC8,0xFA,0x01,0xE0,
#endif
0x00,0x40,0x80,0x04,
0x32,0x6c,0x10,0x03,
0x09,0x8E,0x48,0x8A,
0xC8,0x8A,0x02,0x14,
0xC8,0x8C,0xFE,0xDE,
0xC8,0x8E,0x00,0x0D,
0xC8,0x90,0xFF,0xCB,
0xC8,0x92,0x01,0x4D,
0xC8,0x94,0xFF,0xE8,
0xC8,0x96,0xFF,0xC6,
0xC8,0x98,0xFF,0x2B,
0xC8,0x9A,0x02,0x0F,
0xC8,0x9C,0x00,0x1E,
0xC8,0x9E,0x00,0x44,
0xC8,0xA0,0xFF,0xB7,
0xC8,0xA2,0x00,0x9F,
0xC8,0xA4,0xFF,0xAA,
0xC8,0xA6,0x00,0x05,
0xC8,0xA8,0xFF,0xD3,
0xC8,0xAA,0x00,0x28,
0xC8,0xAC,0x00,0x36,
0xC8,0xAE,0x00,0x67,
0xC8,0xB0,0xFF,0x63,
0xC8,0xB2,0x00,0x12,
0xC8,0xB4,0xFF,0xD9,
0xC8,0xCA,0x03,0x01,
0xC8,0xCC,0x00,0x00,
0xC8,0xCE,0x00,0x00,
0xC8,0xD0,0x00,0x80,
0xC8,0xD2,0x1B,0x80,
0xC8,0xD4,0x16,0x80,
0xC8,0xD6,0x01,0xAC,
0xC8,0xD8,0x00,0x3C,
0xC8,0xDA,0x00,0x00,
0xC8,0xDC,0x00,0x3C,
0xC8,0xDE,0x00,0x57,
0xAC,0x32,0x2E,0x7f,
0xAC,0x34,0x1B,0x83,
0x09,0x8E,0xBC,0x0C,
0xBC,0x02,0x00,0x07,
0xBC,0x0C,0x00,0x03,
0xBC,0x08,0x02,0x01,
0xBC,0x0E,0x0a,0x20,
0xBC,0x10,0x4f,0x71,
0xBC,0x12,0x8d,0xa3,
0xBC,0x14,0xb3,0xc0,
0xBC,0x16,0xcc,0xd5,
0xBC,0x18,0xdd,0xe4,
0xBC,0x1A,0xeb,0xf0,
0xBC,0x1C,0xf6,0xfb,
0xBC,0x1E,0xFf,0x00,
//0xc8,0x1c,0x00,0x14,
0x00,0x40,0x80,0x02,
0x36,0x40,0x03,0x70,
0x36,0x42,0x30,0xE8,
0x36,0x44,0x0A,0xCF,
0x36,0x46,0x62,0xCC,
0x36,0x48,0xA4,0x2F,
0x36,0x4A,0x02,0xD0,
0x36,0x4C,0xB9,0xAB,
0x36,0x4E,0x1B,0x0F,
0x36,0x50,0x1F,0x2B,
0x36,0x52,0x99,0x0F,
0x36,0x54,0x02,0xD0,
0x36,0x56,0xBD,0x89,
0x36,0x58,0x4F,0x2E,
0x36,0x5A,0x81,0x2A,
0x36,0x5C,0xAF,0xCE,
0x36,0x5E,0x03,0x90,
0x36,0x60,0x9E,0xC9,
0x36,0x62,0x16,0xCF,
0x36,0x64,0x11,0x0D,
0x36,0x66,0xBF,0xCF,
0x36,0x80,0x0B,0x8C,
0x36,0x82,0x94,0x6E,
0x36,0x84,0xB1,0x4D,
0x36,0x86,0x51,0xCE,
0x36,0x88,0x0E,0xEF,
0x36,0x8A,0x51,0x0A,
0x36,0x8C,0x85,0x2E,
0x36,0x8E,0x13,0xAB,
0x36,0x90,0x20,0xEE,
0x36,0x92,0x5F,0x6D,
0x36,0x94,0x07,0xEC,
0x36,0x96,0xDB,0x4D,
0x36,0x98,0x03,0xAE,
0x36,0x9A,0x1F,0xAE,
0x36,0x9C,0xE3,0xCD,
0x36,0x9E,0x00,0xED,
0x36,0xA0,0xC4,0x0D,
0x36,0xA2,0x46,0xCB,
0x36,0xA4,0x1F,0x4E,
0x36,0xA6,0x28,0xAB,
0x36,0xC0,0x7E,0xED,
0x36,0xC2,0x09,0x8D,
0x36,0xC4,0x89,0xF1,
0x36,0xC6,0x95,0xEE,
0x36,0xC8,0x47,0xCF,
0x36,0xCA,0x2B,0xCE,
0x36,0xCC,0xC7,0x08,
0x36,0xCE,0x8E,0xD1,
0x36,0xD0,0x06,0x0D,
0x36,0xD2,0x21,0xF0,
0x36,0xD4,0x6D,0x0D,
0x36,0xD6,0xC7,0x2E,
0x36,0xD8,0x93,0x71,
0x36,0xDA,0x05,0xF0,
0x36,0xDC,0x73,0xD0,
0x36,0xDE,0x3D,0x8D,
0x36,0xE0,0x12,0x0D,
0x36,0xE2,0x89,0xD1,
0x36,0xE4,0xEB,0xCD,
0x36,0xE6,0x29,0xD0,
0x37,0x00,0xA6,0x6E,
0x37,0x02,0x65,0xCF,
0x37,0x04,0x02,0x51,
0x37,0x06,0xC2,0x6F,
0x37,0x08,0xC2,0xB1,
0x37,0x0A,0xD9,0x2C,
0x37,0x0C,0x39,0x8F,
0x37,0x0E,0x64,0x0E,
0x37,0x10,0xC3,0xCF,
0x37,0x12,0x20,0x0E,
0x37,0x14,0x22,0x4B,
0x37,0x16,0x1E,0x8F,
0x37,0x18,0x97,0x30,
0x37,0x1A,0xA1,0x6F,
0x37,0x1C,0x33,0x11,
0x37,0x1E,0xB8,0xAD,
0x37,0x20,0x4B,0x8F,
0x37,0x22,0x57,0x8F,
0x37,0x24,0xCE,0x6F,
0x37,0x26,0xF4,0xCF,
0x37,0x40,0x95,0xAE,
0x37,0x42,0x97,0xAF,
0x37,0x44,0x71,0xAC,
0x37,0x46,0x15,0x8D,
0x37,0x48,0x1F,0x72,
0x37,0x4A,0x9A,0x4F,
0x37,0x4C,0xCA,0x6D,
0x37,0x4E,0x02,0xD1,
0x37,0x50,0x17,0x8F,
0x37,0x52,0xF1,0x2F,
0x37,0x54,0xDC,0xCE,
0x37,0x56,0x07,0x10,
0x37,0x58,0x05,0xB2,
0x37,0x5A,0xDB,0x11,
0x37,0x5C,0xC6,0x32,
0x37,0x5E,0x8B,0xCE,
0x37,0x60,0x99,0x2F,
0x37,0x62,0x07,0x90,
0x37,0x64,0x63,0xCD,
0x37,0x66,0x39,0xD0,
0x37,0x82,0x00,0xD8,
0x37,0x84,0x01,0x3C,
0x32,0x10,0x02,0xb8,
0x09,0x8E,0x48,0x60,
0xc8,0x60,0x01,0x00,
0xc8,0x61,0x00,0x00,
0x09,0x8E,0x48,0x61,
0x00,0x40,0x80,0x02,
0x09,0x8E,0x48,0x02,
0xc8,0x02,0x00,0x10,
0xc8,0x06,0x02,0x97,
0xc8,0x04,0x01,0xf3,
0xc8,0x14,0x01,0xe3,
0xc8,0x0e,0x02,0x0d,
0xc8,0x48,0x00,0x00,
0xc8,0x4a,0x00,0x00,
0xc8,0x4c,0x02,0x80,
0xc8,0x4e,0x01,0xe0,
0xc8,0x54,0x02,0x80,
0xc8,0x56,0x01,0xe0,
0xc8,0x50,0x03,0x42,
0xc8,0xf0,0x02,0x7f,
0xc8,0xf2,0x01,0xdf,
0xc8,0xf4,0x00,0x04,
0xc8,0xf6,0x00,0x04,
0xc8,0xf8,0x00,0x7e,
0xc8,0xfa,0x00,0x5e,
0xdc,0x00,0x28,0x00,
0xc8,0x28,0x00,0x00,
//delay = 10
0xc9,0x05,0x02,0x00,
0xc9,0x08,0x03,0x00,
//delay = 10
//0x09,0x8e,0x48,0x18,
//0x09,0x90,0x00,0x9b, //open streaming
0x09,0x8E,0x48,0x48, //VGA streaming
0x09,0x90,0x00,0x00,
0x09,0x8E,0x48,0x4A,
0x09,0x90,0x00,0x00,
0x09,0x8E,0x48,0x4C,
0x09,0x90,0x02,0x80,
0x09,0x8E,0x48,0x4E,
0x09,0x90,0x01,0xE0,
0x09,0x8E,0x48,0x54,
0x09,0x90,0x02,0x80,
0x09,0x8E,0x48,0x56,
0x09,0x90,0x01,0xe0,
0x09,0x8E,0xC8,0x50,
0x09,0x90,0x03,0x00,
0x09,0x8E,0x48,0xF0,
0x09,0x90,0x02,0x7F,
0x09,0x8E,0x48,0xF2,
0x09,0x90,0x01,0xdF,
0x09,0x8E,0x48,0xF4,
0x09,0x90,0x00,0x04,
0x09,0x8E,0x48,0xF6,
0x09,0x90,0x00,0x04,
0x09,0x8E,0x48,0xF8,
0x09,0x90,0x00,0x7e,
0x09,0x8E,0x48,0xFA,
0x09,0x90,0x00,0x5e,
0x09,0x8E,0xDC,0x00,
0x09,0x90,0x28,0x00,
0x09,0x8e,0x48,0x16,
0x09,0x90,0x00,0x83,
0xdc,0x00,0x28,0x31,
0x00,0x40,0x80,0x02,
//delay = 10 //VGA streaming
0x09,0x8E,0x48,0x28,
0xc8,0x28,0x00,0x00,
0xdc,0x00,0x28,0x31,
0x00,0x40,0x80,0x02,
//delay = 30 //normal[flip section]
0x09,0x8E,0x48,0x69, //brightness
0x09,0x90,0x38,0x00,
0x09,0x8E,0x48,0x60, //Hue
0x09,0x90,0x01,0x00,
0x09,0x8E,0x48,0x61,
0x09,0x90,0x00,0x00,
0x00,0x40,0x80,0x02,
0x09,0x8E,0x49,0x05, //sharpness
0x09,0x90,0x02,0x00,
0x09,0x8E,0x49,0x08,
0x09,0x90,0x02,0x00,
//Disable auto exposure
#if 1
0x09,0x8E,0x28,0x04,
0xA8,0x04,0x00,0x00,
0xDC,0x00,0x00,0x28,
0x00,0x40,0x80,0x02,
0x30,0x12,0x01,0x2C,
#endif
//Enable auto exposure
#if 0
0x09,0x8E,0x28,0x04,
0xA8,0x04,0x00,0x1F,
0xDC,0x00,0x00,0x28,
0x00,0x40,0x80,0x02,
#endif
0xA8,0x12,0x01,0x00,
//0xC8,0x1A,0x00,0x06,
//0xC8,0x1C,0x00,0x05,
END_,END_,END_,END_
};
#if 0
unsigned char wieght_table[]=
{
#define AG 0x0
#define CG 0x40
#define CCG 0x64
0xA4,0x07,AG, AG,
0xA4,0x08,AG, AG,
0xA4,0x09,AG, AG,
0xA4,0x0A,AG, AG,
0xA4,0x0B,AG, AG,
0xA4,0x0C,AG, AG,
0xA4,0x0D,CG,CG,
0xA4,0x0E,CG, CG,
0xA4,0x0F,CG,CG,
0xA4,0x10,AG, AG,
0xA4,0x11,AG, AG,
0xA4,0x12,CG,CG,
0xA4,0x13,CCG,CCG,
0xA4,0x14,CG,CG,
0xA4,0x15,AG, AG,
0xA4,0x16,AG, AG,
0xA4,0x17,CG,CG,
0xA4,0x18,CG,CG,
0xA4,0x19,CG,CG,
0xA4,0x1A,AG, AG,
0xA4,0x1B,AG, AG,
0xA4,0x1C,AG, AG,
0xA4,0x1D,AG, AG,
0xA4,0x1E,AG, AG,
0xA4,0x1F,AG, 0x04,
END_,END_,END_ ,END_
};
int InitMT9V136(int width, int height, unsigned char *regs);
void Set_MT9V136_Exposure(int val);
void Set_MT9V136_Gain(int val);
int sensor_set_addr(int sensor_fd, unsigned int addr);
void Set_MT9V136_AutoExposure(int enable);
int Get_MT9V136_Brightness(void);
#endif
#endif
<file_sep>/c/homework/2nd_week/guess_number.c
/* ************************************************************************
* Filename: guess_number.c
* Description:
* Version: 1.0
* Created: 2015年07月20日 星期一 07時04分30秒 HKT
* Revision: none
* Compiler: gcc
* Author: 王秋伟
* Company:
* ************************************************************************/
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <math.h>
#define uint unsigned int
char mygetch()
{
struct termios oldt, newt;
char ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
void get_charnumber(int number,int n,char *buf)
{
char i;
int temp = 0;
int divisor;
temp = number%(int)pow(10,n);
if(temp < pow(10,n-1))
{
buf[n-1] = 0+48;
for(i=n-2;i>=0;i--)
{
divisor =(int)pow(10,i);
buf[i] = temp/divisor+48;
temp %=divisor;
}
}
else
{
for(i=n-1;i>=0;i--)
{
divisor =(int)pow(10,i);
buf[i] = temp/divisor+48;
temp %=divisor;
}
}
}
void guess_number()
{
char *buf,*src;
char ch,i;
int count=0,right=0;
int num, n;
printf("请输入挑战数字位数(1~10):");
scanf("%d",&n);
srand((uint)time(NULL));
do
{
num = rand();
}while(num < pow(10,n-1));
src = (char *)malloc(sizeof(char)*n);
get_charnumber(num,n,src);
printf(">>>请选择难度级别:\n");
printf("1--简单,10次机会\n");
printf("2--中度,7 次机会\n");
printf("3--困难,5 次机会\n");
do
{
ch = mygetch();
}while(ch != '1' && ch != '2' && ch != '3');
switch(ch)
{
case '1': count = 10; break;
case '2': count = 7; break;
case '3': count = 5; break;
}
buf = (char *)malloc(sizeof(char)*n);
printf("\n请输入一个%d位数字:",n);
scanf("%s",buf);
//printf("%s\n",buf);
//printf("%s\n",src);
do
{
right = 0;
for(i=0;i<n;i++)
{
if(buf[i] == src[i])
{
printf("第%d位数字正确\n",i+1);
right++;
}
else if(buf[i] < src[i])
{
printf("第%d位数字小于正确数字\n",i+1);
}
else
{
printf("第%d位数字大于正确数字\n",i+1);
}
}
if(right == n)
{
printf("你输入的数字全部正确,游戏成功\n");
goto leave;
}
count--;
if(count>0)
{
printf("\n你还有%d次机会,请再输入一个%d位数:",count,n);
scanf("%s",buf);
}
else
{
printf("\n在规定次数没能猜中数字,游戏失败\n");
}
}while(count>0);
leave:
getchar();
free(buf);
}
void show_rule()
{
printf("---------------------------\n");
printf(" 猜字游戏规则 \n");
printf("1、系统会产生一个整型随机数\n");
printf("2、选择合适难度级别进行游戏\n");
printf("3、输入你认为正确的整型数字\n");
printf("4、系统根据输入数据给你提示\n");
printf("5、规定的次数内猜对游戏成功\n");
printf("---------------------------\n");
}
int main()
{
char ch = 0;
while(1)
{
printf("\n>>>>>欢迎进行猜字游戏<<<<<\n");
printf("-----按1 进入游戏\n");
printf("-----按2 查看规则\n");
printf("-----按0 退出游戏\n");
ch = mygetch();
switch(ch)
{
case '1':
{
guess_number();
break;
}
case '2':
{
show_rule();
break;
}
case '0': goto exit;
}
}
exit:
return 0;
}
<file_sep>/c/practice/3rd_week/string/Makefile
mystring:main.c mystring.c
gcc -o mystring main.c mystring.c -lm
.PHONY:clean
clean:
rm -rf mystring
<file_sep>/work/test/cim_test-zmm220/conver.c
/*
##############################################################################
# Raw Image Player [ImPlayer] #
# Copyright 2000 <NAME> and <NAME> #
# Video Signal Processing Lab, Dept.EE, NTHU #
# Version 1.5 Created 2/1/2000 #
##############################################################################
# COPYRIGHT NOTICE #
# Copyright 2000 <NAME> and <NAME>, All Rights Reserved. #
# #
# [ImPlayer] may be used and modified free of charge by anyone so long as #
# this copyright notice and the comments above remain intact. By using this #
# code you agree to indemnify Yao-Jen Chang from any liability that might #
# arise from it's use. #
# #
# Comments, feedback, bug reports, improvements are encouraged. Please sent #
# them to <EMAIL>. #
##############################################################################
*/
/************************************************************************
*
* yuvrgb24.c, colour space conversion for tmndecode (H.263 decoder)
* Copyright (C) 1995, 1996 Telenor R&D, Norway
* <NAME> <<EMAIL>>
*
* Contacts:
* <NAME> <<EMAIL>>, or
* <NAME> <<EMAIL>>
*
* Telenor Research and Development http://www.nta.no/brukere/DVC/
* P.O.Box 83 tel.: +47 63 84 84 00
* N-2007 Kjeller, Norway fax.: +47 63 81 00 76
*
************************************************************************/
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any
* license fee or royalty on an "as is" basis. Telenor Research and
* Development disclaims any and all warranties, whether express,
* implied, or statuary, including any implied warranties or
* merchantability or of fitness for a particular purpose. In no
* event shall the copyright-holder be liable for any incidental,
* punitive, or consequential damages of any kind whatsoever arising
* from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs
* and user's customers, employees, agents, transferees, successors,
* and assigns.
*
* Telenor Research and Development does not represent or warrant that
* the programs furnished hereunder are free of infringement of any
* third-party patents.
*
* Commercial implementations of H.263, including shareware, are
* subject to royalty fees to patent holders. Many of these patents
* are general enough such that they are unavoidable regardless of
* implementation design.
* */
#include "futil.h"
static unsigned char* clp;
//modify by seven 2011-06-10
/*
static long int crv_tab[256];
static long int cbu_tab[256];
static long int cgu_tab[256];
static long int cgu_tab[256];
*/
static int crv_tab[256];
static int cbu_tab[256];
//static int cgu_tab[256];
static int cgu_tab[256];
static int cgv_tab[256];
//static long int tab_76309[256];
static int tab_76309[256];
static int bilevel_tab_76309[256];
BITMAPINFO bmi;
static void init_clp()
{
int i;
unsigned char clpbuf[1024]={0};
clp = clpbuf;
clp += 384;
for (i=-384; i<640; i++)
clp[i] = (i<0) ? 0 : ((i>255) ? 255 : i);
}
static void init_dither_tab()
{
long int crv,cbu,cgu,cgv;
int i;
crv = 104597; cbu = 132201; /* fra matrise i global.h */
cgu = 25675; cgv = 53279;
for (i = 0; i < 256; i++) {
crv_tab[i] = (i-128) * crv;
cbu_tab[i] = (i-128) * cbu;
cgu_tab[i] = (i-128) * cgu;
cgv_tab[i] = (i-128) * cgv;
tab_76309[i] = 76309*(i-16);
}
bilevel_tab_76309[0] = tab_76309[0];
for (i = 1; i < 256; i++) {
bilevel_tab_76309[i] = tab_76309[255];
}
}
void init_player()
{
init_dither_tab();
init_clp();
bmi.bmiHeader.biSize = (LONG)sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biCompression = 0l;
bmi.bmiHeader.biSizeImage = 0l;
bmi.bmiHeader.biXPelsPerMeter = 0l;
bmi.bmiHeader.biYPelsPerMeter = 0l;
bmi.bmiHeader.biBitCount = 24;
}
/**********************************************************************
*
* Name: ConvertYUVtoRGB
* Description: Converts YUV image to RGB (packed mode)
*
* Input: pointer to source luma, Cr, Cb, destination,
* image width and height
* Returns:
* Side effects:
*
* Date: 951208 Author: <EMAIL>
*
***********************************************************************/
void rgb5652rgb888(unsigned short* rgb565,unsigned int* rgb888,unsigned int framesize)
{
unsigned int i;
unsigned char r,g,b;
r=g=b=0;
for(i=0;i<framesize;i++)
{
r=((*((unsigned short*)rgb565 + i))>>11)&0x1f;
g=((*((unsigned short*)rgb565 + i))>>5)&0x3f;
b=(*((unsigned short*)rgb565 + i))&0x1f;
*((unsigned int*)rgb888 + i)=(r<<19)|(g<<10)|(b<<3);
}
}
//modify by seven 2011-06-02
int yuv422rgb565(unsigned char *yuv422buf,unsigned short *rgb565,int width,int height)
{
int i, j, k, u, v, u2g, u2b, v2g, v2r, y11, y12;
int width4 = width + (4 - (width%4))%4;
unsigned short R,G,B;
unsigned char *pucy,* pucu, * pucv;//, * pucraster0;
char crgbtmp;
pucy = yuv422buf;
pucu = yuv422buf + width * height;
pucv = yuv422buf + width * height * 3/2;
width = width/2;
height = height/2;
init_player(); //Luck~
// pucraster0 = rgb565 + (((width4/2) * (height-1)))*3;
k = width * (height-1); //Point to the last width_line of rgb565buf,why?
#if 0
for (i = 0; i<256;i++) {
if (i%12==0)
printf("\n");
printf("tab_=[%d]\t",tab_76309[i]);
}
for (i = 0; i<256;i++) {
if (i%12==0)
printf("\n");
printf("cgu=[%d]\t",cgu_tab[i]);
}
for (i = 0; i<256;i++) {
if (i%12==0)
printf("\n");
printf("cbu=[%d]\t",cbu_tab[i]);
}
for (i = 0; i<256;i++) {
if (i%12==0)
printf("\n");
printf("cgv=[%d]\t",cgv_tab[i]);
}
for (i = 0; i<256;i++) {
if (i%12==0)
printf("\n");
printf("crv=[%d]\t",crv_tab[i]);
}
#endif
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j+=4)
{
y11 = tab_76309[*pucy++];
y12 = tab_76309[*pucy++];
u = *pucu++;
v = *pucv++;
u2g = cgu_tab[u];
u2b = cbu_tab[u];
v2g = cgv_tab[v];
v2r = crv_tab[v];
//modify by seven 2011-06-12
/*
*pucraster0++ = clp[(y11 + u2b)>>16]; //B
*pucraster0++ = clp[(y11 - u2g - v2g)>>16]; //G
*pucraster0++ = clp[(y11 + v2r)>>16]; //R
*/
crgbtmp = clp[(y11 + v2r)>>16];
// R = ((crgbtmp >> 3)<<11) & 0xF800;
R = ((crgbtmp >> 3)) & 0x001F;
crgbtmp = clp[(y11 - u2g - v2g)>>16];
G = ((crgbtmp >> 2)<<5) & 0x07E0;
crgbtmp = clp[(y11 + u2b)>>16];
// B = ((crgbtmp >> 3)) & 0x001F;
B = ((crgbtmp >> 3)<<11) & 0xF800;
rgb565[k++] = (R | G | B);
//modify by seven 2011-06-12
/*
*pucraster0++ = clp[(y12 + u2b)>>16];
*pucraster0++ = clp[(y12 - u2g - v2g)>>16];
*pucraster0++ = clp[(y12 + v2r)>>16];
*/
crgbtmp = clp[(y12 + v2r)>>16];
// R = ((crgbtmp >> 3)<<11) & 0xF800;
R = ((crgbtmp >> 3)) & 0x001F;
crgbtmp = clp[(y12 - u2g - v2g)>>16];
G = ((crgbtmp >> 2)<<5) & 0x07E0;
crgbtmp = clp[(y12 + u2b)>>16];
// B = ((crgbtmp >> 3)) & 0x001F;
B = ((crgbtmp >> 3)<<11) & 0xF800;
rgb565[k++] = (R | G | B);
//Skip two pixels,because two pixels as a unit.
pucy+=2;
pucu++;
pucv++;
//modify by seven 2011-06-10 Let two ALU work at the same time
y11 = tab_76309[*pucy++];
y12 = tab_76309[*pucy++];
u = *pucu++;
v = *pucv++;
u2g = cgu_tab[u];
u2b = cbu_tab[u];
v2g = cgv_tab[v];
v2r = crv_tab[v];
//modify by seven 2011-06-12
/*
*pucraster0++ = clp[(y11 + u2b)>>16]; //R
*pucraster0++ = clp[(y11 - u2g - v2g)>>16]; //G
*pucraster0++ = clp[(y11 + v2r)>>16]; //B
*/
crgbtmp = clp[(y11 + v2r)>>16];
R = ((crgbtmp >> 3)) & 0x001F;
crgbtmp = clp[(y11 - u2g - v2g)>>16];
G = ((crgbtmp >> 2)<<5) & 0x07E0;
crgbtmp = clp[(y11 + u2b)>>16];
B = ((crgbtmp >> 3)<<11) & 0xF800;
rgb565[k++] = (R | G | B);
//modify by seven 2011-06-12
/*
*pucraster0++ = clp[(y12 + u2b)>>16];
*pucraster0++ = clp[(y12 - u2g - v2g)>>16];
*pucraster0++ = clp[(y12 + v2r)>>16];
*/
crgbtmp = clp[(y12 + v2r)>>16];
R = ((crgbtmp >> 3)) & 0x001F;
crgbtmp = clp[(y12 - u2g - v2g)>>16];
G = ((crgbtmp >> 2)<<5) & 0x07E0;
crgbtmp = clp[(y12 + u2b)>>16];
B = ((crgbtmp >> 3)<<11) & 0xF800;
rgb565[k++] = (R | G | B);
//Skip two pixels,because two pixels as a unit.
pucy+=2;
pucu++;
pucv++;
}
//modify by seven 2011-06-12
// pucraster0 = pucraster0 - width4*3; //Back two lines to start store new datas.
k=k - width*2;
pucy+=width4; //Skip one width_line Y,U,V
pucu+=width4/2;
pucv+=width4/2;
}
return 0;
}
//modify by seven 2011-06-02
// convert 24bit rgb888 to 16bit rgb565 color format
static inline unsigned short rgb888torgb565(unsigned char red,unsigned char green, unsigned char blue)
{
unsigned short B = (blue >> 3) & 0x001F;
unsigned short G = ((green >> 2) << 5) & 0x07E0;
unsigned short R = ((red >> 3) << 11) & 0xF800;
return (unsigned short) (R | G | B);
}
//modify by seven 2011-06-02
int rgb8882rgb565(unsigned short *rgb565,unsigned char *rgb888,unsigned int imagesize)
{
unsigned int i,j;
unsigned short R,G,B;
for(i = 0; i < imagesize; ++i)
{
j = i * 3;
R = ((rgb888[j++] >> 3)<<11) & 0xF800; //
G = ((rgb888[j++] >> 2)<<5) & 0x07E0; //
B = ((rgb888[j] >> 3)) & 0x001F;
rgb565[i] = R | G | B;
}
return 0;
}
//modify by seven 2011-06-02
int cut_rgb565(unsigned short *rgb565cut,unsigned short *rgb565src,unsigned int width,unsigned int imagesize)
{
int i=0,j=0,n=-1,length=0;
length = imagesize>>2;
unsigned short *p_input = rgb565src;
unsigned short *p_output = rgb565cut;
while(i < length)
{
if(0==(j%width))
p_input += width;
*p_output++ = *p_input++;
p_input++;
j+=2;
i++;
}
return 0;
}
//modify by seven 2011-0612
void rgb565_rotate90(
const unsigned short *input, int width_in, int height_in,
unsigned short *output, int *width_out, int *height_out)
{
unsigned short *pIn=(unsigned short *)input;
unsigned short *pOut=(unsigned short *)output;
int i,j;
for(i=0; i<height_in; i++)
{
for(j=0; j<width_in; j++)
{
*pOut = *pIn++;
pOut = output+height_in*j + i;
}
}
*width_out = height_in;
*height_out = width_in;
}
//modify by seven 2011-06-22
/*************************
*Translate the picture Right_Left.
* ***********************/
void rgb565_folio(unsigned short *rgb565,int width,int height)
{
printf("rgb565_folio\n");
unsigned short *p;
unsigned short *q;
p = rgb565;
q = p + width - 1;
unsigned short ustmp;
int x,y;
for(y=1; y <= height; ++y)
{
for(x=0; x < width; ++x)
{
ustmp = *q;
*q = *p;
*p = ustmp;
q--;
p++;
}
p++;
q=q+width;
}
}
<file_sep>/c/mkheader/app.c
/* ************************************************************************
* Filename: studer_score.c
* Description:
* Version: 1.0
* Created: 2015年07月20日 星期一 11時04分43秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <termios.h>
#if 1
void main()
{
int *p = malloc(100);
printf("This is a test!\n");
printf("sizeof(p)=%lu, sizeof(*p)=%lu\n", sizeof(p), sizeof(*p));
}
#elif 0
/************************************************************************/
/* 把所有的奇数放到所有偶数的前面 /
/************************************************************************/
void reverseString(char *p)
{
//char *ptr=p;
if( *p == '\0' || *(p + 1) == '\0' )
{
return ;
}
else
{
reverseString(p+1);
if(*p%2 == 0)
{
while( *(p + 1) != '\0' )
{
// if (*p%2 == 0)
{
*p = *(p + 1) ^ *p;
*(p + 1) = *p ^ *(p + 1);
*p = *p ^ *(p + 1);
}/*
*p = *(p+1) + *p;
*(p+1) = *p - *(p+1);
*p = *p - *(p+1);*/
p++;
}
}
//reverseString(p + 1);
}
return ;
}
int main(int argc, char *argv[])
{
//int i;
char str[] = "1234567";
reverseString(str);
//for(i = 0; i < 4; i++)
printf("%s",str);
return 0;
}
#elif 0
#define PASSWD_FILE ".passwd"
#define PASSWD_LEN 9
void firewall_get_passwd(char passwd[])
{
FILE *fp = NULL;
char str[PASSWD_LEN] = "";
int i, len;
fp = fopen(PASSWD_FILE, "rb");
if(fp == NULL) {
//文件不存在,则创建,然后退出
fp = fopen(PASSWD_FILE, "wb");
fclose(fp);
return;
}
len = fread(str, 1, PASSWD_LEN, fp); //fread 返回实际读的块数
len--;
str[len] = 0; // 去掉 \n
for(i=0; i<len; i++) {
str[i] -= 22;
}
strcpy(passwd, str);
fclose(fp);
}
void firewall_save_passwd(char passwd[])
{
FILE *fp = NULL;
int i, len;
len = strlen(passwd);
for(i=0; i<len; i++) {
passwd[i] += 22;
}
if(len >= PASSWD_LEN) {
len = PASSWD_LEN-1;
passwd[len] = 0;
}
strcat(passwd,"\n");
fp = fopen(PASSWD_FILE, "wb");
if(fp != NULL) {
fwrite(passwd, 1, len+1, fp);
fclose(fp);
}
}
char getch()
{
struct termios oldt, newt;
char ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
void get_passwd(char *pwd, int len)
{
char ch;
char i =0;
while(i<len)
{
ch = getch();
if(ch == 10){
pwd[i] = 0;
break;
}
pwd[i++] = ch;
putchar('*');
}
}
void main()
{
#if 0
char passwd[PASSWD_LEN] = "";
get_passwd(passwd, PASSWD_LEN);
printf("\n-1- %s\n",passwd);
firewall_save_passwd(passwd);
bzero(passwd, PASSWD_LEN);
firewall_get_passwd(passwd);
printf("-2- %s\n",passwd);
#elif 1
char str[50] = "";
char ip[16] = "10.221.2.221";
char mac[18] = "00:0c:67:fa:c6:1d";
sprintf(str,"%12s\n%-18s\n", ip, mac);
printf("%s", str);
// char ch = getch();
// printf("%d\n",ch);
// putchar('*');
// printf("entry:");
// ch = getch();
//gets(str);
#endif
}
#elif 0
void main(int argc)
{
int ii = 1555444;
char buf[20];
sprintf(buf,"%d",ii);
printf("%s\n",buf);
printf("argc = %d\n",argc);
}
#elif 0
char *read_firewall_rule_file(const char *file_name)
{
FILE *fp = NULL;
char *buf = NULL;
int file_length = 0;
fp = fopen(file_name, "rb");
if(fp == NULL){
printf("Cannot open the flie!\n");
return;
}
fseek(fp,0,SEEK_END);
file_length = ftell(fp);
buf = (char *)malloc(file_length); //
if(buf == NULL){
printf("malloc() cannot apply for memory!\n");
goto out;
}
rewind(fp); //
fread(buf,file_length,1,fp);
out:
fclose(fp);
return buf;
}
void main()
{
char *pbuf = NULL;
char *p = NULL;
pbuf = read_firewall_rule_file("mac_rule");
printf("buf >>\n%s<<\n", pbuf);
p = strtok(pbuf,"\n");
while(p != NULL){
printf("%s $$$len=%d\n",p, strlen(p));
p = strtok(NULL,"\n");
}
free(pbuf);
}
#elif 0
void main()
{
FILE *fp = NULL;
char rule[32] = "";
int i = 0;
fp = fopen("mac_rule", "ab");
for(i=0;i<3;i++)
{
fgets(rule, 32, stdin);
rule[strlen(rule) - 1] = 0;
strcat(rule,"\n");
fwrite(rule,1, strlen(rule), fp);
}
}
#elif 0
void main()
{
printf("\033[35;4mhello\033[47;34m world\033[0m\n");
}
#elif 0
char *read_src_file(int *file_length, char *lrc_src)
{
FILE *fp = NULL;
char *buf = NULL;
//unsigned long int file_length = 0;
fp = fopen(lrc_src,"rb");//以只读方式打开一个二进制文件
if(fp == NULL)
{
printf("Cannot open the flie!\n");
return;
}
fseek(fp,0,SEEK_END);
*file_length = ftell(fp); //获取文件的大小
buf = (char *)malloc(*file_length); //
rewind(fp); //
fread(buf,*file_length,1,fp);
fclose(fp);
return buf;
}
int src_segment(char *psrc, char *pbuf[], char *str)
{
int i = 0;
pbuf[0] = strtok(psrc, str);
while(pbuf[i++] != NULL)
{
pbuf[i] = strtok(NULL, str);
}
//printf("i=%d\n",i);
return (i-1);
}
int check_lines(int file_length, char *lrc_src)
{
int lines = 0;
int i = 0;
char *p = NULL;
p = lrc_src;
#if 1
for(i = 0;i < file_length;i++)
{
if(p[i]=='\n') lines++;
}
#elif 0 //这种方法不行,因为strchr函数和strstr函数遇到 '\0' 就返回
while(p != NULL)
{
p = strchr(p,'\n');
lines++;
}
#endif
return lines;
}
void main()
{
FILE *fp =NULL;
char *buf = NULL, *pbuf[100] = {NULL};
int file_length = 0, i = 0, n = 0;
int lines = 0;
system("ls ./lrc2/music | grep .mp3 >./lrc2/.msgbuf");
fp = fopen("lrc2/.msgbuf","rb");
if(fp == NULL)
{
printf("Cannot open the flie!\n");
return;
}
buf = read_src_file(&file_length,"lrc2/.msgbuf");
lines = check_lines(file_length,buf);
printf("%d\n",lines);
n = src_segment(buf, pbuf, "\r\n");
printf("n = %d\n",n);
for(i=0;i<n-1;i++)
{
printf("%s\n",pbuf[i]);
}
}
#elif 0
int get_chrnumber(char *pbuf, int len)
{
int i = 0,count = 0;
for(i=0;i<len;i++)
{
if(pbuf[i] > 0 && pbuf[i] <127) count++;
}
return count;
}
int main()
{
char str1[100]=" dd笑gh声 喜!!?%欢你 更 迷人g";
int len = strlen(str1);
int count = 0;
system("dir >./test.txt");
count = get_chrnumber(str1,len);
printf("len=%d\n",len);
printf("%d\n",count);
return 0;
}
#elif 0
int main()
{
char str1[20]="hello \r\nr $#$ world";
char ch='\n';
char str2[20]="$#$";
char *result;
result=strchr(str1,ch);
printf("%s\n",result);
printf("%d\n",result-str1);
result=strstr(str1,str2);
printf("%s\n",result);
printf("%d\n",result-str1);
return 0;
}
#elif 0
void main()
{
char buf[1000] = "这是个测试";
int count = 0;
FILE *fp = NULL;
fp = fopen("love.lrc","rb");
printf("%s\n",buf);
if(fp = NULL)
{
// puts("error\n");
return;
}
while(1)
{
fgets(buf,100,fp);
if(feof(fp) != 0)
break;
printf("%s\n",buf);
count++;
}
printf("count=%d\n",count);
free(fp);
}
#elif 0
void main()
{
char *p = "hello";
char *q = "world";
char **pp;
pp = (char **)malloc(20);
pp[0]= p;
pp[1] = q;
printf("%s %s\n",pp[0],pp[1]);
}
#elif 0
int main()
{
struct A
{
char e;
short f;
};
struct B
{
int a;
char b;
struct A c;
char d;
}cc;
printf("%u %u\n",&cc.c.e,&cc.d);
}
#elif 0
struct A
{
int a;
double b;
float c;
};
struct
{
char e[2];
int f;
double g;
short h;
struct A i;
}B;
void main()
{
printf("%d\n",sizeof(B));
}
#elif 0
typedef struct stu
{
int num;
char name[20];
float score;
}STU;
void main()
{
STU stu[3];
int i=0;
float temp = 0;
float ave = 0.0f;
for(i=0;i<3;i++)
{
printf("请输入%d位学生的学号、姓名、成绩:\n",i+1);
scanf("%d %s %f",&stu[i].num,stu[i].name,&stu[i].score);
}
for(i=0;i<3;i++)
{
ave +=stu[i].score;
//printf("num=%d, name=%s, score=%.1f\n",stu[i].num,stu[i].name,stu[i].score);
}
ave /=3;
printf("平均成绩%.1f\n",ave);
temp = stu[0].score>stu[1].score?(stu[0].score>stu[2].score?stu[0].score:stu[2].score)
: (stu[1].score>stu[2].score?stu[1].score:stu[2].score);
printf("最大成绩为%.1f\n",temp);
}
#elif 0
void main()
{
char buf[128] = "abcfff#degghgf#ghi";
char buf1[123] = "";
char m[10] = "",s[10] = "";
int aminute=0,second=0;
sscanf(buf,"%*[^#]#%[^#]",buf1); //当buf第一个字符是'#'时,这样取会出错
printf("buf1=%s\n",buf1);
sscanf("thj[i:简单爱]","%*[^:]%*1s%[^]]",buf1);
printf("buf1=%s\n",buf1);
//sscanf("[02:06.85]","%*[[]%2d%*1s%2d",&aminute,&second);
sscanf("[02:06.85]","[%2d:%2d",&aminute,&second);
printf("aminute=%d,second=%d\n",aminute,second);
sscanf("[12:16.85]","%*[[]%2d%*[:]%2d",&aminute,&second);
printf("aminute=%d,second=%d\n",aminute,second);
sscanf("[02:06.85]","%*[[]%2s%*1s%2s",m,s);
printf("m=%s,s=%s\n",m,s);
}
#elif 0
void main()
{
char buf[128] = "12345678";
int a=0,b=0;
sscanf(buf,"%*2d%2d%*2d%2d",&a,&b);
printf("a=%d,b=%d\n",a,b);
}
#elif 0
void main()
{
char dst[40] = "szsunplusedu.com";
char *p = NULL;
p = dst;
#elif 0
while(1)
{
p = strchr(p, 'u');
if(p != NULL)
{
*p = '#';
}
else
{
break;
}
}
printf("%s\n",dst);
}
#elif 0
#define MIN(a,b) ((a)<(b)?(a):(b))
void main()
{
int a[3]={2,6,8};
int b = 3;
int *p = a;
printf("%d\n",MIN(*p++,b));
}
#elif 0
int main(int argc, char *argv[])
{
float a[5][3]={{80,75,56},{59,65,71},{59,63,70},{85,75,90},{76,77,45}};
int i,j ,person_low[5]={0};
float s=0,lesson_aver[5]={0};
for(j=0;j<5;j++)
{
for(i=0;i<3;i++)
{
s += a[j][i];
if(a[j][i]<60)
{
person_low[j]++;
}
}
lesson_aver[j] = s/3;
s = 0;
}
for(i=0;i<5;i++)
{
printf("第%d个人的各科平均成绩为:%.2f,不及格有%d科\n",i,lesson_aver[i],person_low[i]);
}
return 0;
}
#elif 0
typedef struct game
{
//struct game *head;
char *topic;
char *key;
struct game *next;
}GAME;
int main(int argc, char *argv[])
{
GAME one,two,*p;
char ch[100]={0};
one.topic = "这是个测试";
one.key = "12";
two.topic = "这依然是测试";
two.key = "13";
printf("%d\n",sizeof("哈共和斤斤计较哈哈"));
one.next = &two;
two.next = &one;
p = &one;
do
{
sleep(2);
printf("%s %s\n",p->topic,p->key);
p = p->next;
}while(p != NULL);
printf("%s %s\n",one.topic,one.key);
return 0;
}
#elif 0
void main()
{
int a = 0x01020304;
int *p = NULL;
int *cp= NULL;
char ch = 97;
cp =&ch;
cp = (char *)cp;//cp 还是指向int型,有cp定义类型决定
p = &a;
printf("%d\n",*(char *)cp);
printf("0x%x\n",*(short int *)cp);
// printf("0x%x\n",*((short int *)((char *)p+1)));
}
#elif 0
int sum(int n)
{
int temp = 0;
int i;
if(n==1)
{
return 1;
}
else if(n>1)
{
for(i=1;i<=n;i++)
{
temp +=i;
}
// temp +=sum(n-1);
// return temp;
return temp+sum(n-1);
}
//return temp;
}
void main()
{
int n = 0;
n= sum(6);
printf("%d\n",n);
}
#elif 0
void main()
{
int num[5] = { 1,2,3,4,5};
//int *p[5] = {&num[0],&num[1],&num[2],&num[3],&num[4]};
int *p[5] = { &num[0]};
//printf("%d\n",*p[2]);
printf("%d\n",*(p[0]+2));
char *str[100] = {"hehe1","hehe2","hehe3","hehe4"};
char i;
i = 0;
while(str[i] != NULL)
{
printf("%s\t",str[i]);
i++;
}
putchar('\n');
}
#elif 0
int f(char *s)
{
char *p=s;
while(*p!='\0')
{
p++;
}
return(p-s);
}
int bic(int d, int m)
{
char temp_1[32],temp_2[32];
int i=0,j=0;
memset(temp_1,'\0',sizeof(temp_1));
while(d!=0)
{
temp_1[i++]=d%2;
//printf("%c ",temp_1[i-1]+'0');
d=d/2;
}
memset(temp_2,'\0',sizeof(temp_2));
i=0;
while(m!=0)
{
temp_2[i++]=m%2;
m=m/2;
}
for(i=0;i<32;i++)
{
if(temp_2[i]==1)
{
temp_1[i]=0;
}
}
d=0;
for(i=0;i<32;i++)
{
d+= temp_1[i]*pow(2,i);
}
return d;
}
main()
{
int t;
t = bic(30,5);
printf("%d\n", t);
printf("%d\n",f("FUJIAN"));
}
#elif 0
int main()
{
char buf[]="I am a good programer, am i? hello, world.";
// ?i am ,programer good a am i
char * p[50],ch,*str;
int i=0,j=0,word_num=0;
printf("***%s***\n",buf);
str=(char *)malloc(strlen(buf)+1);
p[i]=strtok(buf," ");//按空格切割字符串
while(p[i]!=NULL)
{
i++;
p[i]=strtok(NULL," ");
}
word_num=i;
for(i=0; i< word_num; i++)//把所有单词中有标点符号的处理完
{
if(ispunct( *(p[i]+strlen(p[i])-1)) != 0) //检查参数是否为标点符号或特殊符号,是,返回TRUE
{
ch=*(p[i]+strlen(p[i])-1);
for(j=strlen(p[i]);j>1 ;j--)
{
*(p[i]+j-1)=*(p[i]+j-2);
}
*p[i]=ch;
}
}
i=word_num;
strcpy(str,p[i-1]);
for(i=word_num-2; i>=0 ;i--)//从后向前把所有字符串追加进来,以空格分开
{
strcat(str," ");
strcat(str,p[i]);
}
strcpy(buf,str);
printf("***%s***\n",buf);
free(str);
return 0;
}
#elif 0
int lenght(char *p)
{
int len=0;
len = strlen(p);
return len;
}
void main()
{
int aa = 0;
long bb = 0;
scanf("%2d%ld",&aa,&bb);
printf("add = %ld\n", aa+bb);
char a[5]={'a','b','c','d','e'};
//char a[]="abcde";
printf("%d\n",lenght(a));
}
#endif
<file_sep>/network/2nd_day/tftp_client.c
/******************************************************************************
文 件 名 : tftp_client.c
版 本 号 :
作 者 :
生成日期 : 2015年9月1日
最近修改 :
功能描述 : TFTP 客户端
******************************************************************************/
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
int main(int argc, char *argv[])
{
FILE *fp = NULL;
char *p = NULL;
char file_name[128] = "a.txt";
char server_ip[16] = "10.221.2.12";
char cmd[128] = "", msg[1024] = "";
int sockfd = 0, cmd_len = 0, msg_len = 0, ask = 0;
unsigned short port = 69; // TFTP服务器的固定端口
if(argc > 1)
{
strcpy(server_ip, argv[1]);
}
if(argc > 2)
{
bzero(file_name, sizeof(file_name));
strcpy(file_name, argv[2]);
}
//创建一个套接字
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
//配置服务器的地址
struct sockaddr_in server_addr;
socklen_t server_len = sizeof(server_addr);
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);//服务器的端口
inet_pton(AF_INET, server_ip ,&server_addr.sin_addr.s_addr);//服务器的IP
//printf("file_name = %s\n",file_name);
cmd_len = sprintf(cmd, "%c%c%s%c%s%c", 0, 1, file_name, 0, "octet", 0);
sendto(sockfd, cmd, cmd_len, 0,\
(struct sockaddr *)&server_addr, sizeof(server_addr));
p = msg; //
fp = fopen(file_name, "wb");
while(1)
{
bzero(msg, sizeof(msg));
//bzero(&server_addr, sizeof(server_addr));
msg_len = recvfrom(sockfd, msg, sizeof(msg), 0, (struct sockaddr *)&server_addr, &server_len);
if(*(p+1) == 3) //数据确认
{
//printf("ask_no = %d&&&&&&&&&\n",*(p+3));
if(ask != *(p+3))
{
ask = *(p+3);
//把接收的数据写入文件
fwrite((p+4), msg_len - 4, 1, fp);
}
if(msg_len < 516)
{
fclose(fp);
break;
}
*(p+1) = 4; //数据确认操作码
//发送确认信号
sendto(sockfd, msg, 4, 0,\
(struct sockaddr *)&server_addr, sizeof(server_addr));
}
}
//fclose(fp);
close(sockfd);
return 0;
}
<file_sep>/sys_program/player/src/inc/gtk_callback.h
#ifndef __GTK_CALLBACK_H__
#define __GTK_CALLBACK_H__
extern gboolean motion_event_callback(GtkWidget *widget, GdkEventMotion *event, gpointer data);
extern void search_entry_callback(GtkWidget *widget, gpointer entry);
extern void keys_board_callback(GtkWidget *widget, GdkEventKey *event, gpointer data);
extern void playmode_button_callback(GtkButton *button, gpointer data);
extern void musiclist_buttons_callback(GtkButton *button, gpointer data);
extern void music_buttons_callback(GtkButton *button, gpointer data);
extern gboolean callback_list_release(GtkWidget *widget, GdkEventButton *event, gpointer data);
#endif<file_sep>/network/route/src/inc/firewall_file.h
/******************************************************************************
文 件 名 : firewall_file.h
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月15日
最近修改 :
功能描述 : firewall_file.c 的头文件
******************************************************************************/
#ifndef __FIREWALL_FILE_H__
#define __FIREWALL_FILE_H__
#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */
/*----------------------------------------------*
* 内部函数原型说明 *
*----------------------------------------------*/
static char *firewall_read_rule_file(const char *file_name);
static char getch();
/*----------------------------------------------*
* 外部函数原型说明 *
*----------------------------------------------*/
extern void firewall_save_all_rules(TYPE_Route *rt);
extern void filrewall_save_rule(const char *rule);
extern void firewall_config(TYPE_Route *rt);
extern void firewall_get_passwd(TYPE_Route *rt);
extern void firewall_save_passwd(char passwd[]);
extern void get_passwd(char passwd[], int max_len);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
#endif /* __FIREWALL_FILE_H__ */
<file_sep>/c/homework/3rd_week/operation/operation.c
/* ************************************************************************
* Filename: operation.c
* Description:
* Version: 1.0
* Created: 2015年07月27日 星期一 11時04分01秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <string.h>
#include "fun.h"
char *cmp[] = { "add", "sub", "mul", "div"};
int (*fp[])(int a,int b) = { add, sub, mul, div};
void main()
{
int i = 0;
int a = 0,b = 0, res = 0;
char buf[10] = {0};
printf("请输入计算指令,例如:\n");
printf("add 15 25 //计算15+25的值,并返回结果\n");
printf("sub 15 25 //计算15-25的值,并返回结果\n");
printf("mul 15 25 //计算15*25的值,并返回结果\n");
printf("div 15 25 //计算15/25的值,并返回结果\n");
scanf("%s %d %d",buf,&a,&b);
while(1)
{
for(i=0;i<sizeof(fp)/sizeof(fp[0]);i++)
{
if(strcmp(buf,cmp[i])==0)
{
res = fp[i](a,b);
printf("计算结果为:%d\n",res);
}
}
}
}
<file_sep>/c/lrc/process_lrc.h
/* ************************************************************************
* Filename: process_lrc.h
* Description:
* Version: 1.0
* Created: 2015年07月31日 星期五 09時17分38秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __PROCESS_LRC_H__
#define __PROCESS_LRC_H__
int src_segment(char *lrc_src, char *plines[], char *str);
int line_segment(char *pline, char *pbuf[], char *str);
LRC *build_link(char *lrc_pline[], char *pheader[], int lines);
void show_lyric(LRC *pnode, int longest);
int get_showoffset(char *pbuf,int longest);
int get_maxtime(LRC *head);
int get_timelag(LRC *head);
#endif
<file_sep>/network/5th_day/bk_filch.c
/* ************************************************************************
* Filename: rarp.c
* Description:
* Version: 1.0
* Created: 2015年09月09日 11时23分33秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netpacket/packet.h>
#include <net/if.h>
#include <netinet/ether.h>
#include <netinet/in.h>
#include "gb2312_ucs2.h"
void get_feiQ_msg(unsigned char const *src)
{
char *p = NULL;
int i = 0, colon = 0;
unsigned char msg[1024] = "";
unsigned char buf[1024] = "";
unsigned short udp_len = 0;
unsigned char utf8[1024] = "";
udp_len = (src[4]*256+src[5]);
printf("udp_len=%d\n",udp_len);
memcpy(buf,src+8,udp_len-8);
for(i=0;i<udp_len-8;i++)
{
printf("%c",buf[i]);
}
printf("\n");
p = buf;
for(i=0;i<udp_len-8;i++)
{
if(buf[i] == ':') colon++;
if(colon == 5) break;
p++;
}
if(colon == 5)
{
memcpy(msg,p+1,udp_len-8-(i+1));
gb2312_to_utf8(msg, utf8);
printf("msg=%s\n",utf8);
}
//udp_len = ntohs((unsigned short *)(src+4));
}
unsigned short get_src_port(unsigned char const *src)
{
//unsigned char port[4] = "";
//sprintf(port,"%d%d",src[0],src[1]);
printf("%d %d ****\n",src[2],src[3]);
return (src[0]*256+src[1]);
}
unsigned char get_IP_type(unsigned char const *src)
{
unsigned char type[1] = "";
//提取数据包类型
sprintf(type,"%c",src[9]);
if(type[0] == 6)
printf("TCP 数据包\n");
else if(type[0] == 17)
printf("UDP 数据包\n");
//printf("IP_TYPE:%d\n", type[0]);
return type[0];
}
unsigned char get_ip_headlen(unsigned char const *src)
{
unsigned char temp = 0;
temp = src[0] & 0x0f;
printf("headlen=%d\n",temp);
return temp;
}
void get_ip(unsigned char const *src)
{
unsigned char dst_ip[16] = "";
unsigned char src_ip[16] = "";
//提取目的ip
sprintf(dst_ip,"%d.%d.%d.%d",\
src[16],src[17],src[18],src[19]);
//提取源ip
sprintf(src_ip,"%d.%d.%d.%d",\
src[12],src[13],src[14],src[15]);
printf("IP:%s >> %s\n", src_ip, dst_ip);
}
void get_ARP_ip(unsigned char const *src)
{
unsigned char dst_ip[16] = "";
unsigned char src_ip[16] = "";
//提取目的ip
sprintf(dst_ip,"%d.%d.%d.%d",\
src[24],src[25],src[26],src[27]);
//提取源ip
sprintf(src_ip,"%d.%d.%d.%d",\
src[14],src[15],src[16],src[17]);
printf("ARP_IP:%s >> %s\n", src_ip, dst_ip);
}
void get_mac(unsigned char const *src)
{
unsigned char dst_mac[18] = "";
unsigned char src_mac[18] = "";
//提取目的mac
sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
src[0],src[1],src[2],src[3],src[4],src[5]);
//提取源mac
sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
src[6],src[7],src[8],src[9],src[10],src[11]);
printf("MAC:%s >> %s\n", src_mac, dst_mac);
}
unsigned short get_type(unsigned char const *src, unsigned char *type)
{
//提取数据包类型
sprintf(type,"%02x%02x",src[12],src[13]);
printf("TYPE:%s\n", type);
//printf("TYPE:%c%c%c%c\n", type[0],type[1],type[2],type[3]);
}
int main(int argc, char *argv[])
{
unsigned char type[4] = "";
unsigned char recv[2048] = "";
unsigned char ip_type = 0;
unsigned short dport = 0;
//创建原始套接字
int sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
//组arp的应答包
unsigned char send_msg[1024] = {
//-----组MAC----14----
0x74,0x27,0xea,0xb3,0x66,0xca,//dst_mac: 柱琦 XP mac
//0x00,0x0c,0x29,0xe4,0xd3,0xd6,//src_mac: me VM mac
0x00,0x0c,0x29,0x98,0xcc,0x6c,//IP = .62 mac
0x08,0x06, //类型: 0x0806 ARP协议
//-----组ARP----28----
0x00,0x01,0x08,0x00, //硬件类型1(以太网地址),协议类型0x0800(IP)
0x06,0x04,0x00,0x02, //硬件、协议的地址长度分别为6和4,ARP应答
//0x00,0x00,0x00,0x00,0x00,0x00,//发送端的mac
//0x00,0x0c,0x29,0xe4,0xd3,0xd6,//发送端的mac,把10.221.2.11的mac伪装成自己的
0x00,0x0c,0x29,0x98,0xcc,0x6c,//
10, 221, 2, 12, //发送端的IP
0x74,0x27,0xea,0xb3,0x66,0xca,//目的mac
10, 221, 2, 6, //目的IP
};
//数据初始化
struct sockaddr_ll sll;
struct ifreq ethreq;
strncpy(ethreq.ifr_name,"eth0", IFNAMSIZ);//指定网卡名称
//将网络接口赋值给原始套接字地址结构
ioctl(sockfd, SIOCGIFINDEX, (char *)ðreq);
bzero(&sll, sizeof(sll));
sll.sll_ifindex = ethreq.ifr_ifindex;
while(1)
{
sendto(sockfd, send_msg, 42, 0, (struct sockaddr *)&sll, sizeof(sll));
recvfrom(sockfd, recv, sizeof(recv), 0, NULL, NULL);
get_type(recv, type);
if(strcmp(type, "0800") == 0)//ip
{
get_ip(recv+14);
get_ip_headlen(recv+14);
ip_type = get_IP_type(recv+14);
if(ip_type == 17) //UDP
{
dport = get_src_port(recv+14+20);
if(dport == 2425)
{
printf("#######$$$$$$$$$\n");
get_feiQ_msg(recv+14+20);
}
}
}
usleep(1000);
}
return 0;
}
<file_sep>/sys_program/2nd_day/am/execle.c
/* ************************************************************************
* Filename: excele.c
* Description:
* Version: 1.0
* Created: 2015年08月14日 12时03分24秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char *env[] = {"USER=ME","COMGSI = sunplusapp.com"};
execle("./getenv","getenv",NULL,env);
return 0;
}
<file_sep>/sys_program/4th_day/r_shm.c
/* ************************************************************************
* Filename: r_shm.c
* Description:
* Version: 1.0
* Created: 2015年08月18日 17时27分33秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdbool.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main(int argc, char *argv[])
{
int i = 20000;
key_t key;
char *buf;
key = ftok("./",66);
while(i--) {
int id = shmget(key,2048,IPC_CREAT | 0666);
//printf("id = %d\n",id);
buf = (char *)shmat(id,NULL,0);
if((long)buf < 0) {
printf("shmat failed: %s", strerror(errno));
break;
}
else
printf("i: %08d, buf = %s\n",i, buf);
}
shmdt(buf);//将共享内存和当前进程分离
return 0;
}
<file_sep>/network/route/go.sh
#!/bin/bash
clear
echo "compiling the route project..."
rm route
make
if [ -e route ]
then
echo "running..."
sudo ./route
fi
<file_sep>/sys_program/6th_day/pdt_csm.c
/* ************************************************************************
* Filename: sem_syn.c
* Description:
* Version: 1.0
* Created: 2015年08月20日 14时38分35秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t semp, semc;
int totol_num = 3;
void *producter(void *arg)
{
while(1)
{
sem_wait(&semp);
sleep(1);
totol_num++;
printf("push into >>totol_num = %d\n",totol_num);
sem_post(&semc);
}
}
void *consumer(void *arg)
{
while(1)
{
sem_wait(&semc);
sleep(2);
totol_num--;
printf("pop out >>totol_num = %d\n",totol_num);
sem_post(&semp);
}
}
int main(int argc, char *argv[])
{
pthread_t pth1,pth2;
sem_init(&semp,0,7);
sem_init(&semc,0,3);
pthread_create(&pth1,NULL,producter,NULL);
pthread_create(&pth2,NULL,consumer,NULL);
pthread_join(pth1,NULL);
pthread_join(pth2,NULL);
sem_destroy(&semp);
sem_destroy(&semc);
return 0;
}
<file_sep>/work/test/cim_test-zmm220/gc0308.c
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include "gc0308.h"
#define IOCTL_READ_REG 0
#define IOCTL_WRITE_REG 1
#define IOCTL_READ_EEPROM 2
#define IOCTL_WRITE_EEPROM 3
#define IOCTL_SET_ADDR 4
#define IOCTL_SET_CLK 5
#define GC0308_CHIPID 0x00
/*exp reg */
#define GC0308_EXP_H 0x03
#define GC0308_EXP_L 0x04
/* windows regs*/
#define GC0308_ROW_H 0x05
#define GC0308_ROW_L 0x06
#define GC0308_COL_H 0x08
#define GC0308_COL_L 0x07
#define GC0308_WINH_H 0x09
#define GC0308_WINH_L 0x0A
#define GC0308_WINW_H 0x0B
#define GC0308_WINW_L 0x0C
#define GC0308_CISCTL_MODE2 0x0E
#define GC0308_CISCTL_MODE1 0x0F
#define GC0308_SCTRA 0x28
#define GC0308ID 0x42
//static pbusparam bus;
static int sensor_0308_fd = -1;
static int m_sensitivity;
static int m_sensor_opt;
static int m_image_reverse;
static int m_image_symmetry=1;
static int exposH;
#define SIZE 12
static struct IO_MSG {
unsigned int write_size;
unsigned int read_size;
unsigned char reg_buf[SIZE];
} reg_msg ;
#define SENC0308 "/dev/sensor-gc0308"
int sensor_open_0308(void)
{
sensor_0308_fd=open(SENC0308,O_RDWR);
if(sensor_0308_fd < 0)
{
perror("sensor_open()");
return -1;
}
printf("%s open ok. \n", SENC0308);
return sensor_0308_fd;
}
int sensor_close_0308()
{
close(sensor_0308_fd);
}
static int sensor_set_addr(unsigned int addr)
{
if (ioctl(sensor_0308_fd, IOCTL_SET_ADDR, (unsigned int)&addr) < 0) {
printf("ioctl: set gc0308 address failed!addr=%x\n",addr);
return -1;
}
return 0;
}
static unsigned char read_reg(int sensor_fd, unsigned char reg)
{
unsigned char read_val;
reg_msg.write_size=1;
reg_msg.read_size=1;
reg_msg.reg_buf[0]=reg;
if (ioctl(sensor_fd, IOCTL_READ_REG, (void *)®_msg) < 0) {
printf("warning: read_reg failed!\n");
return 0;
}
read_val = reg_msg.reg_buf[0];
return read_val;
}
static int write_reg(int sensor_fd, unsigned char reg, unsigned char val)
{
reg_msg.write_size=2;
reg_msg.read_size=0;
reg_msg.reg_buf[0]=reg;
reg_msg.reg_buf[1]=val;
if (ioctl(sensor_fd, IOCTL_WRITE_REG, (unsigned long *)®_msg) < 0) {
printf("warning: write_reg failed!\n");
return 0;
}
return 1;
}
int gc0308_set_clk(int sensor_fd,unsigned int clk)
{
if(sensor_fd==-1)
{
printf("%s m_sensor_fd is -1\n", __FUNCTION__);
return -1;
}
if (ioctl(sensor_fd, IOCTL_SET_CLK, (unsigned int)&clk) < 0)
{
printf("%s ioctl: set clock failed!\n", __FUNCTION__);
return -1;
}
return 0;
}
static void set_EXPOS_GC308(int exposH)
{
//int value=read_reg(m_sensor_fd, 0xd0);
//write_reg(m_sensor_fd, 0xd0, value | 0x20);
write_reg(sensor_0308_fd, GC0308_EXP_H, (exposH>>8)&0xff);
write_reg(sensor_0308_fd, GC0308_EXP_L, exposH&0xff);
}
static void set_BackgroundRGB_GC308(int RBlackLevel, int BBlackLevel, int GBlackLevel, int RBlackFactor, int GBlackFactor, int BBlackFactor)
{
write_reg(sensor_0308_fd, 0x85, RBlackLevel);
write_reg(sensor_0308_fd, 0x86, BBlackLevel);
write_reg(sensor_0308_fd, 0x87, GBlackLevel);
write_reg(sensor_0308_fd, 0x88, RBlackFactor);
write_reg(sensor_0308_fd, 0x89, GBlackFactor);
write_reg(sensor_0308_fd, 0x8a, BBlackFactor);
}
static void set_Contrast_GC308(int contrast)
{
write_reg(sensor_0308_fd, 0xb3, contrast);
write_reg(sensor_0308_fd, 0xb4, 0x80);
}
static void set_RGBGain_GCC308(int GGain, int G1Gain, int RGain, int BGain, int G2Gain)
{
if(GGain > 0)
write_reg(sensor_0308_fd, 0x50, GGain);//Global_Gain
if(G1Gain > 0)
write_reg(sensor_0308_fd, 0x53, G1Gain);//Gain_G1
if(RGain > 0)
write_reg(sensor_0308_fd, 0x54, RGain);//Gain_R
if(BGain > 0)
write_reg(sensor_0308_fd, 0x55, BGain);//Gain_B
if(G2Gain > 0)
write_reg(sensor_0308_fd, 0x56, G2Gain);//Gain_G2
}
static void select_page_gc308(int page)
{
write_reg(sensor_0308_fd, 0xFE, page);
}
static void set_window_GC308(int l, int t, int w, int h)
{
/* Set the row start address */
write_reg(sensor_0308_fd,GC0308_ROW_H, (t >> 8) & 0xff);
write_reg(sensor_0308_fd,GC0308_ROW_L, t & 0xff);
/* Set the column start address */
write_reg(sensor_0308_fd,GC0308_COL_H, (l >> 8) & 0xff);
write_reg(sensor_0308_fd,GC0308_COL_L, l & 0xff);
/* Set the image window width*/
write_reg(sensor_0308_fd,GC0308_WINW_H, ((w+8)>> 8) & 0xff);
write_reg(sensor_0308_fd,GC0308_WINW_L, (w+8) & 0xff);
/* Set the image window height*/
write_reg(sensor_0308_fd,GC0308_WINH_H, ((h+8) >> 8) & 0xff);
write_reg(sensor_0308_fd,GC0308_WINH_L, (h+8) & 0xff);
}
/* VCLK = MCLK/div */
static void set_sensor_clock_gc308(int div)
{
/* ABLC enable */
int FrequencyNumber=div&0x0F;
int FrequencyDiv=(div>>4)&0x0F;
switch (FrequencyNumber+FrequencyDiv) {
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
write_reg(sensor_0308_fd,GC0308_SCTRA, (FrequencyNumber+FrequencyDiv-1)<<4 | FrequencyDiv); // DCF=MCLK
break;
default:
write_reg(sensor_0308_fd,GC0308_SCTRA, 0x00); // DCF=MCLK
break;
}
}
static void set_vertical_GC308(int vertical)
{
int value=0;
value=read_reg(sensor_0308_fd, 0x14);
if(vertical)
write_reg(sensor_0308_fd, 0x14, value | 0x02);
else
write_reg(sensor_0308_fd, 0x14, value & (~0x02));
}
//设置图像是否需要左右镜像处理
static void set_symmetry_GC308(int symmetry)
{
int value=read_reg(sensor_0308_fd, 0x14);
if(symmetry==1)
write_reg(sensor_0308_fd, 0x14, value | 0x01);//图像需要垂直翻转
else
write_reg(sensor_0308_fd, 0x14, value & (~0x01));//图像不需要垂直翻转
}
static void sensor_power_on_GC308(void)
{
unsigned char value;
value = read_reg(sensor_0308_fd, 0x24);
write_reg(sensor_0308_fd, 0x24, value & 0xe0);
value = read_reg(sensor_0308_fd, 0x25);
write_reg(sensor_0308_fd, 0x25, value | 0x0F);
}
static void sensor_power_down_GC308(void)
{
unsigned char value;
value = read_reg(sensor_0308_fd, 0x25);
write_reg(sensor_0308_fd, 0x25, value & (~0x0F));
}
static int sensorid_read(int sensorfd,unsigned char regs)
{
return read_reg(sensorfd,regs);
}
void __gc0308_init(unsigned int (*regs)[2])
{
int i=0;
while (1)
{
if ((_END_==regs[i][0])&&(_END_==regs[i][1])){
break;
}
write_reg(sensor_0308_fd,regs[i][0],regs[i][1]);
i++;
}
}
static int sensor_init_GC308(int left, int top, int width, int height)
{
int ret;
#if 1
gc0308_set_clk(sensor_0308_fd,100000);
sleep(1);
sensor_set_addr(GC0308ID); //IIC ADDR
select_page_gc308(0);
#endif
//
ret = read_reg(sensor_0308_fd,0x00);
if(0x9b == ret){
printf("Found Sensor-Gc0308...\n");
}
else{
printf("That Should Be GC0308.Something-Unlucky-Happen.SensorID = 0x%x\n",ret);
exit(1);
}
__gc0308_init(gc0308reg);
set_window_GC308(left, top, width, height);
return 0;
}
int gc0308_init(void)
{
return sensor_init_GC308(0,0,640,480);
}
<file_sep>/network/5th_day/raw_udp.c
/* ************************************************************************
* Filename: raw_udp.c
* Description:
* Version: 1.0
* Created: 2015年09月08日 17时41分48秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netpacket/packet.h>
#include <netinet/udp.h>
#include <netinet/ip.h>
#include <net/if.h>
#include <net/ethernet.h>
typedef struct _raw_upd
{
int raw_fd;
unsigned char src_mac[6];
unsigned char dst_mac[6];
unsigned char src_ip[4];
unsigned char dst_ip[4];
struct sockaddr_ll sll;
struct ifreq ethreq;
}UDP;
unsigned short checksum(unsigned short *buf, int nword)
{
unsigned long sum;
for(sum = 0; nword > 0; nword--)
{
sum += htons(*buf);
buf++;
}
sum = (sum>>16) + (sum&0xffff);
sum += (sum>>16);
return ~sum;
}
char send_msg(unsigned char msg_buf[], int raw_fd, struct sockaddr_ll sll)
{
int msg_len = 0;
msg_len = strlen(msg_buf);
msg_len--;
msg_buf[msg_len] = 0; //去掉 \n
if(msg_len%2 != 0) //数据个数不是偶数
{
msg_buf[msg_len] = 0;
msg_len++; //
msg_buf[msg_len] = 0;
}
printf("msg_len=%d\n",msg_len);
//2.封装mac头
unsigned char packet[2048] = "";
unsigned char src_mac[6] = {0x00,0x0c,0x29,0xe4,0xd3,0xd6};
unsigned char dst_mac[6] = {0xec,0xa8,0x6b,0xac,0xcf,0xf9};
struct ether_header *eth_hdr = NULL;
eth_hdr = (struct ether_header *)packet;
memcpy(eth_hdr->ether_shost, src_mac, 6);
memcpy(eth_hdr->ether_dhost, dst_mac, 6);
eth_hdr->ether_type = htons(0x0800); //
//3.封装ip头
struct iphdr *ip_hdr = NULL;
ip_hdr = (struct iphdr *)(packet+14);
ip_hdr->ihl = 5;
ip_hdr->version = 4;
ip_hdr->tos = 0; //服务类型
ip_hdr->ttl = 128; //生存时间
ip_hdr->tot_len = htons(20+8+msg_len);//
ip_hdr->protocol = 17; //UDP协议
ip_hdr->saddr = inet_addr("10.221.2.221");
ip_hdr->daddr = inet_addr("10.221.2.12");
ip_hdr->check = htons(0);
//4.封装UDP头部
struct udphdr *udp_hdr = NULL;
udp_hdr = (struct udphdr *)(packet+14+20);
udp_hdr->source = htons(8000); //源端口
udp_hdr->dest = htons(8080); //目的端口
udp_hdr->len = htons(8+msg_len);
udp_hdr->check = htons(0);
//5.udp的数据
memcpy(packet+14+20+8, msg_buf, msg_len);
//6.ip首部校验和
ip_hdr->check = htons(checksum((unsigned short *)(packet+14),20/2));
//7.udp伪头部,用于计算校验和
unsigned char fake[1024] = {
10, 221, 2, 221, //源ip
10, 221, 2, 12, //目的ip
0, 17, 0, 0, //最后两位是UDP的长度
};
*(unsigned short *)(fake+10) = htons(8+msg_len); //UDP的长度
memcpy(fake+12, packet+14+20, 8+msg_len);
udp_hdr->check = htons(checksum((unsigned short *)(fake),(12+8+msg_len)/2));//udp头部校验和
sendto(raw_fd, packet, 14+20+8+msg_len, 0, (struct sockaddr *)&sll, sizeof(sll));
}
int main(int argc, char *argv[])
{
//创建原始套接字
int raw_fd = socket(PF_PACKET,SOCK_RAW,htons(ETH_P_ALL));
//数据初始化
struct sockaddr_ll sll;
struct ifreq ethreq;
bzero(&sll, sizeof(sll));
strncpy(ethreq.ifr_name,"eth0", IFNAMSIZ); //指定网卡名称
ioctl(raw_fd, SIOCGIFINDEX, (char *)ðreq);//获取网络接口
sll.sll_ifindex = ethreq.ifr_ifindex;
while(1)
{
unsigned char msg_buf[1024] = "";
printf("please input the message you want to send:\n");
fgets(msg_buf, sizeof(msg_buf),stdin);
send_msg(msg_buf, raw_fd, sll);
}
return 0;
}
<file_sep>/sys_program/6th_day/sem_have_name2.c
/* ************************************************************************
* Filename: sem_have_name.c
* Description:
* Version: 1.0
* Created: 2015年08月20日 15时13分17秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/stat.h>
void print(sem_t *psem1,sem_t *psem2)
{
int i = 0;
while(1)
{
sem_wait(psem2);
printf("i = %d\n",i);
i++;
sem_post(psem1);
}
}
int main(int argc, char *argv[])
{
sem_t *ptr1,*ptr2;
ptr1 = sem_open("sem_name1",O_CREAT,0777,1);
if(ptr1 == SEM_FAILED)
{
printf("Failed:sem_name1\n");
}
ptr2 = sem_open("sem_name2",O_CREAT,0777,0);
if(ptr2 == SEM_FAILED)
{
printf("Failed:sem_name2\n");
}
print(ptr1,ptr2);
return 0;
}
<file_sep>/work/shell/mktag.sh
#!/bin/sh
function echoc() {
echo -e "\e[0;91m$1\e[0m"
}
function useage() {
echoc "Useage:"
echoc "\t./mktag TAG_NAME"
exit 1
}
if [ $# -ne 1 ]; then
echo $#
useage
fi
TAG_NAME=$1
export TAG_NAME
echoc "tag: $TAG_NAME"
./repo forall -c 'echo $REPO_PATH;echo $TAG_NAME;git tag $TAG_NAME;git push $REPO_REMOTE $TAG_NAME'
<file_sep>/c/practice/2nd_week/libtest/mytest.c
/* ************************************************************************
* Filename: mytest.c
* Description:
* Version: 1.0
* Created: 2015年07月22日 星期三 10時28分13秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include "mylib.h"
int main(int argc, char *argv[])
{
int a = 10, b = 20;
int max_num,min_num;
max_num = max(a,b);
min_num = min(a,b);
printf("max=%d\n",max_num);
printf("min=%d\n",min_num);
return 0;
}
<file_sep>/work/test/cim_test-zmm220/mt9v136.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
//#include"mt9v136.h"
#define u16 unsigned short
#define IOCTL_READ_REG 0
#define IOCTL_WRITE_REG 1
#define JZ_CIM 1
typedef struct
{
u16 reg;
u16 val;
}S_CFG_16;
#define IOCTL_READ_EEPROM 2 /* read sensor eeprom */
#define IOCTL_WRITE_EEPROM 3 /* write sensor eeprom */
#define IOCTL_SET_ADDR 4
#define IOCTL_SET_CLK 5 /* set i2c clock */
static int sensor_367_fd = -1;
#define I2C_MT9V136_CLOCK 100000
#define I2C_MT9V136_ADDR 0Xba
#define SIZE 12
static struct IO_MSG {
unsigned int write_size;
unsigned int read_size;
unsigned char reg_buf[SIZE];
} reg_msg ;
static int MT9V136_set_addr(unsigned int addr)
{
if (ioctl(sensor_367_fd, IOCTL_SET_ADDR, (unsigned int)&addr) < 0) {
printf("ioctl: set address failed!\n");
return -1;
}
return 0;
}
static int MT9V136_set_clk(int fd,unsigned int clk)
{
if(fd==-1)
{
printf("%s m_sensor_fd is -1\n", __FUNCTION__);
return -1;
}
if (ioctl(fd, IOCTL_SET_CLK, (unsigned int)&clk) < 0)
{
printf("%s ioctl: set clock failed!\n", __FUNCTION__);
return -1;
}
return 0;
}
u16 read_reg_(u16 r)
{
u16 read_val;
reg_msg.write_size=2;
reg_msg.read_size=2;
reg_msg.reg_buf[0]=r>>8;
reg_msg.reg_buf[1]=(0xff&r);
if (ioctl(sensor_367_fd, IOCTL_READ_REG, (void *)®_msg) < 0) {
printf("warning: read_reg failed!\n");
return -1;
}
read_val = (reg_msg.reg_buf[0]<<8)|reg_msg.reg_buf[1];
return read_val;
}
u16 write_reg_(u16 r,u16 v)
{
reg_msg.write_size=4;
reg_msg.reg_buf[0]=r>>8;
reg_msg.reg_buf[1]=(0xff&r);
reg_msg.reg_buf[2]=v>>8;
reg_msg.reg_buf[3]=(0xff&v);
if (ioctl(sensor_367_fd, IOCTL_WRITE_REG, (unsigned long *)®_msg) < 0) {
printf("warning: write_reg failed!\n");
return -1;
}
return 0;
}
#define END_ 0xff
void InitMT9V136(int width,int height,unsigned char *regs)
{
u16 addr_,val_, ret;
int i=0;
u16 j=0;
MT9V136_set_addr(I2C_MT9V136_ADDR); //IIC ADDR
MT9V136_set_clk(sensor_367_fd,I2C_MT9V136_CLOCK);
while((regs[i]!=END_)&&(regs[i+1]!=END_))
{
addr_ = (regs[i]<<8)|regs[i+1];
val_ = (regs[i+2]<<8)|regs[i+3];
ret = write_reg_(addr_,val_);
if (ret == (u16)-1)
exit(0);
// printf("----write the reg and the i= %d,reg:%04x,val:%04x\n",i,addr_,val_);
// j=read_reg_(addr_);
// if(j!=val_)
// printf("i2c write error addr=[%x] j=[%x],val=[%x] i=[%d]\n",addr_,j,val_,i);
i += 4;
}
//printf("----write the reg and the i= %d,reg:%04x,val:%04x\n",i,addr_,val_);
write_reg_(0xC854,width);
write_reg_(0xC856,height);
//printf("\n after read width= %d heigh =%d\n",read_reg_(0xC854),read_reg_(0xC856));
}
#define SENMT367DEV "/dev/sensor-mi367"
int sensor_open_mi367(void)
{
sensor_367_fd = open(SENMT367DEV, O_RDWR);
if(sensor_367_fd < 0)
{
printf("Error opening %s \n",SENMT367DEV);
return -1;
}
printf("%s open ok!\n", SENMT367DEV);
return sensor_367_fd;
}
void sensor_close_mi367()
{
close(sensor_367_fd);
}
<file_sep>/c/practice/2nd_week/fun_pointer/fun_pointer.c
/* ************************************************************************
* Filename: fun_pointer.c
* Description:
* Version: 1.0
* Created: 2015年07月24日 星期五 12時14分36秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
//#include <stdlib.h>
#include "fun.h"
char cmd[] = {'+','-','*','/'};
int (*fp[])(int a, int b) = {add, sub, mul, div};
void main()
{
int a=0,b=0,res=0;
char i,ch;
while(1)
{
scanf("%d%c%d",&a,&ch,&b);
for(i=0;i<sizeof(cmd)/sizeof(cmd[0]);i++)
{
if(ch==cmd[i])
{
res = fp[i](a,b);
printf("%d%c%d=%d\n",a,ch,b,res);
}
}
}
}
<file_sep>/c/practice/2nd_week/variable_arg/variable_arg.c
/* ************************************************************************
* Filename: variable_arg.c
* Description:
* Version: 1.0
* Created: 2015年07月23日 星期四 08時20分25秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include<stdio.h>
#include<string.h>
#include<stdarg.h>
int demo(char *msg,...)
{
va_list argp; //定义保存函数参数的结构
int argno; //记录参数个数
char *para; //存放取出的字符串参数
//argp 指向第一个可选的参数
//msg 是最后一个确定的参数
va_start(argp,msg);
while(1)
{
para = va_arg(argp,char *);//取出当前参数,类型为char *
if(strcmp(para,"\0")==0) break;//采用空串指示参数输入结束
printf("argument #%d is: %s\n",argno,para);
argno++;
}
va_end(argp);//将argp设置为NULL
return argno;
}
int main()
{
demo("DEMO","This","is","a","test!","\0");
return 0;
}
<file_sep>/c/practice/2nd_week/libtest/lib/mylib.h
/* ************************************************************************
* Filename: mylib.h
* Description:
* Version: 1.0
* Created: 2015年07月22日 星期三 10時26分46秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __MYLIB_H__
#define __MYLIB_H__
int max(int a, int b);
int min(int a, int b);
#endif
<file_sep>/network/route/src/inc/msg_dispose.h
/******************************************************************************
文 件 名 : msg_dispose.h
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月11日
最近修改 :
功能描述 : msg_dispose.c 的头文件
******************************************************************************/
#ifndef __MSG_DISPOSE_H__
#define __MSG_DISPOSE_H__
#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */
/*----------------------------------------------*
* 函数原型说明 *
*----------------------------------------------*/
extern uint16 get_type(const uchar *recv);
extern void get_mac(const uchar *recv, uchar *dst_mac, uchar *src_mac);
extern void get_ip(const uchar *recv, uchar *dst_ip, uchar *src_ip);
extern void show_msg_ip(uchar const *recv);
extern Boolean check_if_same_subnet(const uchar eth_mask[], const uchar eth_ip[], const uchar dst_ip[]);
extern int get_transpond_port(TYPE_Route *rt, const uchar dst_ip[]);
extern int send_msg(TYPE_Route *rt, int port, int msg_len);
extern int transpond_msg(TYPE_Route *rt, const uchar dst_ip[], int port, int msg_len);
extern int reply_arp_requset(TYPE_Route *rt, MSG_Info *pinfo, ARP_Hdr *arp_hdr);
extern void dispose_arp_reply(ARP_Table *head, ARP_Hdr *arp_hdr);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
#endif /* __MSG_DISPOSE_H__ */
<file_sep>/work/shell/libs.sh
#!/bin/bash
i=0
libs="ld-2.16.so
ld.so.1
libc-2.16.so
libcrypto.so
libcrypto.so.1.0.0
libc.so.6
libdl-2.16.so
libdl.so.2
libm-2.16.so
libm.so.6
libnss_dns-2.16.so
libnss_dns.so.2
libnss_files-2.16.so
libnss_files.so.2
libpthread-2.16.so
libpthread.so.0
libresolv-2.16.so
libresolv.so.2
librt-2.16.so
librt.so.1
libnl-3.so
libnl-3.so.200
libnl-3.so.200.19.0
libnl-genl-3.so
libnl-genl-3.so.200
libnl-genl-3.so.200.19.0
libssl.so
libssl.so.1.0.0"
#for line in `cat libs`
for line in $libs
do
echo "line$i = $line"
i=$[ $i + 1 ]
done
<file_sep>/gtk/1. base/04_scrolled_window/scrolled_window.c
#include <gtk/gtk.h>
// 回调函数
void destroy( GtkWidget *widget, gpointer data )
{
gtk_main_quit();
}
int main( int argc, char *argv[] )
{
gtk_init (&argc, &argv);
// 创建顶层窗口
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
// 设置窗口的标题
gtk_window_set_title(GTK_WINDOW(window), "GtkScrolledWindow");
// 设置窗口在显示器中的位置为居中
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
g_signal_connect(window, "destroy", G_CALLBACK(destroy), NULL);
gtk_widget_set_size_request(window, 300, 200); // 设置窗口的最小大小
/* 创建一个新的滚动窗口。
* 第一个参数是水平方向的调整对象,第二个参数是垂直方向的调整对象。它们总是设置为NULL。
*/
GtkWidget *scrolled_window = gtk_scrolled_window_new(NULL, NULL);
gtk_container_set_border_width(GTK_CONTAINER(scrolled_window), 10);
gtk_container_add(GTK_CONTAINER(window), scrolled_window); // 滚动窗口放入窗口
/* 滚动条的出现方式可以是 GTK_POLICY_AUTOMATIC 或GTK_POLICY_ALWAYS。
* GTK_POLICY_AUTOMATIC:将自动决定是否需要出现滚动条
* GTK_POLICY_AUTOMATIC:将自动决定是否需要出现滚动条
* 第一个是设置水平滚动条,第二个是垂直滚动条
*/
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
// 标签
GtkWidget *label = gtk_label_new("This is an example of a line-wrapped label. It "\
"should not be taking up the entire "\
"width allocated to it, but automatically "\
"wraps the words to fit. "\
"The time has come, for all good men, to come to "\
"the aid of their party. "\
"The sixth sheik's six sheep's sick.\n"\
" It supports multiple paragraphs correctly, "\
"and correctly adds "\
"many extra spaces."\
"This is an example of a line-wrapped label. It "\
"should not be taking up the entire "\
"width allocated to it, but automatically "\
"wraps the words to fit. "\
"The time has come, for all good men, to come to "\
"the aid of their party. "\
"The sixth sheik's six sheep's sick.\n"\
" It supports multiple paragraphs correctly, "\
"and correctly adds "\
"many extra spaces.");
gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); // label 自动换行
// 将标签组装到滚动窗口中
gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled_window), label);
gtk_widget_show_all(window);
gtk_main();
return 0;
}<file_sep>/network/5th_day/sock_raw.c
/* ************************************************************************
* Filename: sock_ram.c
* Description:
* Version: 1.0
* Created: 2015年09月08日 10时30分52秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/ether.h>
#include <netinet/in.h>
void get_port(unsigned char const *src)
{
}
void get_IP_type(unsigned char const *src, unsigned char *type)
{
//提取数据包类型
sprintf(type,"%c",src[9]);
if(*type == 6)
printf("TCP 数据包\n");
else if(*type == 17)
printf("UDP 数据包\n");
//printf("IP_TYPE:%d\n", *type);
}
void get_ip(unsigned char const *src)
{
unsigned char dst_ip[16] = "";
unsigned char src_ip[16] = "";
//提取目的ip
sprintf(dst_ip,"%d.%d.%d.%d",\
src[16],src[17],src[18],src[19]);
//提取源ip
sprintf(src_ip,"%d.%d.%d.%d",\
src[12],src[13],src[14],src[15]);
printf("IP:%s >> %s\n", src_ip, dst_ip);
}
void get_ARP_ip(unsigned char const *src)
{
unsigned char dst_ip[16] = "";
unsigned char src_ip[16] = "";
//提取目的ip
sprintf(dst_ip,"%d.%d.%d.%d",\
src[24],src[25],src[26],src[27]);
//提取源ip
sprintf(src_ip,"%d.%d.%d.%d",\
src[14],src[15],src[16],src[17]);
printf("ARP_IP:%s >> %s\n", src_ip, dst_ip);
}
void get_mac(unsigned char const *src)
{
unsigned char dst_mac[18] = "";
unsigned char src_mac[18] = "";
//提取目的mac
sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
src[0],src[1],src[2],src[3],src[4],src[5]);
//提取源mac
sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
src[6],src[7],src[8],src[9],src[10],src[11]);
printf("MAC:%s >> %s\n", src_mac, dst_mac);
}
unsigned short get_type(unsigned char const *src, unsigned char *type)
{
//提取数据包类型
sprintf(type,"%02x%02x",src[12],src[13]);
printf("TYPE:%s\n", type);
//printf("TYPE:%c%c%c%c\n", type[0],type[1],type[2],type[3]);
}
int main(int argc, char *argv[])
{
unsigned char type[4] = "";
unsigned char ip_type[1] = "";
unsigned char buf[2048] = "";
int sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
while(1)
{
putchar('\n');
int len = recvfrom(sockfd, buf, sizeof(buf), 0, NULL, NULL);
get_mac(buf);
get_type(buf, type);
if(strcmp(type, "0800") == 0)//ip
{
get_ip(buf+14);
get_IP_type(buf+14, ip_type);
}
else if(strcmp(type, "0806") == 0) //ARP
{
get_ARP_ip(buf+14);
}
sleep(1);
}
close(sockfd);
return 0;
}
<file_sep>/network/1st_day/yy.c
/* ************************************************************************
* Filename: qq.c
* Description:
* Version: 1.0
* Created: 2015年08月31日 19时32分08秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
typedef struct _socket
{
int fd;
char server_ip[INET_ADDRSTRLEN];
struct sockaddr_in addr;
}SOCK;
void *pthread_sndmsg(void *arg)
{
SOCK *psock = (SOCK *)arg;
//配置服务器地址
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8000);//服务器的端口
//服务器的IP
inet_pton(AF_INET, psock->server_ip ,&server_addr.sin_addr.s_addr);
while(1)
{
char msg[128] = "";
char buf[10] = "";
bzero(msg, sizeof(msg));
bzero(buf, sizeof(buf));
printf("\033[34mQQudp:\033[0m");
fflush(stdout);
fgets(msg,sizeof(msg),stdin);
msg[strlen(msg) - 1] = 0;
//printf("sndmsg = %s\n", msg);
sscanf(msg,"%[^ ]",buf);
if(strcmp("sayto",buf) == 0)
{
int ret = 0;
sscanf(msg,"%*[^ ] %s",psock->server_ip);
//printf("server_ip = %s##\n", psock->server_ip);
ret = inet_pton(AF_INET, psock->server_ip, &server_addr.sin_addr.s_addr);
if(ret == 1)
{
printf("connect %s successful!!\n", psock->server_ip);
}
else
{
printf("cannot connect to %s\n", psock->server_ip);
}
}
else if(strlen(msg) != 0)
{
sendto(psock->fd, msg, strlen(msg), 0,\
(struct sockaddr *)&server_addr, sizeof(server_addr));
}
}
return NULL;
}
void *pthread_rcvmsg(void *arg)
{
char msg[128];
char ip_buf[INET_ADDRSTRLEN] = "";
SOCK *psock = (SOCK *)arg;
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
bzero(&client_addr, sizeof(client_addr));
while(1)
{
//接收client发送来的数据
bzero(msg, sizeof(msg));
recvfrom(psock->fd, msg, sizeof(msg), 0, (struct sockaddr *)&client_addr, &client_len);
inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, ip_buf, INET_ADDRSTRLEN);
printf("\033[32m\r[%s]: %s\033[0m\n",ip_buf, msg);
printf("\033[34mQQudp:\033[0m");
fflush(stdout);
//printf("port:%d\n",ntohs(client_addr.sin_port));
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t pth_snd, pth_rcv;
SOCK sock;
strcpy(sock.server_ip, "127.0.0.1");
sock.fd = socket(AF_INET, SOCK_DGRAM, 0);
sock.addr.sin_family = AF_INET;
sock.addr.sin_port = htons(8000);
sock.addr.sin_addr.s_addr = htonl(INADDR_ANY);//INADDR_ANY: 通配地址
bind(sock.fd, (struct sockaddr *)&sock.addr, sizeof(sock.addr));//bind只能bind自己的ip
pthread_create(&pth_snd, NULL,pthread_sndmsg, (void *)&sock);
pthread_create(&pth_rcv, NULL,pthread_rcvmsg, (void *)&sock);
pthread_detach(pth_rcv);
pthread_detach(pth_snd);
while(1)
{
usleep(10000);
}
return 0;
}
<file_sep>/work/test/mplay/Makefile
TOPDIR := $(shell pwd)
GCC := mips-linux-gnu-gcc
CFLAGS := -Os -Wall -I$(TOPDIR)/include -L$(TOPDIR)/lib -ltinyalsa
LDFLAGS:= -Wl,-EL
SOURCES := $(wildcard *.c)
TARGET =mplay
all: $(TARGET)
$(TARGET): $(SOURCES)
$(GCC) $(CFLAGS) $(LDFLAGS) -o $@ $^
INSTALL_DIR = ~/work/sz-halley2/out/product/yak/system/usr/bin
install:
cp $(TARGET) $(INSTALL_DIR) -a
.PHONY: clean
clean:
rm -rf *.o $(TARGET)
<file_sep>/work/test/v4l2/mem/jz_mem.c
/*************************************************************************
> Filename: jz_mem.c
> Author: Qiuwei.wang
> Email: <EMAIL>
> Datatime: Fri 02 Dec 2016 05:58:47 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
struct JZ_MEM_DEV {
unsigned int vaddr;
unsigned int paddr;
unsigned int totalsize;
unsigned int usedsize;
}
<file_sep>/c/homework/2nd_week/transform.c
/* ************************************************************************
* Filename: transform.c
* Description:
* Version: 1.0
* Created: 2015年07月20日 星期一 05時42分57秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
int main(int argc, char *argv[])
{
char ch[20]={0};
char i;
printf("请输入一个长度小于或等于20的字符串:");
gets(ch);
for(i=0;i<20;i++)
{
if(ch[i]>='a' && ch[i]<='z')
{
ch[i] -=32;
}
else if(ch[i]>='A' && ch[i]<='z')
{
ch[i] +=32;
}
}
printf("转换后的字符串:%s\n",ch);
return 0;
}
<file_sep>/c/practice/test.c
/* ************************************************************************
* Filename: test.c
* Description:
* Version: 1.0
* Created: 2015年08月06日 星期四 05時26分10秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
int fun(int n)
{
if(n > 1){
return n*fun(n-1);
}
else{
return 1;
}
}
int mypow(int m, int n)
{
if(n > 0){
return m * mypow(m, n-1);
}
else if(n == 0){
return 1;
}
}
int main()
{
int temp;
temp = fun(6);
printf("!5 = %d\n", temp);
temp = mypow(3,5);
printf("pow(3,5) = %d\n",temp);
return 0;
}
<file_sep>/work/debug/2440/buttons/insmod.sh
#!/bin/bash
name=`ls *.ko`
if [ -z "$name" ]
then
exit 1
fi
devno=
devname=${name%.ko}
#echo "devname = $devname"
if [ -n "`cat /proc/devices | grep $devname`" ]
then
sudo rmmod $devname
if [ -e /dev/$devname ]
then
sudo rm /dev/$devname
fi
fi
echo "installing $name"
sudo insmod ./$name
if [ $? -eq 0 ]
then
echo "install $name successful"
else
echo "Cannot install $name"
exit 1
fi
#以下是为了创建设备文件
i=1
for arg in `cat /proc/devices | grep "$devname"`
do
if [ $i -eq 1 ]
then
devno=$arg
fi
i=$[ $i + 1 ]
done
#echo "#$devno# #$devname#"
#cd /dev
if [ ! -f /dev/$devname ]
then
sudo mknod /dev/$devname c $devno 0
if [ $? -eq 0 ]
then
echo "Create device file successful"
fi
fi<file_sep>/c/practice/2nd_week/libtest/Makefile
objects = mytest testlib #定义一个变量,名为:objects,值为:mytest testlib
.PHONY:all #标记 all 为“伪目标”,这里 all 是第一个目标,也是这个Makefile终极目标
all:$(objects) #展开,相当于:all:mytest testlib
mytest:mytest.c mylib.c #目标:依赖
#这里省略了目标生成的规则,由make程序自动推导
testlib:mytest.c libtestlib.a #目标:依赖
#创建目标的规则,必须以Tab键开始
gcc -o testlib mytest.c libtestlib.a
.PHONY:lib
lib:libtestlib.a libtestlib.so # 执行“make lib”命令将生成静态库和动态库
libtestlib.a:mylib.o
ar rc -o libtestlib.a mylib.o
#去掉注释,在编译完成时把静态库复制到/usr/lib目录
#sudo cp libtestlib.a /usr/lib
libtestlib.so:mylib.c
gcc -shared mylib.c -o libtestlib.so
#sudo cp libtestlib.so /usr/lib
mylib.o:mylib.c
gcc -o mylib.o -c mylib.c
.PHONY:clean #clean 为“伪目标” 用于清除make过程生成的文件
clean:
#rm 命令前面加 '-' ,表示忽视这么命令执行过程的错误
-rm *.o *.a *.so $(objects)
<file_sep>/c/mkheader/Makefile
CC := gcc
TAG := app
CFLAG := -lm
all: $(TAG) mkheader loader
$(TAG):$(SRC)
$(CC) -o $(TAG) app.c
mkheader:$(TAG)
$(CC) -o $@ mkheader.c
strip $@
@./mkheader ./app > log
loader:
$(CC) -o $@ loader.c
.PHONY:clean
clean:
rm -f $(TAG) *.o mkheader loader log n_app
<file_sep>/c/practice/2nd_week/libtest/mylib.c
/* ************************************************************************
* Filename: mylib.c
* Description:
* Version: 1.0
* Created: 2015年07月22日 星期三 10時25分27秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
int max(int a,int b)
{
return a>b?a:b;
}
int min(int a, int b)
{
return a<b?a:b;
}
<file_sep>/work/camera/ov7740/ov7740 调试/jz_camera.h
#ifndef __JZ_CAMERA_H__
#define __JZ_CAMERA_H__
#include <media/soc_camera.h>
#include <linux/clk.h>
#include <linux/proc_fs.h>
#define JZ_CAMERA_DATA_HIGH 1
#define JZ_CAMERA_PCLK_RISING 2
#define JZ_CAMERA_VSYNC_HIGH 4
#define CAMERA_GSENSOR_VCC "vcc_gsensor"
//static int debug = 3;
//module_param(debug, int, S_IRUGO);
#define debug 3
#define dprintk(level, fmt, arg...) \
do { \
if (debug >= level) \
printk("jz-camera: " fmt, ## arg); \
} while (0)
/* define the maximum number of camera sensor that attach to cim controller */
#define MAX_SOC_CAM_NUM 2
struct camera_sensor_priv_data {
unsigned int gpio_rst;
unsigned int gpio_power;
unsigned int gpio_en;
};
struct jz_camera_pdata {
unsigned long mclk_10khz;
unsigned long flags;
struct camera_sensor_priv_data cam_sensor_pdata[MAX_SOC_CAM_NUM];
};
/*
* CIM registers
*/
#define CIM_CFG (0x00)
#define CIM_CTRL (0x04)
#define CIM_STATE (0x08)
#define CIM_IID (0x0c)
#define CIM_DA (0x20)
#define CIM_FA (0x24)
#define CIM_FID (0x28)
#define CIM_CMD (0x2c)
#define CIM_SIZE (0x30)
#define CIM_OFFSET (0x34)
#define CIM_CTRL2 (0x50)
#define CIM_FS (0x54)
#define CIM_IMR (0x58)
/*CIM Configuration Register (CIMCFG)*/
#define CIM_CFG_VSP_HIGH (1 << 14) /* VSYNC Polarity: 1-falling edge active */
#define CIM_CFG_HSP_HIGH (1 << 13) /* HSYNC Polarity: 1-falling edge active */
#define CIM_CFG_PCP_HIGH (1 << 12) /* PCLK working edge: 1-falling */
#define CIM_CFG_DMA_BURST_TYPE 10
#define CIM_CFG_DMA_BURST_INCR8 (0 << CIM_CFG_DMA_BURST_TYPE)
#define CIM_CFG_DMA_BURST_INCR16 (1 << CIM_CFG_DMA_BURST_TYPE)
#define CIM_CFG_DMA_BURST_INCR32 (2 << CIM_CFG_DMA_BURST_TYPE)
#define CIM_CFG_DMA_BURST_INCR64 (3 << CIM_CFG_DMA_BURST_TYPE)
#define CIM_CFG_PACK 4
#define CIM_CFG_PACK_VY1UY0 (0 << CIM_CFG_PACK)
#define CIM_CFG_PACK_Y0VY1U (1 << CIM_CFG_PACK)
#define CIM_CFG_PACK_UY0VY1 (2 << CIM_CFG_PACK)
#define CIM_CFG_PACK_Y1UY0V (3 << CIM_CFG_PACK)
#define CIM_CFG_PACK_Y0UY1V (4 << CIM_CFG_PACK)
#define CIM_CFG_PACK_UY1VY0 (5 << CIM_CFG_PACK)
#define CIM_CFG_PACK_Y1VY0U (6 << CIM_CFG_PACK)
#define CIM_CFG_PACK_VY0UY1 (7 << CIM_CFG_PACK)
#define CIM_CFG_BS0 16
#define CIM_CFG_BS0_2_OBYT0 (0 << CIM_CFG_BS0)
#define CIM_CFG_BS1_2_OBYT0 (1 << CIM_CFG_BS0)
#define CIM_CFG_BS2_2_OBYT0 (2 << CIM_CFG_BS0)
#define CIM_CFG_BS3_2_OBYT0 (3 << CIM_CFG_BS0)
#define CIM_CFG_BS1 18
#define CIM_CFG_BS0_2_OBYT1 (0 << CIM_CFG_BS1)
#define CIM_CFG_BS1_2_OBYT1 (1 << CIM_CFG_BS1)
#define CIM_CFG_BS2_2_OBYT1 (2 << CIM_CFG_BS1)
#define CIM_CFG_BS3_2_OBYT1 (3 << CIM_CFG_BS1)
#define CIM_CFG_BS2 20
#define CIM_CFG_BS0_2_OBYT2 (0 << CIM_CFG_BS2)
#define CIM_CFG_BS1_2_OBYT2 (1 << CIM_CFG_BS2)
#define CIM_CFG_BS2_2_OBYT2 (2 << CIM_CFG_BS2)
#define CIM_CFG_BS3_2_OBYT2 (3 << CIM_CFG_BS2)
#define CIM_CFG_BS3 22
#define CIM_CFG_BS0_2_OBYT3 (0 << CIM_CFG_BS3)
#define CIM_CFG_BS1_2_OBYT3 (1 << CIM_CFG_BS3)
#define CIM_CFG_BS2_2_OBYT3 (2 << CIM_CFG_BS3)
#define CIM_CFG_BS3_2_OBYT3 (3 << CIM_CFG_BS3)
#define CIM_CFG_DSM 0
#define CIM_CFG_DSM_CPM (0 << CIM_CFG_DSM) /* CCIR656 Progressive Mode */
#define CIM_CFG_DSM_CIM (1 << CIM_CFG_DSM) /* CCIR656 Interlace Mode */
#define CIM_CFG_DSM_GCM (2 << CIM_CFG_DSM) /* Gated Clock Mode */
/* CIM State Register (CIM_STATE) */
#define CIM_STATE_DMA_EEOF (1 << 11) /* DMA Line EEOf irq */
#define CIM_STATE_DMA_STOP (1 << 10) /* DMA stop irq */
#define CIM_STATE_DMA_EOF (1 << 9) /* DMA end irq */
#define CIM_STATE_DMA_SOF (1 << 8) /* DMA start irq */
#define CIM_STATE_SIZE_ERR (1 << 3) /* Frame size check error */
#define CIM_STATE_RXF_OF (1 << 2) /* RXFIFO over flow irq */
#define CIM_STATE_RXF_EMPTY (1 << 1) /* RXFIFO empty irq */
#define CIM_STATE_STP_ACK (1 << 0) /* CIM disabled status */
#define CIM_STATE_RXOF_STOP_EOF (CIM_STATE_RXF_OF | CIM_STATE_DMA_STOP | CIM_STATE_DMA_EOF)
/* CIM DMA Command Register (CIM_CMD) */
#define CIM_CMD_SOFINT (1 << 31) /* enable DMA start irq */
#define CIM_CMD_EOFINT (1 << 30) /* enable DMA end irq */
#define CIM_CMD_EEOFINT (1 << 29) /* enable DMA EEOF irq */
#define CIM_CMD_STOP (1 << 28) /* enable DMA stop irq */
#define CIM_CMD_OFRCV (1 << 27)
/*CIM Control Register (CIMCR)*/
#define CIM_CTRL_FRC_BIT 16
#define CIM_CTRL_FRC_1 (0x0 << CIM_CTRL_FRC_BIT) /* Sample every n+1 frame */
#define CIM_CTRL_FRC_10 (0x9 << CIM_CTRL_FRC_BIT)
#define CIM_CTRL_DMA_SYNC (1 << 7) /*when change DA, do frame sync */
#define CIM_CTRL_STP_REQ (1 << 4) /*request to stop */
#define CIM_CTRL_CIM_RST (1 << 3)
#define CIM_CTRL_DMA_EN (1 << 2) /* Enable DMA */
#define CIM_CTRL_RXF_RST (1 << 1) /* RxFIFO reset */
#define CIM_CTRL_ENA (1 << 0) /* Enable CIM */
/* CIM Control Register 2 (CIMCR2) */
#define CIM_CTRL2_FSC (1 << 23) /* enable frame size check */
#define CIM_CTRL2_ARIF (1 << 22) /* enable auto-recovery for incomplete frame */
#define CIM_CTRL2_OPG_BIT 4 /* option priority configuration */
#define CIM_CTRL2_OPG_MASK (0x3 << CIM_CTRL2_OPG_BIT)
#define CIM_CTRL2_OPE (1 << 2) /* optional priority mode enable */
#define CIM_CTRL2_APM (1 << 0) /* auto priority mode enable*/
/*CIM Interrupt Mask Register (CIMIMR)*/
#define CIM_IMR_STPM (1<<10)
#define CIM_IMR_EOFM (1<<9)
#define CIM_IMR_SOFM (1<<8)
#define CIM_IMR_FSEM (1<<3)
#define CIM_IMR_RFIFO_OFM (1<<2)
#define CIM_IMR_STPM_1 (1<<0)
/* CIM Frame Size Register (CIM_FS) */
#define CIM_FS_FVS_BIT 16 /* vertical size of the frame */
#define CIM_FS_FVS_MASK (0x1fff << CIM_FS_FVS_BIT)
#define CIM_FS_BPP_BIT 14 /* bytes per pixel */
#define CIM_FS_BPP_MASK (0x3 << CIM_FS_BPP_BIT)
#define CIM_FS_FHS_BIT 0 /* horizontal size of the frame */
#define CIM_FS_FHS_MASK (0x1fff << CIM_FS_FHS_BIT)
#define CIM_BUS_FLAGS (SOCAM_MASTER | SOCAM_VSYNC_ACTIVE_HIGH | \
SOCAM_VSYNC_ACTIVE_LOW | SOCAM_HSYNC_ACTIVE_HIGH | \
SOCAM_HSYNC_ACTIVE_LOW | SOCAM_PCLK_SAMPLE_RISING | \
SOCAM_PCLK_SAMPLE_FALLING | SOCAM_DATAWIDTH_8)
#define VERSION_CODE KERNEL_VERSION(0, 0, 1)
#define DRIVER_NAME "jz-cim"
#define MAX_VIDEO_MEM 16 /* Video memory limit in megabytes */
/*
* Structures
*/
struct jz_camera_dma_desc {
dma_addr_t next;
unsigned int id;
unsigned int buf;
unsigned int cmd;
/* only used when SEP = 1 */
unsigned int cb_frame;
unsigned int cb_len;
unsigned int cr_frame;
unsigned int cr_len;
} __attribute__ ((aligned (32)));
/* buffer for one video frame */
struct jz_buffer {
/* common v4l buffer stuff -- must be first */
struct videobuf_buffer vb;
enum v4l2_mbus_pixelcode code;
int inwork;
};
struct jz_camera_dev {
struct soc_camera_host soc_host;
struct soc_camera_device *icd[MAX_SOC_CAM_NUM];
struct jz_camera_pdata *pdata;
//struct jz_buffer *active;
struct resource *res;
struct clk *clk;
struct clk *mclk;
//struct list_head capture;
void __iomem *base;
unsigned int irq;
unsigned long mclk_freq;
spinlock_t lock;
unsigned int buf_cnt;
struct jz_camera_dma_desc *dma_desc;
void *desc_vaddr;
int is_first_start;
//int stop_flag;
int poll_flag;
//struct videobuf_buffer *vb_address;
struct videobuf_buffer *vb_address[20];
int vb_address_flag;
struct jz_camera_dma_desc *dma_desc_head;
struct jz_camera_dma_desc *dma_desc_tail;
unsigned int is_tlb_enabled;
};
#endif
<file_sep>/network/route/src/inc/arp_link.h
/******************************************************************************
文 件 名 : link.h
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月11日
最近修改 :
功能描述 : link.c 的头文件
******************************************************************************/
#ifndef __LINK_H__
#define __LINK_H__
/*----------------------------------------------*
* 外部函数原型说明 *
*----------------------------------------------*/
extern uint iptoun_btob(const uchar *ip);
extern uint iptoun_btol(const uchar *ip);
extern ARP_Table *insert_arp_table(ARP_Table *head, ARP_Table node);
extern ARP_Table *delete_arp_node(ARP_Table *head, const uchar *ip);
extern ARP_Table *free_arp_table(ARP_Table *pnode);
extern Boolean change_arp_mac(ARP_Table *head, const uchar ip[], const uchar mac[]);
extern void print_arp_table(ARP_Table *head);
#endif /* __LINK_H__ */
<file_sep>/gtk/4st_week/gtk_signal.c
/* ************************************************************************
* Filename: gtk_signal.c
* Description:
* Version: 1.0
* Created: 2015年08月10日 10时52分19秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <gtk/gtk.h>
void button_callback(GtkButton *button, gpointer data)
{
const char *str = gtk_button_get_label(button);
printf("str = %s data = %s\n",str, (gchar *)data);
}
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(window,"destroy",G_CALLBACK(gtk_main_quit),NULL);
GtkWidget *button = gtk_button_new_with_label("button");
gtk_container_add(GTK_CONTAINER(window),button);
g_signal_connect(button,"clicked",G_CALLBACK(button_callback),"hello_button");
gtk_widget_show_all(window);
gtk_main();
return 0;
}
<file_sep>/work/shell/tfcard_test.sh
#!/bin/sh
#########################################################################
########################################################################
# 3. a real report:
#./R_inand-cptest.sh
#########################################################################
#clear
i=0
#export PATH=$PATH:/mnt/sdcard
#测试次数
num=/mnt/sdcard/testlog/set.txt
#校准文件MD5
chk_md5=/mnt/sdcard/testlog/check.md5
tmp_md5=/mnt/sdcard/testlog/tmp.md5
#测试次数
if test ! -e $num; then
echo Not find $num,test stop !!!
read
exit 1
fi
#n=`cat $num`
#get_md5file
get_md5() # $path
{
cd $1
busybox find ./ -type f -print0 |busybox xargs -0 busybox md5sum|busybox sort >$tmp_md5
}
#get_diff
get_diff()
{
busybox diff $chk_md5 $tmp_md5 >/dev/null
if [ $? -ne 0 ];then
echo ---------------------------------------------
echo The number $i Test copy NG!
echo Test copy NG! >>$nlog
read
else
echo ---------------------------------------------
echo The number $i Test copy OK!
echo Test copy OK! >>$nlog
fi
}
#####################测试资源文件######################
star=/mnt/sdcard/scrda
if test ! -d $star; then
mkdir -p $star
fi
busybox tar -xvf /mnt/sdcard/custdata.tar -C $star >/dev/null
if test ! -d $star; then
echo Not find $star,test stop !!!
read
exit 1
fi
#################测试目标文件######################
tmp=`cat /mnt/sdcard/ter.txt`
if test ! -d $tmp; then
mkdir -p $tmp
fi
if test ! -d $tmp; then
echo Not find $tmp,test stop !!!
read
fi
###################测试日志文件########################
if test ! -d /mnt/sdcard/testlog; then
mkdir -p /mnt/sdcard/testlog
fi
nlog=/mnt/sdcard/testlog/n.txt
#elog=/mnt/sdcard/testlog/err.txt
##############检测拷贝过程#################
echo
echo ================== Test cycle start ==================
echo
#*********************************************************
while [ $i -le 1000 ]
do
let i=$i+1
echo ===========current num $i scrda to tmpda============
echo current num $i scrda to tmpda >$nlog
busybox rm -r $tmp
mkdir -p $tmp
busybox cp -r $star/* $tmp
# get_md5 $tmp
# get_diff
echo
echo ===========current num $i tmpda to scrda============
echo current num $i tmpda to scrda >$nlog
busybox rm -r $star
mkdir -p $star
busybox cp -r $tmp/* $star
# get_md5 $star
# get_diff
echo
echo
#n=`cat $num`
done
#*********************************************************
echo
echo ============@@@ copy test over @@@=============
read
exit 1
<file_sep>/c/practice/3rd_week/struct/sort.c
/* ************************************************************************
* Filename: sort.c
* Description:
* Version: 1.0
* Created: 2015年07月28日 星期二 10時51分47秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
typedef struct stu
{
int num;
char name[30];
float score;
}STU;
void sort(STU stu[],int n)
{
STU temp;
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(stu[i].score < stu[j].score)
{
temp = stu[i];
stu[i] = stu[j];
stu[j] = temp;
}
}
}
int main(int argc, char *argv[])
{
STU stu[5];
int i;
float ave = 0;
for(i=0;i<5;i++)
{
printf("请输入第%d位学生的学号、姓名、成绩:\n",i+1);
scanf("%d %s %f",&stu[i].num,stu[i].name,&stu[i].score);
}
sort(stu,5);
for(i=0;i<5;i++)
{
ave += stu[i].score;
printf("学号:%-4d 姓名:%-8s 成绩:%-4.1f 排第%d名\n",stu[i].num,stu[i].name,stu[i].score,i+1);
}
ave /=5;
printf("\n平均成绩 %.1f\n",ave);
return 0;
}
<file_sep>/c/practice/3rd_week/link/link.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "link.h"
#if 0
//尾部插入
STU *insert_link(STU *head, STU temp)
{
//申请插入节点并赋值
STU *pi = NULL;
pi = (STU *)malloc(sizeof(STU));
*pi = temp;
pi->next = NULL;
//判断链表是否为空
if(head == NULL)
{
head = pi;
}
else
{
//寻找链表的尾部
STU *pb = head;
while(pb->next != NULL)
pb = pb->next;
pb->next = pi; //在链表尾部添加pi节点
}
return head;
}
#elif 0
//头部之前插入
STU *insert_link(STU *head, STU temp)
{
//申请插入节点并赋值
STU *pi = NULL;
pi = (STU *)malloc(sizeof(STU));
*pi = temp;
pi->next = NULL;
//判断链表是否为空
if(head == NULL)
{
head = pi;
}
else
{
pi->next = head;
head = pi;
}
return head;
}
#elif 1
//有序插入链表节点
STU *insert_link(STU *head, STU temp)
{
//申请插入节点并赋值
STU *pi = NULL;
pi = (STU *)malloc(sizeof(STU));
*pi = temp;
pi->next = NULL;
if(head == NULL)
{
head = pi;
}
else
{
STU *pb = NULL,*pf = NULL;
pb = pf = head;
//寻找插入点(以num从小到大插入)
while((pb->num < pi->num) && (pb->next != NULL))
{
pf = pb;
pb = pb->next;
}
//找到插入点
if(pb->num >= pi->num)
{
//判断是否在;链表头插入
if(pb == head) //头部插入
{
pi->next = head;
head = pi;
}
else //中部插入
{
pf->next = pi;
pi->next = pb;
}
}
else //尾部插入
{
pb->next = pi;
}
}
return head;
}
#endif
void print_link(STU *head)
{
//1.判断链表是否存在
if(head == NULL)
{
printf("The link not exist!\n");
}
else
{
STU *pb = head;
while(pb != NULL)
{
printf("%d %s %d\n",pb->num,pb->name,pb->score);
pb = pb->next; // 指向链表下个节点
}
}
return;
}
STU *search_link(STU *head, char *name)
{
if(head == NULL)
{
return NULL;
}
else
{
STU *pb = head;
while((strcmp(pb->name,name) != 0) && (pb->next != NULL))
pb = pb->next;
if(strcmp(pb->name,name) == 0)
{
return pb;
}
}
return NULL;
}
STU *delete_link(STU *head, int num)
{
if(head != NULL)//链表不为空
{
STU *pb = NULL, *pf = NULL;
pb = pf = head;
while((pb->num != num) && (pb->next !=NULL))
{
pf = pb;
pb = pb->next;
}
if(pb->num == num) //找到要删除的num
{
if(pb == head) //删除链表头
{
head = pb->next;
}
else if(pb->next == NULL)//删除最后一个
{
pf->next = NULL;
}
else //删除中间位置
{
pf->next = pb->next;
}
free(pb);
}
}
return head;
}
STU *free_link(STU *head)
{
if(head == NULL)
{
printf("Link not exist!\n");
}
else
{
STU *pb = head;
//循环删除链表每个节点的方法:
//1.判断 head 是否为空
//2.让 pb 指向和 head 相同的节点
//3.然后 让 head 指向下个节点
//4.再把 pb 指向的节点释放掉
//5.返回步骤 1
while(head != NULL)
{
pb = head;
head = pb->next;
free(pb);
}
}
return head;
}
<file_sep>/c/practice/3rd_week/time/show_time.c
/* ************************************************************************
* Filename: show_time.c
* Description:
* Version: 1.0
* Created: 2015年07月28日 星期二 05時37分22秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
void show_time(void)
{
time_t rawtime;
struct tm *timeinfo;
int i = 0;
//time(&rawtime); //获取系统时间
//timeinfo = localtime(&rawtime);//转为本地时间
while(1)
{
#if 1
system("clear");
time(&rawtime); //获取系统时间
timeinfo = localtime(&rawtime);//转为本地时间
//asctime(timeinfo); //转为便准的ASCII时间格式
printf("%4d-%02d-%02d %02d:%02d:%02d\n",
timeinfo->tm_year+1900,timeinfo->tm_mon+1,timeinfo->tm_mday,
timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
sleep(1);
#endif
#if 0
usleep(990900); //1ms
i++;
if(1)
{
//i = 0;
timeinfo->tm_sec++;
if(timeinfo->tm_sec == 60)
{
timeinfo->tm_sec = 0;
timeinfo->tm_min++;
if(timeinfo->tm_min == 60)
{
timeinfo->tm_min = 0;
timeinfo->tm_hour++;
if(timeinfo->tm_hour == 24)
{
timeinfo->tm_hour = 0;
}
}
}
system("clear");
printf("%4d-%02d-%02d %02d:%02d:%02d\n",
timeinfo->tm_year+1900,timeinfo->tm_mon+1,timeinfo->tm_mday,
timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
}
#endif
}
}
<file_sep>/network/route/src/route_pthread.c
/******************************************************************************
文 件 名 : route_pthread.c
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月15日
最近修改 :
功能描述 : 线程创建与实现
函数列表 :
create_pthread
pthread_getmsg
pthread_keyeve
修改历史 :
1.日 期 : 2015年9月15日
作 者 : if
修改内容 : 创建文件
******************************************************************************/
#include "common.h"
#include "route_control.h"
#include "msg_dispose.h"
#include "firewall_file.h"
#include "print.h"
/*****************************************************************************
函 数 名 : dispose_cmd()
功能描述 : 处理命令,并执行相应的动作
输入参数 : rt TYPE_Route类型结构体
cmd 待处理、执行的命令
返 回 值 : NULL
修改日期 : 2015年9月10日
*****************************************************************************/
void dispose_key_cmd(TYPE_Route *rt, char cmd[])
{
if(strcmp(cmd, "help") == 0){
show_help();
}
else if(strcmp(cmd,"arp") == 0){
print_arp_table(rt->arp_head);
}
else if(strcmp(cmd,"ifconfig") == 0){
show_port_info(rt, NULL);
}
else if(strcmp(cmd,"lsfire") == 0){
printf("\n------firewall rules-------\n");
print_firewall(rt->mac_head);
print_firewall(rt->ip_head);
print_firewall(rt->port_head);
print_firewall(rt->pro_head);
printf("---------------------------\n\n");
}
else if(strcmp(cmd,"fire on") == 0){
rt->fire_status = UP;
}
else if(strcmp(cmd,"fire off") == 0){
rt->fire_status = DOWN;
}
else if(strcmp(cmd,"setfire") == 0){
int i, len;
char rule[RULE_LEN] = "";
for(i=0; i<2; i++) {
printf("passwd: ");
get_passwd(rule, PASSWD_LEN-1);
if(strcmp(rule, rt->passwd) == 0 ||\
strcmp(rule, ROOT_PASSWD) == 0){
break;
}
else {
printf("\nerror, try again!\n");
}
}
if(i == 2) return;
system("clear");
firewall_rule_set_help();
while(1) {
bzero(rule, RULE_LEN);
printf("entry: ");
fflush(stdout);
fgets(rule, RULE_LEN, stdin);
len = strlen(rule);
rule[len-1] = 0; //去掉 \n
if(strcmp(rule,"ls") == 0){
printf("\n------firewall rules-------\n");
print_firewall(rt->mac_head);
print_firewall(rt->ip_head);
print_firewall(rt->port_head);
print_firewall(rt->pro_head);
printf("---------------------------\n\n");
}
else if(strcmp(rule,"-h") == 0) {
firewall_rule_set_help();
}
else if(strncmp(rule,"-d",2) == 0) {
char *prule = NULL;
prule = rule+3; //跳过 "-d "
delete_firewall_rule(rt, prule);
firewall_save_all_rules(rt);
}
else if(strcmp(rule,"passwd") == 0) {
printf("new passwd: ");
get_passwd(rt->passwd, PASSWD_LEN-1);
firewall_save_passwd(rt->passwd);
putchar('\n');
}
else if(strcmp(rule,"esc") == 0){
printf("exitting set firewall...\n");
break;
}
else {
firewall_build_rule(rt, rule, 1);
}
}
}
else if(strcmp(cmd,"reset") == 0){
free_firewall_link(rt->mac_head);
free_firewall_link(rt->ip_head);
free_firewall_link(rt->port_head);
free_firewall_link(rt->pro_head);
firewall_save_all_rules(rt);
}
else if(strcmp(cmd,"clear") == 0){
system("clear");
}
else if(strcmp(cmd,"exit") == 0){
exit(0);
}
}
/*****************************************************************************
函 数 名 : pthread_deal_message()
功能描述 : 接收处理网络数据
输入参数 : arg 线程函数的唯一参数
返 回 值 : void *
修改日期 : 2015年9月10日
*****************************************************************************/
void *pthread_deal_message(void *arg)
{
TYPE_Route *rt = (TYPE_Route *)arg;
MSG_Info msg;
int ret = 0;
while(1)
{
again:
bzero(&msg, sizeof(msg));
msg.len = recvfrom(rt->raw_fd, rt->recv, sizeof(rt->recv), 0, NULL, NULL);
ret = firewall_filt(rt, &msg);
if(ret < 0) goto again; //ret < 0 表明不能通过防火墙
switch(msg.frame_type)
{
case 0x0800:
{
msg.port = get_transpond_port(rt, msg.dst_ip);
if(msg.port != -1){
ret = transpond_msg(rt, msg.dst_ip, msg.port, msg.len);
//if(ret < 0) printf("transpond message failed!\n");
}
break;
}
case 0x0806:
{
switch(ntohs(rt->arp_hdr->ar_op))
{
case 1: //ARP 请求
{
//应答ARP请求
reply_arp_requset(rt, &msg, rt->arp_hdr);
break;
}
case 2: //ARP 应答
{
//处理ARP应答
dispose_arp_reply(rt->arp_head, rt->arp_hdr);
break;
}
}
break;
}
}
}
}
/*****************************************************************************
函 数 名 : pthread_key_event()
功能描述 : 处理键盘输入命令
输入参数 : arg 线程函数的唯一参数
返 回 值 : void *
修改日期 : 2015年9月10日
*****************************************************************************/
void *pthread_key_event(void *arg)
{
TYPE_Route *rt = (TYPE_Route *)arg;
char cmd[64] = "";
system("clear");
show_help();
while(1)
{
//获取输入命令
printf("cmd: ");
fflush(stdout);
fgets(cmd, sizeof(cmd), stdin);
cmd[strlen(cmd) - 1] = 0;
dispose_key_cmd(rt, cmd);
}
}
/*****************************************************************************
函 数 名 : pthread_tcp_server()
功能描述 : 处理tcp客户端发送的命令
输入参数 : arg 线程函数的唯一参数
返 回 值 : void *
修改日期 : 2015年9月16日
*****************************************************************************/
void *pthread_tcp_server(void *arg)
{
TYPE_Route *rt = (TYPE_Route *)arg;
int connfd = rt->connfd;
int len = 0;
char cmd[64];
send(connfd, "connected!\n", strlen("connected!\n"), 0);
while(1) {
bzero(cmd, sizeof(cmd));
len = recv(connfd, cmd, sizeof(cmd), 0);
if(len == 0) break;
dispose_tcp_cmd(rt, connfd, cmd);
}
close(connfd); // 关闭套接字
}
/*****************************************************************************
函 数 名 : create_pthread()
功能描述 : 添加线程
输入参数 : rt TYPE_Route类型结构体
返 回 值 : NULL
修改日期 : 2015年9月11日
*****************************************************************************/
void create_pthread(TYPE_Route *rt)
{
//创建线程
pthread_create(&rt->pth_getmsg, NULL, pthread_deal_message,(void *)rt);
pthread_create(&rt->pth_keyeve, NULL, pthread_key_event,(void *)rt);
//线程与当前进程分离
pthread_detach(rt->pth_getmsg);
pthread_detach(rt->pth_keyeve);
while(1)
{
struct sockaddr_in c_addr;
socklen_t addr_len = sizeof(c_addr);
rt->connfd = accept(rt->sockfd, (struct sockaddr *)&c_addr, &addr_len);
pthread_t pth_tcpsrv;
pthread_create(&pth_tcpsrv, NULL, (void *)pthread_tcp_server, (void *)rt);
pthread_detach(pth_tcpsrv);
}
}
<file_sep>/sys_program/player/src/main.c
/* ************************************************************************
* Filename: main.c
* Description:
* Version: 1.0
* Created: 2015 年 08月 22日
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include "common.h"
#include "mplayer_ui.h"
#include "mplayer_control.h"
#include "mplayer_pthread.h"
int main(int argc, char *argv[])
{
MPLAYER mplayer;
//bzero(&mplayer, sizeof(&mplayer));
gtk_thread_init();
gtk_init(&argc, &argv);
mplayer_init(&mplayer);
window_init(&mplayer);
mplayer_show_musiclist(&mplayer, &song);
mplayer_process(&mplayer);
create_pthread(&mplayer);
gdk_threads_enter();// 进入多线程互斥区域
gtk_main();
gdk_threads_leave();// 退出多线程互斥区域
return 0;
}
<file_sep>/sys_program/5th_day/pthread.c
/* ************************************************************************
* Filename: pthread.c
* Description:
* Version: 1.0
* Created: 2015年08月19日 11时01分11秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
typedef struct _play
{
int count;
int playflag;
sem_t sem1;
sem_t sem2;
}Play;
int num;
#if 0
void *fun1(void *arg)
{
int i = (int)arg;
printf("i = %d\n",i);
for(;i>=0;i--)
{
printf("in pth1 num = %d\n",num);
sleep(1);
}
}
void *fun2(void *arg)
{
char *pbuf = (char *)arg;
printf("%s\n",pbuf);
while(1)
{
num++;
printf("in pth2\n");
sleep(1);
}
}
#endif
void *fun1(void *arg)
{
Play *p = (Play *)arg;
while(1)
{
if(p->playflag == 1)
{
sem_wait(&p->sem1);
p->count++;
sleep(1);
sem_post(&p->sem2);
}
}
}
void *fun2(void *arg)
{
Play *p = (Play *)arg;
while(1)
{
sem_wait(&p->sem2);
printf("count = %d\n",p->count);
sem_post(&p->sem1);
}
}
int main(int argc, char *argv[])
{
int a = 5;
char buf[] = "hello";
Play play;
play.count = 0;
play.playflag = 1;
pthread_t pth1, pth2;
sem_init(&play.sem1, 0, 1);
sem_init(&play.sem2, 0, 0);
pthread_create(&pth1,NULL,fun1,(void *)&play);
//sleep(1);
pthread_create(&pth2,NULL,fun2,(void *)&play);
while(1)
{
sleep(4);
play.playflag = 0;
}
return 0;
}
<file_sep>/gtk/4st_week/gtk_table.c
/* ************************************************************************
* Filename: gtk_hbox.c
* Description:
* Version: 1.0
* Created: 2015年08月10日 11时34分43秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <gtk/gtk.h>
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(window,"destroy", G_CALLBACK(gtk_main_quit),NULL);
GtkWidget *table = gtk_table_new(2,3,TRUE);
GtkWidget *button1 = gtk_button_new_with_label("button1");
GtkWidget *button2 = gtk_button_new_with_label("button2");
GtkWidget *button3 = gtk_button_new_with_label("button3");
GtkWidget *button4 = gtk_button_new_with_label("button4");
GtkWidget *button5 = gtk_button_new_with_label("button5");
GtkWidget *button6 = gtk_button_new_with_label("button6");
gtk_table_attach_defaults(GTK_TABLE(table),button1,0,1,0,1);
gtk_table_attach_defaults(GTK_TABLE(table),button2,1,2,0,1);
gtk_table_attach_defaults(GTK_TABLE(table),button3,2,3,0,1);
gtk_table_attach_defaults(GTK_TABLE(table),button4,0,1,1,2);
gtk_table_attach_defaults(GTK_TABLE(table),button5,1,2,1,2);
gtk_table_attach_defaults(GTK_TABLE(table),button6,2,3,1,2);
gtk_container_add(GTK_CONTAINER(window),table);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
<file_sep>/work/shell/mkimage.sh
#!/bin/bash
#email: <EMAIL>
if [ $# -lt 1 ]; then
echo "USAGE:`basename $0` [-a] [-k] [-u] [-m] [-c]"
echo " eg:`basename $0` -k -u"
echo " eg:`basename $0` -c"
echo " eg:`basename $0` -a"
exit
fi
#PRODUCT=mozart
#SOURCE_DIR=$HOME/work/$PRODUCT
SOURCE_DIR=$(pwd)
IMAGE_DIR=$SOURCE_DIR/out
ENVSET_FILE=$SOURCE_DIR/tools/source.sh
if [ ! -d $IMAGE_DIR ]; then
mkdir -p $IMAGE_DIR
if [ $? -ne 0 ]; then
echo "mkdir $IMAGE_DIR failed..."
echo "$IMAGE_DIR = $SOURCE_DIR"
IMAGE_DIR=$SOURCE_DIR
else
echo "IMAGE_DIR = $IMAGE_DIR"
fi
fi
if [ -d $SOURCE_DIR/u-boot/tools ];then
echo "PATH=$SOURCE_DIR/u-boot/tools:\$PATH"
export PATH=$SOURCE_DIR/u-boot/tools:$PATH
fi
if [ -f $ENVSET_FILE ];then
echo "source $ENVSET_FILE"
source $ENVSET_FILE
fi
echo "SOURCE_DIR: $SOURCE_DIR"
echo " IMAGE_DIR: $IMAGE_DIR"
while getopts ":akumc" opt
do
case $1 in
-a)
echo "compiling u-boot ..."
cd $SOURCE_DIR/u-boot
make distclean
make halley2_v20_zImage_sfc_nor_config && make -j8
if [ $? -eq 0 ]; then
cp u-boot-with-spl.bin $IMAGE_DIR
fi
echo "compiling kernel ..."
cd $SOURCE_DIR/kernel*
if [ -f .config ];then
make zImage -j8
else
make clean
make halley2_v20_oss_defconfig && make zImage -j8
fi
if [ $? -eq 0 ]; then
cp arch/mips/boot/compressed/zImage $IMAGE_DIR
fi
echo "compiling mozart ..."
cd $SOURCE_DIR/mozart
make canna_v2.0_43438_cramfs_config && make
if [ $? -eq 0 ]; then
cp output/target/appfs.cramfs $IMAGE_DIR
cp output/target/updater.cramfs $IMAGE_DIR
cp output/target/usrdata.jffs2 $IMAGE_DIR
fi
echo "make all ..."
;;
-k)
echo "compiling kernel ..."
cd $SOURCE_DIR/kernel*
if [ -f .config ];then
make zImage -j8
else
make clean;
make halley2_v20_oss_defconfig && make zImage -j8
fi
if [ $? -eq 0 ]; then
cp arch/mips/boot/compressed/zImage $IMAGE_DIR
fi
;;
-u)
echo "compiling u-boot ..."
cd $SOURCE_DIR/u-boot
make distclean
make halley2_v20_zImage_sfc_nor_config && make -j8
if [ $? -eq 0 ]; then
cp u-boot-with-spl.bin $IMAGE_DIR
fi
;;
-m)
echo "compiling mozart ..."
cd $SOURCE_DIR/mozart
if [ -f output/mozart/usr/include/mozart_config.h ];then
make
else
make canna_v2.0_43438_cramfs_config && make
fi
if [ $? -eq 0 ]; then
cp output/target/appfs.cramfs $IMAGE_DIR
cp output/target/updater.cramfs $IMAGE_DIR
cp output/target/usrdata.jffs2 $IMAGE_DIR
fi
;;
-c)
echo "make distclean ..."
if [ -d $IMAGE_DIR ];then
rm $IMAGE_DIR -rf
fi
cd $SOURCE_DIR/u-boot && make distclean
cd $SOURCE_DIR/kernel* && make distclean
cd $SOURCE_DIR/mozart && make distclean
return $?
;;
\?)
echo "Invalid option : `basename $0` [-a] [-k] [-u] [-m] [-c]"
;;
esac
done
<file_sep>/network/route/src/firewall_link.c
/******************************************************************************
文 件 名 : firewall_link.c
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月15日
最近修改 :
功能描述 : 创建防火墙链表
函数列表 :
delete_firewall_node
free_firewall_link
insert_firewall_node
print_firewall
修改历史 :
1.日 期 : 2015年9月15日
作 者 : if
修改内容 : 创建文件
******************************************************************************/
#include "common.h"
/*****************************************************************************
函 数 名 : insert_firewall_node()
功能描述 : 插入一条防火墙规则表
输入参数 : head 链表头
node 待插入节点
返 回 值 : 链表头指针
修改日期 : 2015年9月13日
*****************************************************************************/
FIRE_Wall *insert_firewall_node(FIRE_Wall *head, FIRE_Wall node)
{
FIRE_Wall *pi = NULL;
pi = (FIRE_Wall *)malloc(sizeof(FIRE_Wall));
if(pi != NULL){ //成功申请到空间
*pi = node;
pi->next = NULL;
if(head != NULL){
FIRE_Wall *pb = NULL;
pb = head;
while((strcmp(pb->rule, pi->rule)) != 0 && (pb->next!= NULL))
pb = pb->next;
if(strcmp(pb->rule, pi->rule) != 0){
pi->next = head;
}
}
head = pi;
}
else{
printf("Can not apply for a FIRE_Wall memeory space!\n");
}
return head;
}
/*****************************************************************************
函 数 名 : delete_firewall_node()
功能描述 : 查找ARP表,并删除链表中的指定节点
输入参数 : head 链表头
rule 从链表查找删除的规则
返 回 值 : 链表头指针
修改日期 : 2015年9月13日
*****************************************************************************/
FIRE_Wall *delete_firewall_node(FIRE_Wall *head, const char *rule)
{
if(head == NULL) {
printf("Link is not exist!\n");
}
else
{
FIRE_Wall *pb = NULL, *pf = NULL;
pb = pf =head;
while((strcmp(pb->rule, rule) !=0) && (pb->next != NULL))
{
pf = pb;
pb = pb->next;
}
if(strcmp(pb->rule, rule) == 0)
{
if(pb == head) {//删除的节点是链表头部
head = pb->next;
}
else if(pb->next == NULL) { //删除的节点在链表尾部
pf->next = NULL;
}
else { //删除的节点在中间
pf->next = pb->next;
}
free(pb);
}
else {
printf("haved not set this firewall rule!\n");
}
}
return head;
}
/*****************************************************************************
函 数 名 : print_firewall()
功能描述 : 打印整个防火墙规则表
输入参数 : head 链表头
返 回 值 : 链表头指针
修改日期 : 2015年9月13日
*****************************************************************************/
void print_firewall(FIRE_Wall *head)
{
if(head != NULL){
FIRE_Wall *pb = head;
while(pb != NULL)
{
printf("%s\n", pb->rule);
pb = pb->next;
}
}
}
/*****************************************************************************
函 数 名 : free_firewall_link()
功能描述 : 释放整个防火墙规则表
输入参数 : head 链表头
返 回 值 : 链表头指针
修改日期 : 2015年9月13日
*****************************************************************************/
FIRE_Wall *free_firewall_link(FIRE_Wall *head)
{
if(head != NULL){
FIRE_Wall *pb = head;
//循环删除链表每个节点的方法:
//1.判断 head 是否为空
//2.让 pb 指向和 head 相同的节点
//3.然后 让 head 指向下个节点
//4.再把 pb 指向的节点释放掉
//5.返回步骤 1
while(head != NULL)
{
pb = head;
head = pb->next;
free(pb);
}
}
return head;
}
<file_sep>/work/rootfs/sbin/wifi_connect.sh
#!/bin/sh
INTERFACE=wlan0
WPA_CONF=/etc/wpa_supplicant.conf
# wpa_supplicant config file
if [ ! -f "$WPA_CONF" ]; then
echo "No configuration file"
exit 0
fi
ifconfig $INTERFACE up
wpa_supplicant -Dnl80211 -i$INTERFACE -c$WPA_CONF -B
usleep 1300000
udhcpc -i $INTERFACE -q
exit 0
<file_sep>/sys_program/player/src/file.c
/* ************************************************************************
* Filename: file.c
* Description:
* Version: 1.0
* Created: 2015年07月31日 星期五 05時35分04秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include "common.h"
#include "process_lrc.h"
#include "file.h"
/**************************************************************************
*函数功能:读出文件内容
*参数:file_length 整型指针,此地址中保存文件字节数。
* lrc_src 文件名字,从此文件中读取内容。
* 返回值:读出字符串的首地址
* 函数中测文件的大小并分配空间,再把文件内容读出到分配的空间中,返回此空间首地址
**************************************************************************/
char *read_src_file(ulint *file_length, char *lrc_src)
{
FILE *fp = NULL;
char *buf = NULL;
fp = fopen(lrc_src,"rb");//以只读方式打开一个二进制文件
if(fp == NULL)
{
printf("Cannot open the flie!\n");
return NULL;
}
fseek(fp,0,SEEK_END);
*file_length = ftell(fp); //获取文件的大小
buf = (char *)malloc(*file_length+1); //
if(buf == NULL)
{
printf("malloc() cannot apply for memory!\n");
goto out;
}
bzero(buf, *file_length+1);
rewind(fp); //
fread(buf,*file_length,1,fp);
out:
fclose(fp);
return buf;
}
#if 1
char *get_musiclist(char ***plist, int *plines)
{
FILE *fp =NULL;
char *buf = NULL;
ulint list_length = 0;
//uint lines = 0;
int part = 0;
system("ls ./music | grep .mp3 >./music/musiclist");
fp = fopen("music/musiclist","rb");
if(fp == NULL)
{
printf("Cannot open the flie!\n");
return NULL;
}
buf = read_src_file(&list_length,"music/musiclist");
*plines = check_lines(list_length, buf);
*plist = (char **)malloc((*plines + 1) * sizeof(char **)); //动态分配空间存储每行的首地址
if(*plist == NULL)
{
goto out;
return NULL;
}
bzero(*plist, *plines+1);
part = src_segment(buf, *plist, "\r\n"); //按行分割
plist[*plines ] = NULL;
#if 0 //
int i, len;
for(i=0;i<part;i++)
{
len = strlen(*(*(plist) + i));
*(*(*(plist) + i) + len -4) = '\0';
//printf("%s\n",plist[i]);
}
#endif
out:
fclose(fp);
return buf;
}
#else
char **get_musiclist()
{
FILE *fp =NULL;
char *buf = NULL, **plist = NULL;
ulint list_length = 0;
uint lines = 0;
int part = 0;
system("ls ./music | grep .mp3 >./music/musiclist");
fp = fopen("music/musiclist","rb");
if(fp == NULL)
{
printf("Cannot open the flie!\n");
return;
}
buf = read_src_file(&list_length,"music/musiclist");
lines = check_lines(list_length, buf);
plist = (char **)malloc((lines + 1) * sizeof(char **)); //动态分配空间存储每行的首地址
if(plist == NULL) return NULL;
part = src_segment(buf, plist, "\r\n"); //按行分割
plist[lines] = NULL;
#if 1
int i, len;
for(i=0;i<part-1;i++)
{
len = strlen(*(*(plist) + i));
//printf("len =%d\n",len);
*(*(*(plist) + i) + len -1) = '\0';
//printf("%s\n",plist[i]);
}
#endif
fclose(fp);
return plist;
}
#endif
int check_lines(ulint file_length, char *src)
{
uint lines = 0;
ulint i = 0;
char *p = NULL;
p = src;
#if 1
for(i = 0;i < file_length;i++)
{
if(p[i]=='\n') lines++;
}
#elif 0 //这种方法不行,因为strchr函数和strstr函数遇到 '\0' 就返回
while(p != NULL)
{
p = strchr(p,'\n');
lines++;
}
#endif
return lines;
}
int get_longestline(int lines, char *plines[])
{
int longestline = 0, temp = 0, i = 0;
for(i=0;i<lines;i++)
{
temp = strlen(plines[i]);
if(temp > longestline) longestline = i;
}
return longestline;
}
int get_chrnumber(char *pbuf, int len)
{
int i = 0,count = 0;
for(i=0;i<len;i++)
{
if(pbuf[i] > 0 && pbuf[i] <127) count++;
}
return count;
}
int get_longestlength(LRC *lrc_head)
{
int longest = 0, temp = 0, chrnum = 0;
if(lrc_head != NULL)
{
LRC *pb = NULL, *pf = NULL;
pb = lrc_head;
while(pb != NULL)
{
temp = strlen(pb->src);
if(temp > longest)
{
pf = pb;
longest = temp;
}
//printf("len=%d %s\n",temp,pb->src);
pb = pb->next;
}
temp = strlen(pf->src);
chrnum = get_chrnumber(pf->src,temp);
longest += chrnum/2;
}
return longest;
}
int get_showoffset(char *pbuf, int longest)
{
int len = 0, offset = 0;
int count = 0;
len = strlen(pbuf);
count = get_chrnumber(pbuf, len);
len += count/2;
offset = (longest - len)/3;
//printf("longest=%d len=%d offset=%d %s\n",longest,len,offset,pbuf);
if(offset < 0) offset = 0; //一定要加此判断
return offset;
}
char get_songname(char *desr, char *src)
{
char *p = NULL;
char buf[256];
bzero(buf,sizeof(buf));
if((p = strstr(src, ".mp3")) != NULL)
{
sscanf(src,"%[^.mp3]",buf);
strcat(buf,".mp3");
strcpy(desr,buf);
return 0;
}
return -1;
}
char get_lrcname(char *src)
{
char *p = NULL;
if((p = strstr(src, ".mp3")) != NULL)
{
*p = '\0';
strcat(src,".lrc");
return 0;
}
return -1;
}
char *transfer_space(char src[])
{
int i = 0, j = 0, len = 0;
int space = 0;
char *pbuf = NULL;
len = strlen(src);
while(src[i])
{
if(src[i] == ' ')
{
space++;
}
i++;
}
pbuf = (char *)malloc(sizeof(char) * (len + space + 2));
if(pbuf == NULL)
{
printf("transfer_space >> malloc failed\n");
return NULL;
}
i = 0;
while(src[i])
{
if(src[i] == ' ')
{
pbuf[j] = '\\';
j++;
}
pbuf[j] = src[i];
j++;
i++;
}
pbuf[j] = '\0';
return pbuf;
}
void delete_dot(char *plist[])
{
int i = 0,len = 0;
for(i=0;plist[i] != NULL;i++)
{
len = strlen(plist[i]);
plist[i][len-1] = '\0';
}
}
void recover_dot(char *plist[])
{
int i = 0,len = 0;
for(i=0;plist[i] != NULL;i++)
{
len = strlen(plist[i]);
plist[i][len] = '.';
}
}
void recover_line_dot(char *plist[],int line_num)
{
int len = 0;
len = strlen(plist[line_num]);
plist[line_num][len] = '.';
}
<file_sep>/work/test/socket/socket_client.c
/*************************************************************************
> File Name: socket_client.c
> Author:
> Mail:
> Created Time: Tue 17 May 2016 11:34:19 AM CST
************************************************************************/
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int main(int argc, char ** argv) {
int sockfd, n;
int my;
char buf[100];
struct sockaddr_in servaddr;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("create socket error\n");
exit(1);
}
bzero(&servaddr, sizeof(struct sockaddr_in));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(atoi(argv[2]));
if(inet_pton(AF_INET, argv[1], &servaddr.sin_addr) < 0) {
printf("inet_pton error\n");
exit(1);
}
if((my = connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))) < 0) {
printf("connect error\n");
exit(1);
}
struct sockaddr_in serv, guest;
int serv_len = sizeof(serv);
int guest_len = sizeof(guest);
char serv_ip[20], guest_ip[20];
getsockname(sockfd, (struct sockaddr *)&guest, &guest_len);
getpeername(sockfd, (struct sockaddr *)&serv, &serv_len);
inet_ntop(AF_INET, &guest.sin_addr, guest_ip, sizeof(guest_ip));
inet_ntop(AF_INET, &serv.sin_addr, serv_ip, sizeof(serv_ip));
printf("host %s:%d, guest %s:%d\n", serv_ip, ntohs(serv.sin_port), guest_ip, ntohs(guest.sin_port));
n = read(sockfd, buf, 100);
buf[n] = '\0';
printf("%s\n", buf);
getchar();
close(sockfd);
exit(0);
}
<file_sep>/sys_program/4th_day/homework/mplayer/interface.h
/* ************************************************************************
* Filename: interface.h
* Description:
* Version: 1.0
* Created: 2015年08月18日 20时42分29秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __INTERFACE_H__
#define __INTERFACE_H__
#include <gtk/gtk.h>
typedef struct _Window
{
GtkWidget *main_window;
GtkWidget *table;
GtkWidget *image;
GtkWidget *button_previous;
GtkWidget *button_next;
GtkWidget *button_pause;
//GtkWidget *progress;
}WINDOW;
extern int fd;
extern int playing;
void show_window(gpointer data);
#endif
<file_sep>/sys_program/player/src/mplayer_ui.c
/* ************************************************************************
* Filename: gtk_button.c
* Description:
* Version: 1.0
* Created: 2015年08月10日 10时14分55秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include "common.h"
#include "file.h"
#include "mplayer_pthread.h"
#include "gtk_callback.h"
#include "mplayer_ui.h"
//MPLAYER mplayer;
SunGtkCList *musiclist = NULL;
static void show_boot_animation(MPLAYER *pm)
{
int i;
char ch[2] = "a";
char path[] = "./image/jpg/";
char jpg[] = ".JPG";
char buf[64];
for(i=0; i<18;i++)
{
bzero(buf, sizeof(buf));
ch[0] += i;
strcat(buf, path);
strcat(buf, ch);
strcat(buf, jpg);
printf("jpg path = %s####\n",buf);
sungtk_background_set_picture(pm->ui.main_window,buf,800, 480);
gtk_widget_show_all(pm->ui.main_window);
ch[0] = 'a';
sleep(1);
}
}
static int hbox_left_init(MPLAYER *pm, GtkBuilder *builder)
{
pm->ui.hbox_left.bmusic_list = GTK_BUTTON(gtk_builder_get_object(builder, "bmusic_list"));
pm->ui.hbox_left.bmusic_collect = GTK_BUTTON(gtk_builder_get_object(builder, "bmusic_collect"));
pm->ui.hbox_left.bmusic_recently = GTK_BUTTON(gtk_builder_get_object(builder, "bmusic_recently"));
gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_list), FALSE);
g_signal_connect(pm->ui.hbox_left.bmusic_list, "clicked", G_CALLBACK(musiclist_buttons_callback), pm);
g_signal_connect(pm->ui.hbox_left.bmusic_collect, "clicked", G_CALLBACK(musiclist_buttons_callback), pm);
g_signal_connect(pm->ui.hbox_left.bmusic_recently,"clicked", G_CALLBACK(musiclist_buttons_callback), pm);
pm->ui.hbox_left.eventbox_musiclist = (GtkEventBox *)(gtk_builder_get_object(builder, "eventbox_musiclist"));
gtk_event_box_set_visible_window(pm->ui.hbox_left.eventbox_musiclist, FALSE); //???
//
pm->ui.hbox_left.button_search= GTK_BUTTON(gtk_builder_get_object(builder, "button_search"));
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_left.button_search), "./image/style/find.png",20,20);
g_signal_connect(GTK_WIDGET(pm->ui.hbox_left.button_search), "clicked", G_CALLBACK(search_entry_callback), pm);
pm->ui.hbox_left.table_search = GTK_TABLE(gtk_builder_get_object(builder, "table_search"));
pm->ui.hbox_left.entry_search = GTK_ENTRY(gtk_entry_new()); //б?
gtk_entry_set_max_length(GTK_ENTRY(pm->ui.hbox_left.entry_search), 30); //б????
gtk_table_attach_defaults(pm->ui.hbox_left.table_search,GTK_WIDGET(pm->ui.hbox_left.entry_search),0,1,0,1); //
g_signal_connect(GTK_WIDGET(pm->ui.hbox_left.entry_search), "activate",G_CALLBACK(search_entry_callback), pm);
pm->ui.hbox_left.table_musiclist = GTK_TABLE(gtk_builder_get_object(builder, "table_musiclist"));
//б
musiclist = sungtk_clist_new();
sungtk_clist_set_row_height(musiclist, 25);
sungtk_clist_set_col_width(musiclist, 200);
sungtk_clist_set_text_size(musiclist, 12);
sungtk_clist_set_select_row_signal(musiclist, "button-release-event", callback_list_release);
gtk_table_attach_defaults(pm->ui.hbox_left.table_musiclist, musiclist->fixed, 1, 4, 1, 5);
//sungtk_clist_append(musiclist, "aaaaaaaaaaa");
//sungtk_clist_append(musiclist, "bbbbbbbbbb");
//sungtk_clist_set_row_color(musiclist, 0, "red");
return 0;
}
static int hbox_right_init(MPLAYER *pm, GtkBuilder *builder)
{
#if 1
pm->ui.hbox_right.button_pause = GTK_BUTTON(gtk_builder_get_object(builder, "button_pause"));
pm->ui.hbox_right.button_back = GTK_BUTTON(gtk_builder_get_object(builder, "button_back"));
pm->ui.hbox_right.button_next = GTK_BUTTON(gtk_builder_get_object(builder, "button_next"));
pm->ui.hbox_right.button_backward= GTK_BUTTON(gtk_builder_get_object(builder, "button_backward"));
pm->ui.hbox_right.button_forward = GTK_BUTTON(gtk_builder_get_object(builder, "button_forward"));
pm->ui.hbox_right.button_volume = GTK_BUTTON(gtk_builder_get_object(builder, "button_volume"));
pm->ui.hbox_right.button_playmode= GTK_BUTTON(gtk_builder_get_object(builder, "button_playmode"));
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_back), "./image/style/back.png",70,70);
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_pause), "./image/style/pause.png",70,70);
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_next), "./image/style/next.png",70,70);
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_backward), "./image/style/backward.png",60,60);
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_forward), "./image/style/forward.png",60,60);
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_volume), "./image/style/beam.png",50,50);
sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_playmode), "./image/style/playmode_list_loop.png",20,20);
g_signal_connect(pm->ui.hbox_right.button_pause, "clicked", G_CALLBACK(music_buttons_callback), pm);
g_signal_connect(pm->ui.hbox_right.button_back, "clicked", G_CALLBACK(music_buttons_callback), pm);
g_signal_connect(pm->ui.hbox_right.button_next, "clicked", G_CALLBACK(music_buttons_callback), pm);
g_signal_connect(pm->ui.hbox_right.button_backward, "clicked", G_CALLBACK(music_buttons_callback), pm);
g_signal_connect(pm->ui.hbox_right.button_forward, "clicked", G_CALLBACK(music_buttons_callback), pm);
g_signal_connect(pm->ui.hbox_right.button_volume, "clicked", G_CALLBACK(music_buttons_callback), pm);
g_signal_connect(pm->ui.hbox_right.button_playmode, "clicked", G_CALLBACK(playmode_button_callback), pm);
#endif
#if 1 //label
pm->ui.hbox_right.label_title1 = GTK_LABEL(gtk_builder_get_object(builder, "label_title1"));
pm->ui.hbox_right.label_title2 = GTK_LABEL(gtk_builder_get_object(builder, "label_title2"));
pm->ui.hbox_right.label_title3 = GTK_LABEL(gtk_builder_get_object(builder, "label_title3"));
pm->ui.hbox_right.label_lrc1 = GTK_LABEL(gtk_builder_get_object(builder, "label_lrc1"));
pm->ui.hbox_right.label_lrc2 = GTK_LABEL(gtk_builder_get_object(builder, "label_lrc2"));
pm->ui.hbox_right.label_lrc3 = GTK_LABEL(gtk_builder_get_object(builder, "label_lrc3"));
pm->ui.hbox_right.label_lrc4 = GTK_LABEL(gtk_builder_get_object(builder, "label_lrc4"));
pm->ui.hbox_right.label_lrc5 = GTK_LABEL(gtk_builder_get_object(builder, "label_lrc5"));
pm->ui.hbox_right.label_lrc6 = GTK_LABEL(gtk_builder_get_object(builder, "label_lrc6"));
pm->ui.hbox_right.label_lrc7 = GTK_LABEL(gtk_builder_get_object(builder, "label_lrc7"));
sungtk_widget_set_font_color(GTK_WIDGET(pm->ui.hbox_right.label_lrc2),"yellow", FALSE);
//char pbuf[] = "heheheh";
gtk_label_set_text(pm->ui.hbox_right.label_title1, "");
gtk_label_set_text(pm->ui.hbox_right.label_title2, "");
gtk_label_set_text(pm->ui.hbox_right.label_title3, "");
gtk_label_set_text(pm->ui.hbox_right.label_lrc1, "");
gtk_label_set_text(pm->ui.hbox_right.label_lrc2, "");
gtk_label_set_text(pm->ui.hbox_right.label_lrc3, "");
gtk_label_set_text(pm->ui.hbox_right.label_lrc4, "");
gtk_label_set_text(pm->ui.hbox_right.label_lrc5, "");
gtk_label_set_text(pm->ui.hbox_right.label_lrc6, "");
gtk_label_set_text(pm->ui.hbox_right.label_lrc7, "");
//sungtk_widget_set_font_color(GTK_WIDGET(pm->ui.hbox_right.label_lrc4),"MedSpringGreen", FALSE);
pm->ui.hbox_right.label_cur_time = GTK_LABEL(gtk_builder_get_object(builder, "label_cur_time"));
pm->ui.hbox_right.label_end_time = GTK_LABEL(gtk_builder_get_object(builder, "label_end_time"));
#endif
pm->ui.hbox_right.progress_bar = GTK_PROGRESS_BAR(gtk_builder_get_object(builder, "progress_bar"));
pm->ui.hbox_right.eventbox_bar = (GtkEventBox *)(gtk_builder_get_object(builder, "eventbox_bar"));
pm->ui.hbox_right.eventbox_volume = (GtkEventBox *)(gtk_builder_get_object(builder, "eventbox_volume"));
gtk_event_box_set_visible_window(pm->ui.hbox_right.eventbox_bar, FALSE);
gtk_event_box_set_visible_window(pm->ui.hbox_right.eventbox_volume,FALSE);
//???
gtk_widget_add_events(GTK_WIDGET(pm->ui.hbox_right.eventbox_bar), GDK_BUTTON_MOTION_MASK);
// "motion-notify-event" motion_event_callback ????
g_signal_connect(GTK_WIDGET(pm->ui.hbox_right.eventbox_bar), "motion-notify-event", G_CALLBACK(motion_event_callback), pm);
pm->ui.hbox_right.image_logo = GTK_IMAGE(gtk_builder_get_object(builder, "image_logo"));
sungtk_image_load_picture(GTK_WIDGET(pm->ui.hbox_right.image_logo), "./image/style/picture.png", 140, 140);
return 0;
}
void window_init(MPLAYER *pm)
{
//创建GtkBuilder对象,GtkBuilder在<gtk/gtk.h>声明
//读取Mplayer.glade文件的信息,保存在builder中
GtkBuilder *builder = gtk_builder_new(); //创建GtkBuilder对象,GtkBuilder在<gtk/gtk.h>声明
if(!gtk_builder_add_from_file(builder,"Mplayer.glade", NULL)) //读取Mplayer.glade文件的信息,保存在builder中
{
printf("connot Mplayer.glade file!");
}
//获取窗口指针,注意"main_window"要和glade里面的标签名词匹配
pm->ui.main_window = GTK_WIDGET(gtk_builder_get_object(builder,"main_window"));
gtk_window_set_title(GTK_WINDOW(pm->ui.main_window), "Mplayer"); // 设置窗口标题
gtk_window_set_position(GTK_WINDOW(pm->ui.main_window), GTK_WIN_POS_CENTER); // 设置窗口在显示器中的位置为居中
gtk_widget_set_size_request(pm->ui.main_window, 800, 480); // 设置窗口的最小大小
gtk_window_set_resizable(GTK_WINDOW(pm->ui.main_window), FALSE); // 固定窗口的大小
//gtk_window_set_decorated(GTK_WINDOW(pm->ui.main_window), FALSE); // 设置无边框
g_signal_connect(pm->ui.main_window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
//show_boot_animation(pm);
sungtk_background_set_picture(pm->ui.main_window,"./image/background/11.jpg",800, 480);
hbox_left_init(pm, builder); //
hbox_right_init(pm, builder); //
gtk_widget_show_all(pm->ui.main_window);
}
void mplayer_ui_show(int argc, char *argv[], MPLAYER *pm)
{
pm->playflag = stop; //暂停
pm->soundflag = beam; //播音
gtk_init(&argc, &argv);
window_init(pm);
gtk_main();
}
<file_sep>/work/test/cim_test-zmm220/yuv2jpg.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <jpeglib.h>
#include <jerror.h>
#define uint8 unsigned char
//write_JPEG_file (char * filename, int quality,int image_width,int image_height)
void write_JPEG_file (char * filename, int quality,int image_width,int image_height, unsigned char **yuv_data)
{
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
FILE * outfile; /* target file */
// JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
// int row_stride; /* physical row width in image buffer */
JSAMPIMAGE buffer;
int band,i,buf_width[3],buf_height[3];
int mem_size,max_line, counter;
uint8 *pSrc, *pDst;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
if ((outfile = fopen(filename, "wb")) == NULL) {
fprintf(stderr, "can't open %s\n", filename);
exit(1);
}
jpeg_stdio_dest(&cinfo, outfile);
cinfo.image_width = image_width; /* image width and height, in pixels */
cinfo.image_height = image_height;
cinfo.input_components = 3; /* # of color components per pixel */
cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, quality, TRUE );
//////////////////////////////
cinfo.raw_data_in = TRUE;
cinfo.jpeg_color_space = JCS_YCbCr;
cinfo.comp_info[0].h_samp_factor = 2;
cinfo.comp_info[0].v_samp_factor = 1;
/////////////////////////
jpeg_start_compress(&cinfo, TRUE);
buffer = (JSAMPIMAGE) (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo,
JPOOL_IMAGE, 3*sizeof(JSAMPARRAY));
for(band=0; band<3; band++)
{
buf_width[band] = cinfo.comp_info[band].width_in_blocks * DCTSIZE;
buf_height[band] = cinfo.comp_info[band].v_samp_factor * DCTSIZE;
buffer[band] = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo,
JPOOL_IMAGE, buf_width[band], buf_height[band]);
}
max_line = cinfo.max_v_samp_factor*DCTSIZE;
for(counter=0; cinfo.next_scanline < cinfo.image_height; counter++)
{
//buffer image copy.
for(band=0; band<3; band++)
{
mem_size = buf_width[band];
pDst = (uint8 *) buffer[band][0];
// pSrc = (uint8 *) yuv.data[band] + //yuv.data[band]分别表示YUV起始地址
pSrc = (uint8 *) yuv_data[band] + //yuv.data[band]分别表示YUV起始地址
counter*buf_height[band] * buf_width[band];
for(i=0; i<buf_height[band]; i++)
{
memcpy(pDst, pSrc, mem_size);
pSrc += buf_width[band];
pDst += buf_width[band];
}
}
jpeg_write_raw_data(&cinfo, buffer, max_line);
}
jpeg_finish_compress(&cinfo);
fclose(outfile);
jpeg_destroy_compress(&cinfo);
}
//int main()
//{
// return 0;
//}
<file_sep>/c/practice/1st_week/math/mymath.c
/* ************************************************************************
* Filename: sum.c
* Description:
* Version: 1.0
* Created: 2015年07月16日 星期四 02時11分45秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <string.h>
int sum(int a,int b)
{
return a+b;
}
int abs(int n)
{
return n>0?n:~n;
}
void Bubbing_Methed(char *p)
{
int length = 0;
length = strlen(p);
printf("%d\n",length);
}
<file_sep>/sys_program/4th_day/homework/chat/chat.c
/* ************************************************************************
* Filename: chat.c
* Description:
* Version: 1.0
* Created: 2015年08月18日 17时47分59秒
* Revision: none
* Compiler: gcc
* Author: 王秋伟
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>
#include <unistd.h>
#include <fcntl.h>
#if defined (P)
char name[] = "Peter";
#elif defined (L)
char name[] = "Lucy";
#elif defined (B)
char name[] = "Bob";
#endif
typedef struct _msg
{
long type;
char msg[256];
}MSG;
int main(int argc, char *argv[])
{
key_t key;
pid_t pid;
MSG snd,rcv;
int id;
key = ftok("./",23); //获取key 值
id = msgget(key, IPC_CREAT | 0666); //打开或创建消息队列
if(id == -1) //出错退出
{
perror("");
exit(-1);
}
printf("Hi, I am %s\n",name);
pid = fork(); //创建子进程
if(pid < 0) //出错退出
{
perror("");
exit(-1);
}
else if(pid == 0) //子进程
{
int len = 0, i;
char buf[256] = "";
while(1)
{
printf("%s: ",name);
fflush(stdout);
fgets(buf,sizeof(buf),stdin);
len = strlen(buf);
if(len > 3)
{
char msg[256] = "";
buf[len-1] = '\0';
for(i=0;i < len-1;i++)
{
if(buf[i] == 'P' || buf[i] == 'L' || buf[i] == 'B' && buf[i+1] == ' ')
{
if(buf[i] == name[0]) //判断是不是给自己发信息
{
break; //给自己发信息直接退出,不写入消息队列
}
snd.type = buf[i];
buf[i] = ':';
strcat(msg,name);
strcat(msg, buf+i);
strcpy(snd.msg, msg);
msgsnd(id, &snd, sizeof(snd) - sizeof(long) , 0);
break;
}
}
}
}
}
else //父进程
{
while(1)
{
bzero(rcv.msg, sizeof(rcv.msg));
#if defined (P)
msgrcv(id, &rcv,sizeof(rcv) - sizeof(long), (long)('P'), 0);
#elif defined (L)
msgrcv(id, &rcv,sizeof(rcv) - sizeof(long), (long)('L'), 0);
#elif defined (B)
msgrcv(id, &rcv,sizeof(rcv) - sizeof(long), (long)('B'), 0);
#endif
printf("\r%s\n",rcv.msg);
printf("%s: ",name);
fflush(stdout);
}
}
//printf("name = %s\n",name);
return 0;
}
<file_sep>/work/debug/ingenic/wiegand/wiegand_in.c
/*
* Copyright (C) 2012 Ingenic Semiconductor Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/miscdevice.h>
#include <linux/spinlock.h>
#include <linux/wakelock.h>
#include <linux/clk.h>
#include <linux/syscalls.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/gpio.h>
#include <linux/spinlock.h>
#include <linux/poll.h>
#include <linux/hrtimer.h>
#include <linux/wait.h>
#include <linux/time.h>
#include <linux/kernel.h>
#include <linux/wiegand.h>
#include <linux/module.h>
#define WIEGANDINDRV_LIB_VERSION "1.0.1 ZLM60"__DATE__ /* DRV LIB VERSION */
#define DEF_PULSE_WIDTH 100 //us
#define DEF_PULSE_INTERVAL 1000 //us
#define DEF_DATA_LENGTH 26 //bit
#define DEVIATION 100 //us
struct wiegand_in_dev {
struct device *dev;
struct miscdevice mdev;
unsigned int data0_pin;
unsigned int data1_pin;
unsigned int current_data[2];
unsigned int wiegand_in_data[2];
int data_length;
int recvd_length;
int pulse_width;
int pulse_intval;
int error;
spinlock_t lock;
int use_count;
struct hrtimer timer;
wait_queue_head_t wq;
struct timeval latest;
struct timeval now;
};
static void wiegand_in_data_reset(struct wiegand_in_dev *wiegand_in)
{
wiegand_in->recvd_length = -1;
wiegand_in->current_data[0] = 0;
wiegand_in->current_data[1] = 0;
wiegand_in->wiegand_in_data[0] = 0;
wiegand_in->wiegand_in_data[1] = 0;
wiegand_in->error = 0;
}
static int wiegand_in_open(struct inode *inode, struct file *filp)
{
struct miscdevice *dev = filp->private_data;
struct wiegand_in_dev *wiegand_in = container_of(dev, struct wiegand_in_dev, mdev);
spin_lock(&wiegand_in->lock);
if (wiegand_in->use_count > 0) {
spin_unlock(&wiegand_in->lock);
return -EBUSY;
}
wiegand_in->use_count++;
spin_unlock(&wiegand_in->lock);
wiegand_in_data_reset(wiegand_in);
enable_irq(gpio_to_irq(wiegand_in->data0_pin));
enable_irq(gpio_to_irq(wiegand_in->data1_pin));
return 0;
}
static int wiegand_in_release(struct inode *inode, struct file *filp)
{
struct miscdevice *dev = filp->private_data;
struct wiegand_in_dev *wiegand_in = container_of(dev, struct wiegand_in_dev, mdev);
disable_irq(gpio_to_irq(wiegand_in->data0_pin));
disable_irq(gpio_to_irq(wiegand_in->data1_pin));
spin_lock(&wiegand_in->lock);
wiegand_in->use_count--;
spin_unlock(&wiegand_in->lock);
return 0;
}
static ssize_t wiegand_in_read(struct file *filp, char *buf, size_t size, loff_t *l)
{
struct miscdevice *dev = filp->private_data;
struct wiegand_in_dev *wiegand_in = container_of(dev, struct wiegand_in_dev, mdev);
if (filp->f_flags & O_NONBLOCK)
return -EAGAIN;
if (wait_event_interruptible(wiegand_in->wq,
(wiegand_in->wiegand_in_data[0] > 0) || (wiegand_in->error)))
return -ERESTARTSYS;
if(wiegand_in->wiegand_in_data[0] > 0) {
if(copy_to_user(buf, wiegand_in->wiegand_in_data,
sizeof(wiegand_in->wiegand_in_data)))
return -EFAULT;
wiegand_in->wiegand_in_data[0] = 0;
wiegand_in->wiegand_in_data[1] = 0;
return sizeof(wiegand_in->wiegand_in_data);
}
wiegand_in->error = 0;
return 0;
}
static unsigned int wiegand_in_poll(struct file *filp, poll_table *wait)
{
unsigned int mask = 0;
struct miscdevice *dev = filp->private_data;
struct wiegand_in_dev *wiegand_in = container_of(dev, struct wiegand_in_dev, mdev);
poll_wait(filp, &wiegand_in->wq, wait);
if( wiegand_in->wiegand_in_data[0] )
mask |= POLLIN | POLLRDNORM;
return mask;
}
static long wiegand_in_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct miscdevice *dev = filp->private_data;
struct wiegand_in_dev *wiegand_in = container_of(dev, struct wiegand_in_dev, mdev);
int cs;
switch (cmd) {
case WIEGAND_PULSE_WIDTH:
{
if(get_user(cs, (unsigned int *)arg))
return -EINVAL;
wiegand_in->pulse_width = cs;
break;
}
case WIEGAND_PULSE_INTERVAL:
{
if(get_user(cs, (unsigned int *)arg))
return -EINVAL;
wiegand_in->pulse_intval = cs;
break;
}
case WIEGAND_FORMAT:
{
if(get_user(cs, (unsigned int *)arg))
return -EINVAL;
wiegand_in->data_length = cs;
break;
}
case WIEGAND_READ:
{
if(wiegand_in->wiegand_in_data[0]) {
if( copy_to_user((unsigned int *)arg,
wiegand_in->wiegand_in_data, sizeof(wiegand_in->wiegand_in_data)))
return -EFAULT;
wiegand_in->wiegand_in_data[0] = 0;
wiegand_in->wiegand_in_data[1] = 0;
}
break;
}
case WIEGAND_STATUS:
{
if(wiegand_in->wiegand_in_data[0] == 0)
cs = 0;
else
cs = 1;
if(put_user(cs, (unsigned int *)arg))
return -EINVAL;
break;
}
default:
return -EINVAL;
}
return 0;
}
static struct file_operations wiegand_in_misc_fops = {
.open = wiegand_in_open,
.release = wiegand_in_release,
.read = wiegand_in_read,
.unlocked_ioctl = wiegand_in_ioctl,
.poll = wiegand_in_poll,
};
static void wiegand_in_check_data(struct wiegand_in_dev *wiegand_in)
{
if (wiegand_in->recvd_length == wiegand_in->data_length - 1) {
memcpy(wiegand_in->wiegand_in_data, wiegand_in->current_data, sizeof(wiegand_in->current_data));
wiegand_in->recvd_length = -1;
wiegand_in->current_data[0] = 0;
wiegand_in->current_data[1] = 0;
wake_up_interruptible(&wiegand_in->wq);
} else {
printk("recvd data error: received length = %d, required length = %d\n",
wiegand_in->recvd_length, wiegand_in->data_length);
wiegand_in_data_reset(wiegand_in);
wiegand_in->error = 1;
wake_up_interruptible(&wiegand_in->wq);
}
}
static enum hrtimer_restart wiegand_in_timeout(struct hrtimer * timer)
{
struct wiegand_in_dev *wiegand_in = container_of(timer, struct wiegand_in_dev, timer);
wiegand_in_check_data(wiegand_in);
return HRTIMER_NORESTART;
}
static void wiegand_in_reset_timer(struct wiegand_in_dev *wiegand_in)
{
int us = (wiegand_in->pulse_width + wiegand_in->pulse_intval)
* wiegand_in->data_length;
int s = us / 1000000;
ktime_t time = ktime_set(s, (us % 1000000) * 1000);
hrtimer_start(&wiegand_in->timer, time, HRTIMER_MODE_REL);
}
static int wiegand_in_check_irq(struct wiegand_in_dev *wiegand_in)
{
int diff;
if (wiegand_in->recvd_length < 0) {
do_gettimeofday(&wiegand_in->latest);
return 0;
}
/* Check how much time we have used already */
do_gettimeofday(&wiegand_in->now);
diff = wiegand_in->now.tv_usec - wiegand_in->latest.tv_usec;
/* check fake interrupt */
if (diff < wiegand_in->pulse_width )//+ wiegand_in->pulse_intval - DEVIATION)
return -1;
/*
* if intarval is greater than DEVIATION,
* then cheet it as beginning of another scan
* and discard current data
*/
else if (diff > wiegand_in->pulse_width + wiegand_in->pulse_intval
+ ((wiegand_in->pulse_width + wiegand_in->pulse_intval)<<1)) {
hrtimer_cancel(&wiegand_in->timer);
wiegand_in_data_reset(wiegand_in);
return -1;
}
wiegand_in->latest.tv_sec = wiegand_in->now.tv_sec;
wiegand_in->latest.tv_usec = wiegand_in->now.tv_usec;
return 0;
}
static irqreturn_t wiegand_in_interrupt(int irq, void *dev_id)
{
struct wiegand_in_dev *wiegand_in = (struct wiegand_in_dev *)dev_id;
if (wiegand_in_check_irq(wiegand_in))
return IRQ_HANDLED;
if (wiegand_in->recvd_length < 0)
wiegand_in_reset_timer(wiegand_in);
wiegand_in->recvd_length++;
wiegand_in->current_data[1] <<= 1;
wiegand_in->current_data[1] |= ((wiegand_in->current_data[0] >> 31) & 0x01);
wiegand_in->current_data[0] <<= 1;
if (irq == gpio_to_irq(wiegand_in->data1_pin))
wiegand_in->current_data[0] |= 1;
return IRQ_HANDLED;
}
static int wiegand_in_probe(struct platform_device *pdev)
{
int ret;
struct wiegand_in_dev *wiegand_in;
struct wiegand_platform_data *pdata;
printk(" WIEGAND IN VERSION = %s \n",WIEGANDINDRV_LIB_VERSION);
pdata = dev_get_platdata(&pdev->dev);
if (!pdata) {
dev_err(&pdev->dev, "Failed to get platform_data %s %d.\n", __FUNCTION__, __LINE__);
return -ENXIO;
}
wiegand_in = kzalloc(sizeof(struct wiegand_in_dev), GFP_KERNEL);
if (!wiegand_in) {
printk("%s: alloc mem failed.\n", __FUNCTION__);
ret = -ENOMEM;
}
#if 1
wiegand_in->data0_pin = pdata->data1_pin;
wiegand_in->data1_pin = pdata->data0_pin;
#else
wiegand_in->data0_pin = pdata->data0_pin;
wiegand_in->data1_pin = pdata->data1_pin;
#endif
if (gpio_is_valid(wiegand_in->data0_pin)) {
ret = gpio_request(wiegand_in->data0_pin, "WIEGAND_IN_DATA0");
gpio_direction_input(wiegand_in->data0_pin);
if (ret < 0) {
printk("ERROR: request wiegand_in_data0 gpio failed.\n");
goto err_gpio_request0;
}
}
else {
printk("ERROR: wiegand_in_data0 gpio is invalid.\n");
goto err_gpio_request0;
}
if (gpio_is_valid(wiegand_in->data1_pin)) {
ret = gpio_request(wiegand_in->data1_pin, "WIEGAND_IN_DATA1");
gpio_direction_input(wiegand_in->data1_pin);
if (ret < 0) {
printk("ERROR: request wiegand_in_data1 gpio failed.\n");
goto err_gpio_request1;
}
}
else {
printk("ERROR: wiegand_in_data1 gpio is invalid.\n");
goto err_gpio_request1;
}
ret = request_irq(gpio_to_irq(wiegand_in->data0_pin),
wiegand_in_interrupt,
IRQF_DISABLED |
IRQF_TRIGGER_FALLING,
"wiegand_in_data0", wiegand_in);
if (ret < 0) {
printk("ERROR: request wiegand_in_data0 irq failed.\n");
goto err_request_irq0;
}
disable_irq(gpio_to_irq(wiegand_in->data0_pin));
ret = request_irq(gpio_to_irq(wiegand_in->data1_pin),
wiegand_in_interrupt,
IRQF_DISABLED |
IRQF_TRIGGER_FALLING,
"wiegand_in_data1", wiegand_in);
if (ret < 0) {
printk("ERROR: request wiegand_in_data1 irq failed.\n");
goto err_request_irq1;
}
disable_irq(gpio_to_irq(wiegand_in->data1_pin));
wiegand_in->dev = &pdev->dev;
wiegand_in->mdev.minor = MISC_DYNAMIC_MINOR;
wiegand_in->mdev.name = "wiegand_in";
wiegand_in->mdev.fops = &wiegand_in_misc_fops;
wiegand_in_data_reset(wiegand_in);
wiegand_in->pulse_width = DEF_PULSE_WIDTH;
wiegand_in->pulse_intval = DEF_PULSE_INTERVAL;
wiegand_in->data_length = DEF_DATA_LENGTH;
spin_lock_init(&wiegand_in->lock);
init_waitqueue_head(&wiegand_in->wq);
hrtimer_init(&wiegand_in->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
wiegand_in->timer.function = wiegand_in_timeout;
ret = misc_register(&wiegand_in->mdev);
if (ret < 0) {
dev_err(&pdev->dev, "misc_register failed %s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
goto err_registe_misc;
}
platform_set_drvdata(pdev, wiegand_in);
printk("Weigand in driver register success.\n");
return 0;
err_registe_misc:
free_irq(gpio_to_irq(wiegand_in->data1_pin), NULL);
err_request_irq1:
free_irq(gpio_to_irq(wiegand_in->data0_pin), NULL);
err_request_irq0:
gpio_free(wiegand_in->data1_pin);
err_gpio_request1:
gpio_free(wiegand_in->data0_pin);
err_gpio_request0:
kfree(wiegand_in);
return ret;
}
static int wiegand_in_remove(struct platform_device *dev)
{
struct wiegand_in_dev *wiegand_in = platform_get_drvdata(dev);
misc_deregister(&wiegand_in->mdev);
free_irq(gpio_to_irq(wiegand_in->data0_pin), wiegand_in);
free_irq(gpio_to_irq(wiegand_in->data1_pin), wiegand_in);
gpio_free(wiegand_in->data0_pin);
gpio_free(wiegand_in->data1_pin);
kfree(wiegand_in);
return 0;
}
static struct platform_driver wiegand_in_driver = {
.probe = wiegand_in_probe,
.remove = wiegand_in_remove,
.driver = {
.name = "wiegand_in",
},
};
static int __init wiegand_in_init(void)
{
return platform_driver_register(&wiegand_in_driver);
}
static void __exit wiegand_in_exit(void)
{
platform_driver_unregister(&wiegand_in_driver);
}
module_init(wiegand_in_init);
module_exit(wiegand_in_exit);
MODULE_LICENSE("GPL");
<file_sep>/sys_program/player/src/inc/include.h
/* ************************************************************************
* Filename: include.h
* Description:
* Version: 1.0
* Created: 2015年08月25日 08时02分50秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __INCLUDE_H__
#define __INCLUDE_H__
#endif
<file_sep>/c/lrc/file.h
/* ************************************************************************
* Filename: file.h
* Description:
* Version: 1.0
* Created: 2015年07月31日 星期五 05時35分49秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __FILE_H__
#define __FILE_H__
#include "common.h"
char * read_src_file(ulint *file_length, char *lrc_src);
//char **get_musiclist();
char *get_musiclist(char ***plist);
void delete_dot(char *plist[]);
void recover_dot(char *plist[]);
int check_lines(ulint file_length, char *lrc_src);
int get_longestline(int lines, char *plines[]);
int get_longestlength(LRC *lrc_head);
int get_showoffset(char *pbuf, int longest);
int get_chrnumber(char *pbuf, int len);
#endif
<file_sep>/network/1st_day/test.c
/* ************************************************************************
* Filename: test.c
* Description:
* Version: 1.0
* Created: 2015年09月11日 14时42分35秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define uchar unsigned char
#define uint unsigned int
#define uint16 unsigned short
#define TRUE (1)
#define FALSE (0)
const char *rules[] = {
"ip",
"mac",
"port",
"arp",
"tcp",
"udp",
"icmp",
"igmp",
"http",
"tftp",
};
unsigned int iptoun_btol(unsigned char *ip)
{
unsigned int ip_val = 0;
ip_val = ip[0]<<24 | ip[1]<<16 | ip[2]<<8 | ip[3]; //如果把 “|” 换成 “+”,得到的结果是0
return ip_val;
}
unsigned int iptoun_btob(unsigned char *ip)
{
unsigned int ip_val = 0;
//ip_val = ip[3]<<24 | ip[2]<<16 | ip[1]<<8 | ip[0];
ip_val = *(unsigned int *)ip;
return ip_val;
}
char check_if_same_subnet(uchar eth_mask[], uchar eth_ip[], uchar dst_ip[])
{
if(((*(uint *)eth_ip) & (*(uint *)eth_mask)) ==\
((*(uint *)dst_ip) & (*(uint *)eth_mask)))
return TRUE;
else
return FALSE;
}
#if 1
int main(int argc, char *argv[])
{
uchar buf[64] = "";
int len =0;
char tt[] = "5557";
len = atoi(tt);
printf("##%d\n",len);
fgets(buf, 64, stdin);
len = strlen(buf);
buf[len] = 0;
printf("%d\n", buf[0]);
}
#elif 0
int main(int argc, char *argv[])
{
uchar ip[16] = "10.221.2.12";
uchar part[4][6];
bzero(part, sizeof(part));
sscanf(ip, "%s.%s.%s.%s", *(part+0), *(part+1), *(part+2), *(part+3));
printf("%s #%s #%s #%s\n",*(part+0), *(part+1), *(part+2), *(part+3));
#if 0
int p[4];
sscanf("10.221..12", "%d.%d.%d.%d", (int *)&p[0],(int *)&p[1],(int *)&p[2],(int *)&p[3]);
printf("%d %d %d %d\n",p[0],p[1],p[2],p[3]);
#endif
return 0;
}
#elif 0
int main(int argc, char *argv[])
{
uchar part[2][18];
uchar type[16];
uchar port[16];
uchar ip[4] = {10,221,2,12};
uchar src_ip[16] = "";
uchar dst_ip[16] = "";
uint16 port_val = 0;
uint16 temp = 8000;
char rule[30] = "ip 10.221.2.12";
//提取源ip
sprintf(src_ip,"%d.%d.%d.%d",\
ip[0],ip[1],ip[2],ip[3]);
sscanf(rule, "%*s %s %s", *(part+0), *(part+1));
int len = strlen(*(part+1));
printf("len = %d\n",len);
if(strcmp(src_ip, *(part+1)) == 0) printf("****OK\n");
#if 0
sscanf(rule, "%*s %s %s", type, port);
port_val = (uint16)atoi(port);
if(port_val == temp) printf("***OK\n");
return 0;
#endif
}
#elif 0
typedef struct _arphdr
{
uint16 ar_hrd;
uint16 ar_pro;
uchar ar_hln;
uchar ar_pln;
uint16 ar_op;
uchar src_mac[6];
uchar src_ip[4];
uchar dst_mac[6];
uchar dst_ip[4];
}ARP_Hdr;
int main(int argc, char *argv[])
{
uchar msg[256] = {
//-----组mac----14----
0xff,0xff,0xff,0xff,0xff,0xff,//dst_mac: ff:ff:ff:ff:ff:ff
0x00,0x00,0x00,0x00,0x00,0x00,//src_mac:
0x08,0x06, //类型: 0x0806 ARP协议
//-----组ARP----28----
0x00,0x01,0x08,0x00, //硬件类型1(以太网地址),协议类型:0x800(IP)
0x06,0x04,0x00,0x01, //硬件、协议的地址长度分别为6和4,ARP请求
0x00,0x00,0x00,0x00,0x00,0x00,//发送端的mac
0, 0, 0, 0, //发送端的ip
0x00,0x00,0x00,0x00,0x00,0x00,//目的mac(获取对方的mac,设置为0)
10, 221, 2, 221, //目的ip
};
unsigned char p[4] = "";
ARP_Hdr *arp = NULL;
arp = (ARP_Hdr *)(msg+14);
if(ntohs(arp->ar_op) == 1) printf("arp request\n");
else if(arp->ar_op == 2) printf("arp reply\n");
printf("dst_ip:%d\n",iptoun_btol(arp->dst_ip));
unsigned char ip[4] = {10,221,2,221};
sscanf("10.221.2.12", "%d.%d.%d.%d", (int *)&p[0],(int *)&p[1],(int *)&p[2],(int *)&p[3]);
printf("%d %d %d %d\n",p[0],p[1],p[2],p[3]);
printf("iptoun_btol -- ip=%d\n",iptoun_btol(ip));
printf("rules count=%d\n", sizeof(rules)/sizeof(rules[0]));
return 0;
}
#elif 0
int main(int argc, char *argv[])
{
unsigned char ip[4] = {10,221,2,221};
unsigned char ip2[4] = {192,221,2,1};
unsigned char mask[4] = {255,255,255,0};
unsigned int ip_val = 0, ip_val2 = 0, mask_val = 0;
uchar ty[2] = {0x08,0x00};
unsigned short type = 0;
type = ntohs(*(uint16 *)(ty));
printf("type=%d, %d\n", type, 0x0800);
(*(uint *)ip) = ((*(uint *)ip) & (*(uint *)mask));
printf("%d.%d.%d.%d\n",ip[0],ip[1],ip[2],ip[3]);
char flag = check_if_same_subnet(mask,ip,ip2);
if(flag == TRUE) printf("OK####\n");
else printf("NO*****\n");
//printf("%s\n",((*(uint *)ip) & (*(uint *)mask)));
#if 0
printf("IP:%s\n",(char*)inet_ntoa(ip));
ip_val = ntohl(*(unsigned int *)ip);
printf("ntohl-- ip_val=%d\n",ip_val);
ip_val = iptoun_btol(ip);
printf("iptoun_btol-- ip_val=%d\n",ip_val);
ip_val = htonl(*(unsigned int *)ip);
printf("htonl-- ip_val=%d\n",ip_val);
ip_val = iptoun_btob(ip);
printf("iptoun_btob -1- ip_val=%u\n",ip_val);
ip_val2 = iptoun_btob(ip2);
printf("iptoun_btob -2- ip_val=%u\n",ip_val2);
printf("iptoun_btob -2- ip_val=%u\n",*(unsigned int *)ip2);
if(ip_val2 > ip_val) printf("good\n");
ip_val = ntohl(ip_val2);
printf("iptoun_btol -2- ip_val=%d\n",ip_val);
#endif
return 0;
}
#endif
<file_sep>/network/sockets/GetAddrInfo.c
/*************************************************************************
> File Name: GetAddrInfo.c
> Author:
> Mail:
> Created Time: Fri 06 May 2016 09:20:10 AM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include "Practical.h"
int main(int argc, char *argv[])
{
if(argc != 3)
DieWithUserMessage("Parameter(s)","<Address/Name> <Port/Service");
char *addrString = argv[1];
char *portString = argv[2];
//Tell the system what kind(s) of address info we want
struct addrinfo addrCriterial;
memset(&addrCriterial, 0, sizeof(addrCriterial));
addrCriterial.ai_family = AF_UNSPEC;
addrCriterial.ai_socktype = SOCK_STREAM;
addrCriterial.ai_protocol = IPPROTO_TCP;
//Get address(es) associated with the specified name/Service
struct addrinfo *addrList;
int rtnVal = getaddrinfo(addrString, portString, &addrCriterial, &addrList);
if(rtnVal != 0)
DieWithUserMessage("getaddrinfo() failed",gai_strerror(rtnVal));
//Display returned addresses
struct addrinfo *addr;
for(addr = addrList; addr != NULL; addr = addr->ai_next) {
PrintSocketAddress(addr->ai_addr, stdout);
fputc('\n', stdout);
}
freeaddrinfo(addrList); //Free addrinfo allocated in getaddrinfo()
exit(0);
}
<file_sep>/c/homework/3rd_week/atoi/myatoi.c
/* ************************************************************************
* Filename: myatoi.c
* Description:
* Version: 1.0
* Created: 2015年07月27日 星期一 02時24分00秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <string.h>
#include <math.h>
int myatoi(char *src)
{
int i = 0;
int len = 0, res = 0;
len = strlen(src);
for(i=0;i<len;i++)
{
res += pow(10,len-i-1) * (src[i]-48);
}
return res;
}
void main()
{
char c[]="12345";
printf("%d\n",myatoi(c));
}
<file_sep>/network/6th_day/libnet_test.c
/* ************************************************************************
* Filename: libnet_test.c
* Description:
* Version: 1.0
* Created: 2015年09月10日 10时13分29秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libnet.h>
int main(int argc, char *argv[])
{
char msg[1024] = "1_lbt6_56#128#7427EAB366CA#0#0#0#4000#9:666666:szb05:SZ-B05:32:";
char buf[1024] = "";
char err_buf[100] = "";
unsigned char dst_mac[6] = {0xec,0xa8,0x6b,0xac,0xcf,0xf9};
unsigned char src_mac[6] = {0x00,0x0c,0x29,0xe4,0xd3,0xd6};
char *dst_ip_str = "10.221.2.12";
char *src_ip_str = "10.221.2.221";
unsigned long dst_ip, src_ip;
libnet_t *plib_hdr = NULL;
libnet_ptag_t ptag1 = 0, ptag2 = 0, ptag3 = 0;
fgets(buf, sizeof(buf), stdin);
int len = strlen(buf);
buf[--len] = 0;
strcat(msg,buf);
len = strlen(msg);
plib_hdr = libnet_init(LIBNET_LINK_ADV, "eth0", err_buf);
if(NULL == plib_hdr)
{
perror("");
exit(-1);
}
src_ip = libnet_name2addr4(plib_hdr, src_ip_str, LIBNET_RESOLVE);
dst_ip = libnet_name2addr4(plib_hdr, dst_ip_str, LIBNET_RESOLVE);
ptag1 = libnet_build_udp(2425, 2425, 8+len, 0, msg, len, plib_hdr, 0);
ptag2 = libnet_build_ipv4(20+8+len,0,0,0,128,17,0,src_ip,dst_ip,NULL,0,plib_hdr,0);
ptag3 = libnet_build_ethernet((u_int8_t *)dst_mac,(u_int8_t *)src_mac,ETHERTYPE_IP,NULL,0,plib_hdr,0);
libnet_write(plib_hdr);
libnet_destroy(plib_hdr);
return 0;
}
<file_sep>/sys_program/4th_day/homework/mplayer/Makefile
CC := gcc
SRC := $(shell ls *.c)
#OBJ := $(patsubst %.c,%.o,$(SRC))
OBJ := $(SRC:%.c=%.o)
TAG := elf
CFLAGS = `pkg-config --cflags --libs gtk+-2.0`
$(TAG):$(OBJ)
$(CC) -o $@ $^ $(CFLAGS) -lpthread
%.o:%.c
$(CC) -o $@ -c $< $(CFLAGS) -lpthread
.PHONY:clean
clean:
rm -f $(TAG) *.o *~
<file_sep>/network/1st_day/Makefile
all:qq yy
qq:qq.c
gcc -o qq qq.c -lpthread
yy:qq.c
gcc -o yy qq.c -lpthread
.PHONY:clean
clean:
rm qq yy
<file_sep>/c/homework/3rd_week/message/main.c
/* ************************************************************************
* Filename: message.c
* Description:
* Version: 1.0
* Created: 2015年07月27日 星期一 11時55分11秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "msg.h"
void main()
{
char msg_src[]={"+CMGR:REC UNREAD,+8613466630259,98/10/01,18:22:11+00,ABCdefGHI"};
char *msg_done[5] = {NULL};
msg_deal(msg_src,msg_done,",");
show_message(msg_done);
}
<file_sep>/sys_program/1st_day/cp/Makefile
CC := gcc
SRC := $(shell ls *.c)
OBJ := $(patsubst %.c,%.o,$(SRC))
#OBJ := $(SRC:%.c=%.o)
TAG := cp
CFLAG := -lm
$(TAG):$(OBJ)
$(CC) -o $@ $^ $(CFLAG)
%.o:%.c
$(CC) -o $@ -c $< $(CFLAG)
.PHONY:clean
clean:
rm -f $(TAG) $(OBJ)
<file_sep>/network/1st_day/udp_server.c
/* ************************************************************************
* Filename: udp_server.c
* Description:
* Version: 1.0
* Created: 2015年08月31日 17时33分36秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
//创建一个通信socket
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
//作为一个服务器应该有一个固定的ip、port
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8030);
//INADDR_ANY: 通配地址
addr.sin_addr.s_addr = htonl(INADDR_ANY);
//bind只能bind自己的ip
bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
//定义保存接收信息的源地址信息
char buf[128];
char ip_buf[INET_ADDRSTRLEN] = ""; //INET_ADDRSTRLEN = 16
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
bzero(&client_addr, sizeof(client_addr));
//接收client发送来的数据
recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&client_addr, &client_len);
inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, ip_buf, INET_ADDRSTRLEN);
printf("ipaddr:%s\n",ip_buf);
//printf("ipaddr:%d\n",ntohl(client_addr.sin_addr.s_addr));
printf("port :%d\n",ntohs(client_addr.sin_port));
printf("buf = %s\n",buf);
return 0;
}
<file_sep>/network/4th_day/webserver.c
/* ************************************************************************
* Filename: webserver.c
* Description:
* Version: 1.0
* Created: 2015年09月06日 11时36分46秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
char const err[] = "HTTP/1.1 404 Not Fount\n\
Server:Apache Tomcat/5.0.12\n\
Content-Type:text/html\n\
Content-Length:43\n\
<HTML><BODY>File not Fount</BODY></HTML>";
char const *ack[] ={"HTTP/1.1 200 OK\r\n",
"Server:Apache Tomcat/5.0.12\r\n",
"Content-Type:text/html\r\n",
"Content-Length:",
"\r\n"
};
void *server_fun(void *arg)
{
FILE *fp = NULL;
int connfd = (int)arg;
int len = 0;
char msg[512] = "";
char html[256]= "";
char path[256]= "./html/";
bzero(msg, sizeof(msg));
len = recv(connfd, msg, sizeof(msg),0);
sscanf(msg,"GET /%[^ ]",html);
//printf("html = ###%s###\n",html);
//printf("msg = %s\n", msg);
strcat(path,html);
printf("path = %s\n",path);
fp = fopen(path,"rb");
if(fp == NULL)
{
printf("Not fount file\n");
send(connfd, err, sizeof(err), 0);
close(connfd);
pthread_exit(NULL);//退出线程
}
//fseek(fp,0,SEEK_END);
//len = ftell(fp); //获取文件的大小
//sprintf(msg, "%s%d%s", ack[4],len,"\r\n");
//printf("msg = %s\n",msg);
send(connfd,ack[0],strlen(ack[0]),0);
//send(connfd,ack[1],strlen(ack[1]),0);
send(connfd,ack[2],strlen(ack[2]),0);
//send(connfd,ack[3],strlen(ack[3]),0);
send(connfd,ack[4],strlen(ack[4]),0); //要加上这一句,否则网页的图片无法显示
while(1)
{
bzero(msg,sizeof(msg));
len = fread(msg, 1, 512, fp);
if(len == 0) break;
send(connfd, msg, len, 0);
//printf("_len=%d\n",len);
}
fclose(fp);
close(connfd);
return NULL;
}
int main(int argc, char *argv[])
{
unsigned short port = 8000;
//创建一个监听套接字
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(argc > 1)
{
port = atoi(argv[1]);
}
//让服务器绑定IP和端口
struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
if(ret != 0)
{
perror("bind:");
exit(-1);
}
listen(sockfd, 10);//创建监听队列
struct sockaddr_in c_addr;
socklen_t c_addr_len = sizeof(c_addr);
while(1)
{
int connfd = accept(sockfd, (struct sockaddr *)&c_addr, &c_addr_len);
pthread_t pth;
pthread_create(&pth, NULL, (void *)server_fun, (void *)connfd);
pthread_detach(pth);
}
close(sockfd);
return 0;
}
<file_sep>/sys_program/player/src/inc/common.h
#ifndef __COMMON_H__
#define __COMMON_H__
#include <gtk/gtk.h>
#include <glade/glade.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include "sungtk_interface.h"
#define uint unsigned int
#define ulint unsigned long int
#define uchar unsigned char
#define FIFO "cmd_fifo"
#define MS (1000)
typedef enum
{
sequence = 0, //列表顺序播放
list_loop = 1, //列表循环
loop = 2, //单曲循环
randm = 3, //随机播放
}PLAY_MODE;
typedef enum
{
stop = 0,
playing = 1,
// end = 2,
}PLAY_STATUS;
typedef enum
{
mute = 0, //静音
beam = 1, //播音
}SOUND_STATUS;
typedef enum
{
quiet = 0,
init = 1,
back = 2,
next = 3,
clist = 4,
}KEY_STATUS;
typedef struct _lrc
{
//float time;
int time;
char src[256];
struct _lrc *prev;
struct _lrc *next;
}LRC;
typedef struct _song
{
char *song_src;
char **psong_list;
char *search;
char search_flag;
char name[168];
char *lrc_src;
char *plines[128]; //指向 歌词的每一行
// char *lrc_title[4];
int lrc_lines; //存放歌词的行数
int now; //指向当前播放的歌曲
int old;
int count; //歌的数量
int cur_time; //歌曲播放当前时间
int end_time; //歌曲播放结束时间
int endflag; //歌曲播放结束标志
float rate; //歌曲播放进度
ulint lrc_length;
sem_t sem_setsong;
sem_t sem_keyflag;
LRC *lrc_head;
LRC *pnode;
KEY_STATUS keyflag;
}SONG;
typedef struct _hbox_left
{
GtkButton *bmusic_list;
GtkButton *bmusic_collect;
GtkButton *bmusic_recently;
GtkEntry *entry_search;
GtkButton *button_search;
GtkTable *table_search;
GtkScrolledWindow *scrollbar_musiclist;
GtkCList *music_clist;
GtkTable *table_musiclist;
GtkEventBox *eventbox_musiclist;
}HBOX_LEFT;
typedef struct _hbox_right
{
GtkImage *image_logo;
GtkButton *button_back;
GtkButton *button_next;
GtkButton *button_pause;
GtkButton *button_backward;
GtkButton *button_forward;
GtkButton *button_playmode;
GtkImage *image_back;
GtkImage *image_next;
GtkImage *image_pause;
GtkImage *image_backward;
GtkImage *image_forward;
GtkLabel *label_title1;
GtkLabel *label_title2;
GtkLabel *label_title3;
GtkLabel *label_lrc1;
GtkLabel *label_lrc2;
GtkLabel *label_lrc3;
GtkLabel *label_lrc4;
GtkLabel *label_lrc5;
GtkLabel *label_lrc6;
GtkLabel *label_lrc7;
GtkLabel *label_cur_time;
GtkLabel *label_end_time;
GtkProgressBar *progress_bar;
GtkEventBox *eventbox_bar;
GtkHScale *hscale_volume;
GtkButton *button_volume;
GtkEventBox *eventbox_volume;
}HBOX_RIGHT;
typedef struct _window
{
GtkWidget *main_window;
//GtkImage *image;
HBOX_LEFT hbox_left;
HBOX_RIGHT hbox_right;
}WINDOW;
typedef struct _mplayer
{
WINDOW ui;
// char msg[128]; //接收mplayer信息
int fd_pipe; //命名管道
int fd[2]; //无名管道
pid_t pid; //启动mplayer的子进程pid
pthread_t pth_showlrc;
pthread_t pth_rcvmsg;
pthread_t pth_sendcmd;
pthread_mutex_t mutex;
PLAY_STATUS playflag; //播放状态
PLAY_MODE playmode; //播放模式
SOUND_STATUS soundflag;
// SunGtkCList *musiclist;
}MPLAYER;
#endif
<file_sep>/network/route/src/msg_dispose.c
/******************************************************************************
文 件 名 : msg_dispose.c
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月15日
最近修改 :
功能描述 : 处理网络数据
函数列表 :
get_ip
get_mac
check_if_same_subnet
dispose_arp_reply
get_transpond_port
get_type
reply_arp_requset
send_msg
show_msg_ip
transpond_msg
修改历史 :
1.日 期 : 2015年9月15日
作 者 : if
修改内容 : 创建文件
******************************************************************************/
#include "common.h"
#include "arp_link.h"
/*****************************************************************************
函 数 名 : get_mac()
功能描述 : 提取目的mac、源mac
输入参数 : recv 接收网络数据包的缓存
dst_mac 存储目的mac的首地址 传入NULL 则不提取
src_mac 存储源mac的首地址 传入NULL 则不提取
返 回 值 : NULL
修改日期 : 2015年9月12日
*****************************************************************************/
void get_mac(uchar *recv, uchar *dst_mac, uchar *src_mac)
{
if(dst_mac != NULL){
memcpy(dst_mac, recv, 6);
}
if(src_mac != NULL){
memcpy(src_mac, recv+6, 6);
}
}
/*****************************************************************************
函 数 名 : get_type()
功能描述 : 获取协议类型
输入参数 : recv 接收网络数据包的缓存
返 回 值 : 返回协议类型(无符号短整型整数)
修改日期 : 2015年9月11日
*****************************************************************************/
uint16 get_type(const uchar *recv)
{
uint16 type = 0;
type = ntohs(*(uint16 *)(recv+12));
return type;
}
/*****************************************************************************
函 数 名 : get_ip()
功能描述 : 提取目的ip、源ip
输入参数 : recv 接收网络数据包的缓存
dst_ip 存储目的ip的首地址 传入NULL 则不提取
src_ip 存储源ip的首地址 传入NULL 则不提取
返 回 值 : NULL
修改日期 : 2015年9月12日
*****************************************************************************/
void get_ip(const uchar *recv, uchar *dst_ip, uchar *src_ip)
{
if(src_ip != NULL){
//提取源ip
memcpy(src_ip, recv+12, 4);
}
if(dst_ip != NULL){
//提取目的ip
memcpy(dst_ip, recv+16, 4);
}
}
/*****************************************************************************
函 数 名 : show_msg_ip()
功能描述 : 提取目的ip、源ip
输入参数 : recv 接收网络数据包的缓存
返 回 值 : NULL
修改日期 : 2015年9月11日
*****************************************************************************/
void show_msg_ip(const uchar *recv)
{
unsigned char dst_ip[16] = "";
unsigned char src_ip[16] = "";
//提取源ip
sprintf(src_ip,"%d.%d.%d.%d",\
recv[12],recv[13],recv[14],recv[15]);
//提取目的ip
sprintf(dst_ip,"%d.%d.%d.%d",\
recv[16],recv[17],recv[18],recv[19]);
printf("IP:%s >> %s\n", src_ip, dst_ip);
}
/*****************************************************************************
函 数 名 : check_if_same_subnet()
功能描述 : 检测目的ip跟网卡是否在同一网段
输入参数 : eth_mask 网卡子网掩码
eth_ip 网卡ip
dst_ip 目的ip
返 回 值 : 布尔型
修改日期 : 2015年9月12日
*****************************************************************************/
Boolean check_if_same_subnet(const uchar eth_mask[], const uchar eth_ip[],const uchar dst_ip[])
{
if(((*(uint *)eth_ip) & (*(uint *)eth_mask)) ==\
((*(uint *)dst_ip) & (*(uint *)eth_mask)))
return TRUE;
else
return FALSE;
}
/*****************************************************************************
函 数 名 : get_transpond_port()
功能描述 : 获取数据转发的接口
输入参数 : rt TYPE_Route 类型结构指针
dst_ip 目的ip
返 回 值 : 返回网卡的编号
修改日期 : 2015年9月12日
*****************************************************************************/
int get_transpond_port(TYPE_Route *rt, const uchar dst_ip[])
{
int i = 0;
Boolean flag = FALSE;
for(i=0; i < rt->port_num; i++)
{
flag = check_if_same_subnet(rt->eth_port[i].netmask, rt->eth_port[i].ip, dst_ip);
if(flag == TRUE) return i;
}
return -1;
}
/*****************************************************************************
函 数 名 : send_msg()
功能描述 : 获取ip数据包的转发接口
输入参数 : rt TYPE_Route 类型结构指针
port 网络接口的编号
msg_len 发送数据长度
返 回 值 :
修改日期 : 2015年9月12日
*****************************************************************************/
int send_msg(TYPE_Route *rt, int port, int msg_len)
{
int send_len = 0;
strncpy(rt->ethreq.ifr_name,rt->eth_port[port].name, IFNAMSIZ);
ioctl(rt->raw_fd, SIOCGIFINDEX, (char *)&rt->ethreq);
bzero(&rt->sll, sizeof(rt->sll));
rt->sll.sll_ifindex = rt->ethreq.ifr_ifindex;
send_len = sendto(rt->raw_fd, rt->recv, msg_len, 0, (struct sockaddr *)&rt->sll, sizeof(rt->sll));
return send_len;
}
/*****************************************************************************
函 数 名 : transpond_msg()
功能描述 : 获取ip数据包的转发接口
输入参数 : rt TYPE_Route 类型结构指针
dst_ip 目的ip
port 网络接口的编号
msg_len 发送数据包的长度
返 回 值 : 无法获取目的mac时,返回-1,否则返回实际发送的长度
修改日期 : 2015年9月12日
*****************************************************************************/
int transpond_msg(TYPE_Route *rt, const uchar dst_ip[], int port, int msg_len)
{
ARP_Table *pnode = NULL;
if(rt->arp_head == NULL){ //如果ARP表为空,则建立ARP表
build_arp_table(rt);
}
pnode = (ARP_Table *)search_arp_table(rt->arp_head, dst_ip);
if(pnode == NULL){ //在arp表中没有找到目的ip
Boolean flag = broadcast(rt, dst_ip); //广播获取目的mac
if(flag == FALSE) { //广播没有获取到目的mac
return -1;
}
pnode = (ARP_Table *)search_arp_table(rt->arp_head, dst_ip);
}
// uchar dst_mac[6] = "";
// uchar src_mac[6] = "";
//
// memcpy(dst_mac, pnode->mac, 6);
// memcpy(src_mac, rt->eth_port[port].mac, 6);
memcpy(rt->recv, pnode->mac, 6); //修改ip数据包的目的mac地址
memcpy(rt->recv+6, rt->eth_port[port].mac, 6); //修改ip数据包的源mac地址
int send_len = send_msg(rt, port, msg_len);
return send_len;
}
/*****************************************************************************
函 数 名 : reply_arp_requset()
功能描述 : 应答arp请求
输入参数 : rt TYPE_Route 类型结构指针
pinfo MSG_Info 类型指针
ARP_Hdr ARP_Hdr 类型指针
返 回 值 : 返回发送的长度,出错返回-1
修改日期 : 2015年9月12日
*****************************************************************************/
int reply_arp_requset(TYPE_Route *rt, MSG_Info *pinfo, ARP_Hdr *arp_hdr)
{
int port = 0;
memcpy(pinfo->dst_ip, arp_hdr->dst_ip, 6);
port = get_transpond_port(rt, pinfo->dst_ip);
if(port != -1)
{
//获取ARP请求端的ip和mac地址
memcpy(pinfo->src_mac, arp_hdr->src_mac, 6);
memcpy(pinfo->src_ip, arp_hdr->src_ip, 4);
//组ARP应答包
memcpy(rt->recv, pinfo->src_mac, 6); //
memcpy(rt->recv+6, rt->eth_port[port].mac, 6);
arp_hdr->ar_op = htons(2); // -> 运算符优先级高于 &
memcpy(arp_hdr->src_mac, rt->eth_port[port].mac, 6);
memcpy(arp_hdr->src_ip, pinfo->dst_ip, 4);
memcpy(arp_hdr->dst_mac, pinfo->src_mac,6);
memcpy(arp_hdr->dst_ip, pinfo->src_ip, 4);
int send_len = send_msg(rt, port, pinfo->len);
return send_len;
}
return -1;
}
/*****************************************************************************
函 数 名 : dispose_arp_reply()
功能描述 : 处理arp请求
输入参数 : rt TYPE_Route 类型结构指针
ARP_Hdr ARP_Hdr 类型指针
返 回 值 : NULL
修改日期 : 2015年9月12日
*****************************************************************************/
void dispose_arp_reply(ARP_Table *head, ARP_Hdr *arp_hdr)
{
ARP_Table *pnode = NULL, node;
memcpy(node.ip, arp_hdr->src_ip, 4);
memcpy(node.mac, arp_hdr->src_mac,6);
pnode = (ARP_Table *)search_arp_table(head, node.ip);
if(pnode != NULL) {
change_arp_mac(head, node.ip, node.mac);
}
else {
head = (ARP_Table *)insert_arp_table(head, node);
}
}
<file_sep>/shell/4st_week/test
#!/bin/bash
cd $HOME
if [ ! -d "test" ]
then
echo "test directory is not exist!"
read -p "input 'y' to create or 'n' to leave: " answer
case $answer in
y | Y) mkdir test
echo "create test directory succeed";;
n | N) exit;;
*) echo "input error!"
exit;;
esac
fi
echo "cd test"
cd test
count=1
read -p "please input a file name: " filename
until [ ! -f "$filename" ]
do
read -p "$filename is exist, input again: " filename
count=$[ $count + 1 ]
if [ $count -eq 3 ]
then
echo "exit!"
exit
fi
done
if test touch "$filename"
then
echo "create $filename file succeed"
fi
<file_sep>/sys_program/player/src/process_lrc.c
/* ************************************************************************
* Filename: process_lrc.c
* Description:
* Version: 1.0
* Created: 2015年07月31日 星期五 09時17分27秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include "common.h"
#include "console.h"
#include "mplayer_control.h"
#include "mplayer_pthread.h"
#include "gb2312_ucs2.h"
#include "link.h"
#include "file.h"
#include "process_lrc.h"
uint src_segment(char *src, char *plines[], char *str)
{
uint i = 0;
plines[0] = strtok(src, str);
while(plines[i++] != NULL)
{
plines[i] = strtok(NULL, str);
}
//printf("i=%d\n",i);
return (i-1);
}
uint line_segment(char *pline, char *pbuf[], char *str)
{
uint i = 0;
pbuf[0] = strtok(pline, str);
while(pbuf[i++] != NULL)
{
pbuf[i] = strtok(NULL, str);
//printf("%s\n",pbuf[i]);
}
//printf("i=%d\n",i);
return (i-1);
}
LRC *build_link(MPLAYER *pm,char *plines[],int lines)
{
int i, j;
uint part = 0;
LRC lyric, *lrc_head = NULL;
for(i=0;plines[i] != NULL && i<lines; i++)
{
#if 0
char *pbuf[10] = {NULL};
part = line_segment(plines[i],pbuf, "]"); //切割一行
for(j=0;j<part;j++)
{
int min = 0,sec = 0, msec = 0;
printf("%s\n",pbuf[j]);
}
#elif 1
if(i<4) //
{
char *ptitle = NULL;
//char msg[100]; sscanf ???????
//sscanf(plines[i],"%*[^:]%*1s%[^]]",msg[0]);
ptitle = strtok(plines[i],":]");
if(ptitle != NULL) ptitle = strtok(NULL,":]");
if(ptitle != NULL)
{
//printf("##$@#$ %s***\n",ptitle);
//mplayer_show_lyrtitle(pm, ptitle, i);
}
#if 0
char *trash = NULL;
int len = 0;
if(plines[i] != NULL)
{
trash = strtok(plines[i],":]");
if(trash != NULL)
{
trash = strtok(NULL,":]");
if(trash != NULL)
{
//printf("$$$$$$$$$$$$$$$$$$$$$$$\n");
len = strlen(trash);
if(len == 0) song.lrc_title[i] = NULL;
else
{
char utf8[96] = {0};
song.lrc_title[i] = (char *)malloc(len + 1);
bzero(song.lrc_title[i], len + 1);
gb2312_to_utf8(trash, utf8);
strcpy(song.lrc_title[i], utf8);
printf("lrc_title[%d] = %s\n",i, song.lrc_title[i]);
}
}
else
{
song.lrc_title[i] = NULL;
}
}
}
#endif
}
else
{
char *pbuf[10] = {NULL};
int min = 0, sec = 0, msec = 0;
//float sec;
part = line_segment(plines[i],pbuf, "]"); //切割一行
for(j=0;j<part-1;j++)
{
if(pbuf[part-1][0] != '[')
{
char utf8[256] = {0};
sscanf(pbuf[j],"[%2d:%2d.%2d",&min,&sec,&msec);
//printf("%2d:%2d.%2d\n",min,sec,msec);
lyric.time = (min * 60 + sec)*1000 + msec*10;
gb2312_to_utf8(pbuf[part-1], utf8);
strcpy(lyric.src, utf8);
lrc_head = insert_link(lrc_head,lyric);
//printf("%4d %s\n",lyric.time, lyric.src);
}
}
}
#endif
}
return lrc_head;
}
LRC *dispose_lrc(MPLAYER *pm,char *name)
{
song.lrc_src = NULL;
song.lrc_head = NULL;
song.lrc_src = (char *)read_src_file(&song.lrc_length, name);
if(song.lrc_src != NULL)
{
song.lrc_lines = src_segment(song.lrc_src, song.plines, "\r\n");
song.lrc_head = (LRC *)build_link(pm, song.plines, song.lrc_lines);
song.pnode = song.lrc_head;
//print_link(song.lrc_head);
}
free(song.lrc_src);
return song.lrc_head;
}
void show_lyric(LRC *pnode, int longest)
{
char *empty = " ";
char *pbuf[12];
int i = 0, offset = 0;
LRC *pb = NULL, *pf = NULL;
pb = pnode;
pf = pnode->next;
for(i=3;i>=0;i--)
{
if(pb != NULL)
{
pbuf[i] = pb->src;
pb = pb->prev;
}
else
{
pbuf[i] = empty;
}
}
for(i=4;i<12;i++)
{
if(pf != NULL)
{
pbuf[i] = pf->src;
pf = pf->next;
}
else
{
pbuf[i] = empty;
}
}
for(i = 0;i < 12;i++) //
{
cusor_moveto(55, 20+i); //光标移到 第4+i行,第20列
printf("%-40s",empty); //清除上次的显示
fflush(stdout);
}
for(i = 0;i < 12;i++)
{
offset = get_showoffset(pbuf[i],longest);
cusor_moveto(55+offset, 20+i); //光标移到 第10+i行,第50列
set_fg_color(COLOR_WHITE);
if(i == 3)
{
set_fg_color(COLOR_MAGENTA);
}
printf("%-40s",pbuf[i]);
fflush(stdout);
}
cusor_moveto(9, 36);
//fflush(stdout);
}
void mplayer_show_lyric(MPLAYER *pm, LRC *pnode)
{
char *empty = " ";
char *pbuf[3] = {NULL};
int i = 0;
LRC *pb = NULL, *pf = NULL;
pb = pnode;
pf = pnode->next;
//printf(">>%d ms --- %s\n",song.pnode->time, song.pnode->src);
for(i=0;i>=0;i--)
{
if(pb != NULL)
{
pbuf[i] = pb->src;
pb = pb->prev;
}
else
{
pbuf[i] = empty;
}
}
for(i=1;i<3;i++)
{
if(pf != NULL)
{
pbuf[i] = pf->src;
pf = pf->next;
}
else
{
pbuf[i] = empty;
}
}
set_lrc_lable(pm, pbuf);
}
void mplayer_show_lyrtitle(MPLAYER *pm, char *ptitle, int i)
{
//char *msg[] = { ": ", "?: ", ": "};
char utf8[168];
//char buf[168];
if(i < 3)
{
//bzero(buf, sizeof(buf));
//strcat(buf, msg[i]);
//strcat(buf, ptitle);
bzero(utf8, sizeof(utf8));
gb2312_to_utf8(ptitle, utf8);
printf("##$@#$ %s***\n",utf8);
switch(i)
{
case 0:
{
set_lable(pm->ui.hbox_right.label_title1, utf8);
break;
}
case 2:
{
set_lable(pm->ui.hbox_right.label_title2, utf8);
break;
}
case 3:
{
set_lable(pm->ui.hbox_right.label_title3, utf8);
break;
}
}
}
}
<file_sep>/network/route/src/inc/route_control.h
/******************************************************************************
文 件 名 : route_control.h
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月11日
最近修改 :
功能描述 : route_control.c 的头文件
******************************************************************************/
#ifndef __ROUTE_CONTROL_H__
#define __ROUTE_CONTROL_H__
/*----------------------------------------------*
* 外部函数原型说明 *
*----------------------------------------------*/
extern void route_init(TYPE_Route *rt);
extern void show_port_info(TYPE_Route *rt, char *port_name);
extern void get_ethernet_port(TYPE_Route *rt);
extern void build_arp_table(TYPE_Route *rt);
extern Boolean broadcast(TYPE_Route *rt, const uchar ip[]);
#endif /* __ROUTE_CONTROL_H__ */
<file_sep>/work/test/pwm-led/pwm-led.c
/*************************************************************************
>File Name: pwm-led.c
> Author: <NAME>
> Mail: <EMAIL> / <EMAIL>
> Datatime: Thu 03 Nov 2016 07:45:42 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
/*
* Macro
*/
#define JZ_GENERIC_PWM 0
#define DEFAULT_MAX_BRIGHTNESS 255
#define DEFAULT_DELAY_US 40000
#define DEFAULT_LED "led_state"
/*
* Variables
*/
const float duty[] = {
0.00, 0.01, 0.02, 0.03,
0.04, 0.05, 0.06, 0.07,
0.09, 0.10, 0.11, 0.13,
0.15, 0.17, 0.19, 0.21,
0.23, 0.25, 0.27, 0.29,
0.31, 0.33, 0.35, 0.38,
0.41, 0.44, 0.47, 0.50,
0.53, 0.56, 0.59, 0.62,
0.66, 0.70, 0.74, 0.79,
0.84, 0.89, 0.94, 1.00,
};
/*
* Function
*/
void print_usage()
{
printf("Usage:\n \
pwm-led [OPTIONS]\n \
a pwm-leds test demo\n\n \
OPTIONS:\n \
-l ----> select led name\n \
-m ----> select pwd output method\n \
-n ----> set cycle times\n \
-t ----> set delay_us value\n \
-h ----> get help message\n\n \
eg:\n \
pwm-led -l xxx ----> select /sys/class/leds/xxx\n \
pwm-led -m 1 -t 500 ----> select method 1,and set delay_us = 500us\r\n");
}
int main(int argc, char *argv[])
{
int fd;
int len, oc;
int i = 0, n = 10;
int max_brightness = DEFAULT_MAX_BRIGHTNESS;
int method = 0, delay_us = DEFAULT_DELAY_US;
float val;
char *arg = NULL, tmp[8] = "0";
#if (JZ_GENERIC_PWM == 1)
char led[68] = "/sys/class/jz-pwm/";
#else
char led[68] = "/sys/class/leds/";
#endif
while(1) {
oc = getopt(argc, argv, "hl:m:n:t:");
if(oc == -1)
break;
switch(oc) {
case 'l':
arg = optarg;
break;
case 'm':
method = atoi(optarg);
break;
case 'n':
n = atoi(optarg);
break;
case 't':
delay_us = atoi(optarg);
break;
case 'h':
default:
print_usage();
return 1;
}
}
if(arg != NULL) {
strcat(led, arg);
printf("LED name: %s\n", arg);
} else {
strcat(led, DEFAULT_LED);
printf("LED name: %s\n", DEFAULT_LED);
}
len = strlen(led);
#if (JZ_GENERIC_PWM == 1)
strncpy(led + len, "/max_dutyratio", sizeof("/max_dutyratio"));
#else
strncpy(led + len, "/max_brightness", sizeof("/max_brightness"));
#endif
fd = open(led, O_RDONLY);
if(fd != -1) {
if(read(fd, tmp, sizeof(tmp)) > 0)
max_brightness = atoi(tmp);
close(fd);
}
printf(" method = %d\n", method);
printf(" delay_us = %d\n", delay_us);
printf("max_brightness = %d\n", max_brightness);
#if (JZ_GENERIC_PWM == 1)
strncpy(led + len, "/dutyratio", sizeof("/dutyratio"));
#else
strncpy(led + len, "/brightness", sizeof("/brightness"));
#endif
fd = open(led, O_WRONLY);
if(fd < 0) {
printf("Failed to open: %s\n", led);
return -1;
}
while(n--) {
if(method == 0) {
for(i = 0; i < sizeof(duty)/sizeof(float); i++) {
val = max_brightness * duty[i];
len = snprintf(tmp, sizeof(tmp), "%d", (int)val);
if(write(fd, tmp, len) < 0) {
printf("%d: write failed\n", __LINE__);
continue;
}
usleep(delay_us);
}
for(i = sizeof(duty)/sizeof(float) - 1; i >= 0; i--) {
val = max_brightness * duty[i];
len = snprintf(tmp, sizeof(tmp), "%d", (int)val);
if(write(fd, tmp, len) < 0) {
printf("%d: write failed\n", __LINE__);
continue;
}
usleep(delay_us);
}
} else {
for(val = 0; val < max_brightness; val++) {
len = snprintf(tmp, sizeof(tmp), "%d", (int)val);
if(write(fd, tmp, len) < 0) {
printf("%d: write failed\n", __LINE__);
continue;
}
usleep(delay_us);
}
for(val = max_brightness; val >= 0; val--) {
len = snprintf(tmp, sizeof(tmp), "%d", (int)val);
if(write(fd, tmp, len) < 0) {
printf("%d: write failed\n", __LINE__);
continue;
}
usleep(delay_us);
}
}
}
close(fd);
return 0;
}
<file_sep>/network/4th_day/Makefile
webserver:webserver.c
gcc -o webserver webserver.c -lpthread
.PHONY:clean
clean:
rm webserver
<file_sep>/sys_program/1st_day/fork.c
/* ************************************************************************
* Filename: fork.c
* Description:
* Version: 1.0
* Created: 2015年08月13日 15时34分25秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int gnum = 0;
int main(int argc, char *argv[])
{
int num = 0;
pid_t pid;
pid = fork();
if(pid < 0) perror("error");
else if(pid == 0)
{
while(1)
{
printf("gnum = %d num = %d\n",gnum,num);
printf("in son process\n");
sleep(1);
}
}
else
{
while(1)
{
gnum++;
num++;
printf("in father process\n");
sleep(1);
}
}
return 0;
}
<file_sep>/c/practice/sort/selectsort.c
#include "stdio.h"
void swap(int *a,int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void selectsort(int data[],int n) /*选择排序*/
{
int i,j,k,max;
//int temp;
for(i=0;i<n-1;i++)// “ i ” 就是起始值
{
k = i;
for(j=i+1;j<n;j++)
{
if(data[j] < data[k])
k = j;//k is the always the smaller data location
}
if(k != i)//move the smallest data to the first location
{
swap(&data[i], &data[k]);
}
}
}
int main()
{
int i,a[10] = {2,5,6,3,7,8,0,9,12,1};
printf("The data array is:\n") ;
for(i=0;i<10;i++) /*显示原序列之中的元素*/
printf("%d ",a[i]);
selectsort(a,10); /*执行选择排序*/
printf("\nThe result of selection sorting for the array is:\n");
for(i=0;i<10;i++)
printf("%d ",a[i]); /*输出排序后的结果*/
printf("\n");
return 0;
}
<file_sep>/work/camera/ov7740/jz-ov7740/jz_camera_v13.c
/*
* V4L2 Driver for Ingenic jz camera (CIM) host
*
* Copyright (C) 2014, Ingenic Semiconductor Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
* This program is support Continuous physical address mapping,
* not support sg mode now.
*/
#include <linux/clk.h>
#include <linux/device.h>
#include <linux/types.h>
#include <linux/dma-mapping.h>
#include <linux/mutex.h>
#include <linux/version.h>
#include <linux/platform_device.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/device.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/videodev2.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-common.h>
#include <media/v4l2-dev.h>
#include <media/videobuf-dma-contig.h>
#include <media/soc_camera.h>
#include <media/soc_mediabus.h>
#include <asm/dma.h>
/*kzalloc*/
#include <mach/jz_camera.h>
#include <linux/regulator/consumer.h>
#define CIM_DUMP_REG
#define PRINT_CIM_REG
struct regulator *regul;
#ifdef CIM_DUMP_REG
static void cim_dump_reg(struct jz_camera_dev *pcdev)
{
if(pcdev == NULL) {
printk("===>>%s,%d pcdev is NULL!\n",__func__,__LINE__);
return;
}
#define STRING "\t=\t0x%08x\n"
printk("REG_CIM_CFG" STRING, readl(pcdev->base + CIM_CFG));
printk("REG_CIM_CTRL" STRING, readl(pcdev->base + CIM_CTRL));
printk("REG_CIM_CTRL2" STRING, readl(pcdev->base + CIM_CTRL2));
printk("REG_CIM_STATE" STRING, readl(pcdev->base + CIM_STATE));
printk("REG_CIM_IMR" STRING, readl(pcdev->base + CIM_IMR));
printk("REG_CIM_IID" STRING, readl(pcdev->base + CIM_IID));
printk("REG_CIM_DA" STRING, readl(pcdev->base + CIM_DA));
printk("REG_CIM_FA" STRING, readl(pcdev->base + CIM_FA));
printk("REG_CIM_FID" STRING, readl(pcdev->base + CIM_FID));
printk("REG_CIM_CMD" STRING, readl(pcdev->base + CIM_CMD));
printk("REG_CIM_WSIZE" STRING, readl(pcdev->base + CIM_SIZE));
printk("REG_CIM_WOFFSET" STRING, readl(pcdev->base + CIM_OFFSET));
printk("REG_CIM_FS" STRING, readl(pcdev->base + CIM_FS));
printk("REG_CIM_YFA" STRING, readl(pcdev->base + CIM_YFA));
printk("REG_CIM_YCMD" STRING, readl(pcdev->base + CIM_YCMD));
printk("REG_CIM_CBFA" STRING, readl(pcdev->base + CIM_CBFA));
printk("REG_CIM_CBCMD" STRING, readl(pcdev->base + CIM_CBCMD));
printk("REG_CIM_CRFA" STRING, readl(pcdev->base + CIM_CRFA));
printk("REG_CIM_CRCMD" STRING, readl(pcdev->base + CIM_CRCMD));
printk("REG_CIM_TC" STRING, readl(pcdev->base + CIM_TC));
printk("REG_CIM_TINX" STRING, readl(pcdev->base + CIM_TINX));
printk("REG_CIM_TCNT" STRING, readl(pcdev->base + CIM_TCNT));
}
#endif
static unsigned int get_paddr(unsigned int vaddr)
{
unsigned int addr = vaddr & (PAGE_SIZE-1);
pgd_t *pgdir;
pmd_t *pmdir;
pte_t *pte;
pgdir = pgd_offset(current->mm, vaddr);
if(pgd_none(*pgdir) || pgd_bad(*pgdir))
return 0;
pmdir = pmd_offset((pud_t *)pgdir, vaddr);
if(pmd_none(*pmdir) || pmd_bad(*pmdir))
return 0;
pte = pte_offset(pmdir,vaddr);
if (pte_present(*pte)) {
return addr | (pte_pfn(*pte) << PAGE_SHIFT);
}
return 0;
}
static int is_cim_enable(struct jz_camera_dev *pcdev)
{
unsigned int regval = 0;
regval = readl(pcdev->base + CIM_CTRL);
return (regval & 0x1);
}
static int is_cim_disabled(struct jz_camera_dev *pcdev)
{
unsigned int regval = 0;
regval = readl(pcdev->base + CIM_CTRL);
return ((regval & 0x1) == 0x0);
}
void cim_disable_without_dma(struct jz_camera_dev *pcdev)
{
unsigned long temp = 0;
/* clear status register */
writel(0, pcdev->base + CIM_STATE);
/* disable cim */
temp = readl(pcdev->base + CIM_CTRL);
temp &= (~CIM_CTRL_ENA);
writel(temp, pcdev->base + CIM_CTRL);
/* reset rx fifo */
temp = readl(pcdev->base + CIM_CTRL);
temp |= CIM_CTRL_RXF_RST;
writel(temp, pcdev->base + CIM_CTRL);
/* stop resetting RXFIFO */
temp = readl(pcdev->base + CIM_CTRL);
temp &= (~CIM_CTRL_RXF_RST);
writel(temp, pcdev->base + CIM_CTRL);
}
static int jz_camera_querycap(struct soc_camera_host *ici, struct v4l2_capability *cap)
{
strlcpy(cap->card, "jz-Camera", sizeof(cap->card));
cap->version = VERSION_CODE;
cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
return 0;
}
unsigned long jiff_temp;
static unsigned int jz_camera_poll(struct file *file, poll_table *pt)
{
struct soc_camera_device *icd = file->private_data;
struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
struct jz_camera_dev *pcdev = ici->priv;
struct jz_buffer *buf;
unsigned long temp = 0;
unsigned int regval;
if(!pcdev->poll_flag)
pcdev->poll_flag = 1;
buf = list_entry(icd->vb_vidq.stream.next, struct jz_buffer, vb.stream);
if(pcdev->is_first_start) {
writel(0, pcdev->base + CIM_STATE);
/* please enable dma first, enable cim ctrl later.
* if enable cim ctrl first, RXFIFO can easily overflow.
*/
regval = (unsigned int)(pcdev->dma_desc);
writel(regval, pcdev->base + CIM_DA);
/*enable dma*/
temp = readl(pcdev->base + CIM_CTRL);
temp |= CIM_CTRL_DMA_EN;
writel(temp, pcdev->base + CIM_CTRL);
/* clear rx fifo */
temp = readl(pcdev->base + CIM_CTRL);
temp |= CIM_CTRL_RXF_RST;
writel(temp, pcdev->base + CIM_CTRL);
temp = readl(pcdev->base + CIM_CTRL);
temp &= ~CIM_CTRL_RXF_RST;
writel(temp, pcdev->base + CIM_CTRL);
/* enable cim */
temp = readl(pcdev->base + CIM_CTRL);
temp |= CIM_CTRL_ENA;
writel(temp, pcdev->base + CIM_CTRL);
pcdev->is_first_start = 0;
}
jiff_temp = jiffies;
poll_wait(file, &buf->vb.done, pt);
if (buf->vb.state == VIDEOBUF_DONE ||
buf->vb.state == VIDEOBUF_ERROR) {
return POLLIN | POLLRDNORM;
}
return 0;
}
static int jz_camera_alloc_desc(struct jz_camera_dev *pcdev, struct v4l2_requestbuffers *p)
{
struct jz_camera_dma_desc *dma_desc_paddr;
struct jz_camera_dma_desc *dma_desc;
pcdev->buf_cnt = p->count;
pcdev->desc_vaddr = dma_alloc_coherent(pcdev->soc_host.v4l2_dev.dev,
sizeof(*pcdev->dma_desc) * pcdev->buf_cnt,
(dma_addr_t *)&pcdev->dma_desc, GFP_KERNEL);
dma_desc_paddr = (struct jz_camera_dma_desc *) pcdev->dma_desc;
dma_desc = (struct jz_camera_dma_desc *) pcdev->desc_vaddr;
#if 0
int i = 0;
printk("pcdev->desc_vaddr = 0x%p, pcdev->dma_desc = 0x%p\n",pcdev->desc_vaddr, (dma_addr_t *)pcdev->dma_desc);
for(i = 0; i < pcdev->buf_cnt; i++){
printk("pcdev->desc_vaddr[%d] = 0x%p\n", i, &dma_desc[i]);
}
for(i = 0; i < pcdev->buf_cnt; i++){
printk("dma_desc_paddr[%d] = 0x%p\n", i, &dma_desc_paddr[i]);
}
#endif
if (!pcdev->dma_desc)
return -ENOMEM;
return 0;
}
static int jz_camera_reqbufs(struct soc_camera_device *icd, struct v4l2_requestbuffers *p) {
int i;
struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
struct jz_camera_dev *pcdev = ici->priv;
for (i = 0; i < p->count; i++) {
struct jz_buffer *buf = container_of(icd->vb_vidq.bufs[i],
struct jz_buffer, vb);
buf->inwork = 0;
INIT_LIST_HEAD(&buf->vb.queue);
}
if(jz_camera_alloc_desc(pcdev, p))
return -ENOMEM;
return 0;
}
static int jz_videobuf_setup(struct videobuf_queue *vq, unsigned int *count,
unsigned int *size) {
struct soc_camera_device *icd = vq->priv_data;
int bytes_per_line = soc_mbus_bytes_per_line(icd->user_width,
icd->current_fmt->host_fmt);
if (bytes_per_line < 0)
return bytes_per_line;
*size = bytes_per_line * icd->user_height;
if (!*count)
*count = 32;
if (*size * *count > MAX_VIDEO_MEM * 1024 * 1024)
*count = (MAX_VIDEO_MEM * 1024 * 1024) / *size;
dprintk(7, "count=%d, size=%d\n", *count, *size);
return 0;
}
static void free_buffer(struct videobuf_queue *vq, struct jz_buffer *buf) {
struct videobuf_buffer *vb = &buf->vb;
struct soc_camera_device *icd = vq->priv_data;
struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
struct jz_camera_dev *pcdev = ici->priv;
BUG_ON(in_interrupt());
dprintk(7, "%s (vb=0x%p) 0x%08lx %d\n", __func__,
vb, vb->baddr, vb->bsize);
/*
* This waits until this buffer is out of danger, i.e., until it is no
* longer in STATE_QUEUED or STATE_ACTIVE
*/
videobuf_waiton(vq, vb, 0, 0);
videobuf_dma_contig_free(vq, vb);
vb->state = VIDEOBUF_NEEDS_INIT;
if(pcdev->poll_flag)
pcdev->poll_flag = 0;
if(pcdev->vb_address_flag)
pcdev->vb_address_flag = 0;
}
static int jz_init_dma(struct videobuf_queue *vq, struct videobuf_buffer *vbuf) {
struct soc_camera_device *icd = vq->priv_data;
struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
struct jz_camera_dev *pcdev = ici->priv;
struct jz_camera_dma_desc *dma_desc;
dma_addr_t dma_address;
dma_desc = (struct jz_camera_dma_desc *) pcdev->desc_vaddr;
if (vbuf->memory == V4L2_MEMORY_USERPTR)
dma_address = icd->vb_vidq.bufs[0]->baddr;
else if(vbuf->memory == V4L2_MEMORY_MMAP)
dma_address = videobuf_to_dma_contig(vbuf);
if(!dma_address) {
dprintk(3, "Failed to setup DMA address\n");
return -ENOMEM;
}
dma_desc[vbuf->i].id = vbuf->i;
if (vbuf->memory == V4L2_MEMORY_USERPTR)
dma_desc[vbuf->i].buf = get_paddr(dma_address);
else if (vbuf->memory == V4L2_MEMORY_MMAP)
dma_desc[vbuf->i].buf = dma_address;
if(icd->current_fmt->host_fmt->fourcc == V4L2_PIX_FMT_YUYV) {
dma_desc[vbuf->i].cmd = icd->sizeimage >> 2 |
CIM_CMD_EOFINT | CIM_CMD_OFRCV;
}else if(icd->current_fmt->host_fmt->fourcc == V4L2_PIX_FMT_SBGGR8) {
dma_desc[vbuf->i].cmd = icd->sizeimage >> 2 |
CIM_CMD_EOFINT | CIM_CMD_OFRCV;
} else {
printk("current fourcc is not support, use default fourcc!\n");
dma_desc[vbuf->i].cmd = (icd->sizeimage * 8 / 12) >> 2 |
CIM_CMD_EOFINT | CIM_CMD_OFRCV;
dma_desc[vbuf->i].cb_len = (icd->user_width >> 1) *
(icd->user_height >> 1) >> 2;
dma_desc[vbuf->i].cr_len = (icd->user_width >> 1) *
(icd->user_height >> 1) >> 2;
}
if(icd->current_fmt->host_fmt->fourcc == V4L2_PIX_FMT_YUV420) {
dma_desc[vbuf->i].cb_frame = dma_desc[vbuf->i].buf + icd->sizeimage * 8 / 12;
dma_desc[vbuf->i].cr_frame = dma_desc[vbuf->i].cb_frame + (icd->sizeimage / 6);
} else if(icd->current_fmt->host_fmt->fourcc == V4L2_PIX_FMT_JZ420B) {
dma_desc[vbuf->i].cb_frame = dma_desc[vbuf->i].buf + icd->sizeimage;
dma_desc[vbuf->i].cr_frame = dma_desc[vbuf->i].cb_frame + 64;
}
if(vbuf->i == 0) {
pcdev->dma_desc_head = (struct jz_camera_dma_desc *)(pcdev->desc_vaddr);
}
if(vbuf->i == (pcdev->buf_cnt - 1)) {
//dma_desc[vbuf->i].next = (dma_addr_t) (pcdev->dma_desc);
dma_desc[vbuf->i].next = 0;
dma_desc[vbuf->i].cmd |= CIM_CMD_STOP;
dma_desc[vbuf->i].cmd &= (~CIM_CMD_EOFINT);
pcdev->dma_desc_tail = (struct jz_camera_dma_desc *)(&dma_desc[vbuf->i]);
} else {
dma_desc[vbuf->i].next = (dma_addr_t) (&pcdev->dma_desc[vbuf->i + 1]);
}
dprintk(7, "cim dma desc[vbuf->i] address is: 0x%x\n", dma_desc[vbuf->i].buf);
return 0;
}
static int jz_videobuf_prepare(struct videobuf_queue *vq,
struct videobuf_buffer *vb, enum v4l2_field field)
{
struct soc_camera_device *icd = vq->priv_data;
struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
struct jz_camera_dev *pcdev = ici->priv;
struct device *dev = pcdev->soc_host.v4l2_dev.dev;
struct jz_buffer *buf = container_of(vb, struct jz_buffer, vb);
int bytes_per_line = soc_mbus_bytes_per_line(icd->user_width, icd->current_fmt->host_fmt);
int ret;
if (bytes_per_line < 0)
return bytes_per_line;
dprintk(7, "%s (vb=0x%p) 0x%08lx %d\n", __func__,
vb, vb->baddr, vb->bsize);
/* Added list head initialization on alloc */
WARN_ON(!list_empty(&vb->queue));
BUG_ON(NULL == icd->current_fmt);
/*
* I think, in buf_prepare you only have to protect global data,
* the actual buffer is yours
*/
buf->inwork = 1;
if (buf->code != icd->current_fmt->code ||
vb->width != icd->user_width ||
vb->height != icd->user_height ||
vb->field != field) {
buf->code = icd->current_fmt->code;
vb->width = icd->user_width;
vb->height = icd->user_height;
vb->field = field;
vb->state = VIDEOBUF_NEEDS_INIT;
}
vb->size = bytes_per_line * vb->height;
if (0 != vb->baddr && vb->bsize < vb->size) {
ret = -EINVAL;
goto out;
}
if (vb->state == VIDEOBUF_NEEDS_INIT) {
jz_init_dma(vq, vb);
if(ret) {
dev_err(dev, "%s:DMA initialization for Y/RGB failed\n", __func__);
goto fail;
}
vb->state = VIDEOBUF_PREPARED;
}
buf->inwork = 0;
return 0;
fail:
free_buffer(vq, buf);
out:
buf->inwork = 0;
return ret;
}
static void jz_videobuf_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
{
struct soc_camera_device *icd = vq->priv_data;
struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
struct jz_camera_dev *pcdev = ici->priv;
struct jz_camera_dma_desc *dma_desc_vaddr;
int i = 0;
unsigned int regval = 0;
struct jz_camera_dma_desc *dma_desc_paddr;
dma_desc_vaddr = (struct jz_camera_dma_desc *) pcdev->desc_vaddr;
vb->state = VIDEOBUF_ACTIVE;
/* judged vb->i */
if((vb->i > pcdev->buf_cnt) || (vb->i < 0)) {
printk("Warning: %s, %d, vb->i > pcdev->buf_cnt || vb->i < 0, please check vb->i !!!\n",
__func__, vb->i);
return;
}
/* set pcdev->vb_address */
if(!pcdev->vb_address_flag) {
pcdev->vb_address_flag = 1;
for(i = 0; i < pcdev->buf_cnt; i++)
pcdev->vb_address[i] = (struct videobuf_buffer *)vq->bufs[i];
}
/* has select */
if(pcdev->poll_flag) {
if(pcdev->dma_desc_head != pcdev->dma_desc_tail) {
dma_desc_vaddr[vb->i].cmd |= CIM_CMD_STOP;
dma_desc_vaddr[vb->i].cmd &= (~CIM_CMD_EOFINT);
pcdev->dma_desc_tail->next = (dma_addr_t) (&pcdev->dma_desc[vb->i]);
pcdev->dma_desc_tail->cmd &= (~CIM_CMD_STOP);
pcdev->dma_desc_tail->cmd |= CIM_CMD_EOFINT;
pcdev->dma_desc_tail = (struct jz_camera_dma_desc *)(&dma_desc_vaddr[vb->i]);
} else {
if(is_cim_disabled(pcdev)) {
dma_desc_vaddr[vb->i].cmd |= CIM_CMD_STOP;
dma_desc_vaddr[vb->i].cmd &= (~CIM_CMD_EOFINT);
pcdev->dma_desc_head = (struct jz_camera_dma_desc *)(&dma_desc_vaddr[vb->i]);
pcdev->dma_desc_tail = (struct jz_camera_dma_desc *)(&dma_desc_vaddr[vb->i]);
dma_desc_paddr = (struct jz_camera_dma_desc *) pcdev->dma_desc;
/* Configure register CIMDA */
regval = (unsigned int) (&dma_desc_paddr[vb->i]);
writel(regval, pcdev->base + CIM_DA);
/* clear state register */
writel(0, pcdev->base + CIM_STATE);
/* Reset RXFIFO */
regval = readl(pcdev->base + CIM_CTRL);
regval |= CIM_CTRL_DMA_EN | CIM_CTRL_RXF_RST;
regval &= (~CIM_CTRL_ENA);
writel(regval, pcdev->base + CIM_CTRL);
/* stop resetting RXFIFO */
regval = readl(pcdev->base + CIM_CTRL);
regval |= CIM_CTRL_DMA_EN;
regval &= ((~CIM_CTRL_RXF_RST) & (~CIM_CTRL_ENA));
writel(regval, pcdev->base + CIM_CTRL);
/* enable CIM */
regval = readl(pcdev->base + CIM_CTRL);
regval |= CIM_CTRL_DMA_EN | CIM_CTRL_ENA;
regval &= (~CIM_CTRL_RXF_RST);
writel(regval, pcdev->base + CIM_CTRL);
} else {
dma_desc_vaddr[vb->i].cmd &= (~CIM_CMD_EOFINT);
dma_desc_vaddr[vb->i].cmd |= CIM_CMD_STOP;
pcdev->dma_desc_tail->next = (dma_addr_t) (&pcdev->dma_desc[vb->i]);
pcdev->dma_desc_tail->cmd &= (~CIM_CMD_STOP);
pcdev->dma_desc_tail->cmd |= CIM_CMD_EOFINT;
pcdev->dma_desc_tail = (struct jz_camera_dma_desc *)(&dma_desc_vaddr[vb->i]);
}
}
}
}
static void jz_videobuf_release(struct videobuf_queue *vq,
struct videobuf_buffer *vb) {
struct jz_buffer *buf = container_of(vb, struct jz_buffer, vb);
dprintk(7, "%s (vb=0x%p) 0x%08lx %d\n", __func__,
vb, vb->baddr, vb->bsize);
switch (vb->state) {
case VIDEOBUF_ACTIVE:
dprintk(7, "%s (active)\n", __func__);
break;
case VIDEOBUF_QUEUED:
dprintk(7, "%s (queued)\n", __func__);
break;
case VIDEOBUF_PREPARED:
dprintk(7, "%s (prepared)\n", __func__);
break;
case VIDEOBUF_DONE:
dprintk(7, "%s (DONE)\n", __func__);
break;
case VIDEOBUF_IDLE:
dprintk(7, "%s (IDLE)\n", __func__);
break;
case VIDEOBUF_ERROR:
dprintk(7, "%s (ERROR)\n", __func__);
break;
case VIDEOBUF_NEEDS_INIT:
dprintk(7, "%s (INIT)\n", __func__);
break;
default:
dprintk(7, "%s (unknown)\n", __func__);
break;
}
free_buffer(vq, buf);
}
static int test_platform_param(struct jz_camera_dev *pcdev,
unsigned char buswidth, unsigned long *flags)
{
/*
* Platform specified synchronization and pixel clock polarities are
* only a recommendation and are only used during probing. The PXA270
* quick capture interface supports both.
*/
*flags = V4L2_MBUS_MASTER |
V4L2_MBUS_HSYNC_ACTIVE_HIGH |
V4L2_MBUS_HSYNC_ACTIVE_LOW |
V4L2_MBUS_VSYNC_ACTIVE_HIGH |
V4L2_MBUS_VSYNC_ACTIVE_LOW |
V4L2_MBUS_DATA_ACTIVE_HIGH |
V4L2_MBUS_PCLK_SAMPLE_RISING |
V4L2_MBUS_PCLK_SAMPLE_FALLING;
/* If requested data width is supported by the platform, use it */
//if ((1 << (buswidth - 1)) & pcdev->width_flags)
// return 0;
return 0;
// return -EINVAL;
}
static struct videobuf_queue_ops jz_videobuf_ops = {
.buf_setup = jz_videobuf_setup,
.buf_prepare = jz_videobuf_prepare,
.buf_queue = jz_videobuf_queue,
.buf_release = jz_videobuf_release,
};
static void jz_camera_init_videobuf(struct videobuf_queue *q, struct soc_camera_device *icd) {
struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
struct jz_camera_dev *pcdev = ici->priv;
videobuf_queue_dma_contig_init(q, &jz_videobuf_ops, icd->parent,
&pcdev->lock, V4L2_BUF_TYPE_VIDEO_CAPTURE, V4L2_FIELD_NONE,
sizeof(struct jz_buffer), icd, &ici->host_lock);
}
static int jz_camera_try_fmt(struct soc_camera_device *icd, struct v4l2_format *f) {
struct v4l2_subdev *sd = soc_camera_to_subdev(icd);
const struct soc_camera_format_xlate *xlate;
struct v4l2_pix_format *pix = &f->fmt.pix;
struct v4l2_mbus_framefmt mf;
__u32 pixfmt = pix->pixelformat;
int ret;
/* TODO: limit to jz hardware capabilities */
xlate = soc_camera_xlate_by_fourcc(icd, pix->pixelformat);
if (!xlate) {
printk("Format %x not found\n", pix->pixelformat);
return -EINVAL;
}
v4l_bound_align_image(&pix->width, 48, 2048, 1,
&pix->height, 32, 2048, 0,
pixfmt == V4L2_PIX_FMT_YUV422P ? 4 : 0);
mf.width = pix->width;
mf.height = pix->height;
mf.field = pix->field;
mf.colorspace = pix->colorspace;
mf.code = xlate->code;
/* limit to sensor capabilities */
ret = v4l2_subdev_call(sd, video, try_mbus_fmt, &mf);
if (ret < 0)
return ret;
pix->width = mf.width;
pix->height = mf.height;
pix->field = mf.field;
pix->colorspace = mf.colorspace;
return 0;
}
static int jz_camera_set_fmt(struct soc_camera_device *icd, struct v4l2_format *f) {
struct v4l2_subdev *sd = soc_camera_to_subdev(icd);
const struct soc_camera_format_xlate *xlate;
struct v4l2_pix_format *pix = &f->fmt.pix;
struct v4l2_mbus_framefmt mf;
int ret, buswidth;
xlate = soc_camera_xlate_by_fourcc(icd, pix->pixelformat);
if (!xlate) {
dprintk(4, "Format %x not found\n", pix->pixelformat);
return -EINVAL;
}
buswidth = xlate->host_fmt->bits_per_sample;
if (buswidth > 8) {
dprintk(4, "bits-per-sample %d for format %x unsupported\n",
buswidth, pix->pixelformat);
return -EINVAL;
}
mf.width = pix->width;
mf.height = pix->height;
mf.field = pix->field;
mf.colorspace = pix->colorspace;
mf.code = xlate->code;
ret = v4l2_subdev_call(sd, video, s_mbus_fmt, &mf);
if (ret < 0)
return ret;
if (mf.code != xlate->code)
return -EINVAL;
pix->width = mf.width;
pix->height = mf.height;
pix->field = mf.field;
pix->colorspace = mf.colorspace;
icd->current_fmt = xlate;
return ret;
}
static int jz_camera_set_crop(struct soc_camera_device *icd, const struct v4l2_crop *a) {
struct v4l2_subdev *sd = soc_camera_to_subdev(icd);
return v4l2_subdev_call(sd, video, s_crop, a);
}
static int jz_camera_set_bus_param(struct soc_camera_device *icd) {
struct v4l2_subdev *sd = soc_camera_to_subdev(icd);
struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
struct jz_camera_dev *pcdev = ici->priv;
struct v4l2_mbus_config cfg = {.type = V4L2_MBUS_PARALLEL,};
u32 pixfmt = icd->current_fmt->host_fmt->fourcc;
unsigned long common_flags;
unsigned long bus_flags = 0;
unsigned long cfg_reg = 0;
unsigned long ctrl_reg = 0;
unsigned long ctrl2_reg = 0;
unsigned long fs_reg = 0;
unsigned long temp = 0;
int ret;
ret = test_platform_param(pcdev, icd->current_fmt->host_fmt->bits_per_sample,
&bus_flags);
ret = v4l2_subdev_call(sd, video, g_mbus_config, &cfg);
if (!ret) {
common_flags = soc_mbus_config_compatible(&cfg,
bus_flags);
if (!common_flags) {
dev_warn(icd->parent,
"Flags incompatible: camera 0x%x, host 0x%lx\n",
cfg.flags, bus_flags);
return -EINVAL;
}
} else if (ret != -ENOIOCTLCMD) {
return ret;
} else {
common_flags = bus_flags;
}
/* Make choises, based on platform preferences */
if ((common_flags & V4L2_MBUS_VSYNC_ACTIVE_HIGH) &&
(common_flags & V4L2_MBUS_VSYNC_ACTIVE_LOW)) {
if (pcdev->pdata->flags & JZ_CAMERA_VSYNC_HIGH)
{
dev_warn(icd->parent, "================>V4L2_MBUS_VSYNC_ACTIVE_HIGH\n");
common_flags &= ~V4L2_MBUS_VSYNC_ACTIVE_HIGH;
}
else
{
dev_warn(icd->parent, "================>V4L2_MBUS_VSYNC_ACTIVE_LOW\n");
common_flags &= ~V4L2_MBUS_VSYNC_ACTIVE_LOW;
}
}
else
{
dev_warn(icd->parent, "================>V4L2_MBUS_VSYNC_ACTIVE_NONE\n");
}
if ((common_flags & V4L2_MBUS_PCLK_SAMPLE_RISING) &&
(common_flags & V4L2_MBUS_PCLK_SAMPLE_FALLING)) {
if (pcdev->pdata->flags & JZ_CAMERA_PCLK_RISING)
common_flags &= ~V4L2_MBUS_PCLK_SAMPLE_FALLING;
else
common_flags &= ~V4L2_MBUS_PCLK_SAMPLE_RISING;
}
if ((common_flags & V4L2_MBUS_DATA_ACTIVE_HIGH) &&
(common_flags & V4L2_MBUS_DATA_ACTIVE_LOW)) {
if (pcdev->pdata->flags & JZ_CAMERA_DATA_HIGH)
common_flags &= ~V4L2_MBUS_DATA_ACTIVE_LOW;
else
common_flags &= ~V4L2_MBUS_DATA_ACTIVE_HIGH;
}
cfg.flags = common_flags;
ret = v4l2_subdev_call(sd, video, s_mbus_config, &cfg);
if (ret < 0 && ret != -ENOIOCTLCMD) {
dev_dbg(icd->parent, "camera s_mbus_config(0x%lx) returned %d\n",
common_flags, ret);
return ret;
}
/*PCLK Polarity Set*/
cfg_reg = (common_flags & V4L2_MBUS_PCLK_SAMPLE_RISING) ?
cfg_reg | CIM_CFG_PCP_HIGH : cfg_reg & (~CIM_CFG_PCP_HIGH);
/*VSYNC Polarity Set*/
cfg_reg = (common_flags & V4L2_MBUS_VSYNC_ACTIVE_LOW) ?
cfg_reg | CIM_CFG_VSP_HIGH : cfg_reg & (~CIM_CFG_VSP_HIGH);
dev_warn(icd->parent, "================>vsync active %s\n", (cfg_reg&CIM_CFG_VSP_HIGH)?"falling":"rigsing");
/*HSYNC Polarity Set*/
cfg_reg = (common_flags & V4L2_MBUS_HSYNC_ACTIVE_LOW) ?
cfg_reg | CIM_CFG_HSP_HIGH : cfg_reg & (~CIM_CFG_HSP_HIGH);
dev_warn(icd->parent, "================>hsync active %s\n", (cfg_reg&CIM_CFG_HSP_HIGH)?"falling":"rigsing");
cfg_reg |= CIM_CFG_DMA_BURST_INCR32 | CIM_CFG_DF_YUV422
| CIM_CFG_DSM_GCM | CIM_CFG_PACK_Y0UY1V;
ctrl_reg |= CIM_CTRL_DMA_SYNC | CIM_CTRL_FRC_1;
ctrl2_reg |= CIM_CTRL2_APM | CIM_CTRL2_EME | CIM_CTRL2_OPE |
(1 << CIM_CTRL2_OPG_BIT) | CIM_CTRL2_FSC | CIM_CTRL2_ARIF;
fs_reg = (icd->user_width -1) << CIM_FS_FHS_BIT | (icd->user_height -1)
<< CIM_FS_FVS_BIT | 1 << CIM_FS_BPP_BIT;
if((pixfmt == V4L2_PIX_FMT_YUV420) || (pixfmt == V4L2_PIX_FMT_JZ420B)) {
ctrl2_reg |= CIM_CTRL2_CSC_YUV420;
cfg_reg |= CIM_CFG_SEP | CIM_CFG_ORDER_YUYV;
}
if(pixfmt == V4L2_PIX_FMT_JZ420B)
ctrl_reg |= CIM_CTRL_MBEN;
if(pixfmt == V4L2_PIX_FMT_SBGGR8) {
fs_reg = (icd->user_width -1) << CIM_FS_FHS_BIT | (icd->user_height -1)
<< CIM_FS_FVS_BIT | 0 << CIM_FS_BPP_BIT;
ctrl2_reg |= CIM_CTRL2_CSC_BYPASS;
}
/*BS0 BS1 BS2 BS3 must be 00,01,02,03 when pack is b100*/
if(cfg_reg & CIM_CFG_PACK_Y0UY1V)
cfg_reg |= CIM_CFG_BS1_2_OBYT1 | CIM_CFG_BS2_2_OBYT2 | CIM_CFG_BS3_2_OBYT3;
writel(cfg_reg, pcdev->base + CIM_CFG);
writel(ctrl_reg, pcdev->base + CIM_CTRL);
writel(ctrl2_reg, pcdev->base + CIM_CTRL2);
writel(fs_reg, pcdev->base + CIM_FS);
#ifdef PRINT_CIM_REG
cim_dump_reg(pcdev);
#endif
/* enable end of frame interrupt */
temp = readl(pcdev->base + CIM_IMR);
temp &= (~CIM_IMR_EOFM);
writel(temp, pcdev->base + CIM_IMR);
/* enable stop of frame interrupt */
temp = readl(pcdev->base + CIM_IMR);
temp &= (~CIM_IMR_STPM);
writel(temp, pcdev->base + CIM_IMR);
/* enable rx overflow interrupt */
temp = readl(pcdev->base + CIM_IMR);
temp &= (~CIM_IMR_RFIFO_OFM);
writel(temp, pcdev->base + CIM_IMR);
temp = readl(pcdev->base + CIM_IMR);
temp &= (~CIM_IMR_STPM_1);
writel(temp, pcdev->base + CIM_IMR);
return 0;
}
static void jz_camera_activate(struct jz_camera_dev *pcdev) {
int ret = -1;
dprintk(7, "Activate device\n");
if(pcdev->clk) {
ret = clk_enable(pcdev->clk);
}
if(pcdev->mclk) {
ret = clk_set_rate(pcdev->mclk, pcdev->mclk_freq);
ret = clk_enable(pcdev->mclk);
}
if(regul)
regulator_enable(regul);
if(ret) {
printk("enable clock failed!\n");
}
msleep(10);
}
static void jz_camera_deactivate(struct jz_camera_dev *pcdev) {
unsigned long temp = 0;
if(pcdev->clk) {
clk_disable(pcdev->clk);
}
if(pcdev->mclk) {
clk_disable(pcdev->mclk);
}
if(regul)
regulator_disable(regul);
/* clear status register */
writel(0, pcdev->base + CIM_STATE);
/* disable end of frame interrupt */
temp = readl(pcdev->base + CIM_IMR);
temp |= CIM_IMR_EOFM;
writel(temp, pcdev->base + CIM_IMR);
/* disable rx overflow interrupt */
temp = readl(pcdev->base + CIM_IMR);
temp |= CIM_IMR_RFIFO_OFM;
writel(temp, pcdev->base + CIM_IMR);
/* disable dma */
temp = readl(pcdev->base + CIM_CTRL);
temp &= ~CIM_CTRL_DMA_EN;
writel(temp, pcdev->base + CIM_CTRL);
/* clear rx fifo */
temp = readl(pcdev->base + CIM_CTRL);
temp |= CIM_CTRL_RXF_RST;
writel(temp, pcdev->base + CIM_CTRL);
temp = readl(pcdev->base + CIM_CTRL);
temp &= ~CIM_CTRL_RXF_RST;
writel(temp, pcdev->base + CIM_CTRL);
/* disable cim */
temp = readl(pcdev->base + CIM_CTRL);
temp &= ~CIM_CTRL_ENA;
writel(temp, pcdev->base + CIM_CTRL);
if(pcdev && pcdev->desc_vaddr) {
dma_free_coherent(pcdev->soc_host.v4l2_dev.dev,
sizeof(*pcdev->dma_desc) * pcdev->buf_cnt,
pcdev->desc_vaddr, (dma_addr_t )pcdev->dma_desc);
pcdev->desc_vaddr = NULL;
}
dprintk(7, "Deactivate device\n");
}
static int jz_camera_add_device(struct soc_camera_device *icd) {
struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
struct jz_camera_dev *pcdev = ici->priv;
int icd_index = icd->devnum;
if (pcdev->icd[icd_index])
return -EBUSY;
printk("jz Camera driver attached to camera %d\n",
icd->devnum);
pcdev->icd[icd_index] = icd;
pcdev->is_first_start = 1;
/* disable tlb when open camera every time */
pcdev->is_tlb_enabled = 0;
jz_camera_activate(pcdev);
return 0;
}
static void jz_camera_remove_device(struct soc_camera_device *icd) {
struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
struct jz_camera_dev *pcdev = ici->priv;
int icd_index = icd->devnum;
BUG_ON(icd != pcdev->icd[icd_index]);
jz_camera_deactivate(pcdev);
dprintk(6, "jz Camera driver detached from camera %d\n",
icd->devnum);
pcdev->icd[icd_index] = NULL;
}
static void jz_camera_wakeup(struct jz_camera_dev *pcdev,
struct videobuf_buffer *vb) {
vb->state = VIDEOBUF_DONE;
do_gettimeofday(&vb->ts);
vb->field_count++;
wake_up(&vb->done);
dprintk(7, "after wake up cost %d ms\n", jiffies_to_msecs(jiffies - jiff_temp));
}
static irqreturn_t jz_camera_irq_handler(int irq, void *data) {
struct jz_camera_dev *pcdev = (struct jz_camera_dev *)data;
unsigned long status = 0, temp = 0;
unsigned long flags = 0;
int index = 0, regval = 0;
struct jz_camera_dma_desc *dma_desc_paddr;
//cim_dump_reg(pcdev);
for (index = 0; index < ARRAY_SIZE(pcdev->icd); index++) {
if (pcdev->icd[index]) {
break;
}
}
if(index == MAX_SOC_CAM_NUM)
return IRQ_HANDLED;
/* judged pcdev->dma_desc_head->id */
if((pcdev->dma_desc_head->id > pcdev->buf_cnt) || (pcdev->dma_desc_head->id < 0)) {
printk("Warning: %s, %d, pcdev->dma_desc_head->id >pcdev->buf_cnt || pcdev->dma_desc_head->id < 0, please check pcdev->dma_desc_head->id !!!\n",
__func__, pcdev->dma_desc_head->id);
return IRQ_NONE;
}
spin_lock_irqsave(&pcdev->lock, flags);
/* read interrupt status register */
status = readl(pcdev->base + CIM_STATE);
if (!status) {
printk("status is NULL! \n");
spin_unlock_irqrestore(&pcdev->lock, flags);
return IRQ_NONE;
}
if(!(status & CIM_STATE_RXOF_STOP_EOF)) {
/* other irq */
printk("irq_handle status is 0x%lx, not judged in irq_handle\n", status);
spin_unlock_irqrestore(&pcdev->lock, flags);
return IRQ_HANDLED;
}
if (status & CIM_STATE_RXF_OF) {
printk("RX FIFO OverFlow interrupt!\n");
/* clear rx overflow interrupt */
temp = readl(pcdev->base + CIM_STATE);
temp &= ~CIM_STATE_RXF_OF;
writel(temp, pcdev->base + CIM_STATE);
/* disable cim */
temp = readl(pcdev->base + CIM_CTRL);
temp &= ~CIM_CTRL_ENA;
writel(temp, pcdev->base + CIM_CTRL);
/* clear rx fifo */
temp = readl(pcdev->base + CIM_CTRL);
temp |= CIM_CTRL_RXF_RST;
writel(temp, pcdev->base + CIM_CTRL);
temp = readl(pcdev->base + CIM_CTRL);
temp &= ~CIM_CTRL_RXF_RST;
writel(temp, pcdev->base + CIM_CTRL);
/* clear status register */
writel(0, pcdev->base + CIM_STATE);
/* enable cim */
temp = readl(pcdev->base + CIM_CTRL);
temp |= CIM_CTRL_ENA;
writel(temp, pcdev->base + CIM_CTRL);
spin_unlock_irqrestore(&pcdev->lock, flags);
return IRQ_HANDLED;
}
if(status & CIM_STATE_DMA_STOP) {
/* clear dma interrupt status */
temp = readl(pcdev->base + CIM_STATE);
temp &= (~CIM_STATE_DMA_STOP);
writel(temp, pcdev->base + CIM_STATE);
jz_camera_wakeup(pcdev, (pcdev->vb_address[pcdev->dma_desc_head->id]));
if(pcdev->dma_desc_head == pcdev->dma_desc_tail) {
if(is_cim_enable(pcdev)) {
cim_disable_without_dma(pcdev);
} else {
printk("@@@@@@ not complate!\n");
}
} else {
pcdev->dma_desc_head =
(struct jz_camera_dma_desc *)UNCAC_ADDR(phys_to_virt(pcdev->dma_desc_head->next));
/* Configure register CIMDA */
dma_desc_paddr = (struct jz_camera_dma_desc *) pcdev->dma_desc;
regval = (unsigned int) (&dma_desc_paddr[pcdev->dma_desc_head->id]);
writel(regval, pcdev->base + CIM_DA);
}
spin_unlock_irqrestore(&pcdev->lock, flags);
return IRQ_HANDLED;
}
if(status & CIM_STATE_DMA_EOF) {
/* clear dma interrupt status */
temp = readl(pcdev->base + CIM_STATE);
temp &= (~CIM_STATE_DMA_EOF);
writel(temp, pcdev->base + CIM_STATE);
jz_camera_wakeup(pcdev, (struct videobuf_buffer *)(pcdev->vb_address[pcdev->dma_desc_head->id]));
if(pcdev->dma_desc_head != pcdev->dma_desc_tail) {
pcdev->dma_desc_head =
(struct jz_camera_dma_desc *)UNCAC_ADDR(phys_to_virt(pcdev->dma_desc_head->next));
}
spin_unlock_irqrestore(&pcdev->lock, flags);
return IRQ_HANDLED;
}
spin_unlock_irqrestore(&pcdev->lock, flags);
return IRQ_HANDLED;
}
/* initial camera sensor reset and power gpio */
static int camera_sensor_gpio_init(struct platform_device *pdev) {
int ret, i, cnt = 0;
struct jz_camera_pdata *pdata = pdev->dev.platform_data;
char gpio_name[20];
if(!pdata) {
dev_err(&pdev->dev, "%s:have not cim platform data\n", __func__);
return -1;
}
for (i = 0; i < ARRAY_SIZE(pdata->cam_sensor_pdata); i++) {
if (pdata->cam_sensor_pdata[i].gpio_en){
sprintf(gpio_name, "cim_enable%d", i);
printk("cim_enable%d,%d\n", i,pdata->cam_sensor_pdata[i].gpio_rst);
ret = gpio_request(pdata->cam_sensor_pdata[i].gpio_en, gpio_name);
if (ret){
dev_err(&pdev->dev, "%s:request cim%d vdd en gpio fail\n",
__func__, i);
goto err_request_gpio;
}
gpio_direction_output(pdata->cam_sensor_pdata[i].gpio_en, 0);
cnt++;
}
}
for (i = 0; i < ARRAY_SIZE(pdata->cam_sensor_pdata); i++) {
if(pdata->cam_sensor_pdata[i].gpio_rst) {
sprintf(gpio_name, "sensor_rst%d", i);
printk("sensor_rst%d,%d\n", i,pdata->cam_sensor_pdata[i].gpio_rst);
ret = gpio_request(pdata->cam_sensor_pdata[i].gpio_rst,
gpio_name);
if(ret) {
dev_err(&pdev->dev, "%s:request cim%d reset gpio fail\n",
__func__, i);
goto err_request_gpio;
}
gpio_direction_output(pdata->cam_sensor_pdata[i].gpio_rst, 0);
cnt++;
}
if(pdata->cam_sensor_pdata[i].gpio_power) {
sprintf(gpio_name, "sensor_en%d", i);
printk("sensor_en%d,%d\n", i,pdata->cam_sensor_pdata[i].gpio_power);
ret = gpio_request(pdata->cam_sensor_pdata[i].gpio_power,
gpio_name);
if(ret) {
dev_err(&pdev->dev, "%s:request cim%d en gpio fail\n",
__func__, i);
goto err_request_gpio;
}
// gpio_direction_output(pdata->cam_sensor_pdata[i].gpio_power, 1);
gpio_direction_output(pdata->cam_sensor_pdata[i].gpio_power, 0);
cnt++;
}
}
return 0;
err_request_gpio:
for (i = 0; i < cnt / 2; i++) {
gpio_free(pdata->cam_sensor_pdata[i].gpio_rst);
gpio_free(pdata->cam_sensor_pdata[i].gpio_power);
}
if ((cnt % 2) != 0) {
gpio_free(pdata->cam_sensor_pdata[i].gpio_rst);
}
return ret;
}
static struct soc_camera_host_ops jz_soc_camera_host_ops = {
.owner = THIS_MODULE,
.add = jz_camera_add_device,
.remove = jz_camera_remove_device,
.set_bus_param = jz_camera_set_bus_param,
.set_crop = jz_camera_set_crop,
.set_fmt = jz_camera_set_fmt,
.try_fmt = jz_camera_try_fmt,
.init_videobuf = jz_camera_init_videobuf,
.reqbufs = jz_camera_reqbufs,
.poll = jz_camera_poll,
.querycap = jz_camera_querycap,
//.num_controls = 0,
};
static int __init jz_camera_probe(struct platform_device *pdev) {
int err = 0;
unsigned int irq;
struct resource *res;
void __iomem *base;
struct jz_camera_dev *pcdev;
/* malloc */
pcdev = kzalloc(sizeof(*pcdev), GFP_KERNEL);
if (!pcdev) {
dprintk(3, "Could not allocate pcdev\n");
err = -ENOMEM;
goto err_kzalloc;
}
/* resource */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if(!res) {
dprintk(3, "Could not get resource!\n");
err = -ENODEV;
goto err_get_resource;
}
/* irq */
irq = platform_get_irq(pdev, 0);
if (irq <= 0) {
dprintk(3, "Could not get irq!\n");
err = -ENODEV;
goto err_get_irq;
}
/*get cim1 clk*/
pcdev->clk = clk_get(&pdev->dev, "cim");
if (IS_ERR(pcdev->clk)) {
err = PTR_ERR(pcdev->clk);
dev_err(&pdev->dev, "%s:can't get clk %s\n", __func__, "cim");
goto err_clk_get_cim1;
}
/*get cgu_cimmclk1 clk*/
pcdev->mclk = clk_get(&pdev->dev, "cgu_cim");
if (IS_ERR(pcdev->mclk)) {
err = PTR_ERR(pcdev->mclk);
dev_err(&pdev->dev, "%s:can't get clk %s\n",
__func__, "cgu_cimmclk");
goto err_clk_get_cgu_cimmclk1;
}
regul = regulator_get(NULL, CAMERA_GSENSOR_VCC);
if(IS_ERR(regul)) {
dprintk(3, "get regulator fail !, if you need regulator, please check this place!\n");
err = -ENODEV;
regul = NULL;
// goto exit_put_clk_cim;
}else {
regulator_enable(regul);
}
pcdev->pdata = pdev->dev.platform_data;
if (pcdev->pdata)
pcdev->mclk_freq = pcdev->pdata->mclk_10khz * 10000;
if (!pcdev->mclk_freq) {
dprintk(4, "mclk_10khz == 0! Please, fix your platform data."
"Using default 24MHz\n");
pcdev->mclk_freq = 24000000;
}
if (clk_get_rate(pcdev->mclk) >= pcdev->mclk_freq) {
clk_set_rate(pcdev->mclk, pcdev->mclk_freq);
} else {
clk_set_rate(pcdev->mclk, pcdev->mclk_freq);
}
/* Request the regions. */
if (!request_mem_region(res->start, resource_size(res), DRIVER_NAME)) {
err = -EBUSY;
goto err_request_mem_region;
}
base = ioremap(res->start, resource_size(res));
if (!base) {
err = -ENOMEM;
goto err_ioremap;
}
spin_lock_init(&pcdev->lock);
pcdev->res = res;
pcdev->irq = irq;
pcdev->base = base;
/* request irq */
err = request_irq(pcdev->irq, jz_camera_irq_handler, IRQF_DISABLED,
dev_name(&pdev->dev), pcdev);
if(err) {
dprintk(3, "request irq failed!\n");
goto err_request_irq;
}
/* request sensor reset and power gpio */
err = camera_sensor_gpio_init(pdev);
if(err) {
dump_stack();
goto err_camera_sensor_gpio_init;
}
pcdev->soc_host.drv_name = DRIVER_NAME;
pcdev->soc_host.ops = &jz_soc_camera_host_ops;
pcdev->soc_host.priv = pcdev;
pcdev->soc_host.v4l2_dev.dev = &pdev->dev;
//pcdev->soc_host.nr = pdev->id;
pcdev->soc_host.nr = 0; /* use one cim0 or cim1 */
pcdev->poll_flag = 0;
pcdev->vb_address_flag = 0;
err = soc_camera_host_register(&pcdev->soc_host);
if (err)
goto err_soc_camera_host_register;
if (!IS_ERR(regul))
regulator_disable(regul);
dprintk(6, "jz Camera driver loaded!\n");
return 0;
err_soc_camera_host_register:
err_camera_sensor_gpio_init:
free_irq(pcdev->irq, pcdev);
err_request_irq:
iounmap(base);
err_ioremap:
release_mem_region(res->start, resource_size(res));
err_request_mem_region:
clk_put(pcdev->mclk);
err_clk_get_cgu_cimmclk1:
clk_put(pcdev->clk);
err_clk_get_cim1:
err_get_irq:
err_get_resource:
kfree(pcdev);
err_kzalloc:
return err;
}
static int __exit jz_camera_remove(struct platform_device *pdev)
{
struct soc_camera_host *soc_host = to_soc_camera_host(&pdev->dev);
struct jz_camera_dev *pcdev = container_of(soc_host,
struct jz_camera_dev, soc_host);
struct resource *res;
free_irq(pcdev->irq, pcdev);
clk_put(pcdev->clk);
clk_put(pcdev->mclk);
soc_camera_host_unregister(soc_host);
iounmap(pcdev->base);
res = pcdev->res;
release_mem_region(res->start, resource_size(res));
kfree(pcdev);
dprintk(6, "jz Camera driver unloaded\n");
return 0;
}
static struct platform_driver jz_camera_driver = {
.remove = __exit_p(jz_camera_remove),
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
};
static int __init jz_camera_init(void) {
/*
* platform_driver_probe() can save memory,
* but this Driver can bind to one device only.
*/
return platform_driver_probe(&jz_camera_driver, jz_camera_probe);
}
static void __exit jz_camera_exit(void) {
return platform_driver_unregister(&jz_camera_driver);
}
late_initcall(jz_camera_init);
module_exit(jz_camera_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("yefei <<EMAIL>>");
MODULE_DESCRIPTION("jz Soc Camera Host Driver");
MODULE_ALIAS("a jz-cim platform");
<file_sep>/work/test/fb_test/Makefile
GCC := mips-linux-gnu-gcc
CFLAGS := -EL -mabi=32 -mhard-float -march=mips32r2 -Os
LDFLAGS:= -Wl,-EL
LDLIBS :=
SOURCES := $(wildcard *.c)
TARGET = fb_test
all: $(TARGET)
$(TARGET): $(SOURCES)
$(GCC) $(CFLAGS) $(LDFLAGS) -o $@ $^
.PHONY:install clean distclean
INSTALL_DIR := ~/work/mozart-new/mozart/rootfs/updater/usr/bin/
install:fb_test
cp $(TARGET) $(INSTALL_DIR)
clean:
rm $(TARGET) *.o -rf
distclean:
rm $(TARGET) $(INSTALL_DIR)/$(TARGET) *.o -rf
<file_sep>/work/test/cim_test-zmm220/Makefile
#CC=gcc
#ifeq ($(MAKERULES),)
#include ../../Rules.make
#else
#include $(MAKERULES)
#endif
CC=mipsel-linux-gcc
#CC=arm-marvell-linux-gnueabi-gcc
#CFLAGS+=-Iinclude/ -DDEBUG_BUILD -DCONFIG_IPM \
-I/home/work/300/rel/host/include\
-g -Waggregate-return -Wmissing-noreturn -W -Wall -mcpu=iwmmxt -mtune=iwmmxt -mabi=aapcs-linux
# -I/home/work/300/rel/host/include -L/home/work/300/rel/host/lib -L/home/work/300/rel/target/rootfs/lib -g -Waggregate-return -Wmissing-noreturn -W -Wall -mcpu=iwmmxt -mtune=iwmmxt -mabi=aapcs-linux
CFLAGS+=-O2 -W
#LFLAGS+= -I/opt/zem800/arm-marvell-linux-gnueabi/include -L/opt/zem800/arm-marvell-linux-gnueabi/lib -ljpeg
LFLAGS+= -ljpeg
.PHONY: all compile clean clean-local
all: compile
compile: cimtest
echo "built successfully"
OBJECTS=mt9v136.c cim.c gpio.c camera.c conver.c fvjpg.c futil.c yuv2jpg.c gc0308.c
cimtest:$(OBJECTS)
$(CC) $(CFLAGS) $(LFLAGS) -o $@ $^
clean: clean-local
clean-local:
-rm -f *.o cimtest
<file_sep>/work/test/yuv2bmp/Makefile
LFLAGS =
yuv2bmp:
gcc $(LFLAGS) -o yuv2bmp yuv2bmp.c
clean:
rm -rf yuv2bmp *.o
<file_sep>/sys_program/2nd_day/pm/alarm.c
/* ************************************************************************
* Filename: alarm.c
* Description:
* Version: 1.0
* Created: 2015年08月14日 15时20分17秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
int ret = 0;
ret = alarm(6);
printf("ret 1 = %d\n",ret);
sleep(4);
ret = alarm(5);
printf("ret 2 = %d\n",ret);
while(1)
{
printf("alarm\n");
sleep(1);
}
return 0;
}
<file_sep>/c/practice/3rd_week/encrypt/Makefile
encrypt:main.c encrypt.c
gcc -o encrypt main.c encrypt.c
clean:
rm encrypt
<file_sep>/c/practice/3rd_week/encrypt/encrypt.h
/* ************************************************************************
* Filename: encrypt.h
* Description:
* Version: 1.0
* Created: 2015年07月30日 星期四 02時04分56秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __ENCRYPT_H__
#define __ENCRYPT_H__
void get_file_name(char * dest_file_name,char * src_file_name);
char * read_src_file(unsigned long int *file_length,char *src_file_name);
char * file_text_encrypt(char * src_file_text,unsigned long int length,unsigned int password);
char * file_text_decrypt(char * src_file_text,unsigned long int length,unsigned int password);
void save_file(char* text,unsigned long int length,char * file_name);
#endif
<file_sep>/network/route/src/inc/firewall_link.h
/******************************************************************************
文 件 名 : firewall_link.h
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月13日
最近修改 :
功能描述 : firewall_link.c 的头文件
******************************************************************************/
#ifndef __FIREWALL_LINK_H__
#define __FIREWALL_LINK_H__
#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */
/*----------------------------------------------*
* 函数原型说明 *
*----------------------------------------------*/
extern FIRE_Wall *delete_firewall_node(FIRE_Wall *head, const char *rule);
extern FIRE_Wall *free_firewall_link(FIRE_Wall *head);
extern FIRE_Wall *insert_firewall_node(FIRE_Wall *head, FIRE_Wall node);
extern void print_firewall(FIRE_Wall *head);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
#endif /* __FIREWALL_LINK_H__ */
<file_sep>/c/homework/1st_week/perversion.c
/* ************************************************************************
* Filename: perversion.c
* Description:
* Version: 1.0
* Created: 2015年07月17日 星期五 06時34分20秒 HKT
* Revision: none
* Compiler: gcc
* Author: 王秋伟
* Company:
* ************************************************************************/
#include <stdio.h>
#include <malloc.h>
#include <math.h>
#if 0
int main(int argc, char *argv[])
{
int count = 0;
int number = 0;
int *buf = NULL;
char i;
printf("Please input a integer number:\n");
scanf("%d",&number);
count = printf("%d\n",number) - 1;
//printf("count = %d\n",count);
buf = (int *)malloc((sizeof(int) * count));
perversion(number, buf, count);
for(i=0;i<count;i++)
{
printf("%d",buf[i]);
}
putchar('\n');
return 0;
}
void perversion(int number, int *buf, int count)
{
int i;
int divisor;
for(i=count-1;i>=0;i--)
{
divisor = (int)pow(10,i);
buf[i] = number/divisor;
number %= divisor;
}
}
#else
void perversion(int number, char *buf, int count)
{
int i;
int divisor;
for(i=count-1;i>=0;i--)
{
divisor = (int)pow(10,i);
buf[i] = number/divisor;
number %= divisor;
}
}
int main(int argc, char *argv[])
{
int count = 0;
int number = 0;
char *buf = NULL;
char i;
printf("Please input a integer number:\n");
scanf("%d",&number);
#if 0 //三种方法计算 count 的值
count = printf("%d\n",number) - 1;
#elif 1
while((number/pow(10,count))>=1)
{
count++;
}
#else
count =(int)log10(number) + 1;
#endif
//printf("count = %d\n",count);
buf = (char *)malloc((sizeof(char) * count));
if(count>1)
{
perversion(number, buf, count);
for(i=0;i<count;i++)
{
printf("%d",buf[i]);
}
putchar('\n');
}
else
{
printf("%d\n",number);
}
free(buf);
return 0;
}
#endif
<file_sep>/work/debug/pc/timer/timer_drv.c
/* ************************************************************************
* Filename: timer.c
* Description:
* Version: 1.0
* Created: 2015年08月07日 19时28分40秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <linux/timer.h> /*包括timer.h头文件*/
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/miscdevice.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include <asm/atomic.h>
#define DEVICE_NAME "timer_drv"
struct timer_dev
{
struct cdev timer_cdev;
struct timer_list s_timer;
atomic_t counter;
};
struct timer_dev *p_tdev = NULL;
//dev_t devno; //设备号
//static int majno = 0; //主设备号
//定时器到达expires 时间后,这个函数被调用
static void this_timer_handle(unsigned long arg)
{
mod_timer(&p_tdev->s_timer,jiffies + HZ); //更新定时器
atomic_inc(&p_tdev->counter); //使counter自增
printk(KERN_NOTICE "current jiffies is %ld\n",jiffies);
}
int this_timer_release(struct inode *inode, struct file *filp)
{
del_timer(&p_tdev->s_timer);
return 0;
}
static int timer_open(struct inode *inode, struct file *filp)
{
//初始化定时器,主要对定时器的下一定时器的地址和此定时器所在结构体进行初始化
init_timer(&p_tdev->s_timer);
p_tdev->s_timer.function = this_timer_handle; //设置定时器超时后调度的超时处理函数
//设置定时器超时的时间,jiffies为当前滴答数,HZ为一秒的滴答数
p_tdev->s_timer.expires = jiffies + HZ;
add_timer(&p_tdev->s_timer); //把定时器添加到定时器链表中
atomic_set(&p_tdev->counter,0); //计数清零
return 0;
}
static ssize_t timer_read(struct file *filp,char __user *buf, size_t count,loff_t *ppos)
{
int counter;
counter = atomic_read(&p_tdev->counter); //
if(put_user(counter,(int*)buf))
return -EFAULT;
else
return(sizeof(unsigned int));
}
static struct file_operations timer_fops =
{
.owner = THIS_MODULE,
.open = timer_open,
.read = timer_read,
.release = this_timer_release,
};
static void timer_setup_cdev(struct timer_dev *dev, int index)
{
int err;
//dev_t devno = MKDEV(majno,0);
cdev_init(&dev->timer_cdev,&timer_fops);
dev->timer_cdev.owner = THIS_MODULE;
dev->timer_cdev.ops = &timer_fops;
//err = cdev_add(&dev->timer_cdev,devno,1);
err = cdev_add(&dev->timer_cdev,10,1);
if(err)
{
printk(KERN_NOTICE "Error %d adding timer %d",err,index);
}
}
static struct miscdevice misc =
{
.minor = MISC_DYNAMIC_MINOR, //表示动态分配次设备号
.name = DEVICE_NAME,
.fops = &timer_fops,
};
static int __init timerdrv_init(void)
{
int ret;
ret = misc_register(&misc);
if(ret<0)
{
printk(KERN_INFO " can't register timer_drv\n");
return ret;
}
p_tdev = kmalloc(sizeof(struct timer_dev), GFP_KERNEL);
if(!p_tdev)
{
ret = -ENOMEM;
goto fail_malloc;
}
memset(p_tdev, 0, sizeof(struct timer_dev));
timer_setup_cdev(p_tdev,0);
printk(KERN_INFO "timer_drv initialized\n");
return 0;
fail_malloc:
misc_deregister(&misc);
return -1;
}
static void __exit timerdrv_exit(void)
{
cdev_del(&p_tdev->timer_cdev);//注销cdev
kfree(p_tdev); //回收设备结构的内存
misc_deregister(&misc);
printk(KERN_INFO "timer_drv exited!\n");
}
#if 0
static void timer_setup_cdev(struct timer_dev *dev, int index)
{
int err;
dev_t devno = MKDEV(majno,0);
cdev_init(&dev->timer_cdev,&timer_fops);
dev->timer_cdev.owner = THIS_MODULE;
dev->timer_cdev.ops = &timer_fops;
err = cdev_add(&dev->timer_cdev,devno,1);
if(err)
{
printk(KERN_NOTICE "Error %d adding timer %d",err,index);
}
}
static int __init timerdev_init(void)
{
int ret;
dev_t devno = MKDEV(majno,0);
if(!majno) //动态申请主设备号
{
ret = alloc_chrdev_region(&devno,0,1,DEVICE_NAME);
majno = MAJOR(devno);
}
else
{
ret = register_chrdev_region(devno,1,DEVICE_NAME);
}
if(ret < 0) return ret;//失败
p_tdev = kmalloc(sizeof(struct timer_dev), GFP_KERNEL);
if(!p_tdev)
{
ret = -ENOMEM;
goto fail_malloc;
}
memset(p_tdev, 0, sizeof(struct timer_dev));
timer_setup_cdev(p_tdev,0);
//注册一个类
timer_class = class_create(THIS_MODULE, DEVICE_NAME);//要包含#include <linux/device.h>
if(IS_ERR(timer_class))
{
printk("Err:failed in create leds class\n");
goto fail_add_class;
}
//创建一个设备节点
//device_create(timer_class, NULL, MKDEV(majno, 0), NULL, DEVICE_NAME);
device_create(timer_class, NULL, devno, NULL, DEVICE_NAME);
return 0;
fail_malloc:
unregister_chrdev_region(devno,1);
return -1;
fail_add_class:
cdev_del(&p_tdev->timer_cdev);
kfree(p_tdev);
unregister_chrdev_region(devno,1);
return -1;
}
#endif
module_init(timerdrv_init);
module_exit(timerdrv_exit);
/* 描述驱动程序的一些信息,不是必须的 */
MODULE_AUTHOR("Dawei"); // 驱动程序的作者
MODULE_DESCRIPTION("A Timer Driver"); // 一些描述信息
MODULE_LICENSE("GPL"); // 遵循的协议
<file_sep>/sys_program/5th_day/cancel.c
/* ************************************************************************
* Filename: cancel.c
* Description:
* Version: 1.0
* Created: 2015年08月19日 14时42分08秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
pthread_t pth1,pth2;
void up_fun1(void *arg)
{
printf("push fun1\n");
}
void up_fun2(void *arg)
{
printf("push fun2\n");
}
void up_fun3(void *arg)
{
printf("push fun3\n");
}
void *fun1(void *arg)
{
int i=0;
//pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
pthread_cleanup_push(up_fun1,NULL);
pthread_cleanup_push(up_fun2,NULL);
pthread_cleanup_push(up_fun3,NULL);
pthread_cleanup_pop(0);
//for(i=0;i<20;i++)
while(1)
{
printf("in pth1\n");
sleep(1);
//pthread_testcancel();//
i++;
if(i == 2)
{
return 0;
}
}
pthread_cleanup_pop(0);
pthread_cleanup_pop(1);
return;
}
void *fun2(void *arg)
{
int i=0;
for(i=0;i<10;i++)
{
printf("in pth2\n");
sleep(1);
if(i==5)
{
pthread_exit(NULL);
}
if(i==2)
{
pthread_cancel(pth1);
}
}
return;
}
int main(int argc, char *argv[])
{
pthread_create(&pth1,NULL,fun1,NULL);
//pthread_create(&pth2,NULL,fun2,NULL);
sleep(5);
pthread_cancel(pth1);
pthread_join(pth1,NULL);
//pthread_join(pth2,NULL);
return 0;
}
<file_sep>/work/debug/a8/buttons/buttons_drv.c
#include <linux/module.h> /* module_init */
#include <linux/fs.h> /* file_operations */
#include <linux/device.h> /* class device */
#include <asm/io.h> /* writel() */
#include <plat/gpio-cfg.h> /* s3c_gpio_cfgpin */
#include <mach/gpio.h> /* gpio_set_value */
#include <linux/uaccess.h> /* copy_to_user() */
#include <linux/interrupt.h> /* request_irq() */
#include <linux/irq.h> /* IRQ_TYPE_EDGE_FALLING() */
#include <linux/delay.h> /* mdelay() */
#include <linux/kfifo.h> /* kfifo */
#include <linux/poll.h> /* poll */
#include <linux/kthread.h> /* kthread */
#include <linux/miscdevice.h> /* struct miscdevice */
#include <linux/cdev.h> /* cdev_init */
#include <linux/proc_fs.h> /* proc_dir_entry */
#include <linux/platform_device.h> /* platform_driver_register() */
#include <linux/ioport.h> /* resource */
#include <linux/input.h>
#include <linux/gpio_keys.h>
#define DEVICE_NAME "s5pv210_buttons"
#define DOWN 0 //按键按下
#define UP 1 //按键松开
#define GPH2_7 _IO('g',7)
#define GPH2_6 _IO('g',6)
#define GPH2_5 _IO('g',5)
#define GPH2_4 _IO('g',4)
static struct task_struct *kthread_ops = NULL;
static struct input_dev *input_buttons = NULL;
static struct workqueue_struct *buttons_workqueue = NULL;
static struct work_struct buttons_work;
static struct kfifo buttons_fifo;
static struct completion buttons_compet;
static struct timer_list buttons_timer;
static spinlock_t buttons_spinlock;
static atomic_t open_flag = ATOMIC_INIT(0);
struct gpio_buttons {
u8 status; /* up=0, down=1 */
u8 type; /* short=0, long=1 */
u32 code;
};
struct gpio_buttons button = {
.status = 0,
.type = 0,
.code = 0,
};
static struct gpio_keys_platform_data *pbuttons = NULL;
static int nbuttons = 0; // 记录按键个数
static int key_id = 0; // 记录哪个按键被按下
static struct gpio_keys_button s5pv210_gpio_buttons[] = {
// KEY2
{
.code = KEY_UP,
.gpio = S5PV210_GPH2(3),
.desc = "key-up",
.type = EV_KEY,
},
// KEY4
{
.code = KEY_DOWN,
.gpio = S5PV210_GPH2(5),
.desc = "key-down",
.type = EV_KEY,
},
// KEY6
{
.code = KEY_LEFT,
.gpio = S5PV210_GPH2(7),
.desc = "key-left",
.type = EV_KEY,
},
// KEY5
{
.code = KEY_RIGHT,
.gpio = S5PV210_GPH2(6),
.desc = "key-right",
.type = EV_KEY,
},
};
static struct resource s5pv210_gpio_resource[] = {
[0] = {
.start = S5PV210_GPH3(0),
.end = S5PV210_GPH3(0),
.name = "GPH3_0",
.flags = IORESOURCE_IO,
},
[1] = {
.start = S5PV210_GPH0(3),
.end = S5PV210_GPH0(3),
.name = "GPH0_3",
.flags = IORESOURCE_IO,
}
};
static struct gpio_keys_platform_data s5pv210_buttons_info = {
.buttons = s5pv210_gpio_buttons,
.nbuttons = ARRAY_SIZE(s5pv210_gpio_buttons),
};
static void s5pv210_buttons_release(struct device *pdev)
{
printk(KERN_WARNING "%s\n",__FUNCTION__);
return;
}
static struct platform_device s5pv210_buttons_dev = {
.name = "s5pv210_buttons",
.id = -1,
.num_resources = ARRAY_SIZE(s5pv210_gpio_resource),
.resource = s5pv210_gpio_resource,
.dev = {
.platform_data = &s5pv210_buttons_info,
.release = s5pv210_buttons_release,
},
};
static int input_buttons_open(struct input_dev *dev)
{
int i;
printk(KERN_WARNING "%s\n",__FUNCTION__);
if(atomic_read(&open_flag) == 0){
for(i=0;i<nbuttons;i++)
enable_irq(gpio_to_irq(pbuttons->buttons[i].gpio));
}
atomic_inc(&open_flag);
return 0;
}
static void input_buttons_close(struct input_dev *dev)
{
int i;
printk(KERN_WARNING "%s\n",__FUNCTION__);
del_timer_sync(&buttons_timer);
atomic_dec(&open_flag);
if(atomic_read(&open_flag) == 0){
for(i=0;i<nbuttons;i++)
disable_irq(gpio_to_irq(pbuttons->buttons[i].gpio));
}
}
static void buttons_timerhandler(unsigned long data)
{
int ret = 0;
unsigned long irqflag;
printk(KERN_WARNING "[msg]: %s\n",__FUNCTION__);
spin_lock_irqsave(&buttons_spinlock, irqflag);
button.type = 1; // 等0,表示短按,等1,表示长按
ret = kfifo_in(&buttons_fifo,&button, sizeof(button));
spin_unlock_irqrestore(&buttons_spinlock, irqflag);
if(ret != sizeof(button))
printk(KERN_WARNING "kfifo_in fail!\n");
mod_timer(&buttons_timer,jiffies+20);/* 5ms*20=100ms */
}
static void buttons_workhandler(struct work_struct *work)
{
int ret;
unsigned long irqflag;
if(button.status == 0){
s3c_gpio_cfgpin(pbuttons->buttons[key_id].gpio, S3C_GPIO_INPUT); // 配置引脚为输入,S3C_GPIO_INPUT 可以替换成S3C_GPIO_SFN(0x1)
mdelay(30); // 延时消抖
ret = gpio_get_value(pbuttons->buttons[key_id].gpio);
s3c_gpio_cfgpin(pbuttons->buttons[key_id].gpio, S3C_GPIO_SFN(0xf)); // S3C_GPIO_SFN(0xf)复用功能选择,0xf对应引脚中断功能,
if( ret != 0)
return;
if(kfifo_is_full(&buttons_fifo))
return;
spin_lock_irqsave(&buttons_spinlock, irqflag);
button.status = 1;
button.type = 0; // 等0,表示短按,等1,表示长按
button.code = pbuttons->buttons[key_id].code;
kfifo_in(&buttons_fifo,&button, sizeof(button));
spin_unlock_irqrestore(&buttons_spinlock, irqflag);
if(!timer_pending(&buttons_timer)){ // 查看定时器是否正被调度
buttons_timer.expires = jiffies+1*HZ; // 设置定时器的定时时间为1秒
add_timer(&buttons_timer); // 注册定时器
}
}
else { // 按键抬起 不用去抖动
del_timer_sync(&buttons_timer); // 删除定时器,在定时器时间到前停止一个已注册的定时器
if(kfifo_is_full(&buttons_fifo))
return;
spin_lock_irqsave(&buttons_spinlock, irqflag);
button.status = 0;
button.code = pbuttons->buttons[key_id].code;
kfifo_in(&buttons_fifo,&button, sizeof(button));
spin_unlock_irqrestore(&buttons_spinlock, irqflag);
}
}
static irqreturn_t s5pv210_buttons_irqhandler(int irq, void *dev_id)
{
//printk(KERN_WARNING "%s\n",__FUNCTION__);
key_id = (int)dev_id;
queue_work(buttons_workqueue, &buttons_work);
return IRQ_HANDLED;
}
static int kthread_ops_buttons(void *data)
{
int ret;
unsigned long irqflag;
struct gpio_buttons buttons_read;
for(;;)
{
if(kthread_should_stop()) break; // 是否终止
if(!kfifo_is_empty(&buttons_fifo)){
spin_lock_irqsave(&buttons_spinlock, irqflag);
ret = kfifo_out(&buttons_fifo, &buttons_read, sizeof(buttons_read));
spin_unlock_irqrestore(&buttons_spinlock, irqflag);
if(ret == sizeof(buttons_read)){
input_report_key(input_buttons, buttons_read.code, buttons_read.status); //
input_sync(input_buttons);
//printk(KERN_WARNING "%s\n",__FUNCTION__);
}
}
schedule_timeout(HZ); // 让出CPU,并告诉内核不要超过HZ时间不调‘我’
}
complete_and_exit(&buttons_compet, 0);
return 0;
}
static __devinit int s5pv210_buttons_probe(struct platform_device *pdev)
{
int ret, i;
printk(KERN_WARNING "%s\n",__FUNCTION__);
// 初始化按键公共端接口输出低电平
s3c_gpio_cfgpin(pdev->resource[0].start, S3C_GPIO_OUTPUT);
gpio_set_value(pdev->resource[0].start, 0);
ret = kfifo_alloc(&buttons_fifo, 128, GFP_KERNEL);
if(ret) goto out;
buttons_workqueue = create_workqueue("buttons_workqueue"); // 创建工作队列
INIT_WORK(&buttons_work,buttons_workhandler); // 初始化工作(工作和工作函数建立关联)
spin_lock_init(&buttons_spinlock); // 初始化自旋锁
init_timer(&buttons_timer);
buttons_timer.data = 0; // 设置传给回调函数的参数为0
buttons_timer.function = buttons_timerhandler; // 设置定时器到时回调函数
pbuttons = pdev->dev.platform_data;
nbuttons = pbuttons->nbuttons; // 获取按键个数
for(i=0;i<nbuttons;i++){
s3c_gpio_setpull(pbuttons->buttons[i].gpio, S3C_GPIO_PULL_UP); // 设置引脚上拉使能
// 注册中断
ret = request_irq(gpio_to_irq(pbuttons->buttons[i].gpio), s5pv210_buttons_irqhandler,\
IRQ_TYPE_EDGE_BOTH, pbuttons->buttons[i].desc, (void *)i);
disable_irq(gpio_to_irq(pbuttons->buttons[i].gpio));
if(ret){ //返回非0,中断申请失败
while(i--) //释放注册成功的中断
free_irq(gpio_to_irq(pbuttons->buttons[i].gpio), (void *)i);
goto request_irq_err;
}
}
//input 子系统
input_buttons = input_allocate_device(); // 给input设备分配空间
if(IS_ERR(input_buttons)){
ret = PTR_ERR(input_buttons);
goto input_allocate_err;
}
input_buttons->name = DEVICE_NAME;
input_buttons->phys = "inputkey";
input_buttons->id.bustype = BUS_HOST;
input_buttons->id.vendor = 0x0001;
input_buttons->evbit[0] = BIT(EV_KEY)|BIT(EV_REP)|BIT(EV_SYN); // 支持事件类型: 按键+重复按键+同步事件
for(i=0;i<nbuttons;i++){
set_bit(pbuttons->buttons[i].type, input_buttons->evbit);
set_bit(pbuttons->buttons[i].code, input_buttons->keybit);
//input_buttons->keybit[BIT_WORD(pbuttons->buttons[i].code)] |= BIT_MASK(pbuttons->buttons[i].code);
}
input_buttons->open = input_buttons_open; // 在input_register_device成功后被调用
input_buttons->close = input_buttons_close; // 在input_unregister_device成功后被调用
ret = input_register_device(input_buttons); // 注册input子系统
if(ret) goto input_register_err;
// completion是一种轻量级的机制,它允许一个线程告诉另一个线程工作已经完成
init_completion(&buttons_compet);// 可以利用宏静态创建completion: DECLARE_COMPLETION(my_completion);
// 创建内核线程
kthread_ops = kthread_create(kthread_ops_buttons, NULL, "buttons_ops");
if(IS_ERR(kthread_ops)){
complete(&buttons_compet);
ret = PTR_ERR(kthread_ops);
goto kthread_create_err;
}
wake_up_process(kthread_ops); // 启动内核进程
printk(KERN_WARNING "%s\n",__FUNCTION__);
return 0;
// 出错退出处理
kthread_create_err:
input_unregister_device(input_buttons);
input_register_err:
input_free_device(input_buttons);
input_allocate_err:
for(i=0; i<nbuttons; i++){
free_irq(gpio_to_irq(pbuttons->buttons[i].gpio), (void *)i);
}
request_irq_err:
destroy_workqueue(buttons_workqueue);
out:
kfifo_free(&buttons_fifo);
return ret;
}
static __devexit int s5pv210_buttons_remove(struct platform_device *pdev)
{
int i;
kthread_stop(kthread_ops);
wait_for_completion(&buttons_compet);
destroy_workqueue(buttons_workqueue);
input_unregister_device(input_buttons);
input_free_device(input_buttons);
kfifo_free(&buttons_fifo);
for(i=0; i<nbuttons; i++){
disable_irq(gpio_to_irq(pbuttons->buttons[i].gpio));
free_irq(gpio_to_irq(pbuttons->buttons[i].gpio), (void *)i);
}
printk(KERN_WARNING "%s\n",__FUNCTION__);
return 0;
}
static struct platform_driver s5pv210_buttons_drv = {
.probe = s5pv210_buttons_probe, // 匹配后的回调函数
.remove = s5pv210_buttons_remove, // 在设备注销时或是驱动注销时调用
.driver = {
.owner = THIS_MODULE,
.name = "s5pv210_buttons",
},
};
static __init int s5pv210_buttons_driver_init(void)
{
int ret;
ret = platform_device_register(&s5pv210_buttons_dev);
if(ret){
printk(KERN_ERR "%s: register device failed\n", __FUNCTION__);
goto fail0;
}
ret = platform_driver_register(&s5pv210_buttons_drv);
if(ret){
printk(KERN_ERR "%s: register driver failed\n", __FUNCTION__);
goto fail1;
}
return 0;
fail1:
platform_device_unregister(&s5pv210_buttons_dev);
fail0:
return ret;
}
static __exit void s5pv210_buttons_driver_exit(void)
{
platform_driver_unregister(&s5pv210_buttons_drv);
platform_device_unregister(&s5pv210_buttons_dev);
printk(KERN_WARNING "%s\n",__FUNCTION__);
return;
}
module_init(s5pv210_buttons_driver_init);
module_exit(s5pv210_buttons_driver_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/test/test.c
/* ************************************************************************
* Filename: test.c
* Description:
* Version: 1.0
* Created: 12/03/2015 04:55:09 PM
* Revision: none
* Compiler: gcc
* Author: <NAME> (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <signal.h>
#include <time.h>
#include <sys/types.h>
#if 1
int main(int argc, char argv[])
{
unsigned long length = 0;
FILE *fp = NULL;
char *buf = NULL;
fp = fopen("./qrcode_app", "rb+");
if(fp==NULL) {
printf("Cannot open the file\n");
return -1;
}
fseek(fp, 0, SEEK_END);
length = ftell(fp);
printf("file length: %lu\n", length);
fseek(fp, 0, SEEK_SET);
fwrite(&length, sizeof(length), 1, fp);
unsigned long r_len = 0;
fseek(fp, 0, SEEK_SET);
fread(&r_len, sizeof(length), 1, fp);
printf("read length: %lu\n", r_len);
fclose(fp);
return 0;
}
#elif 0
int test(char *src, char *dst)
{
if (src == NULL || dst == NULL)
return -1;
int count = 0;
char *p=NULL;
p = strtok(src, dst);
while(p != NULL) {
count++;
p = strtok(NULL, src);
}
return count;
}
void main()
{
char *src = "dd23kjdi32kkj23, 423";
char *buf = src;
char *dst = "23";
int count = 0;
char *p[100];
printf("src=%s, dst=%s\n", src, dst);
printf("count=%d\n", count);
//p[count] = strtok(buf, dst);
while((p[count] = strtok(buf, "23")) != NULL) {
count++;
//p[count] = strtok(buf, dst);
}
printf("count=%d\n", count);
}
#elif 0
#include <pwd.h>
static void do_sth(int cnt)
{
printf("This is a test program: %d!\n", cnt);
}
static void dump_compile_info(void)
{
time_t timep;
struct passwd *pwd;
char hostname[16] = "Unknown";
time(&timep);
pwd = getpwuid(getuid());
gethostname(hostname, 16);
printf("mozart compiled at %s on %s@%s\n", asctime(gmtime(&timep)), pwd->pw_name, hostname);
}
int main(int argc, char *argv[])
{
int cnt = 0;
daemon(0, 1);
while(1) {
do_sth(cnt);
cnt++;
sleep(1);
if (cnt > 20)
break;
}
dump_compile_info();
return 0;
}
#elif 0
struct cim_framebuf {
unsigned char id;
unsigned char busy;
unsigned char *pfree;
unsigned char *vaddr;
unsigned char *paddr;
struct cim_framebuf *next;
};
struct jz_cim_dev {
unsigned int nbuf;
unsigned int frame_size;
unsigned char read_flag;
unsigned char dma_started;
struct cim_framebuf *framebuf_head;
struct cim_framebuf *framebuf_index;
};
struct jz_cim_dev *cim = NULL;
static struct cim_framebuf *cim_insert_link(struct cim_framebuf *head, struct cim_framebuf *in)
{
struct cim_framebuf *pi, *pb;
if(in != NULL) {
pi = in;
if(head == NULL) {
head = pi;
head->next = head;
} else {
pb = head;
while(pb->next != head)
pb = pb->next;
pi->next = head;
pb->next = pi;
}
}
return head;
}
static struct cim_framebuf *cim_free_link(struct cim_framebuf *head)
{
struct cim_framebuf *pb, *pn;
if(head != NULL) {
pb = head;
pn = head->next;
while(pn != head) {
free(pb->pfree);
free(pb);
pb = pn;
pn = pn->next;
}
/* Last node */
free(pb->pfree);
free(pb);
}
return NULL;
}
void cim_print_link(struct cim_framebuf *head)
{
struct cim_framebuf *pb;
if(head != NULL) {
pb = head;
printf("pb->id = %d\n", pb->id);
printf("cim->framebuf vaddr = 0x%08x\n", pb->vaddr);
printf("cim->framebuf paddr = 0x%08x\n", pb->paddr);
while(pb->next != head) {
pb = pb->next;
printf("pb->id = %d\n", pb->id);
printf("cim->framebuf vaddr = 0x%08x\n", pb->vaddr);
printf("cim->framebuf paddr = 0x%08x\n", pb->paddr);
}
}
}
static int cim_fb_malloc(struct jz_cim_dev *cim)
{
int i;
struct cim_framebuf *in;
for(i = 0; i < cim->nbuf; i++) {
in = (struct cim_framebuf *)malloc(sizeof(struct cim_framebuf));
if(!in) {
printf("Can nor apply a framebuf memory space!\n");
return -1;
}
in->vaddr = (unsigned char *)malloc(cim->frame_size + 0x3f);
if(!in->vaddr) {
printf("malloc framebuf failed\n");
return -1;
}
memset(in->vaddr, 0, cim->frame_size);
in->id = i;
in->pfree = in->vaddr;
in->paddr = in->vaddr + 0x01;
printf("cim->framebuf vaddr = 0x%08x\n", in->vaddr);
printf("cim->framebuf paddr = 0x%08x\n", in->paddr);
cim->framebuf_head = cim_insert_link(cim->framebuf_head, in);
}
cim->framebuf_index = cim->framebuf_head;
return 0;
}
static void cim_fb_free(struct jz_cim_dev *cim)
{
cim->framebuf_head = cim_free_link(cim->framebuf_head);
}
int main(int argc, char *argv[])
{
int count;
cim = (struct jz_cim_dev *)malloc(sizeof(struct jz_cim_dev));
if(!cim) {
printf("%s -- malloc cim dev failed\n", __FUNCTION__);
return -1;
}
memset(cim, 0, sizeof(struct jz_cim_dev));
cim->nbuf = 1;
cim->frame_size = 640 * 480 * 2;
cim_fb_malloc(cim);
count = 4;
while(count--)
cim_print_link(cim->framebuf_head);
cim->nbuf = 3;
cim_fb_free(cim);
cim_fb_malloc(cim);
printf("====================================\n");
count = 25;
while(count--) {
printf("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n");
printf("cim framebuf id = %d\n", cim->framebuf_index->id);
printf("cim->framebuf vaddr = 0x%08x\n", cim->framebuf_index->vaddr);
printf("cim->framebuf paddr = 0x%08x\n", cim->framebuf_index->paddr);
cim->framebuf_index = cim->framebuf_index->next;
printf("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n");
}
return 0;
}
#elif 0
struct img_param_t {
unsigned int width; /* width */
unsigned int height; /* height */
unsigned int bpp; /* bits per pixel: 8/16/32 */
};
struct timing_param_t {
unsigned long mclk_freq;
unsigned int pclk_active_level; //0 for rising edge, 1 for falling edge
unsigned int hsync_active_level;
unsigned int vsync_active_level;
};
struct pix_buffer_t {
int read_flag;
void *pbuf; /* point to a frame_size buffer */
};
struct get_frame_t {
unsigned int nbuf; /* buffer number */
unsigned int frame_size; /* frame image size */
struct pix_buffer_t pix[0];
};
struct jz_cim_dev {
unsigned int frame_size;
unsigned char read_flag;
unsigned char dma_started;
unsigned char *pframebuf;
unsigned char *framebuf_vaddr;
unsigned char *framebuf_paddr;
void *desc_vaddr;
struct cim_dma_desc *dma_desc_paddr;
struct img_param_t img;
struct timing_param_t timing;
struct get_frame_t *frame;
};
int main(int argc, char *argv[])
{
printf("sizeof(long) = %lu\n", sizeof(long));
printf("sizeof(void *) = %lu\n", sizeof(void *));
printf("sizeof(struct img_param_t) = %lu\n", sizeof(struct img_param_t));
printf("sizeof(struct timing_param_t) = %lu\n", sizeof(struct timing_param_t));
printf("sizeof(struct pix_buffer_t) = %lu\n", sizeof(struct pix_buffer_t));
printf("sizeof(struct get_frame_t) = %lu\n", sizeof(struct get_frame_t));
printf("sizeof(struct jz_cim_dev) = %lu\n", sizeof(struct jz_cim_dev));
return 0;
}
#elif 0
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
typedef unsigned char u8;
typedef unsigned long u32;
struct regval_list {
u8 reg_num;
u8 value;
};
struct mode_list {
u8 index;
const struct regval_list *mode_regs;
};
/* Supported resolutions */
enum gc2155_width {
W_QVGA = 320,
W_VGA = 640,
W_720P = 1280,
};
enum gc2155_height {
H_QVGA = 240,
H_VGA = 480,
H_720P = 720,
};
struct gc2155_win_size {
char *name;
enum gc2155_width width;
enum gc2155_height height;
const struct regval_list *regs;
};
#define GC2155_SIZE(n, w, h, r) \
{.name = n, .width = w , .height = h, .regs = r }
static const struct gc2155_win_size gc2155_supported_win_sizes[] = {
GC2155_SIZE("QVGA", W_QVGA, H_QVGA, NULL),
GC2155_SIZE("VGA", W_VGA, H_VGA, NULL),
GC2155_SIZE("720P", W_720P, H_720P, NULL),
};
/* Select the nearest higher resolution for capture */
static const struct gc2155_win_size *gc2155_select_win(u32 *width, u32 *height)
{
int i, default_size = ARRAY_SIZE(gc2155_supported_win_sizes);
for (i = 0; i < default_size; i++) {
if (gc2155_supported_win_sizes[i].width >= *width &&
gc2155_supported_win_sizes[i].height >= *height) {
*width = gc2155_supported_win_sizes[i].width;
*height = gc2155_supported_win_sizes[i].height;
return &gc2155_supported_win_sizes[i];
}
}
*width = gc2155_supported_win_sizes[default_size-1].width;
*height = gc2155_supported_win_sizes[default_size-1].height;
return &gc2155_supported_win_sizes[default_size-1];
}
void fun1(int val)
{
printf("val = %d\n", val);
val = val + 100;
printf("val = %d\n", val);
if(val)
goto error;
error:
printf("%s: Error\n", __FUNCTION__);
}
void fun2(int val)
{
if(val)
goto error;
error:
printf("%s: Error\n", __FUNCTION__);
}
void main(void)
{
u32 width = 340, height = 500;
struct gc2155_win_size *win = NULL;
win = (struct gc2155_win_size *)malloc(sizeof(struct gc2155_win_size));
//win->width = 320;
//win->height = 240;
printf("win->width: %d win->height: %d\n", win->width, win->height);
win = gc2155_select_win(&width, &height);
printf("width: %d height: %d\n", width, height);
printf("win->width: %d win->height: %d\n", win->width, win->height);
fun1(1);
fun2(2);
}
#elif 0
int main()
{
int i;
int val = 0x12345678;
char buf[4] = "";
*(int *)buf = val;
for(i = 0; i <4; i++) {
printf("buf[%d] = %d\n", i, buf[i]);
}
}
#elif 0
int main(int argc, char *argv[])
{
unsigned int val = 0;
printf("## argc[1] = %s\n", argv[1]);
val = atoi(argv[1]);
printf("## atoi(): val = 0x%08x \n",val);
sscanf(argv[1],"%x", &val);
printf("## sscanf(): val = 0x%08x \n", val);
return 0;
}
#elif 0
int main(int argc, char *argv[])
{
int opt;
int option_index = 0;
char *optstring = "a:b:c:d";
static struct option long_options[] = {
{"reqarg", required_argument, NULL, 'r'},
{"nonarg",no_argument, NULL, 'n'},
{"optarg", optional_argument, NULL, 'o'},
{0,0,0,0},
};
while((opt = getopt_long(argc, argv, optstring, long_options, &option_index)) != -1) {
printf("opt = %c\n", opt);
printf("optarg = %s\n", optarg);
printf("optind = %d\n",optind);
printf("argv[optind - 1] = %s\n", argv[optind -1]);
printf("option_index = %d\n", option_index);
}
return 0;
}
#elif 0
extern char *optarg;
extern int optind, opterr, optopt;
int main(int argc, char *argv[])
{
int opt;
char *optstring = "a:b:c:d";
while ((opt = getopt(argc, argv, optstring)) != -1)
{
printf("opt = %c\n", opt);
printf("optarg = %s\n", optarg);
printf("optind = %d\n", optind);
printf("argv[optind - 1] = %s\n\n", argv[optind - 1]);
}
return 0;
}
#elif 0
//#define DEBUG
#ifdef DEBUG
#define debug(fmt, arg...) \
printf("jz-cim: "fmt, ##arg)
#else
#define debug(fmt, arg...)
#endif
#if 0
#ifdef DEBUG
#define _DEBUG 1
#define debug(fmt, arg...) \
do { \
if(_DEBUG) \
printf("jz-cim: "fmt, ##arg); \
}while(0)
#else
#define _DEBUG 0
#define debug(fmt, arg...) \
do { \
if(_DEBUG) \
printf("jz-cim: "fmt, ##arg); \
}while(0)
#endif
#endif
int main(int argc, char *argv[])
{
int i = 100;
debug("=== Hello world --%d ===\n", i);
return 0;
}
#elif 0
typedef struct {
int a;
short s[2];
}MSG;
void main() {
MSG *mp, m = {4, 1, 256};
char *fp, *tp;
mp = (MSG *)malloc(sizeof(MSG));
for(fp=(char *)mp->s, tp=(char *)m.s; fp < (char *)(mp + 1);) {
//*fp++ = *tp++;
*fp = *tp;
printf("*fp = %d *tp = %d\n", *fp, *tp);
fp++;
tp++;
}
}
#elif 0
#if 0
The passwd structure is defined in<pwd.h>asfollows:
struct passwd {
char*pw_name; /*user name */
char*pw_passwd; /*<PASSWORD> */
uid_t pw_uid; /*user id */
gid_t pw_gid; /*group id */
char*pw_gecos; /*real name */
char*pw_dir; /*home directory */
char*pw_shell; /*shell program */
};
#endif
#include <time.h>
#include <pwd.h>
#include <sys/types.h>
int main()
{
time_t timep;
struct tm *lct, *gmt;
struct passwd *pwd;
char hostname[64] = "Unknown";
time(&timep);
lct = localtime(&timep);
gmt = gmtime(&timep);
pwd = getpwuid(getuid());
gethostname(hostname, 16);
printf("system localtime: %s\n", asctime(lct));
printf("system gmtime: %s\n", asctime(gmt));
printf("hostname: %s\n", hostname);
printf("pw_name: %s\n", pwd->pw_name);
printf("pw_passwd: %s\n", pwd->pw_passwd);
printf("pw_uid: %d\n", pwd->pw_uid);
return 0;
}
#elif 0
int main()
{
if(daemon(1,0) != 0) {
perror("daemon");
return -1;
}
int i;
for(i = 0; i < 5; i++) {
printf("this is a test\n");
}
return 0;
}
#elif 0
int fun(int a)
{
return a != 0;
}
void main()
{
printf("ret = %d\n",fun(1));
}
#elif 0
#define A
#define B
int main()
{
#ifndef A
#ifdef B
printf("defined B\n");
#endif
#endif
#ifdef A
printf("defined A\n");
#endif
return 0;
}
#endif
<file_sep>/gtk/4st_week/gtk_awindow.c
/* ************************************************************************
* Filename: gtk_awimdow.c
* Description:
* Version: 1.0
* Created: 2015年08月10日 09时35分14秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <gtk/gtk.h>
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
//设置窗口标题
gtk_window_set_title(GTK_WINDOW(window),"Hello GTK");
//设置窗口的位置
gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER);
//设置窗口的大小
gtk_widget_set_size_request(window, 400, 300);
//设置窗口是否可以改变大小
gtk_window_set_resizable(GTK_WINDOW(window),FALSE);
g_signal_connect(window,"destroy",G_CALLBACK(gtk_main_quit),NULL);
gtk_widget_show_all(window);
//隐藏窗口
gtk_main();
return 0;
}
<file_sep>/gtk/4st_week/picture_browse/scan_dir.c
/* ************************************************************************
* Filename: scan_dir.c
* Description:
* Version: 1.0
* Created: 2015年08月11日 14时34分04秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
int gs_index = 0; //指向当前显示的图片
int gs_bmp_total = 0; //图片总数
char *gs_bmp_name[50] = {""};//存放图片目录和文件名地址的指针数组
//=================================================================================
// 函数介绍: 保存图片的目录和名字的地址到指针数组里
// 输入参数: 图片的路径:path
// 图片的名字:bmp
// 返回值: 无
//=================================================================================
void save_bmp_name(char *path, char *bmp)
{
gs_bmp_name[gs_bmp_total] = (char *)malloc(strlen(bmp)+1+strlen(path));
bzero(gs_bmp_name[gs_bmp_total], strlen(bmp)+1); //将申请的内存清零
strcpy(gs_bmp_name[gs_bmp_total], path);
strcat(gs_bmp_name[gs_bmp_total], bmp);
gs_bmp_total++;
}
//=================================================================================
// 函数介绍: 获取并保存图片的名字
// 输入参数: 图片的路径:path
// 返回值: 无
//=================================================================================
void get_bmp_name(char *path)
{
DIR *dir;
struct dirent *ptr;
dir = opendir(path);
while((ptr = readdir(dir)) != NULL)
{
//存图片名
if(strstr(ptr->d_name, ".bmp"))
{
//printf("ptr->d_name = %s\n", ptr->d_name);
save_bmp_name(path, ptr->d_name);
}
}
closedir(dir);
}
//=================================================================================
// 函数介绍: 转换图片的名字为数字
// 输入参数: 图片的路径+图片名:bmp_pathname
// 返回值: 图片的编号
//=================================================================================
int conver_bmp_name(char *bmp_pathname)
{
int num = 0;
sscanf(bmp_pathname, "./image/%d", &num);
//printf("num=%d\n", num);
return num;
}
//=================================================================================
// 函数介绍: 根据图片的名字排序
// 输入参数: 无
// 返回值: 无
//=================================================================================
void order_bmp_name(void)
{
char *tmp = NULL;
int j, k;
for(j=0;j<gs_bmp_total-1;j++)
{
for(k=j+1; k<gs_bmp_total; k++)
{
if(conver_bmp_name(gs_bmp_name[j]) > conver_bmp_name(gs_bmp_name[k]))
{
tmp = gs_bmp_name[k];
gs_bmp_name[k] = gs_bmp_name[j];
gs_bmp_name[j]= tmp;
}
}
}
}
//=================================================================================
// 函数介绍: 打印图片的名字
// 输入参数: 无
// 返回值: 无
//=================================================================================
void bmp_name_print(void)
{
int i;
printf("gs_bmp_total = %d\n", gs_bmp_total);
for(i=0;i<gs_bmp_total;i++)
{
printf("bmp_name = %s\n", gs_bmp_name[i]);
}
}<file_sep>/c/practice/3rd_week/string/mystring.h
/* ************************************************************************
* Filename: mystring.h
* Description:
* Version: 1.0
* Created: 2015年07月24日 星期五 06時44分57秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __MYSTRING_H__
#define __MYSTRING_H__
extern void mystrinv(char *src);
extern int mystrlen(const char *src);
extern int mystrcpy(char *obj, const char *src);
extern int mystrcmp(const char *src1, const char *src2);
extern int strchange(const char *src);
#endif
<file_sep>/c/practice/recursion.c
#include <stdio.h>
float fun(int n)
{
float res = 0.0;
int temp = 0, i = n;
if(n==1) return 1;
while(i>0)
{
temp += i;
i--;
}
res = 1.0/temp;
return (res + fun(n-1));
}
void main(void)
{
float res = 0.0;
res = fun(11);
printf("res = %f\n",res);
}<file_sep>/network/sockets/Makefile
CC := gcc
EXC :=
.PHONY:all
all:
.PHONY:clean
clean:
<file_sep>/sys_program/7th_day/gpio_buttons.c
/* ************************************************************************
* Filename: gpio_buttons.c
* Description:
* Version: 1.0
* Created: 2015年08月21日 14时16分42秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "s5pv210-gpio.h"
static open_dev(const char *devname)
{
int fd;
fd = open(devname,O_RDWR);
if(fd < 0)
{
perror("open_dev");
_exit(-1);
}
return fd;
}
int main(int argc,char *argv[])
{
int fd_row = 0;
int fd_col = 0;
int key_ret = 0, key_tmp = 0;
fd_row = open_dev("/dev/gpH3");
ioctl(fd_row,GPIO_SET_PIN_OUT,0x0);
ioctl(fd_row,GPIO_CLR_PIN,0x0);
fd_col = open_dev("/dev/gpH2");
ioctl(fd_col,GPIO_SET_PIN_IN,0x3);
ioctl(fd_col,GPIO_SET_PIN_IN,0x4);
ioctl(fd_col,GPIO_SET_PIN_IN,0x5);
ioctl(fd_col,GPIO_SET_PIN_IN,0x6);
ioctl(fd_col,GPIO_SET_PIN_IN,0x7);
ioctl(fd_col,GPIO_SET_PULL_UP,0x3);
ioctl(fd_col,GPIO_SET_PULL_UP,0x4);
ioctl(fd_col,GPIO_SET_PULL_UP,0x5);
ioctl(fd_col,GPIO_SET_PULL_UP,0x6);
ioctl(fd_col,GPIO_SET_PULL_UP,0x7);
while(1)
{
read(fd_col, &key_tmp, sizeof(key_tmp));
key_tmp &= 0xf8;
if(key_tmp != 0xf8)
{
switch(key_tmp)
{
case 0xf0:
key_ret = 2;
printf("key2 pressed\n");
break;
case 0xe8:
key_ret = 3;
printf("key3 pressed\n");
break;
case 0xd8:
key_ret = 4;
printf("key4 pressed\n");
break;
case 0xb8:
key_ret = 5;
printf("key5 pressed\n");
break;
case 0x78:
key_ret = 6;
printf("key6 pressed\n");
break;
}
do
{
read(fd_col, &key_tmp, sizeof(key_tmp));
key_tmp &= 0xf8;
}while(key_tmp != 0xf8);
}
else
{
printf("Err: key_ret = %d\n",key_tmp);
}
}
return 0;
}
<file_sep>/network/route/tcp/tcp_client.c
/*****************************************************************************
函 数 名 : getch()
功能描述 : 获取一个字符
输入参数 : NULL
返 回 值 : NULL
修改日期 : 2015年9月15日
*****************************************************************************/
static char getch()
{
struct termios oldt, newt;
char ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
/*****************************************************************************
函 数 名 : get_passwd()
功能描述 : 获取密码
输入参数 : pwd 保存获取密码的指针
返 回 值 : max_len 密码的最大长度
修改日期 : 2015年9月15日
*****************************************************************************/
void get_passwd(char passwd[], int max_len)
{
char ch;
char i = 0;
while(i < max_len)
{
ch = getch();
if(ch == 10){ // 回车键
passwd[i] = 0;
break;
}
else if(ch ==127) { // 回格键
//i--;
//if(i<0) i = 0;
continue;
}
passwd[i++] = ch;
putchar('*');
}
passwd[max_len] = 0;
}
int tcp_receive_msg(int sockfd, char recv[])
{
int len = 0;
while(1) {
len = recv(sockfd, recv, sizeof(recv), 0);
if((strcmp(recv, "#end#") == 0) || (len == 0)){
return len;
}
printf("%s", recv);
}
}
void tcp_send_cmd(char cmd[], int sockfd)
{
int len = 0;
char recv[1024] = "";
if(strcmp(cmd, "help") == 0){
send(sockfd, cmd, strlen(cmd), 0);
tcp_receive_msg(sockfd, recv);
}
else if(strcmp(cmd,"arp") == 0){
send(sockfd, cmd, strlen(cmd), 0);
tcp_receive_msg(sockfd, recv);
}
else if(strcmp(cmd,"ifconfig") == 0){
send(sockfd, cmd, strlen(cmd), 0);
tcp_receive_msg(sockfd, recv);
}
else if(strcmp(cmd,"lsfire") == 0){
send(sockfd, cmd, strlen(cmd), 0);
tcp_receive_msg(sockfd, recv);
}
else if(strcmp(cmd,"setfire") == 0){
int i;
char passwd[PASSWD_LEN] = "";
send(sockfd, cmd, strlen(cmd), 0);
for(i=0; i<2; i++) {
tcp_receive_msg(sockfd, recv);
get_passwd(passwd, PASSWD_LEN-1);
send(sockfd, passwd, strlen(passwd), 0);
tcp_receive_msg(sockfd, recv);
if(strcmp(recv, "passed") == 0) break;
}
if(i == 2) return;
tcp_receive_msg(sockfd, recv);
while(1) {
bzero(cmd, RULE_LEN);
tcp_receive_msg(sockfd, recv);
fgets(cmd, RULE_LEN, stdin);
len = strlen(cmd);
rule[len-1] = 0; //去掉 \n
if(strcmp(cmd,"ls") == 0){
send(sockfd, cmd, strlen(cmd), 0);
tcp_receive_msg(sockfd, recv);
}
else if(strcmp(cmd,"-h") == 0) {
send(sockfd, cmd, strlen(cmd), 0);
tcp_receive_msg(sockfd, recv);
}
else if(strncmp(cmd,"-d",2) == 0) {
char *prule = NULL;
prule = cmd+3; //跳过 "-d "
send(sockfd, cmd, strlen(cmd), 0);
}
else if(strcmp(cmd,"passwd") == 0) {
send(sockfd, cmd, strlen(cmd), 0);
tcp_receive_msg(sockfd, recv);
get_passwd(passwd, PASSWD_LEN-1);
send(sockfd, passwd, strlen(passwd), 0);
}
else if(strcmp(cmd,"esc") == 0){
send(sockfd, cmd, strlen(cmd), 0);
tcp_receive_msg(sockfd, recv);
break;
}
else {
send(sockfd, cmd, strlen(cmd), 0);
}
}
}
out:
pthread_mutex_unlock(&rt->mutex);// 解锁
}
<file_sep>/sys_program/2nd_day/am/atexit.c
/* ************************************************************************
* Filename: atexit.c
* Description:
* Version: 1.0
* Created: 2015年08月14日 09时59分51秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
void fun1(void)
{
printf("in fun1 atexit\n");
}
void fun2(void)
{
printf("in fun2 atexit\n");
}
void fun3(void)
{
printf("in fun3 atexit\n");
}
int main(int argc, int *argvp[])
{
atexit(fun1);
atexit(fun2);
atexit(fun3);
sleep(3);
return 0;
}
<file_sep>/network/sockets/DieWithMessage.c
/*************************************************************************
> File Name: DieWithMessage.c
> Author:
> Mail:
> Created Time: Wed 04 May 2016 03:52:24 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
void DieWithUserMessage(const char *msg, const char *detail) {
fputs(msg, stderr);
fputs(": ", stderr);
fputs(detail, stderr);
fputc('\n', stderr);
exit(1);
}
void DieWithSystemMessage(const char *msg) {
perror(msg);
exit(1);
}
<file_sep>/work/camera/bf3703/bf3703/bf3703_camera.h
/*
* linux/drivers/misc/camera_source/bf3703/camera.h -- Ingenic CIM driver
*
* Copyright (C) 2005-2010, Ingenic Semiconductor Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#ifndef bf3703_CAMERA_H
#define bf3703_CAMERA_H
#include <linux/jz_cim_core.h>
#include <linux/jz_sensor.h>
/*
struct private_info
{
int cur_rwidth;
int cur_rheight;
int cur_mode;
int cur_focus_mode;
};
*/
struct bf3703_sensor
{
struct i2c_client *client;
// struct private_info pinfo;
struct camera_sensor_desc desc;
};
#endif
<file_sep>/shell/top.sh
#!/bin/bash
HEADFLAGD="-n 20"
PSFLAGS=aux
SLEEPFLAGS=2
SORTFLAGS=`-k3nr -k1,1 -k2n`
HEADER="`ps $PSFLAGS | head -n 1`"
while true
do
clear
uptime
echo "$HEADER"
ps $HEADER |
sed -e ld |
sort $SORTFLAGS |
head $HEADFLAGD
sleep $SLEEPFLAGS
done
<file_sep>/work/test/cim_test-zmm220/futil.h
#ifndef _FUTIL_H_
#define _FUTIL_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stddef.h>
#include <time.h>
#include <sys/time.h>
#include "bmp.h"
DWORD GetTickCount(void);
int WriteBitmap(const BYTE *buffer, int Width, int Height, const char *file);
BYTE *LoadFile(const char *FileName);
int SaveToFile(const char *fileName, void *buffer, int size);
int logClose();
int logMsg(char *fmt, ...);
int ReadBitmap(BYTE *p, BYTE *buffer, int *Width, int *Height);
int LoadBitmapFile(const char *FileName, BYTE *buffer, int *Width, int *Height);
void msleep(int msec);
int dumpData(const unsigned char *data, int dataSize, const char *title);
#endif
<file_sep>/work/debug/a8/delmod.sh
#!/bin/sh
name=`ls *.ko`
if [ -z "$name" ]
then
exit 1
fi
devname=${name%.ko}
devno=
#echo "devname=$devname"
if [ -z "`cat /proc/devices | grep $devname`" ]
then
echo "$devname haven't installed!"
exit 1
fi
#echo "$devno $devname"
if [ -e /dev/$devname ]
then
rm /dev/$devname
if [ $? -eq 0 ]
then
echo "remove /dev/$devname successful"
fi
fi
rmmod $devname
if [ $? -eq 0 ]
then
echo "uninstall $devname successful"
fi
<file_sep>/c/practice/3rd_week/time/Makefile
atime:main.c show_time.c
gcc -o atime main.c show_time.c
.PHONY:clean
clean:
rm atime
<file_sep>/network/3rd_day/multicast.c
/* ************************************************************************
* Filename: multicast.c
* Description:
* Version: 1.0
* Created: 2015年09月02日 11时44分58秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
char group[INET_ADDRSTRLEN] = "172.16.31.10";
char msg[512] = "";
int sockfd;
struct sockaddr_in addr;
struct ip_mreq mreq;//定义一个多播组
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
mreq.imr_multiaddr.s_addr = inet_addr(group); //设置多播组IP
mreq.imr_interface.s_addr = htonl(INADDR_ANY);//向多播组添加一个IP
setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
while(1)
{
bzero(msg, sizeof(msg));
recvfrom(sockfd, msg, sizeof(msg), 0, NULL, NULL);
printf("msg = %s\n",msg);
}
close(sockfd);
return 0;
}
<file_sep>/sys_program/1st_day/cp/cp.c
/* ************************************************************************
* Filename: systemcall.c
* Description:
* Version: 1.0
* Created: 2015年08月13日 10时16分10秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#if 1
int main(int argc, char *argv[])
{
int fd, ft, ret;
char *pbuf = NULL, ch;
unsigned long filelen = 0;
fd = open(argv[1],O_RDWR);
if(fd < 0)
{
perror("error:\n");
return -1;
}
while(read(fd,&ch,sizeof(ch)) == 1) filelen++;
pbuf = (char *)malloc(filelen);
if(pbuf == NULL)
{
printf("Err:failed to malloc!\n");
return -1;
}
close(fd);
fd = open(argv[1],O_RDWR);
ret = read(fd,pbuf,filelen);
ft = open(argv[2],O_RDWR | O_CREAT,0777);
write(ft,pbuf,filelen);
printf("filelen = %lu\n",filelen);
printf("ret = %d\n",ret);
close(fd);
close(ft);
free(pbuf);
return 0;
}
#endif<file_sep>/network/route/src/route_control.c
/******************************************************************************
文 件 名 : route_control.c
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月15日
最近修改 :
功能描述 : 数据发送
函数列表 :
broadcast
build_arp_table
get_ethernet_port
route_init
show_port_info
修改历史 :
1.日 期 : 2015年9月15日
作 者 : if
修改内容 : 创建文件
******************************************************************************/
#include "common.h"
#include "arp_link.h"
#include "firewall_file.h"
#include "route_control.h"
/*****************************************************************************
函 数 名 : route_init()
功能描述 : 初始化
输入参数 : 无
返 回 值 : NULL
修改日期 : 2015年9月10日
*****************************************************************************/
void route_init(TYPE_Route *rt)
{
//创建原始套接字
rt->raw_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
//创建监听套接字
rt->sockfd = socket(AF_INET, SOCK_STREAM, 0);
//让服务器绑定端口和ip
bzero(&rt->s_addr, sizeof(rt->s_addr));
rt->s_addr.sin_family = AF_INET;
rt->s_addr.sin_port = htons(8080);
rt->s_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(rt->sockfd, (struct sockaddr *)&rt->s_addr, sizeof(rt->s_addr));
if(ret != 0)
{
perror("bind:");
exit(-1);
}
//listen 创建链接队列
listen(rt->sockfd, 5);
rt->fire_status = UP; // 初始化防火墙的状态: 开启
//初始化链表头指针
rt->arp_head = NULL;
rt->mac_head = NULL;
rt->ip_head = NULL;
rt->port_head = NULL;
rt->pro_head = NULL;
pthread_mutex_init(&rt->mutex, NULL); // 初始化互斥锁
get_ethernet_port(rt); // 获取网卡接口信息
build_arp_table(rt); // 创建ARP表
firewall_config(rt); // 读取规则文件,配置防火墙
firewall_get_passwd(rt); // 获取保存在文件的防火墙密码
}
#if 0
/*****************************************************************************
函 数 名 : show_help()
功能描述 : 输入帮助提示
输入参数 : 无
返 回 值 : void
修改日期 : 2015年9月10日
*****************************************************************************/
void show_help(void)
{
printf("***************************************************\n");
printf("- help: 查看帮助信息 *\n");
printf("- arp: 查看 ARP 表 *\n");
printf("- ifconfig: 查看网卡信息 *\n");
printf("- fire on: 开启防火墙 *\n");
printf("- fire off: 关闭防火墙 *\n");
printf("- lsfire: 查看防火墙规则 *\n");
printf("- setfire: 设置防火墙规则 *\n");
printf("***************************************************\n");
}
#endif
/*****************************************************************************
函 数 名 : get_ethernet_port()
功能描述 : 获取网络接口信息
输入参数 : 无
返 回 值 : NULL
修改日期 : 2015年9月10日
*****************************************************************************/
void get_ethernet_port(TYPE_Route *rt)
{
struct ifreq buf[MAX_PORT]; /* ifreq结构数组 */
struct ifconf ifc; /* ifconf结构 */
/* 初始化ifconf结构 */
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = (caddr_t) buf;
/* 获得接口列表 */
if (ioctl(rt->raw_fd, SIOCGIFCONF, (char *)&ifc) == -1)
{
perror("SIOCGIFCONF ioctl");
return ;
}
rt->port_num= ifc.ifc_len / sizeof(struct ifreq); /* 接口数量 */
printf("port_num=%d\n\n", rt->port_num);
char buff[20]="";
int ip;
int if_len = rt->port_num;
while(if_len-- > 0) /* 遍历每个接口 */
{
sprintf(rt->eth_port[if_len].name, "%s", buf[if_len].ifr_name); /* 接口名称 */
/* 获得接口标志 */
if(!(ioctl(rt->raw_fd, SIOCGIFFLAGS, (char *) &buf[if_len])))
{
/* 接口状态 */
if(buf[if_len].ifr_flags & IFF_UP)
{
rt->eth_port[if_len].status = UP;
}
else
{
rt->eth_port[if_len].status = DOWN;
}
}
else
{
char str[256];
sprintf(str, "SIOCGIFFLAGS ioctl %s", buf[if_len].ifr_name);
perror(str);
}
/* IP地址 */
if(!(ioctl(rt->raw_fd, SIOCGIFADDR, (char *)&buf[if_len])))
{
bzero(buff,sizeof(buff));
sprintf(buff, "%s", (char*)inet_ntoa(((struct sockaddr_in*)(&buf[if_len].ifr_addr))->sin_addr));
inet_pton(AF_INET, buff, &ip);
memcpy(rt->eth_port[if_len].ip, &ip, 4);
}
else
{
char str[256];
sprintf(str, "SIOCGIFADDR ioctl %s", buf[if_len].ifr_name);
perror(str);
}
/* 子网掩码 */
if(!(ioctl(rt->raw_fd, SIOCGIFNETMASK, (char *)&buf[if_len])))
{
bzero(buff,sizeof(buff));
sprintf(buff, "%s", (char*)inet_ntoa(((struct sockaddr_in*)(&buf[if_len].ifr_addr))->sin_addr));
inet_pton(AF_INET, buff, &ip);
memcpy(rt->eth_port[if_len].netmask, &ip, 4);
}
else
{
char str[256];
sprintf(str, "SIOCGIFADDR ioctl %s", buf[if_len].ifr_name);
perror(str);
}
/* 广播地址 */
if(!(ioctl(rt->raw_fd, SIOCGIFBRDADDR, (char *)&buf[if_len])))
{
//printf("bc_ip:%s\n",(char*)inet_ntoa(((struct sockaddr_in*)(&buf[if_len].ifr_addr))->sin_addr));
bzero(buff,sizeof(buff));
sprintf(buff, "%s", (char*)inet_ntoa(((struct sockaddr_in*)(&buf[if_len].ifr_addr))->sin_addr));
inet_pton(AF_INET, buff, &ip);
memcpy(rt->eth_port[if_len].bc_ip, &ip, 4);
}
else
{
char str[256];
sprintf(str, "SIOCGIFADDR ioctl %s", buf[if_len].ifr_name);
perror(str);
}
/*MAC地址 */
if(!(ioctl(rt->raw_fd, SIOCGIFHWADDR, (char *) &buf[if_len])))
{
memcpy(rt->eth_port[if_len].mac, (unsigned char *)buf[if_len].ifr_hwaddr.sa_data, 6);
}
else
{
char str[256];
sprintf(str, "SIOCGIFHWADDR ioctl %s", buf[if_len].ifr_name);
perror(str);
}
}//–while end
}
/*****************************************************************************
函 数 名 : show_port_info()
功能描述 : 打印网络接口信息
输入参数 : rt TYPE_Route 类型指针
port_name 网络接口名称,当为NULL时,打印所有接口信息
返 回 值 : NULL
修改日期 : 2015年9月10日
*****************************************************************************/
void show_port_info(TYPE_Route *rt, char *port_name)
{
int i = 0;
if(port_name != NULL)
{
for(i=0;i<rt->port_num;i++)
{
if(strcmp(port_name, rt->eth_port[i].name) == 0)
{
printf("___________%s___________\n", rt->eth_port[i].name);
if(rt->eth_port[i].status == UP) printf("UP\n");
else printf("DOWN\n");
//ip
printf(" ip: %d.%d.%d.%d\n",\
rt->eth_port[i].ip[0],rt->eth_port[i].ip[1],\
rt->eth_port[i].ip[2],rt->eth_port[i].ip[3]);
//mac
printf(" mac: %02x:%02x:%02x:%02x:%02x:%02x\n",\
rt->eth_port[i].mac[0],rt->eth_port[i].mac[1],\
rt->eth_port[i].mac[2],rt->eth_port[i].mac[3],\
rt->eth_port[i].mac[4],rt->eth_port[i].mac[5]);
//netmask
printf("netmask: %d.%d.%d.%d\n",\
rt->eth_port[i].netmask[0],rt->eth_port[i].netmask[1],\
rt->eth_port[i].netmask[2],rt->eth_port[i].netmask[3]);
//broadcast ip
printf(" bc_ip: %d.%d.%d.%d\n",\
rt->eth_port[i].bc_ip[0],rt->eth_port[i].bc_ip[1],\
rt->eth_port[i].bc_ip[2],rt->eth_port[i].bc_ip[3]);
printf("__________________________\n");
}
}
}
else
{
for(i=0;i<rt->port_num;i++)
{
printf("___________%s___________\n", rt->eth_port[i].name);
if(rt->eth_port[i].status == UP) printf("UP\n");
else printf("DOWN\n");
//ip
printf(" ip: %d.%d.%d.%d\n",\
rt->eth_port[i].ip[0],rt->eth_port[i].ip[1],\
rt->eth_port[i].ip[2],rt->eth_port[i].ip[3]);
//mac
printf(" mac: %02x:%02x:%02x:%02x:%02x:%02x\n",\
rt->eth_port[i].mac[0],rt->eth_port[i].mac[1],\
rt->eth_port[i].mac[2],rt->eth_port[i].mac[3],\
rt->eth_port[i].mac[4],rt->eth_port[i].mac[5]);
//netmask
printf("netmask: %d.%d.%d.%d\n",\
rt->eth_port[i].netmask[0],rt->eth_port[i].netmask[1],\
rt->eth_port[i].netmask[2],rt->eth_port[i].netmask[3]);
//broadcast ip
printf(" bc_ip: %d.%d.%d.%d\n",\
rt->eth_port[i].bc_ip[0],rt->eth_port[i].bc_ip[1],\
rt->eth_port[i].bc_ip[2],rt->eth_port[i].bc_ip[3]);
printf("__________________________\n");
}
}
}
/*****************************************************************************
函 数 名 : build_arp_table()
功能描述 : 建立ARP表
输入参数 : 无
返 回 值 : void
修改日期 : 2015年9月10日
*****************************************************************************/
void build_arp_table(TYPE_Route *rt)
{
int i = 0, port_num = 0;
uchar recv[2024] = "";
uchar arp[256] = {
//-----组mac----14----
0xff,0xff,0xff,0xff,0xff,0xff,//dst_mac: ff:ff:ff:ff:ff:ff
0x00,0x00,0x00,0x00,0x00,0x00,//src_mac:
0x08,0x06, //类型: 0x0806 ARP协议
//-----组ARP----28----
0x00,0x01,0x08,0x00, //硬件类型1(以太网地址),协议类型:0x800(IP)
0x06,0x04,0x00,0x01, //硬件、协议的地址长度分别为6和4,ARP请求
0x00,0x00,0x00,0x00,0x00,0x00,//发送端的mac
0, 0, 0, 0, //发送端的ip
0x00,0x00,0x00,0x00,0x00,0x00,//目的mac(获取对方的mac,设置为0)
0, 0, 0, 0, //目的ip
};
if(rt->arp_head != NULL){
free_arp_table(rt->arp_head);
rt->arp_head = NULL;
}
while(port_num < rt->port_num)
{
memcpy(arp+6, rt->eth_port[port_num].mac, 6);
memcpy(arp+22,rt->eth_port[port_num].mac, 6);
memcpy(arp+28,rt->eth_port[port_num].ip, 4);
memcpy(arp+38,rt->eth_port[port_num].ip, 4);
strncpy(rt->ethreq.ifr_name,rt->eth_port[port_num].name, IFNAMSIZ);
ioctl(rt->raw_fd, SIOCGIFINDEX, (char *)&rt->ethreq);
bzero(&rt->sll, sizeof(rt->sll));
rt->sll.sll_ifindex = rt->ethreq.ifr_ifindex;
for(i=0;i<255;i++)
{
arp[41] = i;
//发送ARP请求
sendto(rt->raw_fd, arp, 42, 0, (struct sockaddr *)&rt->sll, sizeof(rt->sll));
//接收对方的ARP应答
recvfrom(rt->raw_fd, recv, sizeof(recv), 0, NULL, NULL);
if(recv[21] == 2) //接收到ARP应答数据包
{
ARP_Table node;
memcpy(node.ip, recv + 28, 4); //提取ip
memcpy(node.mac, recv + 22, 6); //提取mac
rt->arp_head = (ARP_Table *)insert_arp_table(rt->arp_head, node);
}
}
port_num++;
}
//print_arp_table(rt->arp_head);
}
Boolean broadcast(TYPE_Route *rt, const uchar ip[])
{
int i = 0, port_num = 0;
uchar recv[2024] = "";
uchar arp[256] = {
//-----组mac----14----
0xff,0xff,0xff,0xff,0xff,0xff,//dst_mac: ff:ff:ff:ff:ff:ff
0x00,0x00,0x00,0x00,0x00,0x00,//src_mac:
0x08,0x06, //类型: 0x0806 ARP协议
//-----组ARP----28----
0x00,0x01,0x08,0x00, //硬件类型1(以太网地址),协议类型:0x800(IP)
0x06,0x04,0x00,0x01, //硬件、协议的地址长度分别为6和4,ARP请求
0x00,0x00,0x00,0x00,0x00,0x00,//发送端的mac
0, 0, 0, 0, //发送端的ip
0x00,0x00,0x00,0x00,0x00,0x00,//目的mac(获取对方的mac,设置为0)
0, 0, 0, 0, //目的ip
};
while(port_num < rt->port_num)
{
memcpy(arp+6, rt->eth_port[port_num].mac, 6);
memcpy(arp+22,rt->eth_port[port_num].mac, 6);
memcpy(arp+28,rt->eth_port[port_num].ip, 4);
memcpy(arp+38,ip, 4);
strncpy(rt->ethreq.ifr_name,rt->eth_port[port_num].name, IFNAMSIZ);
ioctl(rt->raw_fd, SIOCGIFINDEX, (char *)&rt->ethreq);
bzero(&rt->sll, sizeof(rt->sll));
rt->sll.sll_ifindex = rt->ethreq.ifr_ifindex;
for(i=0;i<5;i++) //广播五次
{
//发送ARP请求
sendto(rt->raw_fd, arp, 42, 0, (struct sockaddr *)&rt->sll, sizeof(rt->sll));
//接收对方的ARP应答
recvfrom(rt->raw_fd, recv, sizeof(recv), 0, NULL, NULL);
if(recv[21] == 2) //接收到ARP应答数据包
{
if(iptoun_btol(recv + 28) == iptoun_btol(ip))
{
ARP_Table node;
memcpy(node.ip, recv + 28, 4); //提取ip
memcpy(node.mac, recv + 22, 6); //提取mac
rt->arp_head = (ARP_Table *)insert_arp_table(rt->arp_head, node);
return TRUE;
}
}
}
port_num++;
}
return FALSE;
}
<file_sep>/network/5th_day/Makefile
all:filch feiQ udp sock_raw arp
filch:
gcc -o filch filch.c gb2312_ucs2.c
feiQ:
gcc raw_feiQ.c gb2312_ucs2.c -o feiQ
udp:
gcc raw_udp.c -o udp
sock_raw:sock_raw.c
gcc -o sock_raw sock_raw.c
arp:
gcc -o arp arp.c
.PHONY:clean
clean:
rm sock_raw feiQ udp filch
<file_sep>/work/test/yuv2bmp/conver.h
#ifndef __CONVER_H__
#define __CONVER_H__
int init_conver();
void rgb5652rgb888(unsigned short* rgb565,unsigned int* rgb888,unsigned int framesize);
int yuv422rgb565_scale(unsigned char *yuv422buf,unsigned short *rgb565,int width,int height);
int yuv422rgb565(unsigned char *yuv422buf,unsigned short *rgb565,int width,int height);
int yuv422rgb888_scale(unsigned char *yuv422buf,unsigned int *rgb888,int width,int height);
int yuv422rgb888(unsigned char *yuv422buf,unsigned int *rgb888,int width,int height);
int rgb8882rgb565(unsigned short *rgb565,unsigned char *rgb888,unsigned int imagesize);
int cut_rgb565(unsigned short *rgb565cut,unsigned short *rgb565src,unsigned int width,unsigned int imagesize);
void rgb565_rotate90(const unsigned short *input, int width_in, int height_in,unsigned short *output);//, int *width_out, int *height_out);
/*************************
*Translate the picture Right_Left.
* ***********************/
void rgb565_folio(unsigned short *rgb565,int width,int height);
int close_conver();
#endif
<file_sep>/c/practice/mate_bracket.c
/* ************************************************************************
* Filename: mate_bracket.c
* Description:
* Version: 1.0
* Created: 2015年11月17日 20时31分35秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int mate_bracket(char *str)
{
char *p = NULL;
int i = 0, j = 0, len = strlen(str);
p = (char *)malloc(len + 1);
memset(p, 0, len+1);
for(i=0;i<len;i++)
{
if(str[i] == '(' || str[i] == '['
|| str[i] == '{' || str[i] == '<')
{
p[j] = str[i];
j++;
continue;
}
switch(str[i])
{
case ')':
j--;
if(j < 0 || p[j] != '(')
return 0;
break;
case ']':
j--;
if(j < 0 || p[j] != '[')
return 0;
break;
case '}':
j--;
if(j < 0 || p[j] != '{')
return 0;
break;
case '>':
j--;
if(j < 0 || p[j] != '<')
return 0;
break;
}
}
free(p);
if(j != 0)
return 0;
else
return 1;
}
int main(int argc, char *argv[])
{
char exp[128] = {0};
int ret, len;
fgets(exp, sizeof(exp),stdin);
len = strlen(exp);
exp[len - 1] = 0;
ret = mate_bracket(exp);
printf("ret = %d\n",ret);
return 0;
}
<file_sep>/work/camera/bf3703/bf3703/bf3703_camera.c
#include <asm/jzsoc.h>
#include <linux/i2c.h>
#include "bf3703_camera.h"
#include "bf3703_set.h"
#include "bf3703_set_mode.h"
#include <asm/jzsoc.h>
#define bf3703_DEBUG
#ifdef bf3703_DEBUG
#define dprintk(x...) do{printk("bf3703---\t");printk(x);printk("\n");}while(0)
#else
#define dprintk(x...)
#endif
/* gpio init */
#define GPIO_CAMERA_RST (32*4+18) /*GPE18*/
#define GPIO_CAMERA_PDN (32*4+19) /*GPE19*/
#define GPIO_CIM_PDN (32 * 4 + 24 ) // GPE24
struct bf3703_sensor bf3703;
void bf3703_reset(void)
{
printk("bf3703_reset\n");
__gpio_as_output(GPIO_CAMERA_RST);
mdelay(50);
__gpio_clear_pin(GPIO_CAMERA_RST);
mdelay(50);
__gpio_set_pin(GPIO_CAMERA_RST);
mdelay(50);
}
void bf3703_power_down(void)
{
printk("bf3703_power_down\n");
__gpio_as_output(GPIO_CIM_PDN);
__gpio_clear_pin(GPIO_CIM_PDN);
mdelay(100);
//-----------------
__gpio_as_output(GPIO_CAMERA_PDN);
__gpio_set_pin(GPIO_CAMERA_PDN);
mdelay(100);
}
void bf3703_power_up(void)
{
printk("bf3703_power_up \n");
//bf3703_power_on later
__gpio_as_output(GPIO_CAMERA_PDN);
__gpio_set_pin(GPIO_CAMERA_PDN);
mdelay(100);
__gpio_as_output(GPIO_CIM_PDN);
__gpio_clear_pin(GPIO_CIM_PDN);
mdelay(100);
}
#if 0
void bf3703_reset(void)
{
printk("bf3703_reset\n");
__gpio_as_output(GPIO_CAMERA_RST);
mdelay(50);
__gpio_clear_pin(GPIO_CAMERA_RST);
mdelay(50);
__gpio_set_pin(GPIO_CAMERA_RST);
mdelay(50);
}
#endif
int bf3703_set_balance(balance_flag_t balance_flag,int arg)
{
dprintk("bf3703_set_balance");
switch(balance_flag)
{
case WHITE_BALANCE_AUTO:
bf3703_set_wb_auto_mode(bf3703.client);
dprintk("wb_auto ");
break;
case WHITE_BALANCE_DAYLIGHT ://ri guang
bf3703_set_wb_sunny_mode(bf3703.client);
dprintk("wb_daylight ");
break;
case WHITE_BALANCE_CLOUDY_DAYLIGHT ://ying tian
bf3703_set_wb_cloudy_mode(bf3703.client);
dprintk("wb_cloudy daylight ");
break;
case WHITE_BALANCE_INCANDESCENT :
bf3703_set_wb_office_mode(bf3703.client);
dprintk("wb_incandenscent ");
break;
}
return 0;
}
void bf3703_set_effect_whiteboard(struct i2c_client *client);
int bf3703_set_effect(effect_flag_t effect_flag,int arg)
{
dprintk("bf3703_set_effect");
switch(effect_flag)
{
case EFFECT_NONE:
bf3703_set_effect_normal(bf3703.client);
dprintk("effect_none");
break;
case EFFECT_MONO :
bf3703_set_effect_blackwhite(bf3703.client);
dprintk("effect_mono ");
break;
case EFFECT_NEGATIVE :
bf3703_set_effect_negative(bf3703.client);
dprintk("effect_negative ");
break;
case EFFECT_SOLARIZE ://bao guang
dprintk("effect_solarize ");
break;
case EFFECT_SEPIA :
bf3703_set_effect_sepia(bf3703.client);
dprintk("effect_sepia ");
break;
case EFFECT_POSTERIZE ://se diao fen li
dprintk("effect_posterize ");
break;
case EFFECT_WHITEBOARD :
dprintk("effect_whiteboard ");
break;
case EFFECT_BLACKBOARD :
bf3703_set_effect_whiteboard(bf3703.client);
dprintk("effect_blackboard ");
break;
case EFFECT_AQUA ://qian lv se
bf3703_set_effect_greenish(bf3703.client);
dprintk("effect_aqua ");
break;
case EFFECT_PASTEL:
dprintk("effect_pastel");
break;
case EFFECT_MOSAIC:
dprintk("effect_mosaic");
break;
case EFFECT_RESIZE:
dprintk("effect_resize");
break;
}
return 0;
}
int bf3703_set_antibanding(antibanding_flag_t antibanding_flag,int arg)
{
dprintk("bf3703_set_antibanding");
switch(antibanding_flag)
{
case ANTIBANDING_AUTO :
bf3703_ab_auto(bf3703.client);
dprintk("ANTIBANDING_AUTO ");
break;
case ANTIBANDING_50HZ :
bf3703_ab_50hz(bf3703.client);
dprintk("ANTIBANDING_50HZ ");
break;
case ANTIBANDING_60HZ :
bf3703_ab_60hz(bf3703.client);
dprintk("ANTIBANDING_60HZ ");
break;
case ANTIBANDING_OFF :
bf3703_ab_off(bf3703.client);
dprintk("ANTIBANDING_OFF ");
break;
}
return 0;
}
int bf3703_set_flash_mode(flash_mode_flag_t flash_mode_flag,int arg)
{
return 0;
}
int bf3703_set_scene_mode(scene_mode_flag_t scene_mode_flag,int arg)
{
return 0;
}
int bf3703_set_focus_mode(focus_mode_flag_t flash_mode_flag,int arg)
{
return 0;
}
int bf3703_set_fps(int fps)
{
dprintk("set fps : %d",fps);
return 0;
}
int bf3703_set_luma_adaptation(int arg)
{
dprintk("luma_adaptation : %d",arg);
return 0;
}
int bf3703_set_parameter(int cmd, int mode, int arg)
{
switch(cmd)
{
case CPCMD_SET_BALANCE :
bf3703_set_balance(mode,arg);
break;
case CPCMD_SET_EFFECT :
bf3703_set_effect(mode,arg);
break;
case CPCMD_SET_ANTIBANDING :
bf3703_set_antibanding(mode,arg);
break;
case CPCMD_SET_FLASH_MODE :
bf3703_set_flash_mode(mode,arg);
break;
case CPCMD_SET_SCENE_MODE :
bf3703_set_scene_mode(mode,arg);
break;
case CPCMD_SET_PIXEL_FORMAT :
break;
case CPCMD_SET_FOCUS_MODE :
bf3703_set_focus_mode(mode,arg);
break;
case CPCMD_SET_PREVIEW_FPS:
bf3703_set_fps(arg);
break;
case CPCMD_SET_NIGHTSHOT_MODE:
break;
case CPCMD_SET_LUMA_ADAPTATION:
bf3703_set_luma_adaptation(arg);
break;
}
return 0;
}
int bf3703_set_power(int state)
{
switch (state)
{
case 0:
/* hardware power up first */
bf3703_power_up();
/* software power up later if it implemented */
break;
case 1:
bf3703_power_down();
break;
case 2:
break;
default:
printk("%s : EINVAL! \n",__FUNCTION__);
}
return 0;
}
int bf3703_sensor_init(void)
{
//bf3703_reset();
bf3703_init_setting(bf3703.client);
return 0;
}
int bf3703_sensor_probe(void)
{
int sensor_id = 0;
bf3703_power_up();
bf3703_reset();
sensor_id = (sensor_read_reg(bf3703.client,0xFC)<<8)|sensor_read_reg(bf3703.client,0xFD);
bf3703_power_down();
if(sensor_id == 0x3703)
return 0;
return -1;
}
/* sensor_set_function use for init preview or capture.there may be some difference between preview and capture.
* so we divided it into two sequences.param: function indicated which function
* 0: preview
* 1: capture
* 2: recording
*/
int bf3703_set_function(int function)
{
switch (function)
{
case 0:
preview_set(bf3703.client);
printk("preview set %s \n",__func__);
break;
case 1:
capture_set(bf3703.client);
printk("capture set %s \n",__func__);
break;
case 2:
break;
}
return 0;
}
int bf3703_set_resolution(int width,int height,int bpp,pixel_format_flag_t fmt,camera_mode_t mode)
{
size_switch(bf3703.client,width,height,mode);
return 0;
}
static ssize_t bf3703_write_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
//uint32_t reg,val;
//sscanf(buf,"%x,%x",®,&val);
//printk("write reg : %x | value : %x\n",reg&0xffff,val&0xff);
//sensor_write_reg16(bf3703.client,reg&0xffff,val&0xff);
return count;
}
static ssize_t bf3703_read_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
//uint32_t reg;
//sscanf(buf,"%x",®);
//printk("read reg 0x%x = 0x%x\n",reg&0xffff,sensor_read_reg16(bf3703.client,reg&0xffff));
return count;
}
static DEVICE_ATTR(write, 0664, NULL, bf3703_write_store);
static DEVICE_ATTR(read, 0664, NULL, bf3703_read_store);
//static struct attribute *bf3703_attributes[] = {
//&dev_attr_write.attr,
//&dev_attr_read.attr,
//NULL
//};
//static const struct attribute_group bf3703_attr_group = {
// .attrs = bf3703_attributes,
//};
static int bf3703_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
bf3703.client = client;
//sysfs_create_group(&client->dev.kobj, &bf3703_attr_group);
sensor_set_i2c_speed(client,400000);
return camera_sensor_register(&bf3703.desc);
}
struct camera_sensor_ops bf3703_sensor_ops = {
.sensor_init = bf3703_sensor_init,
.camera_sensor_probe = bf3703_sensor_probe,
.sensor_set_function = bf3703_set_function,
.sensor_set_resolution = bf3703_set_resolution,
.sensor_set_parameter = bf3703_set_parameter,
.sensor_set_power = bf3703_set_power,
};
struct resolution_info bf3703_resolution_table[] = {
{640,480,16,PIXEL_FORMAT_YUV422I}, //
{352,288,16,PIXEL_FORMAT_YUV422I},
{320,240,16,PIXEL_FORMAT_YUV422I}, //
{176,144,16,PIXEL_FORMAT_YUV422I},
};
struct bf3703_sensor bf3703 = {
.desc = {
.name = "bf3703",
.wait_frames = 0,
.ops = &bf3703_sensor_ops,
.resolution_table = bf3703_resolution_table,
.resolution_table_nr=ARRAY_SIZE(bf3703_resolution_table),
.capture_parm = {640,480, 16,PIXEL_FORMAT_YUV422I},
.max_capture_parm = {640,480, 16,PIXEL_FORMAT_YUV422I},
.preview_parm = {640,480, 16,PIXEL_FORMAT_YUV422I},
.max_preview_parm = {640,480, 16,PIXEL_FORMAT_YUV422I},
.cfg_info = {
.configure_register= 0x0
|CIM_CFG_PACK_3 /* pack mode : 4 3 2 1 */
|CIM_CFG_BYPASS /* Bypass Mode */
|CIM_CFG_VSP /* VSYNC Polarity:1-falling edge active */
// |CIM_CFG_HSP
// |CIM_CFG_PCP /* PCLK working edge:1-falling */
|CIM_CFG_DSM_GCM, /* Gated Clock Mode */
},
.flags = {
.effect_flag = 0
|EFFECT_NONE
|EFFECT_MONO
|EFFECT_SEPIA
|EFFECT_NEGATIVE
|EFFECT_AQUA,
.balance_flag = 0
| WHITE_BALANCE_AUTO
| WHITE_BALANCE_DAYLIGHT
| WHITE_BALANCE_CLOUDY_DAYLIGHT
| WHITE_BALANCE_INCANDESCENT,
.antibanding_flag = ~0x0,
.flash_mode_flag = 0,
.scene_mode_flag = 0,
.pixel_format_flag = 0,
.focus_mode_flag = 0,
},
},
};
static const struct i2c_device_id bf3703_id[] = {
{ "bf3703", 0 },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(i2c, bf3703_id);
static struct i2c_driver bf3703_driver = {
.probe = bf3703_i2c_probe,
.id_table = bf3703_id,
.driver = {
.name = "bf3703",
},
};
static int __init bf3703_i2c_register(void)
{
return i2c_add_driver(&bf3703_driver);
}
module_init(bf3703_i2c_register);
<file_sep>/sys_program/2nd_day/am/vfork.c
/* ************************************************************************
* Filename: vfork.c
* Description:
* Version: 1.0
* Created: 2015年08月14日 10时28分00秒
* Revision: none
* Compiler: gcc
* Author: 王秋伟,
* Company:
* ************************************************************************/
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int gnum = 0;
int main(int argc, char *argv[])
{
pid_t pid;
int num = 1;
//pid = fork();
pid = vfork();
if(pid < 0) perror("");
else if(pid == 0)
{
int i;
for(i=0;i<3;i++)
{
printf("in son process\n");
gnum++;
num++;
sleep(1);
}
printf("in #son process\n");
execl("/bin/ls","ls","-l","-h",NULL); //当调用exec函数后,用vfork创建的子进程也会有自己的地址空间,
//并且exec启动的程序会把,该地址空间的数据段、代码段和堆栈段覆盖掉
//所以就导致后面的printf打印不出信息
//当遇到exec函数,用vfork创建子进程的父进程将不再等待子进程执行完
//所以这里会先看到父进程for循环中打印出一条信息,然后再有 ls 执行的打印信息
printf("in son# process\n"); //加了execl函数后,并没有把这条信息打印到屏幕
//exit(2);// 退出子进程,并返回2,会刷新缓冲区
//return 0;//加了这句,会弹栈,因为这里的子进程跟父进程共用同一地址空间,
//导致父进程找不到栈原来的内容,则出错,
//比如这里,返回后,父进程中访问num的值为0,而实际在子进程return前num != 0
}
else
{
int i;
int status = 0;
for(i=0;i<3;i++)
{
printf("in father process\n");
printf("gnum = %d num = %d\n",gnum,num);
sleep(1);
}
//wait(&status);
waitpid(-1,&status,0); // 这里跟 wait(&status) 一样
if(WIFEXITED(status) != 0) //判断返回状态 ,存在status的低8位
{
printf("return = %d\n",WEXITSTATUS(status)); //取返回值,存在status的8~16位
}
}
return 0;
}
<file_sep>/c/practice/bitree/bitree.c
/* ************************************************************************
* Filename: bitree.c
* Description:
* Version: 1.0
* Created: 2015年09月06日 18时35分22秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _BiTNode
{
char data; //节点数据域
struct _BiTNode *lchild, *rchild; /*指向左孩子和右孩子*/
}BiTNode, *pBiTNode;
/*创建一棵二叉树*/
//不管是先序或中序或后序创建二叉树,对遍历二叉树不影响
CreatBiTree(pBiTNode *T) // T为二级指针
{
char ch;
ch = getchar();
getchar();
printf("get = %c\n",ch);
if(ch == ' ')
{
*T = NULL;
}
else
{
*T = (BiTNode *)malloc(sizeof(BiTNode));/*创建一个结点*/
bzero(*T, sizeof(BiTNode));
// * 运算符的优先级比 -> 运算符低
(*T)->data = ch; //这条语句放这里是先序创建二叉树,
CreatBiTree(&((*T)->lchild)); // 递归创建左子树
//(*T)->data = ch;
CreatBiTree(&((*T)->rchild)); // 递归创建右子树
//(*T)->data = ch;
}
}
/*遍历二叉树*/
//先序
PreOrderTraverse(pBiTNode T,int level)
{
if(T)
{ /*递归结束条件,T为空*/
printf("level: %d node: %c\n",level, T->data);
PreOrderTraverse(T->lchild, level+1);
PreOrderTraverse(T->rchild, level+1);
}
}
//中序
MiOrderTraverse(pBiTNode T,int level)
{
if(T)
{ /*递归结束条件,T为空*/
MiOrderTraverse(T->lchild, level+1);
printf("level: %d node: %c\n",level, T->data);
MiOrderTraverse(T->rchild, level+1);
}
}
//后序
PostOrderTraverse(pBiTNode T,int level)
{
if(T)
{ /*递归结束条件,T为空*/
PostOrderTraverse(T->lchild, level+1);
PostOrderTraverse(T->rchild, level+1);
printf("level: %d node: %c\n",level, T->data);
}
}
//统计二叉树叶子节点数
int CountLeaf(pBiTNode T)
{
static int count = 0;
if(T)
{
count = CountLeaf(T->lchild);
if(T->lchild == NULL && T->rchild == NULL)
{
count++;
}
count = CountLeaf(T->rchild);
}
return count;
}
//求二叉树的深度
int TreeDepth(pBiTNode T)
{
static int count = 0;
if(T)
{
count++;
count = TreeDepth(T->lchild);
count = TreeDepth(T->rchild);
}
return count;
}
int main(int argc, char *argv[])
{
int level = 1;
int Node_num = 0,Depth_num = 0;
pBiTNode T = NULL; /*最开始T指向空*/
CreatBiTree(&T); //创建二叉树,先画出树形图,根据图进行输入创建
printf("\n先序遍历:\n");
PreOrderTraverse(T,level); //遍历二叉树,找到包含D字符结点位于二叉树中的层数
printf("\n中序遍历:\n");
MiOrderTraverse(T,level); //遍历二叉树,找到包含D字符结点位于二叉树中的层数
printf("\n后序遍历:\n");
PostOrderTraverse(T,level); //遍历二叉树,找到包含D字符结点位于二叉树中的层数
Node_num = CountLeaf(T);
Depth_num = TreeDepth(T);
printf("\nNode_num = %d, Depth_num = %d\n",Node_num,Depth_num);
return 0;
}
<file_sep>/c/lrc/main.c
/* ************************************************************************
* Filename: main.c
* Description:
* Version: 1.0
* Created: 2015年07月31日 星期五 05時36分37秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include "common.h"
#include "process_lrc.h"
#include "start_mplayer.h"
#include "interface.h"
#include "file.h"
#include "link.h"
int main(int argc, char *argv[])
{
char *lrc_src = NULL, **plines = NULL, *pheader[4] = {NULL};
char *list_src = NULL, **plist = NULL;
char playing = 0; //播放标志,1 为正在播放
int lines = 0, longestlength = 0, i = 0;
int time = 0, maxtime = 0, timelag = 0;
ulint lrc_length = 0;
LRC *lrc_head = NULL, *pnode = NULL;
struct timeval start_time,end_time;
show_interface(); //
list_src = get_musiclist(&plist);
show_musiclist(plist);
while(1)
{
#if 1
if(!playing)
{
mplayer_play("./music/喜欢你.mp3");
lrc_src = read_src_file(&lrc_length, "lyric/喜欢你.lrc"); //读出歌词文件的内容到lrc_src指向的地址空间
lines = check_lines(lrc_length, lrc_src); //检测歌词有几行
plines = (char **)malloc(lines*sizeof(char **)); //动态分配空间存储每行的首地址
if(plines == NULL) goto out; //如果分配空间失败,退出程序
src_segment(lrc_src, plines, "\r\n"); //按行分割歌词
lrc_head = build_link(plines, pheader, lines); //按时间建立链表
longestlength = get_longestlength(lrc_head);
pnode = lrc_head;
//print_link(lrc_head);
show_lrcheader(pheader);
maxtime = get_maxtime(lrc_head);
timelag = maxtime/60;
gettimeofday(&start_time,0); //开始计时
playing = 1; //
}
gettimeofday(&end_time,0);
time = 1000000*(end_time.tv_sec - start_time.tv_sec) + end_time.tv_usec - start_time.tv_usec;
time = (int)time/1000; //除以1000则进行毫秒计时
if(pnode != NULL && time >= pnode->time) //
{
show_lyric(pnode,longestlength);
pnode = pnode->next;
}
show_progressbar(time,timelag);
show_time(time, maxtime);
if(pnode == NULL)
{
sleep(12);
playing = 0;
move = 1; //在interface.c里定义,用于记录进度条的进度
lrc_head = free_link(lrc_head);
free(lrc_src);
}
#endif
}
free(lrc_src);
free_link(lrc_head);
out:
return 0;
}
<file_sep>/work/camera/bf3703/bf3703/bf3703_set.c
#include <linux/jz_cim_core.h>
#include <linux/jz_sensor.h>
#include <linux/i2c.h>
#include <asm/jzsoc.h>
//#define bf3703_DEBUG
#undef bf3703_DEBUG
#ifdef bf3703_DEBUG
#define dprintk(x...) do{printk("bf3703-\t");printk(x);printk("\n");}while(0)
#else
#define dprintk(x...)
#endif
//for test
void retry_write_reg(struct i2c_client *client ,int addr, int value)
{
int num = 0;
sensor_write_reg(client,addr,value);
while(sensor_read_reg(client,addr) != value)
{
num++;
//printk("this is %d to retry_write_reg, addr is %d \n",num,addr);
sensor_write_reg(client,addr,value);
if(num > 10)
break;
}
}
//end
void preview_set(struct i2c_client *client)
{
} //===preview setting end===
void set_size_640x480(struct i2c_client *client,int mode)
{
#if 1
retry_write_reg(client,0x17,0x00);
retry_write_reg(client,0x18,0xa0);
retry_write_reg(client,0x19,0x00);
retry_write_reg(client,0x1a,0x78);
retry_write_reg(client,0x03,0x00);
retry_write_reg(client,0x12,0x00);
retry_write_reg(client,0x8e,0x05);
retry_write_reg(client,0x8f,0xfb);
// frame
// retry_write_reg(client,0x0b,0x00);
#endif
dprintk("VGA 640x480");
}
void set_size_352x288(struct i2c_client *client,int mode)
{
#if 1
retry_write_reg(client,0x17,0x36);
retry_write_reg(client,0x18,0x8e);
retry_write_reg(client,0x19,0x1b);
retry_write_reg(client,0x1a,0x63);
retry_write_reg(client,0x03,0xf0);
retry_write_reg(client,0x12,0x00);
retry_write_reg(client,0x8e,0x03);
retry_write_reg(client,0x8f,0xfc);
// frame
// retry_write_reg(client,0x0b,0x00);
#endif
dprintk("CIF 352x288");
}
void set_size_320x240(struct i2c_client *client,int mode)
{
retry_write_reg(client,0x17,0x00);
retry_write_reg(client,0x18,0xa0);
retry_write_reg(client,0x19,0x00);
retry_write_reg(client,0x1a,0x78);
retry_write_reg(client,0x03,0x00);
sensor_write_reg(client,0x12,0x10);
dprintk("QVGA 320x320");
}
void set_size_176x144(struct i2c_client *client,int mode)
{
sensor_write_reg(client,0x17,0x36);
sensor_write_reg(client,0x18,0x8e);
sensor_write_reg(client,0x19,0x1b);
sensor_write_reg(client,0x1a,0x63);
sensor_write_reg(client,0x03,0xf0);
sensor_write_reg(client,0x12,0x10);
dprintk("QCIF 176x144");
}
void size_switch(struct i2c_client *client,int width,int height,int setmode)
{
dprintk("%dx%d - mode(%d)",width,height,setmode);
//return;
if(width == 640 && height == 480)
{
set_size_640x480(client,setmode);
}
else if(width == 352 && height == 288)
{
set_size_352x288(client,setmode);
}
else if(width == 320 && height == 240)
{
set_size_320x240(client,setmode);
}
else if(width == 176 && height == 144)
{
set_size_176x144(client,setmode);
}
else
return;
// mdelay(500);
}
void bf3703_reset(void);
void bf3703_init_setting(struct i2c_client *client)
{
//SOFE RESET
//retry_write_reg16(client,0x12,0x80);
bf3703_reset();
mdelay(10);
retry_write_reg(client,0x11,0x80);
//retry_write_reg(client,0x11,0x80);//modify by huawu
retry_write_reg(client,0x20,0x40);
retry_write_reg(client,0x09,0xc0);
//retry_write_reg(client,0x12,0x00);
retry_write_reg(client,0x13,0x00);
retry_write_reg(client,0x01,0x13);
retry_write_reg(client,0x01,0x13);//retry 01
retry_write_reg(client,0x02,0x25);
retry_write_reg(client,0x8c,0x02);
retry_write_reg(client,0x8d,0xfd);
retry_write_reg(client,0x87,0x1a);
retry_write_reg(client,0x13,0x07);
//POLARITY of Signal
retry_write_reg(client,0x15,0x00);
retry_write_reg(client,0x3a,0x03);
//black level ,对上电偏绿有改善,如果需要请使用
/*
retry_write_reg(client,0x05,0x1f);
retry_write_reg(client,0x06,0x60);
retry_write_reg(client,0x14,0x1f);
retry_write_reg(client,0x06,0xe0);
*/
/*
retry_write_reg(client,0x17,0x00);
retry_write_reg(client,0x18,0xa0);
retry_write_reg(client,0x19,0x00);
retry_write_reg(client,0x1a,0x78);
retry_write_reg(client,0x03,0x00);
*/
//lens shading
retry_write_reg(client,0x35,0x68);
retry_write_reg(client,0x65,0x68);
retry_write_reg(client,0x66,0x62);
retry_write_reg(client,0x36,0x05);
retry_write_reg(client,0x37,0xf6);
retry_write_reg(client,0x38,0x46);
retry_write_reg(client,0x9b,0xf6);
retry_write_reg(client,0x9c,0x46);
retry_write_reg(client,0xbc,0x01);
retry_write_reg(client,0xbd,0xf6);
retry_write_reg(client,0xbe,0x46);
//AE
retry_write_reg(client,0x82,0x14);
retry_write_reg(client,0x83,0x23);
retry_write_reg(client,0x9a,0x23);
retry_write_reg(client,0x84,0x1a);
retry_write_reg(client,0x85,0x20);
retry_write_reg(client,0x89,0x04);
retry_write_reg(client,0x8a,0x08);
retry_write_reg(client,0x86,0x28);
retry_write_reg(client,0x96,0xa6);
retry_write_reg(client,0x97,0x0c);
retry_write_reg(client,0x98,0x18);
//AE target
retry_write_reg(client,0x24,0x7a);
retry_write_reg(client,0x25,0x8a);
retry_write_reg(client,0x94,0x0a);
retry_write_reg(client,0x80,0x55);
//denoise
retry_write_reg(client,0x70,0x6f);
retry_write_reg(client,0x72,0x4f);
retry_write_reg(client,0x73,0x2f);
retry_write_reg(client,0x74,0x27);
retry_write_reg(client,0x7a,0x4e);
retry_write_reg(client,0x7b,0x28);
//black level
retry_write_reg(client,0X1F,0x20);
retry_write_reg(client,0X22,0x20);
retry_write_reg(client,0X26,0x20);
//模拟部分参数
retry_write_reg(client,0X16,0x00);
retry_write_reg(client,0xbb,0x20);
retry_write_reg(client,0xeb,0x30);
retry_write_reg(client,0xf5,0x21);
retry_write_reg(client,0xe1,0x3c);
retry_write_reg(client,0xbb,0x20);
retry_write_reg(client,0X2f,0X66);
retry_write_reg(client,0x06,0xe0);
//anti black sun spot
retry_write_reg(client,0x61,0xd3);
retry_write_reg(client,0x79,0x48);
//Gamma
retry_write_reg(client,0x3b,0x60);
retry_write_reg(client,0x3c,0x20);
retry_write_reg(client,0x56,0x40);
retry_write_reg(client,0x39,0x80);
//gamma1
retry_write_reg(client,0x3f,0xa8);
retry_write_reg(client,0X40,0X48);
retry_write_reg(client,0X41,0X54);
retry_write_reg(client,0X42,0X4E);
retry_write_reg(client,0X43,0X44);
retry_write_reg(client,0X44,0X3e);
retry_write_reg(client,0X45,0X39);
retry_write_reg(client,0X46,0X35);
retry_write_reg(client,0X47,0X31);
retry_write_reg(client,0X48,0X2e);
retry_write_reg(client,0X49,0X2b);
retry_write_reg(client,0X4b,0X29);
retry_write_reg(client,0X4c,0X27);
retry_write_reg(client,0X4e,0X23);
retry_write_reg(client,0X4f,0X20);
retry_write_reg(client,0X50,0X20);
/*
//gamma2 高亮度
retry_write_reg(client,0x3f,0xc8);
retry_write_reg(client,0X40,0X9b);
retry_write_reg(client,0X41,0X88);
retry_write_reg(client,0X42,0X6e);
retry_write_reg(client,0X43,0X59);
retry_write_reg(client,0X44,0X4d);
retry_write_reg(client,0X45,0X45);
retry_write_reg(client,0X46,0X3e);
retry_write_reg(client,0X47,0X39);
retry_write_reg(client,0X48,0X35);
retry_write_reg(client,0X49,0X31);
retry_write_reg(client,0X4b,0X2e);
retry_write_reg(client,0X4c,0X2b);
retry_write_reg(client,0X4e,0X26);
retry_write_reg(client,0X4f,0X23);
retry_write_reg(client,0X50,0X1F);
*/
/*
//gamma3 清晰亮丽
retry_write_reg(client,0X3f,0Xa0);
retry_write_reg(client,0X40,0X60);
retry_write_reg(client,0X41,0X60);
retry_write_reg(client,0X42,0X66);
retry_write_reg(client,0X43,0X57);
retry_write_reg(client,0X44,0X4c);
retry_write_reg(client,0X45,0X43);
retry_write_reg(client,0X46,0X3c);
retry_write_reg(client,0X47,0X37);
retry_write_reg(client,0X48,0X32);
retry_write_reg(client,0X49,0X2f);
retry_write_reg(client,0X4b,0X2c);
retry_write_reg(client,0X4c,0X29);
retry_write_reg(client,0X4e,0X25);
retry_write_reg(client,0X4f,0X22);
retry_write_reg(client,0X50,0X20);
//gamma 4 low noise
retry_write_reg(client,0X3f,0Xa0);
retry_write_reg(client,0X40,0X48);
retry_write_reg(client,0X41,0X54);
retry_write_reg(client,0X42,0X4E);
retry_write_reg(client,0X43,0X44);
retry_write_reg(client,0X44,0X3E);
retry_write_reg(client,0X45,0X39);
retry_write_reg(client,0X46,0X34);
retry_write_reg(client,0X47,0X30);
retry_write_reg(client,0X48,0X2D);
retry_write_reg(client,0X49,0X2A);
retry_write_reg(client,0X4b,0X28);
retry_write_reg(client,0X4c,0X26);
retry_write_reg(client,0X4e,0X22);
retry_write_reg(client,0X4f,0X20);
retry_write_reg(client,0X50,0X1E);
*/
//color matrix
//艳丽
retry_write_reg(client,0x51,0x0d);
retry_write_reg(client,0x52,0x21);
retry_write_reg(client,0x53,0x14);
retry_write_reg(client,0x54,0x15);
retry_write_reg(client,0x57,0x8d);
retry_write_reg(client,0x58,0x78);
retry_write_reg(client,0x59,0x5f);
retry_write_reg(client,0x5a,0x84);
retry_write_reg(client,0x5b,0x25);
retry_write_reg(client,0x5c,0x0e);
retry_write_reg(client,0x5d,0x95);
/*
//适中
retry_write_reg(client,0x51,0x06);
retry_write_reg(client,0x52,0x16);
retry_write_reg(client,0x53,0x10);
retry_write_reg(client,0x54,0x11);
retry_write_reg(client,0x57,0x62);
retry_write_reg(client,0x58,0x51);
retry_write_reg(client,0x59,0x49);
retry_write_reg(client,0x5a,0x65);
retry_write_reg(client,0x5b,0x1c);
retry_write_reg(client,0x5c,0x0e);
retry_write_reg(client,0x5d,0x95);
*/
/*
//淡
retry_write_reg(client,0x51,0x03);
retry_write_reg(client,0x52,0x0d);
retry_write_reg(client,0x53,0x0b);
retry_write_reg(client,0x54,0x14);
retry_write_reg(client,0x57,0x59);
retry_write_reg(client,0x58,0x45);
retry_write_reg(client,0x59,0x41);
retry_write_reg(client,0x5a,0x5f);
retry_write_reg(client,0x5b,0x1e);
retry_write_reg(client,0x5c,0x0e);
retry_write_reg(client,0x5d,0x95);
*/
retry_write_reg(client,0x60,0x20);
//AWB
retry_write_reg(client,0x6a,0x81); //01
retry_write_reg(client,0x23,0x66); //Green gain
retry_write_reg(client,0xa0,0x03); //07
retry_write_reg(client,0xa1,0X41);
retry_write_reg(client,0xa2,0X0e);
retry_write_reg(client,0xa3,0X26);
retry_write_reg(client,0xa4,0X0d);
retry_write_reg(client,0xa5,0x28);
retry_write_reg(client,0xa6,0x04);
retry_write_reg(client,0xa7,0x80);
retry_write_reg(client,0xa8,0x80);
retry_write_reg(client,0xa9,0x28);
retry_write_reg(client,0xaa,0x28);
retry_write_reg(client,0xab,0x28);
retry_write_reg(client,0xac,0x3c);
retry_write_reg(client,0xad,0xf0);
retry_write_reg(client,0xc8,0x18);
retry_write_reg(client,0xc9,0x20);
retry_write_reg(client,0xca,0x17);
retry_write_reg(client,0xcb,0x1f);
retry_write_reg(client,0xaf,0x00);
retry_write_reg(client,0xc5,0x18);
retry_write_reg(client,0xc6,0x00);
retry_write_reg(client,0xc7,0x20);
retry_write_reg(client,0xae,0x81); //83
retry_write_reg(client,0xcc,0x30);
retry_write_reg(client,0xcd,0x70);
retry_write_reg(client,0xee,0x4c);
retry_write_reg(client,0xae,0x81); //83 retry ae
// color saturation
retry_write_reg(client,0xb0,0xd0);
retry_write_reg(client,0xb1,0xc0);
retry_write_reg(client,0xb2,0xb0);
retry_write_reg(client,0xb3,0x88);
//retry_write_reg(client,0x8e,0x05); //0x07,8帧//0x03,10
//retry_write_reg(client,0x8f,0xfb); //0x79//0xfc,10
retry_write_reg(client,0x9d,0x99);
//switch
// retry_write_reg(client,0x1e,0x00); //00,10,20,30
retry_write_reg(client,0x1e,0x20); //00,10,20,30 //modify by huawu
}
uint32_t stop_ae(struct i2c_client *client)
{
return 0;
}
void capture_set(struct i2c_client *client)
{
}
<file_sep>/work/debug/pc/timer/test_timer.c
/* ************************************************************************
* Filename: test_timer.c
* Description:
* Version: 1.0
* Created: 2015年08月08日 10时43分53秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
void main()
{
int fd = 0;
int counter = 0;
int old_counter = 0;
fd = open("/dev/timer_drv",O_RDONLY);
if(fd != -1)
{
while(1)
{
read(fd,&counter,sizeof(unsigned int));
if(counter != old_counter)
{
old_counter = counter;
printf("seconds open /dev/timer_dev: %d\n",counter);
}
}
}
else
{
printf("Device open failure!\n");
}
}
<file_sep>/work/test/fibonacci/fibonacci.c
long long fibonacci(long i)
{
long long fib1 = 1;
long long fib2 = 1;
long long temp;
while(i > 2) {
temp = fib2;
fib2 = fib2 + fib1;
fib1 = temp;
i--;
}
return fib2;
}
int main(int argc, char *argv[])
{
(void)fibonacci(30000000);
return 0;
}
<file_sep>/work/debug/pc/snull/snull.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/in.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/skbuff.h>
#include <linux/in6.h>
#include <asm/checksum.h>
#include "snull.h"
static int lockup = 0;
module_param(lockup, int, 0);
static int timeout = SNULL_TIMEOUT;
module_param(timeout, int, 0);
struct net_device snull_devs[2];
int snull_open(struct net_device *dev)
{
//将硬件(MAC)从硬件设备复制到dev->dev_addr
memcpy(dev->dev_addr, "\0SNUL0", ETH_ALEN);
if(dev == snull_devs[1])
dev->dev_addr[ETH_ALEN - 1]++; /* \0SNUL1 */
netif_start_queue(dev);//启动接口的传输队列,允许接口接受传输包
return 0;
}
int snull_release(struct net_device *dev)
{
netif_stop_queue(dev);//在接口被关闭时,必须调用该函数,但该函数也可以用来临时停止传输。
return 0;
}
int snull_config(struct net_device *dev, struct ifmap *map)
{
if(dev->flags & IFF_UP)
return -EBUSY;
if(map->base_addr != dev->base_addr) {
printk(KERN_WARNING "snull: Can't change I/O address\n");
return -EOPNOTSUPP;
}
if(map->irq != dev->irq)
dev->irq = map->irq;
return 0;
}
void snull_rx(struct net_device *dev, int len, unsigned char *buf)
{
struct sk_buff *skb;
struct snull_priv *prvi = netdev_priv(dev);
skb = dev_alloc_skb(len + 2);//分配一个保存数据包的缓冲区
if(!skb) {
printk("snull rx: low on mem - packet dropped\n");
priv->stats.rx_dropped++;
return;
}
skb_reserve(skb, 2);
memcpy(skb_put(skb, len), buf, len);//skb_put函数刷新缓冲区内的数据末尾指针,并且返回新创建数据区的指针
skb->dev = dev;
skb->protocol = eth_type_trans(skb, dev);
skb->ip_summed = CHECKSUM_UNNECESSARY;
priv->stats.rx_packets++;
priv->stats.rx_bytes += len;
netif_rx(skb);//将套接字缓冲区传递给上层软件处理
return;
}
void snull_interrupt(int irq, void *dev_id, struct pt_regs *regs)
{
int statusword;
struct net_device *dev = (struct net_device *)dev_id;
struct snull_priv *priv = netdev_priv(dev);
if(!dev)
return;
spin_lock(&priv->lock);
statusword = priv->status;
priv->status = 0;
if(statusword & SNULL_RX_INTR)
snull_rx(dev, priv->rx_packetlen, priv->rx_packetdata);
if(statusword & SNULL_TX_INTR) {
priv->stats.tx_packets++;
priv->stats.tx_bytes += priv->tx_packetlen;
dev_kfree_skb(priv->skb);
}
spin_unlock(&priv->lock);
return;
}
void snull_tx_timeout(struct net_device *dev)
{
struct snull_priv = netdev_priv(dev);
printk(KERN_INFO"Transmit timeout at %ld, latency %ld\n", jiffies,jiffies - dev->trans_start);
priv->status = SNULL_TX_INTR;
snull_interrupt(0, dev, NULL); // 模拟一个传输中断
priv->stats.tx_errors++;
netif_wake_queue(dev);
return;
}
void snull_hw_tx(char *buf, int len, struct net_device *dev)
{
struct iphdr *ih;
struct net_device *dest;
struct snull_priv *priv = netdev_priv(dev);
unsigned long *saddr, *daddr;
if(len < sizeof(struct ethhdr) + sizeof(struct ipdhr)){
printk("snull: Hmm... packet too short (%i octets)\n", len);
return;
}
ih = (struct iphdr *)(buf + sizeof(struct iphdr));
saddr = &ih->saddr;
daddr = &ih->daddr;
((u8 *)saddr)[2] ^= 1;
((u8 *)daddr)[2] ^= 1;
ih->check = 0;
/* 重新计算ip校验和,正常情况下还应该重新计算tcp头校验和,icmp头检验和.. */
ih->check = ip_fast_csum((u8 *)ih, ih->ihl);
if(dev == snull_devs[0])
printk(KERN_INFO"%08x:%05i --> %08x:%05i\n",
ntohl(ih->saddr),ntohs(((struct tcphdr *)(ih+1))->source),
ntohl(ih->daddr),ntohs(((struct tcphdr *)(ih+1))->dest));
else
printk(KERN_INFO"%08x:%05i <-- %08x:%05i\n",
ntohl(ih->daddr),ntohs(((struct tcphdr *)(ih+1))->dest),
ntohl(ih->saddr),ntohs(((struct tcphdr *)(ih+1))->source));
dest = snull_devs[dev == snull_devs[0] ? 1 : 0];
priv->status = SNULL_RX_INTR;
priv->rx_packetlen = len;
priv->rx_packetdata = buf;
snull_interrupt(0, dest, NULL); // 产生中断--->接收
priv->status = SNULL_TX_INTR;
priv->tx_packetlen = len;
priv->tx_packetdata = buf;
if (lockup && ((priv->stats.tx_packets + 1) % lockup) == 0) {
netif_stop_queue(dev);
printk(KERN_INFO"Simulate lockup at %ld, txp %ld\n", jiffies,(unsigned long) priv->stats.tx_packets);
}
else
snull_interrupt(0, dev, NULL);// 产生中断--->发送
return;
}
int snull_tx(struct sk_buff *skb, struct net_device *dev)
{
int len;
chat *data, shortpkt[ETH_ZLEN];
struct snull_priv *priv = netdev_priv(dev);
data = skb->data;
len =skb->len;
if(len < ETH_ZLEN) {
memset(shortpkt, 0, ETH_ZLEN);
memcpy(shortpkt, skb->data, len);
data = shortpkt;
}
dev->trans_start = jiffies; //保存时间
priv->sbk = skb; //记住skb,以便释放
snull_hw_tx(data, len, dev);//硬件相关的传输函数
return 0;
}
int snull_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
return 0;
}
struct net_device_stats *snull_stats(struct net_device *dev)
{
struct snull_priv = netdev_priv(dev);
return &priv->stats;
}
int snull_rebuild_header(struct sk_buff *skb)
{
struct ethhdr *eth = (struct ethhdr *)skb->data;
struct net_device *dev = skb->dev;
memcpy(eth->h_source, dev->dev_addr, dev->addr_len);
memcpy(eth->h_dest, dev->dev_addr, dev->addr_len);
eth->h_dest[ETH_ALEN - 1] ^= 0x01;
return 0;
}
int snull_header(struct sk_buff *skb, struct net_device *dev,
unsigned short type, const void *daddr, const void *saddr,
unsigned int len)
{
struct ethhdr *eth = (struct ethhdr *)skb_push(skb, ETH_HLEN);
eth->h_proto = htons(type);
memcpy(eth->h_source, saddr?saddr:dev->dev_addr, dev->addr_len);
memcpy(eth->h_dest, daddr?daddr:dev->dev_addr, dev->addr_len);
eth->h_dest[ETH_ALEN - 1] ^= 0x01;
return (dev->hard_harder_len);
}
int snull_change_mtu(struct net_device *dev, int new_mtu)
{
unsigned long flags;
struct snull_priv *priv = netdev_priv(dev);
spinlock_t *lock = &priv->lock;
if((new_mtu < 68) || (new_mtu > 1500)) //以太网的MTU是1500个octet(ETH_DATA_LEN)
return -EINVAL;
spin_lock_irqsave(lock, flags);
dev->mtu = new_mtu;
spin_unlock_irqsave(lock, flags);
return 0;
}
//以下两个结构是相关接口函数的初始化
static const struct net_device_ops snull_dev_ops = {
.ndo_open = snull_open,
.ndo_stop = snull_release,
.ndo_set_config = snull_config,
.ndo_start_xmit = snull_tx,
.ndo_do_ioctl = snull_ioctl,
.ndo_get_stats = snull_stats,
.ndo_change_mtu = snull_change_mtu,
.ndo_tx_timeout = snull_tx_timeout,
};
static const struct header_ops snull_header_ops = {
.creat = snull_header,
.rebuild = snull_rebuild_header,
.cache = NULL,
};
static void snull_init_netdev(struct net_device *dev)
{
struct snull_priv *priv = NULL;
ether_setup(dev);//对某些成员作一些初始化
dev->netdev_ops = &snull_dev_ops;
dev->header_ops = &snull_header_ops;
dev->watchdog_timeo = timeout;
dev->flags |= IFF_NOARP; //禁止ARP
dev->features |= NETIF_F_NO_CSUM;
priv = netdev_priv(dev);//priv是net_device中的一个成员,它与net_device一起被分配,当需要访问私有成员priv时使用该函数
memset(priv, 0, sizeof(struct snull_priv));
priv->dev = dev;
spin_lock_init(&priv->lock);
return;
}
static __init int snull_init(void)
{
int ret, i;
snull_devs[0] = alloc_netdev(sizeof(struct snull_priv), "sn%d", snull_init_netdev);
snull_devs[1] = alloc_netdev(sizeof(struct snull_priv), "sn%d", snull_init_netdev);
if(snull_devs[0] == NULL || snull_devs[1] == NULL) {
for(i = 0; i < 2; i++) {
if(snull_devs[i] != NULL)
free_netdev(snull_devs[i]); //将net_device结构返还给系统
}
goto fail0;
}
for(i = 0; i < 2; i++) {
//注册设备,必须在初始化一切事情后再注册
ret = register_netdev(snull_devs[i]);
if(ret) {
printk("snull: error %i registering device \"%s\"\n",result, snull_devs[i]->name);
break;
}
}
if(i != 2) {
while(i >= 0)
unregister_netdev(snull_devs[i]); //从系统中删除接口
goto fail1
}
return 0;
fail1:
free_netdev(snull_devs[0]);
free_netdev(snull_devs[1]);
fail0:
return -ENODEV;
}
static __exit void snull_exit(void)
{
int i;
for(i=0; i<2;i++) {
if(snull_devs[i]) {
unregister_netdev(snull_devs[i]); //从系统中删除接口
free_netdev(snull_devs[i]); //将net_device结构返还给系统
}
}
return;
}
module_init(snull_init);
module_exit(snull_exit);
MODULE_VERSION("snull_v1.0");
MODULE_LICENSE("GPL");<file_sep>/work/debug/pc/snull/snull.h
#ifndef __SNULL_H__
#define __SNULL_H__
#define u8 unsigned short
#define u32 unsigned long
#define SNULL_RX_INTR 0x0001
#define SNULL_TX_INTR 0x0002
#define SNULL_TIMEOUT 5
struct snull_prib {
int status;
int rx_packetlen;
int tx_packetlen;
unsigned short *rx_packetdata;
unsigned short *tx_packetdata;
spinlock_t lock;
struct sk_buff *skb;
struct net_device *dev;
struct net_device_stats stats;
};
#endif
<file_sep>/gtk/4st_week/gtk_entry.c
/* ************************************************************************
* Filename: entry.c
* Description:
* Version: 1.0
* Created: 2015年08月10日 14时28分21秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <gtk/gtk.h>
void entry_callback(GtkWidget *widget, gpointer entry)
{
const gchar *entry_text;
entry_text = (gchar *)gtk_entry_get_text(GTK_ENTRY(entry));
printf("Entry contents: %s\n",entry_text);
}
int main(int argc, char *argv[])
{
gtk_init(&argc,&argv);
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window),"GTK entry");
GtkWidget *vbox1 = gtk_vbox_new(TRUE, 5); //创建一个垂直布局容器
gtk_container_add(GTK_CONTAINER(window), vbox1);
GtkWidget *hbox1 = gtk_hbox_new(TRUE, 0); //创建一个水平布局容器
gtk_container_add(GTK_CONTAINER(vbox1), hbox1); //加入垂直布局里面
GtkWidget *label = gtk_label_new("text: ");
gtk_container_add(GTK_CONTAINER(hbox1), label); //加入垂直布局里面
GtkWidget *entry = gtk_entry_new(); //创建行编辑
gtk_entry_set_max_length(GTK_ENTRY(entry), 100);//设置行编辑显示最大字符的长度
//gtk_entry_set_text(GTK_ENTRY(entry), "hello world");//设置显示内容
gtk_entry_set_visibility(GTK_ENTRY(entry), FALSE); //密码模式
gtk_container_add(GTK_CONTAINER(hbox1), entry); //加入水平布局里面
g_signal_connect(entry, "activate",G_CALLBACK(entry_callback), entry);
GtkWidget *vbox2 = gtk_vbox_new(TRUE, 5); //创建一个垂直布局容器
gtk_container_add(GTK_CONTAINER(window), vbox2);
GtkWidget *hbox2 = gtk_hbox_new(TRUE, 0); //创建一个水平布局容器
GtkWidget *button1 = gtk_button_new_with_label("button 1");
gtk_container_add(GTK_CONTAINER(hbox2), button1);
GtkWidget *button2 = gtk_button_new_with_label("button 2");
gtk_container_add(GTK_CONTAINER(hbox2), button2);
gtk_container_add(GTK_CONTAINER(vbox2), hbox2);
GtkWidget *button_close = gtk_button_new_with_label("close");
g_signal_connect(button_close,"clicked", G_CALLBACK(gtk_main_quit),NULL);
gtk_container_add(GTK_CONTAINER(vbox2), button_close);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
<file_sep>/network/1st_day/qq.c
/* ************************************************************************
* Filename: qq.c
* Description:
* Version: 1.0
* Created: 2015年08月31日 19时32分08秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
void *pthread_sndmsg(void *arg)
{
int snd_fd = 0;
unsigned short port = 8000;
char server_ip[INET_ADDRSTRLEN] = "127.0.0.1";
snd_fd = socket(AF_INET, SOCK_DGRAM, 0);
//配置服务器地址
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);//服务器的端口
inet_pton(AF_INET, server_ip ,&server_addr.sin_addr.s_addr);//服务器的IP
while(1)
{
char msg[128] = "";
char buf[10] = "";
bzero(msg, sizeof(msg));
bzero(buf, sizeof(buf));
printf("\033[34mQQudp:\033[0m");
fflush(stdout);
fgets(msg,sizeof(msg),stdin);
msg[strlen(msg) - 1] = 0;
//printf("sndmsg = %s\n", msg);
sscanf(msg,"%[^ ]",buf);
if(strcmp("sayto",buf) == 0)
{
int ret = 0;
sscanf(msg,"%*[^ ] %s",server_ip);
//printf("server_ip = %s##\n", server_ip);
ret = inet_pton(AF_INET, server_ip ,&server_addr.sin_addr.s_addr);
if(ret == 1)
{
printf("connect %s successful!!\n",server_ip);
}
else
{
printf("cannot connect to %s\n",server_ip);
}
}
else if(strlen(msg) != 0)
{
sendto(snd_fd, msg, strlen(msg), 0,\
(struct sockaddr *)&server_addr, sizeof(server_addr));
}
}
return NULL;
}
void *pthread_rcvmsg(void *arg)
{
char msg[128];
char ip_buf[INET_ADDRSTRLEN] = "";
//创建一个通信socket
int rvc_fd = socket(AF_INET, SOCK_DGRAM, 0);
//作为一个服务器应该有一个固定的ip、port
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8000);
//INADDR_ANY: 通配地址
addr.sin_addr.s_addr = htonl(INADDR_ANY);
//bind只能bind自己的ip
bind(rvc_fd, (struct sockaddr *)&addr, sizeof(addr));
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
bzero(&client_addr, sizeof(client_addr));
while(1)
{
//接收client发送来的数据
bzero(msg, sizeof(msg));
recvfrom(rvc_fd, msg, sizeof(msg), 0, (struct sockaddr *)&client_addr, &client_len);
inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, ip_buf, INET_ADDRSTRLEN);
printf("\033[32m\r[%s]: %s\033[0m\n",ip_buf, msg);
printf("\033[34mQQudp:\033[0m");
fflush(stdout);
//printf("port:%d\n",ntohs(client_addr.sin_port));
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t pth_snd, pth_rcv;
pthread_create(&pth_snd, NULL,pthread_sndmsg, NULL);
pthread_create(&pth_rcv, NULL,pthread_rcvmsg, NULL);
pthread_detach(pth_rcv);
pthread_detach(pth_snd);
while(1)
{
sleep(10);
}
return 0;
}
<file_sep>/work/test/timer/timer.c
/*************************************************************************
> Filename: timer.c
> Author:
> Email: <EMAIL> / <EMAIL>
> Datatime: Wed 04 Jan 2017 02:22:26 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <signal.h>
#include <pthread.h>
#include <errno.h>
#include <time.h>
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/epoll.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/timerfd.h>
#if 1
/*
* POSIX Timer
*/
static int counter = 0;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void print_time(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
printf("Current time: %ld.%ld\n",tv.tv_sec, tv.tv_usec);
}
void timer_thread(union sigval sgv)
{
pthread_mutex_lock(&mutex);
if (++counter >= 8)
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pid_t tid = (pid_t)syscall(SYS_gettid);
printf("Timer %d in PID:[%d], TID:[%d]\n", *((int *)(sgv.sival_ptr)), getpid(), tid);
print_time();
}
int main(int argc, char *argv[])
{
timer_t timerid1, timerid2;
struct sigevent evp1, evp2;
struct itimerspec its1, its2;
/*
* create timer
*/
bzero(&evp1, sizeof(evp1));
evp1.sigev_notify = SIGEV_THREAD;
evp1.sigev_value.sival_ptr = &timerid1;
evp1.sigev_notify_function = timer_thread;
evp1.sigev_notify_attributes = NULL;
if (timer_create(CLOCK_MONOTONIC, &evp1, &timerid1) < 0) {
printf("Failed to create timer1: %s", strerror(errno));
return -1;
}
bzero(&evp2, sizeof(evp2));
evp2.sigev_notify = SIGEV_THREAD;
evp2.sigev_value.sival_ptr = &timerid2;
evp2.sigev_notify_function = timer_thread;
evp2.sigev_notify_attributes = NULL;
if (timer_create(CLOCK_MONOTONIC, &evp2, &timerid2) < 0) {
printf("Failed to create timer2: %s", strerror(errno));
return -1;
}
/*
* start timer
*/
its1.it_interval.tv_sec = 2;
its1.it_interval.tv_nsec = 0;
its1.it_value.tv_sec = 3;
its1.it_value.tv_nsec = 0;
if (timer_settime(timerid1, 0, &its1, NULL) < 0) {
printf("Failed to set timer1: %s\n", strerror(errno));
return -1;
}
its2.it_interval.tv_sec = 1;
its2.it_interval.tv_nsec = 0;
its2.it_value.tv_sec = 5;
its2.it_value.tv_nsec = 0;
if (timer_settime(timerid2, 0, &its2, NULL) < 0) {
printf("Failed to set timer2: %s\n", strerror(errno));
return -1;
}
print_time();
while(counter < 8)
pthread_cond_wait(&cond, &mutex);
return 0;
}
#elif 0
/*
* setitimer
*/
static int cnt = 0;
void print_time(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
printf("Current time: %ld.%ld, cnt = %d\n",tv.tv_sec, tv.tv_usec, cnt);
}
void sighandler(int signo)
{
switch(signo) {
case SIGALRM:
printf("Timer fired, signo: %s\n", "SIGALRM");
break;
case SIGVTALRM:
printf("Timer fired, signo: %s\n", "SIGVTALRM");
break;
case SIGPROF:
printf("Timer fired, signo: %s\n", "SIGPROF");
break;
}
cnt++;
print_time();
}
int main(int argc, char *argv[])
{
struct sigaction act;
struct itimerval val;
/*
* init sigaction
*/
act.sa_handler = sighandler;
act.sa_flags = 0; //见注 3)
//act.sa_flags = SA_RESETHAND | SA_NODEFER; //见注 2)
//sigaddset(&act.sa_mask, SIGQUIT); //见注 1)
sigemptyset(&act.sa_mask);
sigaction(SIGPROF, &act, NULL);
/*
* init timer
*/
val.it_value.tv_sec = 5;
val.it_value.tv_usec = 0;
val.it_interval.tv_sec = 3;
val.it_interval.tv_usec = 0;
setitimer(ITIMER_PROF, &val, NULL);
print_time();
while(cnt < 4)
usleep(100);
return 0;
}
/**
* 注:
* 1) 如果在信号SIGINT(Ctrl + c)的信号处理函数show_handler执行过程中,本进程收到信号SIGQUIT(Crt+\),将阻塞该信号,直到show_handler执行结束才会处理信号SIGQUIT。
*
* 2) SA_NODEFER :一般情况下,当信号处理函数运行时,内核将阻塞<该给定信号:SIGINT>。但是如果设置了SA_NODEFER标记,那么在该信号处理函数运行时,内核将不会阻塞该
* 信号。SA_NODEFER是这个标记的正式的POSIX名字(还有一个名字SA_NOMASK,为了软件的可移植性,一般不用这个名字)
*
* SA_RESETHAND:当调用信号处理函数时,将信号的处理函数重置为缺省值。 SA_RESETHAND是这个标记的正式的POSIX名字(还有一个名字SA_ONESHOT,为了软件的可移植性,一般不用这个名字)
*
* 3) 如果不需要重置该给定信号的处理函数为缺省值;并且不需要阻塞该给定信号(无须设置sa_flags标志),那么必须将sa_flags清零,否则运行将会产生段错误。但是sa_flags清零后可能会造成信号丢失!
*/
#endif
<file_sep>/work/test/cim_test-zmm220/sensor.h
/*************************************************
ZEM 200
sensor.h
Copyright (C) 2003-2006, ZKSoftware Inc.
*************************************************/
#ifndef _SENSOR_H_
#define _SENSOR_H_
#define CMOS_WIDTH 640
#define CMOS_HEIGHT 480
void InitSensor(int LeftLine, int TopLine, int Width, int Height, int FPReaderOpt);
void FreeSensor(void);
int CaptureSensor(char *Buffer);
#endif
<file_sep>/gtk/4st_week/gtk_button.c
/* ************************************************************************
* Filename: gtk_button.c
* Description:
* Version: 1.0
* Created: 2015年08月10日 10时14分55秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <gtk/gtk.h>
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_container_set_border_width(GTK_CONTAINER(window),15);
GtkWidget *button = gtk_button_new_with_label("button");
const char *str = gtk_button_get_label(GTK_BUTTON(button));
printf("str = %s\n",str);
gtk_container_add(GTK_CONTAINER(window),button);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
<file_sep>/network/sockets/UDPEchoClient.c
/*************************************************************************
> File Name: UDPEchoClient.c
> Author:
> Mail:
> Created Time: Mon 16 May 2016 04:50:18 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include "Practical.h"
int main(int argc, char *argv[])
{
if(argc < 3 || argc > 4)
DieWithUserMessage("Parameter(s)",
"<Server Address/Name> <Echo Word> [<Server Port/Service]");
char *server = argv[1];
char *echoString = argv[2];
size_t echoStringLen = strlen(echoString);
if(echoStringLen > MAXSTRINGLENGTH) //Check input length
DieWithUserMessage(echoString, "string too long");
//Thrid arg(optional): server port/service
char *servPort = argv[3];
//Tell the system what kind(s) of address info we want
struct addrinfo addrCriteria;
memset(&addrCriteria, 0, sizeof(addrCriteria));
addrCriteria.ai_family = AF_UNSPEC;
addrCriteria.ai_socktype = SOCK_DGRAM; //Only datagram sockets
addrCriteria.ai_protocol = IPPROTO_UDP; //Onlu UDP protocol
//Get address(es)
struct addrinfo *servAddr;
int rtnVal = getaddrinfo(server, servPort, &addrCriteria, &servAddr);
if(rtnVal != 0)
DieWithUserMessage("getaddrinfo() failed", gai_strerror(rtnVal));
//Create a datagram/UDP socket
int sock = socket(servAddr->ai_family, servAddr->ai_socktype, servAddr->ai_protocol);
if(sock < 0)
DieWithSystemMessage("socket() failed");
//Send the string to server
ssize_t numBytes = sendto(sock, echoString, echoStringLen, 0,
servAddr->ai_addr, servAddr->ai_addrlen);
if(numBytes < 0)
DieWithSystemMessage("sendto() failed");
else if(numBytes != echoStringLen)
DieWithUserMessage("sendto() error", "sent unexpected number of bytes");
//Receive a response
struct sockaddr_storage fromAddr; //Source address of server
socklen_t fromAddrLen = sizeof(fromAddr);
char buffer[MAXSTRINGLENGTH + 1] = {0};
numBytes = recvfrom(sock, buffer, MAXSTRINGLENGTH, 0,
(struct sockaddr *)&fromAddr, &fromAddrLen);
if(numBytes < 0)
DieWithSystemMessage("recvfrom() failed");
else if(numBytes != echoStringLen)
DieWithUserMessage("recvfrom() error", "received unexpected number of bytes");
//Verify reception from expected source
if(!SockAddrsEqual(servAddr->ai_addr, (struct sockaddr *)&fromAddr))
DieWithUserMessage("recvfrom()","received a packet from unknown source");
freeaddrinfo(servAddr);
buffer[MAXSTRINGLENGTH] = '\n';
printf("Received: %s\n", buffer);
close(sock);
return 0;
}
<file_sep>/shell/2nd_week/with_param_option2
#!/bin/bash
while getopts :ab:cd opt
do
case "$opt" in
a) echo "-a option";;
b) echo "-b option,with parameter value $OPTARG";;
c) echo "-c option";;
d) echo "-d option";;
*) echo "Unknown option: $opt";;
esac
done
shift $[ $OPIND + 2 ]
count=1
for param in $@
do
echo "Parameter #$count: $param"
count=$[ $count + 1 ]
done
<file_sep>/gtk/4st_week/gtk_login.c
/* ************************************************************************
* Filename: login.c
* Description:
* Version: 1.0
* Created: 2015年08月10日 14时27分03秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <gtk/gtk.h>
#define PSW "123456"
char psw[50] = "";
/* 功能: 设置背景图
* widget: 主窗口
* w, h: 图片的大小
* path: 图片路径
*/
static void chang_background(GtkWidget *widget, int w, int h, const gchar *path)
{
gtk_widget_set_app_paintable(widget, TRUE); //允许窗口可以绘图
gtk_widget_realize(widget);
/* 更改背景图时,图片会重叠
* 这时要手动调用下面的函数,让窗口绘图区域失效,产生窗口重绘制事件(即 expose 事件)。
*/
gtk_widget_queue_draw(widget);
GdkPixbuf *src_pixbuf = gdk_pixbuf_new_from_file(path, NULL); // 创建图片资源对象
// w, h是指定图片的宽度和高度
GdkPixbuf *dst_pixbuf = gdk_pixbuf_scale_simple(src_pixbuf, w, h, GDK_INTERP_BILINEAR);
GdkPixmap *pixmap = NULL;
/* 创建pixmap图像;
* NULL:不需要蒙版;
* 123: 0~255,透明到不透明
*/
gdk_pixbuf_render_pixmap_and_mask(dst_pixbuf, &pixmap, NULL, 50);
// 通过pixmap给widget设置一张背景图,最后一个参数必须为: FASLE
gdk_window_set_back_pixmap(widget->window, pixmap, FALSE);
// 释放资源
g_object_unref(src_pixbuf);
g_object_unref(dst_pixbuf);
g_object_unref(pixmap);
}
void entry_callback(GtkWidget *widget, gpointer entry)
{
const gchar *entry_text;
entry_text = (gchar *)gtk_entry_get_text(GTK_ENTRY(entry));
printf("Entry contents: %s\n",entry_text);
if(strcmp(entry_text, PSW) == 0)
{
printf("Entry password right!\n");
}
else
{
char empty[] = "";
gtk_entry_set_text(GTK_ENTRY(entry), empty);//设置显示内容
printf("Entry password wrong!\n");
}
}
void num_callback(GtkButton *button, gpointer entry)
{
const char *button_label = gtk_button_get_label(button);
gtk_entry_append_text(GTK_ENTRY(entry), button_label);
//strcat(psw,button_label);
//gtk_entry_set_text(GTK_ENTRY(entry), psw);//设置显示内容
}
void button_callback(GtkButton *button, gpointer entry)
{
const char *button_label = gtk_button_get_label(button);
gint len = GTK_ENTRY(entry)->text_length;
if(strcmp(button_label,"<-") == 0)
{
gtk_editable_delete_text(GTK_EDITABLE(entry), len-1,len);
}
else if(strcmp(button_label,"sure") == 0)
{
const char *databuf = gtk_entry_get_text(GTK_ENTRY(entry));
if(strcmp(databuf,PSW) == 0)
{
printf("Entry password right!\n");
}
else
{
char empty[] = "";
gtk_entry_set_text(GTK_ENTRY(entry), empty);//设置显示内容
printf("Entry password wrong!\n");
}
}
}
int main(int argc, char *argv[])
{
int i, j, num = 0;
gtk_init(&argc,&argv);
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window),"GTK entry");
gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER);//设置窗口的位置
gtk_widget_set_size_request(window, 500, 300); //设置窗口的大小
gtk_window_set_resizable(GTK_WINDOW(window),FALSE); //设置窗口是否可以改变大小
g_signal_connect(window,"destroy",G_CALLBACK(gtk_main_quit),NULL);
GtkWidget *table = gtk_table_new(4,6,TRUE); //创建一个三行六列的表格容器
GtkWidget *entry = gtk_entry_new(); //创建行编辑
gtk_entry_set_max_length(GTK_ENTRY(entry), 100); //设置行编辑显示最大字符的长度
//gtk_entry_set_text(GTK_ENTRY(entry), "hello world"); //设置显示内容
gtk_entry_set_visibility(GTK_ENTRY(entry), FALSE); //密码模式
//创建一个标签
GtkWidget *label = gtk_label_new("password: ");
gtk_table_attach_defaults(GTK_TABLE(table),label,0,1,0,1);
gtk_table_attach_defaults(GTK_TABLE(table),entry,1,6,0,1); //
for(i=2;i<4;i++)
{
for(j=0;j<5;j++)
{
char pnum[3] = "";
sprintf(pnum,"%d",num);
GtkWidget *button = gtk_button_new_with_label(pnum);
num++;
gtk_widget_set_size_request(button, 60, 35);
gtk_table_attach_defaults(GTK_TABLE(table),button,j,j+1,i,i+1);
g_signal_connect(button, "pressed", G_CALLBACK(num_callback), entry);
}
}
#if 0
GtkWidget *button0 = gtk_button_new_with_label("0");
GtkWidget *button1 = gtk_button_new_with_label("1");
GtkWidget *button2 = gtk_button_new_with_label("2");
GtkWidget *button3 = gtk_button_new_with_label("3");
GtkWidget *button4 = gtk_button_new_with_label("4");
GtkWidget *button5 = gtk_button_new_with_label("5");
GtkWidget *button6 = gtk_button_new_with_label("6");
GtkWidget *button7 = gtk_button_new_with_label("7");
GtkWidget *button8 = gtk_button_new_with_label("8");
GtkWidget *button9 = gtk_button_new_with_label("9");
GtkWidget *sure = gtk_button_new_with_label("sure");
GtkWidget *delete = gtk_button_new_with_label("<-");
gtk_table_attach_defaults(GTK_TABLE(table),button0,0,1,2,3);
gtk_table_attach_defaults(GTK_TABLE(table),button1,1,2,2,3);
gtk_table_attach_defaults(GTK_TABLE(table),button2,2,3,2,3);
gtk_table_attach_defaults(GTK_TABLE(table),button3,3,4,2,3);
gtk_table_attach_defaults(GTK_TABLE(table),button4,4,5,2,3);
gtk_table_attach_defaults(GTK_TABLE(table),delete, 5,6,2,3);
gtk_table_attach_defaults(GTK_TABLE(table),button5,0,1,3,4);
gtk_table_attach_defaults(GTK_TABLE(table),button6,1,2,3,4);
gtk_table_attach_defaults(GTK_TABLE(table),button7,2,3,3,4);
gtk_table_attach_defaults(GTK_TABLE(table),button8,3,4,3,4);
gtk_table_attach_defaults(GTK_TABLE(table),button9,4,5,3,4);
gtk_table_attach_defaults(GTK_TABLE(table),sure,5,6,3,4);
//6.设置button的大小
gtk_widget_set_size_request(button0,60, 35);
gtk_widget_set_size_request(button1,60, 35);
gtk_widget_set_size_request(button2,60, 35);
gtk_widget_set_size_request(button3,60, 35);
gtk_widget_set_size_request(button4,60, 35);
gtk_widget_set_size_request(button5,60, 35);
gtk_widget_set_size_request(button6,60, 35);
gtk_widget_set_size_request(button7,60, 35);
gtk_widget_set_size_request(button8,60, 35);
gtk_widget_set_size_request(button9,60, 35);
gtk_widget_set_size_request(sure,60, 30);
gtk_widget_set_size_request(delete,60, 30);
//7.注册信号函数,把entry传给回调函数deal_num()
g_signal_connect(button0, "pressed", G_CALLBACK(num_callback), entry);
g_signal_connect(button1, "pressed", G_CALLBACK(num_callback), entry);
g_signal_connect(button2, "pressed", G_CALLBACK(num_callback), entry);
g_signal_connect(button3, "pressed", G_CALLBACK(num_callback), entry);
g_signal_connect(button4, "pressed", G_CALLBACK(num_callback), entry);
g_signal_connect(button5, "pressed", G_CALLBACK(num_callback), entry);
g_signal_connect(button6, "pressed", G_CALLBACK(num_callback), entry);
g_signal_connect(button7, "pressed", G_CALLBACK(num_callback), entry);
g_signal_connect(button8, "pressed", G_CALLBACK(num_callback), entry);
g_signal_connect(button9, "pressed", G_CALLBACK(num_callback), entry);
#endif
GtkWidget *sure = gtk_button_new_with_label("sure");
GtkWidget *delete = gtk_button_new_with_label("<-");
gtk_widget_set_size_request(sure,60, 30);
gtk_widget_set_size_request(delete,60, 30);
gtk_table_attach_defaults(GTK_TABLE(table),delete, 5,6,2,3);
gtk_table_attach_defaults(GTK_TABLE(table),sure, 5,6,3,4);
g_signal_connect(delete, "pressed", G_CALLBACK(button_callback), entry);
g_signal_connect(sure, "pressed", G_CALLBACK(button_callback), entry);
g_signal_connect(entry, "activate",G_CALLBACK(entry_callback), entry);
GtkWidget *fixed= gtk_fixed_new();
gtk_fixed_put(GTK_FIXED(fixed),table,50,100);
gtk_container_add(GTK_CONTAINER(window),fixed);
chang_background(window, 500, 300, "image.jpg"); // 设置窗口背景图
gtk_widget_show_all(window);
gtk_main();
return 0;
}
<file_sep>/c/homework/2nd_week/super_macro.c
/* ************************************************************************
* Filename: super_macro.c
* Description:
* Version: 1.0
* Created: 2015年07月22日 星期三 06時51分27秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#define SUPER(x,op,y) (op=='+'?(x)+(y):op=='-'?(x)-(y):op=='*'?(x)*(y):op=='/'?(x)/(y):op=='%'?(x)%(y):0)
int main(int argc, char *argv[])
{
int m=25,k=4;
printf("m=%d,k=%d\n",m,k);
printf("m+k=%d\n",SUPER(m,'+',k));
printf("m-k=%d\n",SUPER(m,'-',k));
printf("m*k=%d\n",SUPER(m,'*',k));
printf("m/k=%d\n",SUPER(m,'/',k));
printf("m%k=%d\n",SUPER(m,'%',k));
return 0;
}
<file_sep>/sys_program/player/src/inc/file.h
/* ************************************************************************
* Filename: file.h
* Description:
* Version: 1.0
* Created: 2015年07月31日 星期五 05時35分49秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __FILE_H__
#define __FILE_H__
//#include "common.h"
extern char *read_src_file(ulint *file_length,char *lrc_src);
//char **get_musiclist();
extern char *get_musiclist(char ***plist, int *plines);
extern int check_lines(ulint file_length, char *psrc);
extern int get_longestline(int lines, char *plines[]);
extern int get_longestlength(LRC *lrc_head);
extern int get_showoffset(char *pbuf, int longest);
extern int get_chrnumber(char *pbuf, int len);
extern char get_songname(char *desr, char *src);
extern char get_lrcname(char *src);
extern char *transfer_space(char src[]);
extern void delete_dot(char *plist[]);
extern void recover_dot(char *plist[]);
extern void recover_line_dot(char *plist[],int line_num);
#endif<file_sep>/sys_program/3rd_day/dup.c
/* ************************************************************************
* Filename: dup.c
* Description:
* Version: 1.0
* Created: 2015年08月17日 11时10分56秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
int fd;
int fd2;
fd = open("a.txt",O_CREAT | O_RDWR,0777);
close(1);
fd2 = dup(fd);
printf("fd2 = %d\n",fd2);
return 0;
}
<file_sep>/work/test/Makefile
CC := gcc
#CC := mips-linux-gnu-gcc
SRC=test.c
TAG=test
all: $(TAG)
$(TAG):test.c
$(CC) -o $(TAG) $(SRC)
.PHONY:clean
clean:
rm -rf $(TAG)
<file_sep>/sys_program/6th_day/sem_syn.c
/* ************************************************************************
* Filename: sem_syn.c
* Description:
* Version: 1.0
* Created: 2015年08月20日 14时38分35秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t sem1, sem2;
char ch = 'a';
void print(char *str)
{
sem_wait(&sem1);
while(*str != '\0')
{
putchar(*str++);
fflush(stdout);
sleep(1);
}
putchar('\n');
sem_post(&sem1);
}
void *fun1(void *arg)
{
while(1)
{
sem_wait(&sem1);
ch++;
sleep(1);
sem_post(&sem2);
}
}
void *fun2(void *arg)
{
while(1)
{
sem_wait(&sem2);
printf("%c",ch);
fflush(stdout);
sem_post(&sem1);
}
}
int main(int argc, char *argv[])
{
int val = 0;
pthread_t pth1,pth2;
sem_init(&sem1,0,0);
sem_init(&sem2,0,1);
pthread_create(&pth1,NULL,fun1,NULL);
pthread_create(&pth2,NULL,fun2,NULL);
pthread_join(pth1,NULL);
pthread_join(pth2,NULL);
val = sem_destroy(&sem1);
if(val==0)
{
printf("delete sem succeed\n");
}
return 0;
}
<file_sep>/c/homework/3rd_week/operation/Makefile
operation:operation.c fun.c
.PHONY:clean
clean:
rm operation
<file_sep>/work/debug/2440/ts/s3c2440_ts.c
/* ************************************************************************
* Filename: s3c2440_ts.c
* Description:
* Version: 1.0
* Created: 2015年10月30日 20时43分30秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <linux/kernel.h> /* 提供prink等内核特有属性 */
#include <linux/module.h> /* 提供如MODULE_LICENSE()、EXPORT_SYMBOL() */
#include <linux/init.h> /* 设置段,如_init、_exit,设置初始化优先级,如__initcall */
#include <linux/wait.h> /* 等待队列wait_queue */
#include <linux/interrupt.h> /* 中断方式,如IRQF_SHARED */
#include <linux/fs.h> /* file_operations操作接口等 */
#include <linux/clk.h> /* 时钟控制接口,如struct clk */
#include <linux/input.h> /* 内核输入子系统操作接口 */
#include <linux/slab.h> /* kzalloc内存分配函数 */
#include <linux/time.h> /* do_gettimeofday时间函数 */
#include <linux/timer.h> /* timer定时器 */
#include <linux/miscdevice.h> /* 杂项设备 */
#include <linux/sched.h>
#include <linux/irq.h>
#include <asm/io.h> /* 提供readl、writel */
#include <asm/irq.h> /* 提供中断号,中断类型等,如IRQ_ADC中断号 */
#include <asm/uaccess.h> /* 提供copy_to_user等存储接口 */
#include <plat/regs-adc.h> /* 提供控制器的寄存器操作,如S3C2410_ADCCON */
#include <mach/hardware.h>
#include <mach/regs-gpio.h>
#include <mach/regs-irq.h>
#define __IRQT_FALEDGE IRQ_TYPE_EDGE_FALLING
#define __IRQT_RISEDGE IRQ_TYPE_EDGE_RISING
#define __IRQT_LOWLVL IRQ_TYPE_LEVEL_LOW
#define __IRQT_HIGHLVL IRQ_TYPE_LEVEL_HIGH
#define IRQT_NOEDGE (0)
#define IRQT_RISING (__IRQT_RISEDGE)
#define IRQT_FALLING (__IRQT_FALEDGE)
#define IRQT_BOTHEDGE (__IRQT_RISEDGE|__IRQT_FALEDGE)
#define IRQT_LOW (__IRQT_LOWLVL)
#define IRQT_HIGH (__IRQT_HIGHLVL)
#define IRQT_PROBE IRQ_TYPE_PROBE
#define CONFIG_S3C2440_TOUCHSCREEN__DEBUG 1
#define DEVICE_NAME "s3c2440ts"
// 定义一个宏WAIT4INT,用于对ADCTSC触摸屏控制寄存器进行操作
#define WAIT4INT(x) (((x)<<8) | S3C2410_ADCTSC_YM_SEN | S3C2410_ADCTSC_YP_SEN | \
S3C2410_ADCTSC_XP_SEN | S3C2410_ADCTSC_XY_PST(3))
// 定义一个宏AUTOPST,用于设置ADCTSC触摸屏控制寄存器为自动转换模式
#define AUTOPST (S3C2410_ADCTSC_YM_SEN | S3C2410_ADCTSC_YP_SEN | S3C2410_ADCTSC_XP_SEN | \
S3C2410_ADCTSC_AUTO_PST | S3C2410_ADCTSC_XY_PST(0))
struct ts_event
{
short pressure; /* 是否按下 */
short xp; /*触摸屏x坐标值 */
short yp; /*触摸屏y坐标值 */
};
struct s3c2440_ts
{
struct input_dev *input;/* 输入子系统设备结构体 */
struct timer_list timer;/* 定时器,用于ADC转换操作 */
struct ts_event tc; /* ADC转换的值的保存位置,也用于上报input子系统的数据 */
int pendown; /* 判断是否有按下 */
int count; /* 用于驱动去抖的计数 */
int shift; /* 用于驱动去抖的基数 */
};
struct s3c2440_ts *pts = NULL;
static void __iomem *base_addr;
static struct clk *adc_clock;
static struct semaphore adc_lock;
static void touch_timer_callback(unsigned long data)
{
unsigned long data0;
unsigned long data1;
// 禁止中断,处理完数据再打开中断
set_irq_type(IRQ_TC, IRQT_NOEDGE);
set_irq_type(IRQ_ADC,IRQT_NOEDGE);
// 读取ADCDAT0和ADCDAT1寄存器,提取ADC转换的x,y坐标值
data0 = readl(base_addr + S3C2410_ADCDAT0);
data1 = readl(base_addr + S3C2410_ADCDAT1);
// 判断ADCDAT0和ADCDAT1中的[15]位,[15]位为等待中断模式下用于判断笔尖是否有抬起或落下,0=落下
pts->pendown = (!(data0 &S3C2410_ADCDAT0_UPDOWN)) && (!(data1 & S3C2410_ADCDAT0_UPDOWN));
// 当触摸屏处于被按下状态,执行下面代码
if(pts->pendown){
/* count不为0,说明正在转换,xp和yp往右移动shift(2)位是为了去抖
* 需要结合stylus_action中断函数来看,当count=4时,才能认为转换结束,
* 即最后所得的xp和yp是累加了4次的,最终上报时需要除以4,因此这里预先
* 右移2位,相当于除以4
*/
if(pts->count != 0){
pts->tc.xp >>= pts->shift; // pts->tc.xp = pts->tc.xp >> pts->shift
pts->tc.yp >>= pts->shift;
// 终端打印调试信息
#ifdef CONFIG_S3C2440_TOUCHSCREEN__DEBUG
{
struct timeval tv;
do_gettimeofday(&tv);
printk(KERN_INFO"T: %06d, X: %03x, Y: %03x\n", (int)tv.tv_usec, pts->tc.xp, pts->tc.yp);
}
#endif
// 报告X、Y的绝对坐标值
input_report_abs(pts->input, ABS_X, pts->tc.xp);
input_report_abs(pts->input, ABS_Y, pts->tc.yp);
input_report_abs(pts->input, ABS_PRESSURE, pts->tc.pressure);// 报告触摸屏的状态,1表明触摸屏被按下
input_report_key(pts->input, BTN_TOUCH,pts->pendown);// 报告按键事件,键值为1(代表触摸屏对应的按键被按下)
input_sync(pts->input);// 等待接收方受到数据后回复确认,用于同步
}
// count=0执行这里面的代码,ADC还没有开始转换
pts->tc.xp = 0;
pts->tc.yp = 0;
pts->tc.xp = 0;
pts->tc.pressure= 0;
pts->count = 0;
// 因为触摸屏是按下状态,ADC还没有转换,需要启动ADC开始转换
// 本句代码是设置触摸屏为自动转换模式
writel(S3C2410_ADCTSC_PULL_UP_DISABLE | AUTOPST, base_addr + S3C2410_ADCTSC);
// 启动ADC转换
writel(readl(base_addr +S3C2410_ADCCON) | S3C2410_ADCCON_ENABLE_START, base_addr + S3C2410_ADCCON);
}
else {
// 执行到这里说明按键没有被按下或按键抬起,count清0
pts->count = 0;
input_report_key(pts->input, BTN_TOUCH, 0); // 报告按键事件,给0值说明按键抬起
input_report_abs(pts->input, ABS_PRESSURE, 0);// 报告按键事件,给0值说明按键抬起
input_sync(pts->input);
writel(WAIT4INT(0), base_addr +S3C2410_ADCTSC);// 将触摸屏重新设置为等待中断状态,等待触摸屏被按下
del_timer_sync(&pts->timer); // 删除定时器,在定时器时间到前停止一个已注册的定时器
up(&adc_lock); // 触摸屏抬起了,可以释放信号量了
}
// 使能中断触发条件,IRQT_BOTHEDGE为使能上升沿和下降沿触发
set_irq_type(IRQ_TC, IRQT_BOTHEDGE);
set_irq_type(IRQ_ADC,IRQT_BOTHEDGE);
}
// ADC中断服务程序,ADC启动转换后被执行
static irqreturn_t stylus_action(int irq, void *dev_id)
{
unsigned long data0;
unsigned long data1;
#ifdef CONFIG_S3C2440_TOUCHSCREEN__DEBUG
printk(KERN_ERR "%s() No.%dline:\n\r",__FUNCTION__,__LINE__);
#endif
// 获取触摸屏的x,y坐标值
data0 = readl(base_addr + S3C2410_ADCDAT0);
data1 = readl(base_addr + S3C2410_ADCDAT1);
pts->tc.xp += data0 & S3C2410_ADCDAT0_XPDATA_MASK;
pts->tc.yp += data1 & S3C2410_ADCDAT1_YPDATA_MASK;
pts->tc.pressure = 1;
pts->count++;
// 如果count小于4,需要重启设置自动转换模式,并进行ADC转换,用于去抖
if((pts->count) < (1 << pts->shift)){
writel(S3C2410_ADCTSC_PULL_UP_DISABLE | AUTOPST, base_addr + S3C2410_ADCTSC);
writel(readl(base_addr + S3C2410_ADCCON) | S3C2410_ADCCON_ENABLE_START, base_addr + S3C2410_ADCCON);
}
else {
// pts->count=4,启动定时器去执行touch_timer_callback函数上报按键和触摸事件
mod_timer(&pts->timer, jiffies + HZ/100);
// 检测触摸屏抬起的中断信号
writel(WAIT4INT(1),base_addr + S3C2410_ADCTSC);
}
return IRQ_HANDLED;
}
// 触摸屏中断服务程序,触摸屏按下或抬起时触发执行
static irqreturn_t stylus_updown(int irq, void *dev_id)
{
unsigned long data0;
unsigned long data1;
// 由于是中断程序,所以不能使用down和down_interruptible,会导致睡眠
if(down_trylock(&adc_lock) == 0){
// 读取ADCDAT0和ADCDAT1,用于判断触摸屏是否被按下
data0 = readl(base_addr + S3C2410_ADCDAT0);
data1 = readl(base_addr + S3C2410_ADCDAT1);
pts->pendown = (!(data0 & S3C2410_ADCDAT0_UPDOWN)) && (!(data1 & S3C2410_ADCDAT1_UPDOWN));
if(pts->pendown){
// 启动ADC转换,设置ADCCON寄存器的bit[0]为1,bit[0]在启动ADC转换后自动清零
writel(readl(base_addr + S3C2410_ADCCON) | S3C2410_ADCCON_ENABLE_START, base_addr + S3C2410_ADCCON);
}
}
return IRQ_RETVAL(IRQ_HANDLED);
}
static void adc_init(void)
{
// S3C2410_ADCCON_PRSCEN设置ADCCON的位[14]=1为使能A/D预分频器
// S3C2410_ADCCON_PRSCVL设置ADCCON的位[13:6]=32表示设置的分频值,
// ADC的转换频率需要在2.5MHZ以下,我们使用的ADC输入时钟为PCLK=50MHZ,50MHZ/(49+1)=1MHZ,满足条件
writel(S3C2410_ADCCON_PRSCEN |S3C2410_ADCCON_PRSCVL(49), base_addr + S3C2410_ADCCON);
// 初始化ADC启动或延时寄存器,ADC转换启动延时值设置为0xffff
writel(0xffff, base_addr + S3C2410_ADCDLY);
/* 初始化ADC触摸屏控制寄存器ADCTSC,
* WAIT4INT(0)在上面定义,引脚YM、YP、XM、XP的使能位在ADCTSC的[7:4]位,
* 设置触摸屏的工作状态在[1:0]位,WAIT4INT(0)=11010011,
* 1101代表笔尖按下时发生触摸屏中断信号IRQ_TS给CPU,0011表示XP上拉使能,
* 使用正常ADC转换,转换的方式为等待中断模式
*/
writel(WAIT4INT(0), base_addr + S3C2410_ADCTSC);
}
static __init int s3c2440_ts_init(void)
{
int ret;
struct input_dev *input_dev;
pts = kzalloc(sizeof(struct s3c2440_ts), GFP_KERNEL);
input_dev = input_allocate_device(); //给输入设备申请空间
if(!pts || !input_dev){
goto fail1;
}
adc_clock = clk_get(NULL, "adc"); //获得adc的时钟源
if(!adc_clock){
printk(KERN_ERR "failed to get adc clock source\n");
ret = -ENOENT;
goto fail1;
}
clk_enable(adc_clock); // 使能adc时钟源,ADC转换需要输入时钟
// 使用ioremap获得操作ADC控制器的虚拟地址
// S3C2410_PA_ADC=ADCCON,是ADC控制器的基地址,寄存器组的长度=0x1c
base_addr = ioremap(S3C2410_PA_ADC, 0x1c);
if (base_addr == NULL) {
printk(KERN_ERR "Failed to remapregister block\n");
ret = -ENOMEM;
goto fail2;
}
adc_init(); // 初始化ADC控制寄存器和ADC触摸屏控制寄存器
sema_init(&adc_lock, 1); // 初始化信号量的值为1
pts->shift = 2; // 设置驱动去抖基数
// 申请ADC中断,AD转换完成后触发。这里使用共享中断IRQF_SHARED是因为该中断号在ADC驱动中也使用了,
// 最后一个参数用于区分共享中断,如果设为NULL,中断申请失败
ret = request_irq(IRQ_ADC, stylus_action, IRQF_SHARED | IRQF_SAMPLE_RANDOM, DEVICE_NAME, (void *)pts);
if(ret){
ret = -EBUSY;
goto fail3;
}
// 申请触摸屏中断,对触摸屏按下或提笔时触发
ret = request_irq(IRQ_TC, stylus_updown, IRQF_SAMPLE_RANDOM, DEVICE_NAME, (void *)pts);
if(ret){
ret = -EBUSY;
goto fail4;
}
// 设置中断触发条件,IRQT_BOTHEDGE为使能上升沿和下降沿触发
set_irq_type(IRQ_TC, IRQT_BOTHEDGE);
set_irq_type(IRQ_ADC,IRQT_BOTHEDGE);
// 初始化定时器
init_timer(&pts->timer);
pts->timer.data = 1;
pts->timer.function = touch_timer_callback;
/* 设置触摸屏输入设备的标志,注册输入设备成功进入根文件系统,可以cat /proc/bus/input/devices查看其内容*/
input_dev->name = DEVICE_NAME;
input_dev->phys = "s3c2440ts/input0";
input_dev->id.bustype = BUS_HOST; /*总线类型 */
input_dev->id.vendor = 0x1; /*经销商ID */
input_dev->id.product = 0x2; /*产品ID */
input_dev->id.version = 0x0100; /*版本ID */
// evbit字段用于描述支持的事件,这里支持同步事件、按键事件、绝对坐标事件
input_dev->evbit[0] = BIT_MASK(EV_SYN) |BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); // keybit字段用于描述按键的类型,BTN_TOUCH表示触摸屏的点击
//对于触摸屏来说,使用的是绝对坐标系统。这里设置该坐标系统中X和Y坐标的最小值和最大值(0-1023范围)
//ABS_X和ABS_Y就表示X坐标和Y坐标,ABS_PRESSURE就表示触摸屏是按下还是抬起状态
input_set_abs_params(input_dev, ABS_X, 0,0x3FF, 0, 0);
input_set_abs_params(input_dev, ABS_Y, 0,0x3FF, 0, 0);
input_set_abs_params(input_dev, ABS_PRESSURE, 0, 1, 0, 0);
pts->input = input_dev;
ret = input_register_device(pts->input); // 注册输入子系统
if(ret)
goto fail5;
return 0;
fail5:
free_irq(IRQ_TC, (void *)pts);
disable_irq(IRQ_TC);
fail4:
free_irq(IRQ_ADC, (void *)pts);
disable_irq(IRQ_ADC);
fail3:
iounmap(base_addr);
fail2:
clk_disable(adc_clock); // 禁止ADC的时钟源
clk_put(adc_clock);
fail1:
input_free_device(input_dev);
kfree(pts);
return ret;
}
static __exit void s3c2440_ts_exit(void)
{
// 屏蔽并释放中断
disable_irq(IRQ_TC);
disable_irq(IRQ_ADC);
free_irq(IRQ_TC, (void *)pts);
free_irq(IRQ_ADC, (void *)pts);
// 注销定时器
del_timer_sync(&pts->timer);
// 屏蔽和禁止adc时钟
if(adc_clock) {
clk_disable(adc_clock);
clk_put(adc_clock);
adc_clock = NULL;
}
// 注销触摸屏输入子系统
input_unregister_device(pts->input);
// 释放虚拟地址
iounmap(base_addr);
// 释放触摸屏设备结构体
kfree(pts);
}
module_init(s3c2440_ts_init);
module_exit(s3c2440_ts_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/debug/2440/lcd/s3c24xx_fb.c
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/fb.h>
#include <linux/clk.h>
#include <linux/interrupt.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/div64.h>
#include <mach/regs-lcd.h>
#include <mach/regs-gpio.h>
#include <mach/fb.h>
#include <linux/pm.h>
#define DEVICE_NAME "s3cfb"
#define PALETTE_BUFF_CLEAR (0x80000000) //用做清空调色板(颜色表)
struct fb_var
{
int lcd_irq_no; /*保存LCD中断号*/
struct clk *lcd_clock; /*保存从平台时钟队列中获取的LCD时钟*/
struct resource *lcd_mem; /*LCD的IO空间*/
void __iomem *lcd_base; /*LCD的IO空间映射到虚拟地址*/
struct device *dev;
struct s3c2410fb_hw regs; /*表示5个LCD配置寄存器,s3c2410fb_hw定义在mach-s3c2410/include/mach/fb.h中*/
/*定义一个数组来充当调色板。据数据手册描述,TFT屏色位模式为8BPP时,调色板(颜色表)的长度
为256,调色板起始地址为0x4D000400*/
u32 palette_buffer[256];
u32 pseudo_pal[16];
unsigned intpalette_ready; /*标识调色板是否准备好了*/
};
static struct file_operations lcd_fb_fops = {
};
//该函数实现修改GPIO端口的值,第三个参数mask的
//作用是将要设置的寄存器值先清零
static inline void modify_gpio(void __iomem *reg,
unsigned long set, unsigned long mask)
{
unsigned long tmp;
tmp = readl(reg) & ~mask;
writel(tmp | set, reg);
}
static void s3cfb_init_registers(struct fb_info *fbinfo) // LCD 相关寄存器的初始化
{
unsigned long flags;
void __iomem *tpal;
void __iomem *lpcsel;
struct fb_var *fbvar = fbinfo->par;
struct s3c2410fb_mach_info *mach_info = fbvar->dev->platform_data;
//获得临时调色板寄存器基地址,S3C2410_TPAL宏定义在mach-s3c2410/include/mach/regs-lcd.h中
//注意对于lpcsel这是一个针对三星TFT屏的一个专用寄存器,如果用的不是三星的TFT屏应该不用管它
tpal = fbvar->lcd_base + S3C2410_TPAL;
lpcsel = fbvar->lcd_base + S3C2410_LPCSEL;
//*在修改下面寄存器值之前先屏蔽中断,将中断状态保存到flags中
local_irq_save(flags);
//把IO端口C和D配置成LCD模式
modify_gpio(S3C2410_GPCUP, mach_info->gpcup, mach_info->gpcup_mask);
modify_gpio(S3C2410_GPCCON, mach_info->gpccon, mach_info->gpccon_mask);
modify_gpio(S3C2410_GPDUP, mach_info->gpdup, mach_info->gpdup_mask);
modify_gpio(S3C2410_GPDCON, mach_info->gpdcon, mach_info->gpdcon_mask);
local_irq_restore(flags);//恢复被屏蔽的中断
writel(0x00,tpal); //临时调色板寄存器使能禁止
writel(mach_info->lpcsel,lpcsel); //它是三星TFT屏的一个寄存器,这里可以不管
return 0;
}
static void s3cfb_check_var(struct fb_info *fbinfo)
{
unsigned int i;
//从lcd_fb_probe探测函数设置的平台数据中再获得LCD相关信息的数据
struct fb_var_screeninfo *var = &fbinfo->var;//fb_info中的LCD可变参数
struct fb_var *fbvar = fbinfo->par; //在lcd_fb_probe探测函数中设置的私有结构体数据
struct s3c2410fb_mach_info *mach_info = fbvar->dev->platform_data; //从LCD平台设备资源 取出LCD的配置结构体数据
struct s3c2410fb_display *display = NULL;
struct s3c2410fb_display *default_display = mach_info->displays + mach_info->default_display;
int type = default_display->type; //LCD的类型
//验证X/Y解析度
if (var->yres == default_display->yres &&
var->xres == default_display->xres &&
var->bits_per_pixel == default_display->bpp)
{
display =default_display;
}
else
{
for (i =0;i <mach_info->num_displays;i++)
{
if (type == mach_info->displays[i].type &&
var->yres == mach_info->displays[i].yres &&
var->xres == mach_info->displays[i].xres &&
var->bits_per_pixel == mach_info->displays[i].bpp)
{
display = mach_info->displays + i;
break;
}
}
}
if (!display)
return -EINVAL;
//配置LCD配置寄存器1中的5-6位(配置成TFT类型)和配置LCD配置寄存器5
fbvar->regs.lcdcon1 = display->type;
fbvar->regs.lcdcon5 = display->lcdcon5;
//设置屏幕的虚拟解析像素和高度宽度
var->xres_virtual = display->xres;
var->yres_virtual = display->yres;
var->height = display->height;
var->width = display->width;
//设置时钟像素,行、帧切换值,水平同步、垂直同步长度值
var->pixclock = display->pixclock;
var->left_margin = display->left_margin;
var->right_margin = display->right_margin;
var->upper_margin = display->upper_margin;
var->lower_margin = display->lower_margin;
var->vsync_len = display->vsync_len;
var->hsync_len = display->hsync_len;
//设置透明度
var->transp.offset = 0;
var->transp.length = 0;
//根据色位模式(BPP)来设置可变参数中R、G、B的颜色位域
//对于这些参数值的设置请参考CPU数据
switch (var->bits_per_pixel)
{
case 1:
case 2:
case 4:
var->red.offset = 0;
var->red.length = var->bits_per_pixel;
var->green = var->red;
var->blue = var->red;
break;
case 8:/* 8 bpp 332 */
if (display->type != S3C2410_LCDCON1_TFT)
{
var->red.length = 3;
var->red.offset = 5;
var->green.length = 3;
var->green.offset = 2;
var->blue.length = 2;
var->blue.offset = 0;
}
else
{
var->red.offset = 0;
var->red.length = 8;
var->green = var->red;
var->blue = var->red;
}
break;
case 12:/* 12 bpp 444 */
var->red.length = 4;
var->red.offset = 8;
var->green.length = 4;
var->green.offset = 4;
var->blue.length = 4;
var->blue.offset = 0;
break;
case 16:/* 16 bpp */
if (display->lcdcon5 &S3C2410_LCDCON5_FRM565)
{
/* 565 format */
var->red.offset = 11;
var->green.offset = 5;
var->blue.offset = 0;
var->red.length = 5;
var->green.length = 6;
var->blue.length = 5;
}
else
{
/* 5551 format */
var->red.offset = 11;
var->green.offset = 6;
var->blue.offset = 1;
var->red.length = 5;
var->green.length = 5;
var->blue.length = 5;
}
break;
case 32:/* 24 bpp 888 and 8 dummy */
var->red.length = 8;
var->red.offset = 16;
var->green.length = 8;
var->green.offset = 8;
var->blue.length = 8;
var->blue.offset = 0;
break;
}
return 0;
}
//申请帧缓冲设备fb_info的显示缓冲区空间
static int __init s3cfb_map_video_memory(struct fb_info *fbinfo)
{
dma_addr_t map_dma; //用于保存DMA缓冲区总线地址
struct fb_var *fbvar = fbinfo->par;//获得在lcd_fb_probe探测函数中设置的私有结构体数据
unsigned map_size = PAGE_ALIGN(fbinfo->fix.smem_len);//获得FrameBuffer缓存的大小, PAGE_ALIGN定义在mm.h中
//分配的一个写合并DMA缓存区设置为LCD屏幕的虚拟地址
//dma_alloc_writecombine定义在arch/arm/mm/dma-mapping.c中
fbinfo->screen_base = dma_alloc_writecombine(fbvar->dev, map_size, &map_dma, GFP_KERNEL);
if(fbinfo->screen_base)
{
//设置这片DMA缓存区的内容为空
memset(fbinfo->sreen_base, 0x00, map_size);
//将DMA缓冲区总线地址设成fb_info不可变参数中framebuffer缓存的开始位置
fbinfo->fix.smem_start = map_dma;
}
return fbinfo->screen_base ? 0 : -ENOMEM;
}
//释放帧缓冲设备fb_info的显示缓冲区空间
static int inline s3cfb_unmap_video_memory(struct fb_info *fbinfo)
{
struct fb_var *fbvar = fbinfo->par;
unsigned map_size = PAGE_ALIGN(fbinfo->fix.smem_len);
//释放写合并DMA缓存区,跟申请DMA的地方想对应
dma_free_writecombine(fbvar->dev,map_size,fbinfo->screen_base,fbinfo->fix.smem_start);
}
static void s3cfb_write_palette(struct fb_var *fbvar)
{
unsigned int i;
void __iomem *regs = fbvar->lcd_base;
fbvar->palette_ready =0;
for(i = 0 ; i <256 ; i++)
{
unsigned long ent = fbvar->palette_buffer[i];
if(ent == PALETTE_BUFF_CLEAR)
continue;
writel(ent, regs + S3C2410_TFTPAL(i));
if(readw(regs + S3C2410_TFTPAL(i)) == ent)
fbvar->palette_buffer[i] =PALETTE_BUFF_CLEAR;
else
fbvar->palette_ready = 1;
}
}
static irqreturn_t lcd_fb_irq(void *dev_id)
{
struct fb_var *fbvar = dev_id;
void __iomem *lcd_irq_base;
unsigned long lcdirq;
lcd_irq_base = fbvar->lcd_base + S3C2410_LCDINTBASE;//LCD中断寄存器基地址
lcdirq = readl(lcd_irq_base + S3C24XX_LCDINTPND); //读取LCD中断挂起寄存器的值
//判断是否为中断挂起状态
if(lcdirq & S3C2410_LCDINT_FRSYNC)
{
//填充调色板
if (fbvar->palette_ready)
s3cfb_write_palette(fbvar);
//清除帧中断请求标志
writel(S3C2410_LCDINT_FRSYNC, lcd_irq_base + S3C24XX_LCDINTPND);
writel(S3C2410_LCDINT_FRSYNC, lcd_irq_base + S3C24XX_LCDSRCPND);
}
return IRQ_HANDLED;
}
static void s3cfb_lcd_enable(struct fb_var *fbvar, int enable)
{
unsigned long flags;
//在修改下面寄存器值之前先屏蔽中断,将中断状态保存到flags中
local_irq_save(flags);
if(enable)
{
fbvar->regs.lcdcon1 |= S3C2410_LCDCON1_ENVID;
}
else
{
fbvar->regs.lcdcon1 &= ~S3C2410_LCDCON1_ENVID;
}
writel(fbvar->regs.lcdcon1, fbvar->lcd_base + S3C2410_LCDCON1);
//恢复被屏蔽的中断
local_irq_restore(flags);
}
//有两个地方会调用到:一个是设备注销时,一个是驱动注销时
static __devexit int lcd_fb_remove(struct platform_device *pdev)
{
struct fb_info *fbinfo = platform_get_drvdata(pdev);
struct fb_var *fbvar = fbinfo->par;
//从系统中注销帧缓冲设备
unregister_framebuffer(fbinfo);
//停止LCD控制器的工作
s3cfb_lcd_enable(fbvar,0);
msleep(1); // 延迟一段时间,因为停止LCD控制器需要一点时间
//释放帧缓冲设备fb_info的显示缓冲区空间
s3cfb_unmap_video_memory(fbinfo);
//将LCD平台数据清空和释放fb_info空间资源
platform_set_drvdata(pdev, NULL);
framebuffer_release(fbinfo);
//释放中断资源
free_irq(fbvar->lcd_irq_no,fbvar);
//释放时钟资源
if (fbvar->lcd_clock)
{
clk_disable(fbvar->lcd_clock);
clk_put(fbvar->lcd_clock);
fbvar->lcd_clock = NULL;
}
//释放LCD IO空间映射的虚拟内存空间
iounmap(fbvar->lcd_base);
//释放申请的LCD IO端口所占用的IO空间
release_resource(fbvar->lcd_mem);
return 0;
}
static __devinit int lcd_fb_probe(struct platform_device *pdev)
{
int ret, i;
struct resource *res; //保存从LCD平台设备中获取的LCD资源
struct fb_info *fbinfo;//FrameBuffer驱动所对应的fb_info结构
struct s3c2410fb_mach_info *mach_info;//保存从内核中获取的平台设备数据
struct fb_var *fbvar; //上面定义的驱动程序全局变量结构体
struct s3c2410fb_display *display; //LCD屏的配置信息结构体,该结构体定义在mach-s3c2410/include/mach/fb.h中
//获取LCD硬件相关信息数据,在mach-s3c2440.c中
//s3c24xx_fb_set_platdata()函数将LCD的硬件相关信息保存到LCD平台数据中
mach_info = pdev->dev.platform_data;
if(mach_info == NULL)
{
/*判断获取数据是否成功*/
dev_err(&pdev->dev, "no platform data for lcd\n");
return -EINVAL;
}
//获得在mach-s3c2440.c中定义的FrameBuffer平台设备的LCD配置信息
display = mach_info->displays + mach_info->default_display;
//申请一段大小为sizeof(fb_info)+sizeof(fb_var)的空间,fb_var是这个设备的私有数据结构
//并初始化fb_info->par = &fb_var, fb_info->device = &pdev->dev,
//目的是在其他接口函数中通过fb_info结构取出这些成员
//返回这段空间的首地址
fbinfo = framebuffer_alloc(sizeof(fb_var), &pdev->dev);
if(!fbinfo)
{
dev_err(&pdev->dev, "framebuffer alloc of registers failed\n");
ret = -ENOMEM;
goto err_noirq;
}
//重新将LCD平台设备数据设置为fbinfo,好在后面的一些函数中来使用
platform_set_drvdata(pdev, fbinfo);
//fbinfo->par 在framebuffer_alloc()函数中赋值,指向了fb_var私有数据结构
//这里从fbinfo->par获取到fb_var私有数据结构的地址,进行成员的初始化
fbvar = fbinfo->par;
fbvar->dev = &pdev->dev;//保存pdev->dev到私有数据结构,这样在其他函数可以通过fbva私有数据结构取出LCD平台设备资源
//从LCD平台设备资源中获取LCD中断号,platform_get_irq定义在platform_device.h中
fbvar->lcd_irq_no =platform_get_irq(pdev, 0);
if(fbvar->lcd_irq_no <0)
{
/*判断获取中断号是否成功*/
dev_err(&pdev->dev, "no lcd irq for platform\n");
return -ENOENT;
}
//获取LCD平台设备所使用的IO端口资源,注意这个IORESOURCE_MEM
//标志和LCD平台设备定义中的一致
res =platform_get_resource(pdev,IORESOURCE_MEM,0);
if(res == NULL)
{
/*判断获取资源是否成功*/
dev_err(&pdev->dev, "failed to get memory region resource\n");
return -ENOENT;
}
//申请LCD IO端口所占用的IO空间(注意理解IO空间和内存空间的
//区别),request_mem_region定义在ioport.h中
fbvar->lcd_mem =request_mem_region(res->start, res->end - res->start + 1,pdev->name);
if(fbvar->lcd_mem == NULL)
{
/*判断申请IO空间是否成功*/
dev_err(&pdev->dev, "failed to reserve memory region\n");
return -ENOENT;
}
//从平台时钟队列中获取LCD的时钟,这里为什么要取得这个时钟,
//从LCD屏的时序图上看,各种控制信号的延迟都跟LCD的时钟有关
fbvar->lcd_clock =clk_get(NULL, "lcd");
if(!fbvar->lcd_clock)
{
/*判断获取时钟是否成功*/
dev_err(&pdev->dev, "failed to find lcd clock source\n");
ret = -ENOENT;
goto err_nomap;
}
//时钟获取后要使能后才可以使用,clk_enable定义在arch/arm/plat-s3c/clock.c中
clk_enable(fbvar->lcd_clock);
//申请LCD中断服务,上面获取的中断号lcd_fb_irq,使用快速中断方式:IRQF_DISABLED
ret =request_irq(fbvar->lcd_irq_no, lcd_fb_irq, IRQF_DISABLED, pdev->name, fbvar)
if(ret)
{
/*判断申请中断服务是否成功*/
dev_err(&pdev->dev, "IRQ%d error %d\n",fbvar->lcd_irq_no,ret);
ret = -EBUSY;
goto err_noclk;
}
/*以上是对要使用的资源进行了获取和设置。下面就开始初始化填充fb_info结构体*/
/*首先初始化fb_info中代表LCD固定参数的结构体fb_fix_screeninfo*/
/*像素值与显示内存的映射关系有5种,定义在fb.h中。现在采用FB_TYPE_PACKED_PIXELS方式,
在该方式下,像素值与内存直接对应,比如在显示内存某单元写入一个"1"时,该单元对应的像
素值也将是"1",这使得应用层把显示内存映射到用户空间变得非常方便。Linux中当LCD为TFT
屏时,显示驱动管理显示内存就是基于这种方式*/
strcpy(fbinfo->fix.id, DEVICE_NAME); // 字符串形式的标识符
fbinfo.fix.type = FB_TYPE_PACKED_PIXELS;
fbinfo->fix.type_aux = 0;//以下这些根据fb_fix_screeninfo定义中的描述,当没有硬件是都设为0
fbinfo->fix.xpanstep = 0;
fbinfo->fix.ypanstep = 0;
fbinfo->fix.ywrapstep = 0;
fbinfo->fix.accel = FB_ACCEL_NONE;
//接着,再初始化fb_info中代表LCD可变参数的结构体fb_var_screeninfo
fbinfo->var.nonstd = 0;
fbinfo->var.activate = FB_ACTIVATE_NOW;
fbinfo->var.accel_flags = 0;
fbinfo->var.vmode = FB_VMODE_NONINTERLACED;
fbinfo->var.xres = display->xres;
fbinfo->var.yres = display->yres;
fbinfo->var.bits_per_pixel = display->bpp;
//指定对底层硬件操作的函数指针, 因内容较多故其定义在第3步中再讲
fbinfo->fbops = &lcd_fb_fops;
fbinfo->flags = FBINFO_FLAG_DEFAULT;
fbinfo->pseudo_palette = &fbvar->pseudo_pal;
//初始化色调色板(颜色表)为空
for(i=0;i<256;i++)
fbvar->palette_buffer[i] = PALETTE_BUFF_CLEAR;
for ( i = 0 ; i < mach_info->num_displays; i++ )
{
//计算FrameBuffer缓存的最大大小,这里右移3位(即除以8)
//是因为色位模式BPP是以位为单位
unsigned long smem_len = (mach_info->displays[i].xres * \
mach_info->displays[i].xres * \
mach_info->displays[i].bpp) >> 3;
if(fbinfo->fix.smem_len < smem_len)
fbinfo->fix.smem_len = smem_len;
}
msleep(1); //初始化LCD控制器之前要延迟一段时间
s3cfb_init_registers(fbinfo);//初始化完fb_info后,开始对LCD各寄存器进行初始化
s3cfb_check_var(fbinfo); //初始化完寄存器后,开始检查fb_info中的可变参数
ret = s3cfb_map_video_memory(fbinfo);//申请帧缓冲设备fb_info的显示缓冲区空间
if (ret)
{
dev_err(&pdev->dev, "failed to allocate video RAM: %d\n",ret);
ret = -ENOMEM;
goto err_nofb;
}
//最后,注册这个帧缓冲设备fb_info到系统中,
//register_framebuffer定义在fb.h中在fbmem.c中
ret =register_framebuffer(fbinfo);
if (ret <0)
{
dev_err(&pdev->dev, "failed to register framebuffer device: %d\n",ret);
goto err_video_nomem;
}
//对设备文件系统的支持创建frambuffer设备文件,
//device_create_file定义在linux/device.h中
ret =device_create_file(&pdev->dev, &dev_attr_debug);
if (ret)
{
dev_err(&pdev->dev, "failed to add debug attribute\n");
}
printk(KERN_WARNING "%s\n",__FUNCTION__);
return 0;
//以下是出错处理
err_video_nomem:
s3cfb_unmap_video_memory(fbinfo);
err_nofb:
platform_set_drvdata(pdev, NULL);
framebuffer_release(fbinfo);
err_noirq:
free_irq(fbvar->lcd_irq_no, fbvar);
err_noclk:
clk_disable(fbvar->lcd_clock);
clk_put(fbvar->lcd_clock);
err_nomap:
iounmap(fbvar->lcd_base);
err_nomem:
release_resource(fbvar->lcd_mem);
kfree(fbvar->lcd_mem);
return ret;
}
static struct platform_driver lcd_fb_driver = {
.probe = lcd_fb_probe,
.driver = {
.name = "s3c2410-lcd",
.owner = THIS_MODULE,
}
};
static __init int lcd_fb_init(void)
{
// Linux中,帧缓冲设备被看做是平台设备
platform_driver_register(&lcd_fb_driver);
}
static __exit void lcd_fb_exit(void)
{
// 注销设备
platform_driver_unregister(&lcd_fb_driver);
}
module_init(lcd_fb_init);
module_exit(lcd_fb_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/debug/2440/adc/adc_drv.c
/* ************************************************************************
* Filename: adc_drv.c
* Description:
* Version: 1.0
* Created: 2015年10月30日 16时00分23秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <linux/kernel.h> /* 提供prink等内核特有属性 */
#include <linux/module.h> /* 提供如MODULE_LICENSE()、EXPORT_SYMBOL() */
#include <linux/init.h> /* 设置段,如_init、_exit,设置初始化优先级,如__initcall */
#include <linux/wait.h> /* 等待队列wait_queue */
#include <linux/interrupt.h> /* 中断方式,如IRQF_SHARED */
#include <linux/fs.h> /* file_operations操作接口等 */
#include <linux/clk.h> /* 时钟控制接口,如struct clk */
#include <linux/miscdevice.h> /* 杂项设备 */
#include <linux/sched.h>
#include <asm/io.h> /* 提供readl、writel */
#include <asm/irq.h> /* 提供中断号,中断类型等,如IRQ_ADC中断号 */
#include <asm/uaccess.h> /* 提供copy_to_user等存储接口 */
#include <mach/hardware.h>
#include <mach/regs-gpio.h>
#include <mach/regs-irq.h>
#include <plat/regs-adc.h> /* 提供控制器的寄存器操作,如S3C2410_ADCCON */
#define DEVICE_NAME "adc"
static struct clk *adc_clock; // 定义adc时钟,通过adc_clock接口获得adc输入时钟,adc转换器需要
static void __iomem *base_addr; //定义虚拟地址访问硬件寄存器,__iomem只是用于表示指针将指向I/O内存
static wait_queue_head_t adc_waitqueue; //定义一个等待队列adc_waitqueue,对ADC资源进行阻塞访问
/* 定义并初始化信号量adc_lock,用于控制共享中断IRQ_ADC资源的使用 */
DECLARE_MUTEX(adc_lock);
EXPORT_SYMBOL(adc_lock);
static volatile int read_ok = 0; //定义等待队列的条件,当read_ok=1时,ADC转换完毕,数据可读
static volatile int adc_data; //定义ADC转换的数据内容
/*ADC中断服务程序,获取ADC转换后的数据 */
static irqreturn_t adc_irq_callback(int irq, void *dev_id)
{
// 仅当read_ok=0时才进行转换,防止多次中断
if(!read_ok){
// 读取ADCCON[9:0]的值,0x3ff为只获取[9:0]位,ADCCON为转换后的数据
adc_data = readl(base_addr + S3C2410_ADCDAT0) & 0x3ff;
read_ok = 1; // 设置标识为1,唤醒读等待进程可以拷贝数据给用户空间了
wake_up_interruptible(&adc_waitqueue);
}
return IRQ_HANDLED;
}
static int adc_drv_open(struct inode *pinode, struct file *filp)
{
int ret;
// 由于IRQ_ADC为共享中断,因此中断类型选择IRQF_SHARED,最后一个参数需要设置NULL以外的值
ret = request_irq(IRQ_ADC, adc_irq_callback, IRQF_SHARED, DEVICE_NAME, (void *)1);
if(ret) {
printk(KERN_ERR "Could notallocate ts IRQ_ADC !\n");
return -EBUSY;
}
return ret;
}
static void adc_run(void)
{
volatile unsigned int adccon;
/* ADCCON的位[14]=1为使能A/D预分频器,位[13:6]=32表示设置的分频值,ADC的转换频率需要在2.5MHZ以下
* 我们使用的ADC输入时钟为PCLK=50MHZ,50MHZ/32<2.5MHZ,满足条件
* 位[5:3]=000,表示模拟输入通道选择AIN0
*/
adccon = (1 << 14) | (32 << 6);
writel(adccon, base_addr + S3C2410_ADCCON);
// 位[0]=1表示使能ADC转换,当转换完毕后此位被ADC控制器自动清0
adccon = readl(base_addr + S3C2410_ADCCON) | S3C2410_ADCCON_ENABLE_START;
writel(adccon, base_addr + S3C2410_ADCCON);
}
static ssize_t adc_drv_read(struct file *filp, char __user *buf, size_t count, loff_t *ppos)
{
int err;
// 获取信号量,如果被占用,睡眠等待持有者调用up唤醒
// 这样做的原因是,有可能其他进程抢占执行或是触摸屏驱动抢占执行
down_interruptible(&adc_lock);
adc_run(); // 启动adc转换,调用中断处理函数adc_irq
// 如果read_ok为假,则睡眠等待条件为真,由中断处理函数唤醒
wait_event_interruptible(adc_waitqueue, read_ok);
read_ok = 0; // 执行到此说明中断处理程序获得了ADC转换后的值,清除为0等待下一次的读
// 将转换后的数据adc_data提交给用户
err = copy_to_user(buf, (char *)&adc_data, min(sizeof(adc_data), count));
up(&adc_lock); // 释放信号量,并唤醒因adc_lock而睡眠的进程
return err ? -EFAULT : min(sizeof(adc_data), count);
}
static int adc_drv_close(struct inode *pinode, struct file *filp)
{
// 释放中断
free_irq(IRQ_ADC, (void *)1);
return 0;
}
static struct file_operations adc_fops = { //字符设备操作接口
.owner = THIS_MODULE,
.open = adc_drv_open,
.read = adc_drv_read,
.release= adc_drv_close,
};
static struct miscdevice adc_misc = {
.minor = MISC_DYNAMIC_MINOR, // 动态获取次设备号
.name = DEVICE_NAME, // 杂项设备名称
.fops = &adc_fops, // 杂项设备子系统接口,指向adc_fops操作接口
};
static __init int adc_drv_init(void)
{
int ret;
// 获得adc的时钟源,通过arch/arm/mach-s3c2410/clock.c获得提供的时钟源为PCLK
adc_clock = clk_get(NULL, "adc");
if(!adc_clock){
printk(KERN_ERR "failed to get adcclock source\n");
return -ENOENT;
}
// 使能adc时钟源,ADC转换需要输入时钟
clk_enable(adc_clock);
// 使用ioremap获得操作ADC控制器的虚拟地址
// S3C2410_PA_ADC=ADCCON,是ADC控制器的基地址,寄存器组的长度=0x1c
base_addr = ioremap(S3C2410_PA_ADC, 0x1c);
if (base_addr == NULL){
printk(KERN_ERR "Failed to remapregister block\n");
ret = -ENOMEM;
goto fail1;
}
// 初始化等待队列
init_waitqueue_head(&adc_waitqueue);
// 注册杂项设备
ret = misc_register(&adc_misc);
if(ret<0){
printk(KERN_INFO " can't register adc_drv\n");
goto fail2;
}
fail2:
iounmap(base_addr);
fail1:
clk_disable(adc_clock); // 禁止ADC的时钟源
clk_put(adc_clock);
return ret;
}
static __exit void adc_drv_exit(void)
{
/* 释放虚拟地址 */
iounmap(base_addr);
/* 禁止ADC的时钟源 */
if (adc_clock)
{
clk_disable(adc_clock);
clk_put(adc_clock);
adc_clock = NULL;
}
misc_deregister(&adc_misc);
}
module_init(adc_drv_init);
module_exit(adc_drv_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/test/timer/Makefile
#GCC := gcc
GCC := mips-linux-gnu-gcc
CFLAGS := -EL -mabi=32 -mhard-float -march=mips32r2 -Os
LDFLAGS:= -Wl,-EL
LDLIBS := -lrt -lpthread
SOURCES := $(wildcard *.c)
TARGET = timer
all: $(TARGET)
$(TARGET): $(SOURCES)
$(GCC) -o $@ $^ $(CFLAGS) $(LDFLAGS) $(LDLIBS)
INSTALL_DIR = ~/work/sz-halley2/out/product/yak/system/usr/bin
install:
cp $(TARGET) $(INSTALL_DIR) -a
.PHONY: clean
clean:
rm -rf *.o $(TARGET)
<file_sep>/c/lrc/link.c
/* ************************************************************************
* Filename: link.c
* Description:
* Version: 1.0
* Created: 2015年08月01日 星期六 10時18分27秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include "common.h"
LRC *insert_link(LRC *head, LRC slrc)
{
LRC *pi = NULL;
pi = (LRC *)malloc(sizeof(LRC));
if(pi != NULL) //成功申请到空间
{
*pi = slrc;
pi->next = NULL;
if(head == NULL)
{
head = pi;
}
else //链表不为空
{
LRC *pb = NULL, *pf =NULL;
pb = pf = head;
//按num从小到大插入链表
while((pi->time > pb->time) && (pb->next != NULL))
{
pf = pb;
pb = pb->next;
}
if(pi->time <= pb->time)//链表头插入新节点
{
if(pb == head)
{
pi->next = pb;
pb->prev = pi;
head = pi;
}
else //中间插入新节点
{
pb->prev = pi;
pi->prev = pf;
pi->next = pb;
pf->next = pi;
}
}
else //尾部插入新节点
{
pb->next = pi;
pi->prev = pb;
}
}
}
else
{
printf("Can not apply for a LRC memeory space!\n");
}
return head;
}
/**************************************************
*函数:free_link
*功能:将整个链表所占的内存空间释放
*************************************************/
LRC *free_link(LRC *head)
{
if(head == NULL)
{
printf("Link is not exist!\n");
}
else
{
LRC *pb = head;
//循环删除链表每个节点的方法:
//1.判断 head 是否为空
//2.让 pb 指向和 head 相同的节点
//3.然后 让 head 指向下个节点
//4.再把 pb 指向的节点释放掉
//5.返回步骤 1
while(head != NULL)
{
pb = head;
head = pb->next;
free(pb);
}
}
return head;
}
/**************************************************
*函数:print_link
*功能:遍历链表中每个节点,并打印节点的内容
*************************************************/
void print_link(LRC *head)
{
if(head == NULL)
{
printf("Link is not exist!\n");
}
else
{
LRC *pb = head;
while(pb != NULL)
{
//printf("%.2f %s\n",pb->time,pb->psrc);
printf("%d %s\n",pb->time,pb->psrc);
pb = pb->next;
}
}
}
<file_sep>/network/route/src/arp_link.c
/******************************************************************************
文 件 名 : arp_link.c
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月15日
最近修改 :
功能描述 : 链表创建、查找、打印、释放等
函数列表 :
iptoun_btob
iptoun_btol
insert_arp_table
search_arp_table
delete_arp_node
free_arp_table
change_arp_mac
print_arp_table
修改历史 :
1.日 期 : 2015年9月10日
作 者 : if
修改内容 : 创建文件
******************************************************************************/
#include "common.h"
/*****************************************************************************
函 数 名 : iptoun_btol()
功能描述 : 将存在ip[]的ip地址(大端)转化为32无符号整数(小端),相当ntohl()函数
输入参数 : ip[]
返 回 值 : 返回32无符号整数的ip地址(小端)
修改日期 : 2015年9月10日
*****************************************************************************/
uint iptoun_btol(const uchar *ip)
{
uint ip_val = 0;
ip_val = ip[0]<<24 | ip[1]<<16 | ip[2]<<8 | ip[3];
return ip_val;
}
/*****************************************************************************
函 数 名 : iptoun_btob()
功能描述 : 将存在ip[]的ip地址(大端)转化为32无符号整数(大端)
输入参数 : ip[]
返 回 值 : 返回32无符号整数的ip地址(大端)
修改日期 : 2015年9月10日
*****************************************************************************/
uint iptoun_btob(const uchar *ip)
{
uint ip_val = 0;
ip_val = ip[3]<<24 | ip[2]<<16 | ip[1]<<8 | ip[0];
//ip_val = *(uint *)ip;
return ip_val;
}
/*****************************************************************************
函 数 名 : insert_arp_table()
功能描述 : 建立ARP表
输入参数 : head 链表头
node 待插入节点
返 回 值 : 链表头指针
修改日期 : 2015年9月10日
*****************************************************************************/
ARP_Table *insert_arp_table(ARP_Table *head, ARP_Table node)
{
ARP_Table *pi = NULL;
pi = (ARP_Table *)malloc(sizeof(ARP_Table));
//bzero(pi, 0, sizeof(ARP_Table));
if(pi != NULL) //成功申请到空间
{
*pi = node;
pi->next = NULL;
int ip_val = iptoun_btol(node.ip);
if(head == NULL)
{
head = pi;
}
else //链表不为空
{
ARP_Table *pb = NULL, *pf =NULL;
pb = pf = head;
//按从小到大插入链表
while((ip_val > iptoun_btol(pb->ip)) && (pb->next != NULL))
{
pf = pb;
pb = pb->next;
}
if(ip_val <= iptoun_btol(pb->ip))//链表头插入新节点
{
if(pb == head)
{
pi->next = pb;
head = pi;
}
else //中间插入新节点
{
pi->next = pb;
pf->next = pi;
}
}
else //尾部插入新节点
{
pb->next = pi;
}
}
}
else
{
printf("Can not apply for a ARP_Table node memeory space!\n");
}
return head;
}
/*****************************************************************************
函 数 名 : search_arp_table()
功能描述 : 查找ARP表
输入参数 : head 链表头
ip 从链表查找的ip
返 回 值 : 链表头指针
修改日期 : 2015年9月10日
*****************************************************************************/
ARP_Table *search_arp_table(ARP_Table *head, const uchar *ip)
{
if(head == NULL)
{
printf("Link is not exist!\n");
}
else
{
ARP_Table *pb = head;
uint ip_val;
ip_val = iptoun_btol(ip);
while((ip_val != iptoun_btol(pb->ip)) && (pb->next != NULL))
pb = pb->next;
if(ip_val == iptoun_btol(pb->ip)) //在ARP表找到匹配的ip
{
return pb;
}
}
return NULL; //没找到匹配的ip返回NULL
}
/*****************************************************************************
函 数 名 : delete_arp_node()
功能描述 : 查找ARP表,并删除链表中的指定节点
输入参数 : head 链表头
ip 从链表查找的ip
返 回 值 : 链表头指针
修改日期 : 2015年9月10日
*****************************************************************************/
ARP_Table *delete_arp_node(ARP_Table *head, const uchar *ip)
{
if(head == NULL)
{
printf("Link is not exist!\n");
}
else
{
ARP_Table *pb = NULL, *pf = NULL;
pb = pf =head;
uint ip_val = iptoun_btol(ip);
while((ip_val != iptoun_btol(pb->ip)) && (pb->next != NULL))
{
pf = pb;
pb = pb->next;
}
if(ip_val == iptoun_btol(pb->ip))
{
if(pb == head) //删除的节点再链表头
head = pb->next;
else if(pb->next == NULL) //删除的节点在表尾
pf->next = NULL;
else //删除的节点再中间
pf->next = pb->next;
free(pb);
}
}
return head;
}
/*****************************************************************************
函 数 名 : free_arp_table()
功能描述 : 释放整个ARP表
输入参数 : head 链表头
返 回 值 : 链表头指针
修改日期 : 2015年9月10日
*****************************************************************************/
ARP_Table *free_arp_table(ARP_Table *head)
{
if(head == NULL)
{
printf("Link is not exist!\n");
}
else
{
ARP_Table *pb = head;
//释放整个链表的方法:
//1、判断head是否为空
//2、让pb指向和head相同的节点
//3、然后head指向下一个节点
//4、再释放pb指向的节点
//5、返回步骤1
while(head != NULL)
{
pb = head;
head = pb->next;
free(pb);
}
}
return head;
}
/*****************************************************************************
函 数 名 : change_arp_mac()
功能描述 : 查找整个ARP表,修改ip对应的mac
输入参数 : head 链表头
ip 要修改mac对应的ip
mac 新的mac
返 回 值 : Boolean 类型值,成功返回:TRUE
修改日期 : 2015年9月12日
*****************************************************************************/
Boolean change_arp_mac(ARP_Table *head, const uchar ip[], const uchar mac[])
{
if(head == NULL){
printf("Link is not exist!\n");
}
else {
ARP_Table *pnode = NULL;
pnode = search_arp_table(head, ip);
if(pnode != NULL){
memcpy(pnode->mac, mac, 6);
return TRUE;
}
}
return FALSE;
}
/*****************************************************************************
函 数 名 : print_arp_table()
功能描述 : 打印整个ARP表
输入参数 : head 链表头
返 回 值 : 链表头指针
修改日期 : 2015年9月10日
*****************************************************************************/
void print_arp_table(ARP_Table *head)
{
if(head == NULL)
{
printf("Link is not exist!\n");
}
else
{
uchar ip[16] ="";
uchar mac[18]="";
ARP_Table *pb = head;
printf("_____IP________________MAC_______\n");
while(pb != NULL)
{
bzero(ip, 16);
bzero(mac,18);
sprintf(ip,"%d.%d.%d.%d",\
pb->ip[0],pb->ip[1],pb->ip[2],pb->ip[3]);
sprintf(mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
pb->mac[0],pb->mac[1],pb->mac[2],pb->mac[3],pb->mac[4],pb->mac[5]);
printf("%-12s -- %s\n", ip,mac);
pb = pb->next;
}
printf("_________________________________\n");
}
}
<file_sep>/sys_program/player/src/inc/link.h
/* ************************************************************************
* Filename: link.h
* Description:
* Version: 1.0
* Created: 2015年07月31日 星期五 05時39分46秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __LINK_H__
#define __LINK_H__
#include "common.h"
LRC *insert_link(LRC *head, LRC slrc);
LRC *free_link(LRC *head);
void print_link(LRC *head);
LRC *search_link(LRC *head,int time);
#endif
<file_sep>/work/test/sndkit/sound.c
/*************************************************************************
> File Name: sound.c
> Author:
> Mail:
> Created Time: Tue 06 Sep 2016 05:26:44 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <linux/soundcard.h>
#define LENGTH 8 /* 存储秒数 */
#define RATE 16000 /* 采样频率 */
#define BITS 16 /* 量化位数 */
#define CHANNELS 1 /* 声道数目 */
/********以下是wave格式文件的文件头格式说明******/
/*------------------------------------------------
| RIFF WAVE Chunk |
| ID = 'RIFF' |
| RiffType = 'WAVE' |
------------------------------------------------
| Format Chunk |
| ID = 'fmt ' |
------------------------------------------------
| Fact Chunk(optional) |
| ID = 'fact' |
------------------------------------------------
| Data Chunk |
| ID = 'data' |
------------------------------------------------*/
/**********以上是wave文件格式头格式说明***********/
/*wave 文件一共有四个Chunk组成,其中第三个Chunk可以省略,每个Chunk有标示(ID),大小(size,就是本Chunk的内容部分长度),内容三部分组成*/
typedef struct waveheader
{
/****RIFF WAVE CHUNK*/
unsigned char a[4];//四个字节存放'R','I','F','F'
long int b; //整个文件的长度-8;每个Chunk的size字段,都是表示除了本Chunk的ID和SIZE字段外的长度;
unsigned char c[4];//四个字节存放'W','A','V','E'
/****Format CHUNK*/
unsigned char d[4];//四个字节存放'f','m','t',''
long int e; //16后没有附加消息,18后有附加消息;一般为16,其他格式转来的话为18
short int f; //编码方式,一般为0x0001;
short int g; //声道数目,1单声道,2双声道;
long int h; //采样频率;
long int i; //每秒所需字节数;
short int j; //每个采样需要多少字节,若声道是双,则两个一起考虑;
short int k; //即量化位数
/***Data Chunk**/
unsigned char p[4];//四个字节存放'd','a','t','a'
long int q; //语音数据部分长度,不包括文件头的任何部分
} waveheader;//定义WAVE文件的文件头结构体
waveheader *get_waveheader(int bits, int rates, int channels, unsigned long size)
{
waveheader *header = malloc(sizeof(*header));
header->a[0] = 'R';
header->a[1] = 'I';
header->a[2] = 'F';
header->a[3] = 'F';
header->b = size - 8;
header->c[0] = 'W';
header->c[1] = 'A';
header->c[2] = 'V';
header->c[3] = 'E';
header->d[0] = 'f';
header->d[1] = 'm';
header->d[2] = 't';
header->d[3] = ' ';
header->e = 16;
header->f = 1;
header->g = channels;
header->h = rates;
header->i = size / (rates * channels * bits / 8);
header->j = channels * bits / 8;
header->k = bits;
header->p[0] = 'd';
header->p[1] = 'a';
header->p[2] = 't';
header->p[3] = 'a';
header->q = size;
return header;
}
int main(int argc, char *argv[])
{
unsigned char *buf = NULL, *pbuf = NULL;
unsigned int size = 0, cnt = 0;
int len;
int fd; /* 声音设备的文件描述符 */
int arg; /* 用于ioctl调用的参数 */
int status; /* 系统调用的返回值 */
if (argc > 2) {
printf("Too many arguments!\n");
exit(1);
}
if (argc == 2) {
/* 打开声音设备 */
fd = open("/dev/mixer3", O_RDWR);
if (fd < 0) {
perror("open of /dev/mixer3 failed");
exit(1);
}
arg = atoi(argv[1]);
/* set dmix gain */
status = ioctl(fd, SOUND_MIXER_WRITE_MIC, &arg);
if(status < 0)
perror("SOUND_MIXER_WRITE_MIC ioctl failed");
int vol = 0, left = 0, right = 0;
/* get dmic gain */
status = ioctl(fd, SOUND_MIXER_READ_IGAIN, &vol);
left = vol & 0xff;
right = vol >> 8;
printf("left gain id %d %%, right gain is %d %%\n", left, right);
close(fd);
}
/* 打开声音设备 */
fd = open("/dev/dsp3", O_RDONLY);
if (fd < 0) {
perror("open of /dev/dsp3 failed");
exit(1);
}
/* 设置采样时的量化位数 */
arg = BITS;
status = ioctl(fd, SNDCTL_DSP_SETFMT, &arg);
if (status < 0)
perror("SOUND_PCM_WRITE_BITS ioctl failed");
if (arg != BITS)
perror("unable to set sample size");
/* 设置采样时的声道数目 */
arg = CHANNELS;
status = ioctl(fd, SNDCTL_DSP_CHANNELS, &arg);
if (status < 0)
perror("SOUND_PCM_WRITE_CHANNELS ioctl failed");
if (arg != CHANNELS)
perror("unable to set number of channels");
/* 设置采样时的采样频率 */
arg = RATE;
status = ioctl(fd, SNDCTL_DSP_SPEED, &arg);
if (status < 0)
perror("SOUND_PCM_WRITE_WRITE ioctl failed");
/* 用于保存数字音频数据的内存缓冲区 */
size = LENGTH * RATE * CHANNELS * BITS/8;
buf = (unsigned char *)malloc(size);
if(buf == NULL) {
printf("malloc data buffer failed!\n");
exit(1);
}
printf("Say something now...\n");
len = read(fd, buf, size);
if(len != size) {
perror("read wrong number of bytes");
exit(1);
}
/* make the wav file header */
waveheader *header = get_waveheader(BITS, RATE, CHANNELS, len);
/* creat wav file */
int wav_fd = open("/tmp/record.wav", O_WRONLY | O_CREAT, 0777);
/* write wav file header */
write(wav_fd, header, sizeof(*header));
free(header);
header = NULL;
pbuf = buf;
/* write pcm data */
while(len > 0) {
cnt = len > 10240 ? 10240 : len;
cnt = write(wav_fd, pbuf, cnt);
if(cnt < 0) {
printf("write error, retry.\n");
exit(1);
}
len -= cnt;
pbuf += cnt;
}
free(buf);
close(fd);
close(wav_fd);
printf("record done, output file: /tmp/recorder.wav\n");
return 0;
}
<file_sep>/sys_program/2nd_day/am/system.c
/* ************************************************************************
* Filename: system.c
* Description:
* Version: 1.0
* Created: 2015年08月14日 19时09分10秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
pid_t pid;
char cmd[128] = "";
while(1)
{
//printf("Please input a cmd: ");
//fgets(cmd,sizeof(cmd),stdin);
//printf("%d\n",strlen(cmd));
//cmd[strlen(cmd)-1] = '\0'; //把获取的字符后面的\n转化成 '\0'
pid = fork(); //创建子进程
if(pid == 0) //子进程
{
int len = 0;
printf("Please input a cmd: ");
fgets(cmd,sizeof(cmd),stdin);
len = strlen(cmd);
//printf("%d\n",len);
if(len > 1)
{
cmd[len-1] = '\0'; //把获取的字符后面的\n转化成 '\0'
}
else
{
exit(0);
}
//printf("in son process\n");
execl("/bin/sh","sh","-c",cmd,NULL);
exit(1);
}
wait(NULL);
}
return 0;
}
<file_sep>/work/test/v4l2/include/capture.h
/*************************************************************************
> Filename: capture.h
> Author: Qiuwei.wang
> Email: <EMAIL>
> Datatime: Fri 02 Dec 2016 10:07:17 AM CST
************************************************************************/
#ifndef _CAPTURE_H
#define _CAPTURE_H
/*
* Struct
*/
typedef enum {
IO_METHOD_READ,
IO_METHOD_MMAP,
IO_METHOD_USERPTR,
} io_method;
struct buffer {
void *start;
size_t length;
};
struct capture_t {
char *dev_name;
int fd;
unsigned int width;
unsigned int height;
unsigned int bpp;
unsigned int sizeimage;
unsigned int nbuf;
unsigned int count;
io_method io;
struct buffer *pbuf;
};
/*
* Extern functions
*/
int read_frame(struct capture_t *capt);
void process_image(struct capture_t *capt, int index);
void start_capturing(struct capture_t *capt);
void stop_capturing(struct capture_t *capt);
void test_framerate(struct capture_t *capt);
void open_device(struct capture_t *capt);
void close_device(struct capture_t *capt);
void init_device(struct capture_t *capt);
void free_device(struct capture_t *capt);
void main_loop(struct capture_t *capt);
#endif
<file_sep>/network/route/tcp/main.c
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
char cmd[] =
char ip[16] = "192.168.1.221";
unsigned short port = 8080;
if(argc > 1) {
strcpy(ip, argv[1]);
}
//1.创建一个用于通信的tcp套接字
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
//2.连接制定的服务器
struct sockaddr_in s_addr;
bzero(&s_addr, sizeof(s_addr));
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(8080);
s_addr.sin_addr.s_addr = inet_addr(ip);
//3.连接
int ret = connect(sockfd, (struct sockaddr *)&s_addr, sizeof(s_addr));
if(ret != 0)
{
perror("connect:");
exit(-1);
}
while(1)
{
printf("cmd: ");
fflush(stdout);
cmd[strlen(cmd)- 1] = 0; // 去掉 \n
}
return 0;
}
<file_sep>/network/route/src/firewall_file.c
/******************************************************************************
文 件 名 : firewall_file.c
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月15日
最近修改 :
功能描述 : 将防火墙规则写入文件或从文件读出
函数列表 :
filrewall_save_rule
firewall_config
firewall_read_rule_file
firewall_save_all_rules
firewall_get_passwd
firewall_save_passwd
修改历史 :
1.日 期 : 2015年9月15日
作 者 : if
修改内容 : 创建文件
******************************************************************************/
#include "common.h"
#include "route_firewall.h"
/*----------------------------------------------*
* 宏定义 *
*----------------------------------------------*/
#define RULE_FILE ".firewall_rule"
#define PASSWD_FILE ".passwd"
/*****************************************************************************
函 数 名 : firewall_save_all_rules()
功能描述 : 把防火墙规则链表的所有规则保存到文件
输入参数 : rt TYPE_Route 类型结构指针
返 回 值 : NULL
修改日期 : 2015年9月15日
*****************************************************************************/
void firewall_save_all_rules(TYPE_Route *rt)
{
FILE *fp = NULL;
FIRE_Wall *pnode = NULL;
FIRE_Wall *pbuf[4] = {rt->mac_head,rt->ip_head,rt->port_head,rt->pro_head};
char rule[RULE_LEN] = "";
int i = 0;
fp = fopen(RULE_FILE, "wb");
if(fp != NULL){
for(i=0; i<4; i++)
{
pnode = pbuf[i];
while(pnode != NULL)
{
strcpy(rule, pnode->rule);
strcat(rule,"\n");
fwrite(rule, 1, strlen(rule), fp);
pnode = pnode->next;
}
}
fclose(fp);
}
}
/*****************************************************************************
函 数 名 : filrewall_save_rule()
功能描述 : 把新加的防火墙规则保存到文件
输入参数 : rule 要保存的规则
返 回 值 : NULL
修改日期 : 2015年9月15日
*****************************************************************************/
void filrewall_save_rule(const char *rule)
{
FILE *fp = NULL;
fp = fopen(RULE_FILE, "ab");
if(fp != NULL){
char buf[RULE_LEN] = "";
strcpy(buf, rule);
strcat(buf, "\n");
fwrite(buf, 1, strlen(buf), fp);
fclose(fp);
}
}
/*****************************************************************************
函 数 名 : firewall_read_rule_file()
功能描述 : 读出防火墙规则文件的内容
输入参数 : file_name 文件名
返 回 值 : 返回指向文件内容的首部的指针
修改日期 : 2015年9月15日
*****************************************************************************/
static char *firewall_read_rule_file(const char *file_name)
{
FILE *fp = NULL;
char *buf = NULL;
ulint file_length = 0;
fp = fopen(file_name, "rb");
if(fp == NULL){
//printf("Cannot open the flie!\n");
//Z文件不存在,则创建,然后返回
fp = fopen(file_name, "wb");
fclose(fp);
return;
}
fseek(fp,0,SEEK_END);
file_length = ftell(fp);
buf = (char *)malloc(file_length); //动态分配内存
if(buf == NULL){
printf("malloc() cannot apply for memory!\n");
goto out;
}
rewind(fp); //
fread(buf,file_length,1,fp);
out:
fclose(fp);
return buf;
}
/*****************************************************************************
函 数 名 : firewall_config()
功能描述 : 读出防火墙规则文件的内容,建立过滤规则链表
输入参数 : rt TYPE_Route 类型结构指针
返 回 值 : NULL
修改日期 : 2015年9月15日
*****************************************************************************/
void firewall_config(TYPE_Route *rt)
{
char *p_src = NULL;
char *p_rule= NULL;
p_src = (char *)firewall_read_rule_file(RULE_FILE);
p_rule = strtok(p_src, "\n");
while(p_rule != NULL){
firewall_build_rule(rt, p_rule, 0);
p_rule = strtok(NULL, "\n");
}
free(p_src);
}
/*****************************************************************************
函 数 名 : firewall_get_passwd()
功能描述 : 从文件获取防火墙的密码
输入参数 : rt TYPE_Route 类型结构指针
返 回 值 : NULL
修改日期 : 2015年9月15日
*****************************************************************************/
void firewall_get_passwd(TYPE_Route *rt)
{
FILE *fp = NULL;
char str[PASSWD_LEN] = "";
int i, len;
fp = fopen(PASSWD_FILE, "rb");
if(fp == NULL) {
//文件不存在,则创建,然后退出
fp = fopen(PASSWD_FILE, "wb");
fclose(fp);
return;
}
len = fread(str, 1, PASSWD_LEN, fp); //fread 返回实际读的块数
len--;
str[len] = 0; // 去掉 \n
for(i=0; i<len; i++) {
str[i] -= ENCRYPT_KEY;
}
strcpy(rt->passwd, str);
fclose(fp);
}
/*****************************************************************************
函 数 名 : firewall_save_passwd()
功能描述 : 防火墙的密码加密后保存到文件
输入参数 : passwd 要保存的密码
返 回 值 : NULL
修改日期 : 2015年9月15日
*****************************************************************************/
void firewall_save_passwd(char passwd[])
{
FILE *fp = NULL;
int i, len;
len = strlen(passwd);
for(i=0; i<len; i++) {
passwd[i] += ENCRYPT_KEY;
}
if(len >= PASSWD_LEN) {
len = PASSWD_LEN-1;
passwd[len] = 0;
}
strcat(passwd,"\n");
fp = fopen(PASSWD_FILE, "wb");
if(fp != NULL) {
fwrite(passwd, 1, len+1, fp);
fclose(fp);
}
}
/*****************************************************************************
函 数 名 : getch()
功能描述 : 获取一个字符
输入参数 : NULL
返 回 值 : NULL
修改日期 : 2015年9月15日
*****************************************************************************/
static char getch()
{
struct termios oldt, newt;
char ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
/*****************************************************************************
函 数 名 : get_passwd()
功能描述 : 获取密码
输入参数 : pwd 保存获取密码的指针
返 回 值 : max_len 密码的最大长度
修改日期 : 2015年9月15日
*****************************************************************************/
void get_passwd(char passwd[], int max_len)
{
char ch = 0, i = 0;
char buf[PASSWD_LEN];
while(i < max_len)
{
ch = getch();
if(ch == 10){ // 回车键
passwd[i] = 0;
break;
}
else if(ch ==127) { // 回格键
//i--;
//if(i<0) i = 0;
continue;
}
passwd[i++] = ch;
putchar('*');
}
passwd[max_len] = 0;
}
<file_sep>/work/test/v4l2/include/common.h
/*************************************************************************
> Filename: common.h
> Author: Qiuwei.wang
> Email: <EMAIL> / <EMAIL>
> Datatime: Fri 02 Dec 2016 02:24:29 PM CST
************************************************************************/
#ifndef _COMMON_H
#define _COMMON_H
#define TRUE 1
#define FALSE 0
#define CLEAR(x) memset (&(x), 0, sizeof (x))
#define errno_exit(str) \
do { \
fprintf(stderr, "%s error %d, %s\n", \
str, errno, strerror(errno)); \
exit(EXIT_FAILURE); \
} while(0)
#define xioctl(fd, request, arg) \
({ \
int ret; \
do { \
ret = ioctl(fd, request, arg); \
} while(-1 == ret && EINTR == errno); \
\
ret; \
})
/*
* Extern functions
*/
void *JZMalloc(int align, int size);
void jz47_free_alloc_mem();
unsigned int get_phy_addr(unsigned int vaddr);
#endif
<file_sep>/network/5th_day/raw_test.c
int main(int argc,char *argv[])
{
//1.创建一个原始套接字
int raw_fd = socket(PF_PACKET,SOCK_RAW,htons(ETH_P_ALL));
unsigned char msg[2048]="";
//1.封装mac头
unsigned char dst_mac[6]={0x00,0x0c,0x29,0xef,0x4d,0x3d};
unsigned char src_mac[6]={0x00,0x0c,0x29,0xf5,0xc6,0x39};
struct ether_header *eth_hdr = NULL;
eth_hdr = (struct ether_header *)msg;
memcpy(eth_hdr->ether_dhost,6);
memcpy(eth_hdr->ether_shost,6);
ether_hdr->ether_type = htons(0x0800);
//2.封装ip头
struct iphdr *ip_hdr =NULL;
ip_hdr = (struct iphdr *)(msg+14);
ip_hdr->version =4;
ip_hdr->ihl=5;
ip_hdr->tos=0;
ip_hdr->tot_len = htons(20+ip_data_len);//两个字节的 要htons
ip_hdr->saddr = inet_addr("10.221.2.16");
ip_hdr->daddr = inet_addr("");
ip_hdr->check = htons(0);//????????
//2.封装udp头部
struct udphdr *udp_hdr;
udp_hdr = (struct udphdr *)(msg+14+20);
udp_hdr->source = htons(8000);
udp_hdr->dest = htons(8000);
udp_hdr->len = htons(8+udp_data_len);
udp_hdr->check=htons(0);//??
//3.udp数据
memcpy(msg +14 +20+8,"hehe",strlen("hehe"));
//4.ip首部校验
ip->check = htons(checksum(msg+14),20/2);
//5.0 udp校验
unsigned char wei_udp[1024]={
10.221.2.66//源ip
10.221.2.16//目的ip
0,17,0,0//长度需要对其赋值&
}
*(unsigned short *)(wei_udp+10) = htons(8+strlen("hehe"));//&
memcpy(wei_udp+12,msg+12+20,8+strlen("hehe"));
udp_hdr->check = htons(checksum(wei_udp,(12+8+strlen("hehe"))/2));
sendto();
}
<file_sep>/network/route/Makefile
DIR_INC := ./src/inc
DIR_SRC := ./src
DIR_OBJ := ./obj
DIR_BIN := ./bin
SRC = $(wildcard ${DIR_SRC}/*.c)
OBJ = $(patsubst %.c,${DIR_OBJ}/%.o,$(notdir ${SRC}))
TARGET = route
#BIN_TARGET = ${DIR_BIN}/${TARGET} # 目标存放在 bin目录
BIN_TARGET = ./${TARGET} # 目标存放在当前目录
CC = gcc
INCFAG = -I$(DIR_INC)
CFLAGES = -lpthread
$(shell test -e obj || mkdir obj)
$(BIN_TARGET):$(OBJ)
$(CC) $(OBJ) -o $@ $(CFLAGES)
$(DIR_OBJ)/%.o:$(DIR_SRC)/%.c
$(CC) $(INCFAG) -c $< -o $@ $(CFLAGES)
.PHONY:clean
clean:
# find $(DIR_OBJ) -name *.o -exec rm -rf {}\ ;
rm ${DIR_OBJ}/* ${TARGET}
<file_sep>/c/practice/3rd_week/mylink/link.h
#ifndef __LINK_H__
#define __LINK_H__
typedef struct student
{
int num;
char name[64];
int score;
struct student *next;
}STU;
/*******************************************/
extern STU *insert_link(STU *head, STU temp);
extern void print_link(STU *head);
extern STU *search_link(STU *head, char *name);
extern STU *delete_link(STU *head, int num);
extern STU *delete_head(STU *head);
extern STU *free_link(STU *head);
extern STU *sort_link(STU *head);
extern STU *invert_link(STU *head);
#endif
<file_sep>/work/test/socket/socket_server.c
/*************************************************************************
> File Name: socket_server.c
> Author:
> Mail:
> Created Time: Tue 17 May 2016 11:28:50 AM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int main(int argc, char ** argv) {
int listenfd;
struct sockaddr_in servaddr;
pid_t pid;
char temp[100];
int n = 0;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(atoi(argv[1]));
bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
listen(listenfd, n);
for(;;) {
struct sockaddr_in local;
int connfd = accept(listenfd, (struct sockaddr *)NULL, NULL);
if((pid = fork()) == 0) {
struct sockaddr_in serv, guest;
char serv_ip[20];
char guest_ip[20];
int serv_len = sizeof(serv);
int guest_len = sizeof(guest);
getsockname(connfd, (struct sockaddr *)&serv, &serv_len);
getpeername(connfd, (struct sockaddr *)&guest, &guest_len);
inet_ntop(AF_INET, &serv.sin_addr, serv_ip, sizeof(serv_ip));
inet_ntop(AF_INET, &guest.sin_addr, guest_ip, sizeof(guest_ip));
printf("host %s:%d guest %s:%d\n", serv_ip, ntohs(serv.sin_port), guest_ip, ntohs(guest.sin_port));
char buf[] = "hello world";
write(connfd, buf, strlen(buf));
close(connfd);
exit(0);
}
close(connfd);
}
}
<file_sep>/sys_program/2nd_day/am/Makefile
elf:vfork.c
gcc -o elf vfork.c
.PHONY:clean
clean:
rm elf
<file_sep>/work/test/mplay/wavsound.c
/*************************************************************************
> File Name: wavsound.c
> Author:
> Mail:
> Created Time: Fri 14 Oct 2016 02:26:26 PM CST
************************************************************************/
#include <tinyalsa/asoundlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
/*
* Macro
*/
#define ID_RIFF 0x46464952
#define ID_WAVE 0x45564157
#define ID_FMT 0x20746d66
#define ID_DATA 0x61746164
#define FORMAT_PCM 1
/*
* Struct
*/
struct riff_wave_header {
uint32_t riff_id;
uint32_t riff_sz;
uint32_t wave_id;
};
struct chunk_header {
uint32_t id;
uint32_t sz;
};
struct chunk_fmt {
uint16_t audio_format;
uint16_t num_channels;
uint32_t sample_rate;
uint32_t byte_rate;
uint16_t block_align;
uint16_t bits_per_sample;
};
struct wav_header {
uint32_t riff_id;
uint32_t riff_sz;
uint32_t riff_fmt;
uint32_t fmt_id;
uint32_t fmt_sz;
uint16_t audio_format;
uint16_t num_channels;
uint32_t sample_rate;
uint32_t byte_rate;
uint16_t block_align;
uint16_t bits_per_sample;
uint32_t data_id;
uint32_t data_sz;
};
extern int close_flag;
void play_sample(char *filename, unsigned int device)
{
char *buffer = NULL;
int size, num_read;
static FILE *file = NULL;
struct pcm *pcm;
struct pcm_config config;
struct wav_header header;
printf("entry: %s\n", __FUNCTION__);
bzero(&config, sizeof(struct pcm_config));
file = fopen(filename, "rb");
if(!file) {
printf("Unable to open file '%s'\n", filename);
return;
}
fread(&header, sizeof(struct wav_header), 1, file);
if((header.riff_id != ID_RIFF) || (header.riff_fmt != ID_WAVE) ||
(header.fmt_id != ID_FMT) || (header.audio_format != FORMAT_PCM) ||
(header.fmt_sz != 16)) {
printf("Error: '%s' is not a PCM riff/wave file\n", filename);
fclose(file);
return;
}
config.channels = header.num_channels;
config.rate = header.sample_rate;
config.period_size = 1024;
config.period_count = 4;
if(header.bits_per_sample == 32)
config.format = PCM_FORMAT_S32_LE;
else if(header.bits_per_sample == 16)
config.format = PCM_FORMAT_S16_LE;
config.start_threshold = 0;
config.stop_threshold = 0;
config.silence_threshold = 0;
pcm = pcm_open(0, device, PCM_OUT, &config);
if(!pcm || !pcm_is_ready(pcm)) {
printf("Unable to open PCM device %u (%s)\n", device, pcm_get_error(pcm));
return;
}
size = pcm_frames_to_bytes(pcm, pcm_get_buffer_size(pcm));
buffer = malloc(size);
if(!buffer) {
printf("Unable to allocate %d bytes\n", size);
pcm_close(pcm);
return;
}
printf("Playing sample: %u ch, %u hz, %u bit\n", header.num_channels,
header.sample_rate, header.bits_per_sample);
do {
num_read = fread(buffer, 1, size, file);
if(num_read > 0) {
if(pcm_write(pcm, buffer, num_read)) {
printf("Error playing sample\n");
break;
}
}
} while(num_read > 0);
printf("pcm_write over...\n");
fclose(file);
free(buffer);
pcm_close(pcm);
}
<file_sep>/network/3rd_day/tcp_client.c
/* ************************************************************************
* Filename: tcp_client.c
* Description:
* Version: 1.0
* Created: 2015年09月02日 14时38分49秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
//1.创建一个用于通信的tcp套接字
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
//2.连接制定的服务器
struct sockaddr_in s_addr;
bzero(&s_addr, sizeof(s_addr));
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(8080);
s_addr.sin_addr.s_addr = inet_addr("10.221.2.12");
//连接
int ret = connect(sockfd, (struct sockaddr *)&s_addr, sizeof(s_addr));
if(ret != 0)
{
perror("connect:");
exit(-1);
}
//3.给服务器发送数据
send(sockfd, "hehe", strlen("hehe"), 0);
//4.接收服务器的应答
char buf[128]="";
recv(sockfd, buf, sizeof(buf),0);
//5.关闭tcp套接字
close(sockfd);
return 0;
}
<file_sep>/c/practice/3rd_week/string/main.c
#include <stdio.h>
#include <string.h>
#include "mystring.h"
void main()
{
char a[]="jkdjgse";
char b[20]="hjakh";
char c[]="12345";
int num = 0;
mystrinv(a);
printf("a=%s\n",a);
printf("%d\n",mystrcmp(a,b));
num = strchange(c);
printf("num=%d\n",num);
mystrcpy(b,a);
printf("b=%s\n",b);
}
<file_sep>/work/shell/test.sh
#!/bin/bash
UBOOT_BUILD_CONFIG=halley2_v10_xImage_sfc_nor
KERNEL_BUILD_CONFIG=halley2_nor_v10_linux_defconfig
KERNEL_TARGET_IMAGE=xImage
echo "$KERNEL_BUILD_CONFIG, $KERNEL_TARGET_IMAGE, $UBOOT_BUILD_CONFIG"
tmp=${1#-j}
echo "$tmp"
x="xx87+ jdlj"
echo $x | grep -o '[0-9]\+'
case "$2" in
[1-9][0-9]*)
echo "$2 is number"
;;
*)
;;
esac
if [ -n "$(echo $2 | sed -n "/^[0-9]\+$/p")" ];then
echo "$2 is number."
else
echo 'no.'
fi
<file_sep>/sys_program/player/src/inc/mplayer_pthread.h
/* ************************************************************************
* Filename: mplayer_process.h
* Description:
* Version: 1.0
* Created: 2015年08月23日 18时05分21秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __MPLAYER_PTHREAD_H__
#define __MPLAYER_PTHREAD_H__
extern SONG song;
extern void mplayer_init(MPLAYER *pm);
extern void gtk_thread_init(void);
extern void get_song_msg(MPLAYER *pm);
extern int mplayer_process(MPLAYER *pm);
extern void create_pthread(MPLAYER *pm);
#endif<file_sep>/c/practice/check_samechar.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int check_samechar(char *str)
{
char ch[127] = {0};
int i = 0;
if(str == NULL) return 0;
while(str[i] != 0){
if(ch[str[i]] == 0){
ch[str[i]] = str[i];
}
else return 1;
i++;
}
return 0;
}
int main(int argc, char *argv[])
{
char str[64] = "";
int len = 0;
printf("输入字符串:");
// 刷新标准输出,因为在printf函数的缓冲没满,并且打印的
// 字符串后面没有 "\n",调用这个函数屏幕马上可以看到”输入字符串:“
fflush(stdout);
fgets(str, sizeof(str), stdin); // 从标准输入获取输入字符串
len = strlen(str); // 求出长度
str[len - 1] = 0; // 去掉字符串后的换行符
int flag = check_samechar(str); // 处理
if(flag == 1)
printf("##:%s\n", str);
return 0;
}
<file_sep>/c/lrc/Makefile
CC := gcc
SRC := $(shell ls *.c)
#OBJ := $(patsubst %.c,%.o,$(SRC))
OBJ := $(SRC: %.c=%.o)
TAG := lrc
$(TAG):$(OBJ)
$(CC) -o $@ $^
%.o:%.c
$(CC) -o $@ -c $<
.PHONY:clean
clean:
rm -f $(TAG) *.o
<file_sep>/c/practice/3rd_week/time/show_time.h
#ifndef __SHOW_TIME_H__
#define __SHOW_TIME_H__
extern void show_time(void);
#endif
<file_sep>/sys_program/1st_day/wait.c
/* ************************************************************************
* Filename: wait.c
* Description:
* Version: 1.0
* Created: 2015年08月13日 17时03分10秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
pid_t pid;
pid = fork();
if(pid < 0) perror("error\n");
else if (pid == 0)
{
int i = 0;
for(i = 0;i<5;i++)
{
printf("in son process");
sleep(1);
}
exit(2); //退出时会刷新缓冲区
//_exit(2);//退出时 不会 刷新缓冲区
//return 2; //这里return 2 跟 exit(2) 效果一样
}
else
{
int status = 0;
int i;
//wait(&status);
waitpid(-1,&status,0);
if(WIFEXITED(status) != 0) //判断返回状态 ,存在status的低8位
{
printf("return = %d\n",WEXITSTATUS(status)); //取返回值,存在status的8~16位
}
for(i=0;i<5;i++)
{
printf("in father process\n");
sleep(1);
}
}
return 0;
}
<file_sep>/work/notes/notes.c
配置:
source build/envsetup.sh
编译uboot:
cd bootable/bootloader/uboot
make aw808_wisesquare_an51_msc0
cat build/smk.sh | grep aw808
build/smk.sh --preset=aw808_v11_wisesquare_iwop -j32
======================================================================
m200 watch:
版级代码所在目录:
qiuweiwang@sw1:~/4.3/kernel/arch/mips/xburst/soc-m200/chip-m200/watch$
该目录下的common目录下的keyboard_gpio.c
/4.3/kernel/drivers/input/keyboard/gpio_keys.c
======================================================================
out/host/linux-x86/bin/mkbootimg --kernel kernel-3.10.14/arch/mips/boot/compressed/zImage --ramdisk out/target/product/aw808/ramdisk.img --output out/target/product/aw808/boot.img
./out/host/linux-x86/bin/mkbootimg --kernel ./kernel/arch/mips/boot/compressed/zImage --ramdisk ./out/target/product/aw808_iwop/ramdisk.img --output ./out/target/product/aw808_iwop/boot.img
out/host/linux-x86/bin/mkbootimg --kernel kernel-3.10.14/arch/mips/boot/compressed/zImage --ramdisk out/target/product/aw808/ramdisk.img --output out/target/product/aw808/boot.img
/5.1/kernel-3.10.14/arch/mips/xburst/soc-m200/chip-m200/watch/common$ vi i2c_bus.c
======================================================================
烧录kernel:
adb push boot.img /data
cat boot.img > /dev/block/mmcblk0p1
======================================================================
从历史命令中查看与sshfs相关的
history | grep sshfs
sshfs [email protected]:/home/qiuweiwang/ /home/qwwang/server
======================================================================
setenv bootargs mem=256M mem=768M@0x30000000 console=ttyS3,57600n8 ip=off root=/dev/mmcblk0p5 bk_root=/dev/mmcblk0p7 rw rootdelay=2 keep_bootcon
qwwang@qiuweiwang:/$ /etc/init.d/xinetd start
* Starting internet superserver xinetd [ OK ]
sudo /etc/init.d/tftpd-hpa start
ps -aux | grep 6847
sudo chmnod 777 /var/lib/tftpboot/
======================================================================
在内核中, sysfs 属性一般是由 __ATTR 系列的宏来声明的,如对设备的使用 DEVICE_ATTR ,对总线使用 BUS_ATTR ,对驱动使用 DRIVER_ATTR ,对类别(class)使用 CLASS_ATTR, 这四个高级的宏来自于 <include/linux/device.h>, 都是以更低层的来自 <include/linux/sysfs.h> 中的 __ATTR/__ATRR_RO 宏实现。这几个东东的区别就是,DEVICE_ATTR对应的文件在/sys/devices/目录中对应的device下面。而其他几个分别在driver,bus,class中对应的目录下
在documentation/driver-model/Device.txt中有对DEVICE_ATTR的详细介绍,这儿主要说明使用方法。
先看看DEVICE_ATTR的原型:
DEVICE_ATTR(_name, _mode, _show, _store)
_name:名称,也就是将在sys fs中生成的文件名称。
_mode:上述文件的访问权限,与普通文件相同,UGO的格式。
_show:显示函数,cat该文件时,此函数被调用。
_store:写函数,echo内容到该文件时,此函数被调用。
在终端查看到接口,当我们将数据 echo 到接口中时,在上层实际上完成了一次 write 操作,对应到 kernel ,调用了驱动中的 “store”。同理,当我们cat 一个 接口时则会调用 “show” 。
======================================================================
struct mmc_host是mmc core层与host层的接口,mmc_host.ops是控制host完成用户请求的接口函数集,其类型是struct mmc_host_ops,该结构体定义在include/linux/mmc/host.h文件中:
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
83structmmc_host_ops {
88 int (*enable)(struct mmc_host *host);
89 int (*disable)(struct mmc_host *host);
98 void (*post_req)(structmmc_host *host, struct mmc_request *req,
99 int err);
100 void (*pre_req)(struct mmc_host*host, struct mmc_request *req,
101 bool is_first_req);
102 void (*request)(struct mmc_host*host, struct mmc_request *req);
103 /*
104 * Avoid calling these three functions too often or in a "fastpath",
105 * since underlaying controller might implement them in an expensive
106 * and/or slow way.
107 *
108 * Also note that these functions might sleep, so don't call them
109 * in the atomic contexts!
110 *
111 * Return values for the get_ro callback should be:
112 * 0 for a read/write card
113 * 1 for a read-only card
114 * -ENOSYS when not supported(equal to NULL callback)
115 * or a negative errno value whensomething bad happened
116 *
117 * Return values for the get_cd callback should be:
118 * 0 for a absent card
119 * 1 for a present card
120 * -ENOSYS when not supported(equal to NULL callback)
121 * or a negative errno value whensomething bad happened
122 */
123 void (*set_ios)(struct mmc_host*host, struct mmc_ios *ios);
124 int (*get_ro)(struct mmc_host *host);
125 int (*get_cd)(struct mmc_host *host);
126
127 void (*enable_sdio_irq)(structmmc_host *host, int enable);
128
129 /* optional callback for HC quirks */
130 void (*init_card)(struct mmc_host*host, struct mmc_card *card);
131
132 int (*start_signal_voltage_switch)(struct mmc_host *host, struct mmc_ios*ios);
133
134 /* Check if the card is pulling dat[0:3] low */
135 int (*card_busy)(struct mmc_host *host);
136
137 /* The tuning command opcode value is different for SD and eMMC cards */
138 int (*execute_tuning)(struct mmc_host *host, u32 opcode);
139 int (*select_drive_strength)(unsigned int max_dtr, int host_drv, intcard_drv);
140 void (*hw_reset)(struct mmc_host*host);
141 void (*card_event)(structmmc_host *host);
142};
request函数用于处理用户的请求。
set_ios函数用于设置SDI的控制参数,如时钟、总线宽度等等。
get_ro函数用于探测SD卡是否有写保护。
get_cd函数用于探测卡是否已插入插槽。
enable_sdio_irq函数用于启动或禁用SDI中断。
需要注意的是,为什么没有对MMC/SD进行读写的read和write函数呢?这是因为Linux块设备的读写操作是通过request函数完成的。
--------------------------------------------------------------------------
jz4775mmc 驱动
0) 两大招
grep -rn "xxx" ./
find ./ -name "xxx"
1) arch/mips/xburst/soc-4775/common/platform.c
179: int jz_device_register(struct platform_device *pdev,void *pdata)
{
pdev->dev.platform_data = pdata;
return platform_device_register(pdev);
}
274:#define DEF_MSC(NO) \
275: static struct resource jz_msc##NO##_resources[] = {..}
287: struct platform_device jz_msc##NO##_device = {..}
297: DEF_MSC(0);
这个宏展开 => static struct resource jz_msc0_resources[] = {..} and
static struct resource jz_msc0_device = {...}
298: DEF_MSC(1); // 同DEF_MSC(0)
299: DEF_MSC(2); // 同DEF_MSC(0)
2) arch/mips/xburst/soc-4775/board/zmm220/zmm220-mmc.c
47: struct jzmmc_platform_data inand_pdata = {..}
72: struct jzmmc_platform_data tf_pdata = {..}
96: struct jzmmc_platform_data tf_pdata = {..}
116: struct jzmmc_platform_data sdio_pdata = {..}
3) arch/mips/xburst/soc-4775/board/zmm220/zmm220-misc.c:
>>> 以下注册设备
628: jz_device_register(&jz_msc0_device, &inand_pdata); // MSC0 接的是存储
631: jz_device_register(&jz_msc1_device, &sdio_pdata);
634: jz_device_register(&jz_msc2_device, &tf_pdata); // 可能是wifi模块
638: jz_device_register(&jz_msc0_device, &tf_pdata);
641: jz_device_register(&jz_msc2_device, &sdio_pdata);
4) drivers/mmc/host/jz4775_mmc.c
1864: static struct platform_driver jzmmc_driver = {..}
1877: static int __init jzmmc_init(void)
{
return platform_driver_probe(&jzmmc_driver, jzmmc_probe);
}
5) drivers/mmc/host/jz4775_mmc.c
1684:
static int __init jzmmc_probe(struct platform_device *pdev)
{
...
struct jzmmc_host *host = NULL;
struct mmc_host *mmc;
...
mmc = mmc_alloc_host(sizeof(struct jzmmc_host), &pdev->dev); // 原型在core/host.c函数展开如下
{
/* 建立数据结构 */
struct mmc_host *host;
/*申请 sizeof(struct mmc_host) + sizeof(struct jzmmc_host) 大小空间
*struct mmc_host
*{ ..
* unsigned long private[0] ____cacheline_aligned; //后面有这个长度为零的数组
*}
*/这样 private 的位置正好是 struct jzmmc_host 的首地址
host = kzalloc(sizeof(struct mmc_host) + extra, GFP_KERNEL);
/* 建立kobject */
host->parent = dev;
host->class_dev.parent = dev;
host->class_dev.class = &mmc_host_class;
device_initialize(&host->class_dev);
/* 初始化等待队列,工作队列 */
init_waitqueue_head(&host->wq);
INIT_DELAYED_WORK(&host->detect, mmc_rescan); // 初始化延时工作,指定工作函数
//注意这里的工作队列的延时时间delay为0,
//因为系统启动的时候不考虑插拔卡
//目的在系统初始化的时候就扫描查看是否存在卡
/* 配置控制器 */
host->max_hw_segs = 1;
host->max_seg_size = PAGE_CACHE_SIZE;
host->max_req_size = PAGE_CACHE_SIZE;
host->max_blk_size = 512;
host->max_blk_count = PAGE_CACHE_SIZE / 512;
return host;
}
host = mmc_priv(mmc); // host = mmc->private,即指向了struct jzmmc_host 结构
...
mmc_set_drvdata(pdev, host); //pdev->dev->p->driver_data = host,保存驱动的数据结构
ret = jzmmc_msc_init(host); // 初始化 msc
ret = jzmmc_gpio_init(host);// 初始化连接的IO口,申请中断等
jzmmc_host_init(host, mmc);
{
struct jzmmc_platform_data *pdata = host->pdata;
mmc->ops = &jzmmc_ops; // !!!!
...
host->mmc = mmc;
setup_timer(&host->request_timer, jzmmc_request_timeout,
(unsigned long)host); // 设置mmc host 的定时器
mmc_add_host(mmc);
{
...
device_add(&host->class_dev);
...
mmc_start_host(host);
{
mmc_power_off(host);
mmc_detect_change(host, 0);
}
}
}
return 0;
...
}
6) drivers/mmc/host/jz4775_mmc.c
struct mmc_host是mmc core层与host层的接口,mmc_host.ops是控制host完成用户请求的接口函数集,其类型是struct mmc_host_ops,该结构体定义在include/linux/mmc/host.h文件中。
1392:
static const struct mmc_host_ops jzmmc_ops = {
.request = jzmmc_request,
.set_ios = jzmmc_set_ios,
.get_ro = jzmmc_get_read_only,
.get_cd = jzmmc_get_card_detect,
.enable_sdio_irq = jzmmc_enable_sdio_irq,
};
request :用于处理用户的请求。
set_ios :用于设置SDI的控制参数,如时钟、总线宽度等等。
get_ro :用于探测SD卡是否有写保护。
get_cd :用于探测卡是否已插入插槽。
enable_sdio_irq :用于启动或禁用SDI中断。
为什么没有对MMC/SD进行读写的read和write函数呢?这是因为Linux块设备的读写操作是通过request函数完成的。
934:
static void jzmmc_request(struct mmc_host *mmc, struct mmc_request *mrq)
{
...
jzmmc_command_start(host, host->cmd); //实现命令的传输
if (host->data)
jzmmc_data_start(host, host->data);//实现数据的传输
if (unlikely(test_and_clear_bit(JZMMC_CARD_NEED_INIT, &host->flags)))
host->cmdat_def &= ~CMDAT_INIT;
}
======================================================================
/data/misc/bluetooth # cat bt_addr
su
echo 1 > /sys/power/wake_lock
time busybox wget -P /data ftp://qwwang:[email protected]//home/qwwang/test.mp3
======================================================================
gitk filename
git reset --hard 00c18a2d0c9b36aae147ad28e320842b3d7fe3de(哈希值)
kernel/sound/oss$ gitk --all &
kernel/arch/mips/xburst/soc-m200/chip-m200/watch/acrab$ gitk sound.c
kernel/arch/mips/xburst/soc-m200/chip-m200/watch/common$ gitk sound.c
======================================================================
zlm60 编译:
代码获取:
repo init -u ssh://[email protected]:29418/mirror/linux-x1000/manifest.git
platform/
source tools/build/source.sh
make
development/device/device.mk :
U-BOOT-CONFIG := zlm60_v10_uImage_spi_nand
KERNEL-CONFIG := zlm60_linux_spinand_ubi_defconfig
out/target/product/zlm60/image/
>> 编译 system.ubifs :
cd out/target/product/zlm60 &&
./mkfs.ubifs -d system -e 0x1f000 -c 2048 -m 0x800 -o image/system.ubifs
解决在启动时不接串口会进入uboot命令行的问题,修改uboot如下:
include/configs/zlm60.h: 499 行添加
/*
* UART configuration
*/
#define UART2_RXD_PORT GPIO_PC(31)
arch/mips/cpu/xburst/x1000/soc.c: 76 行添加
gpio_enable_pull(GPIO_PC(31));
======================================================================
需要说明的是网卡芯片也有“软硬”之分,特别是对与主板板载(LOM)的网卡芯片来说更是如此,这是怎么回事呢?大家知道,以太网接口可分为协议层和物理层。
协议层是由一个叫MAC(Media Access Layer,媒体访问层)控制器的单一模块实现。
物理层由两部分组成,即PHY(Physical Layer,物理层)和传输器。
常见的网卡芯片都是把MAC和PHY集成在一个芯片中,但目前很多主板的南桥芯片已包含了以太网MAC控制功能,只是未提供物理层接口,因此,需外接PHY芯片以提供以太网的接入通道。这类PHY网络芯片就是俗称的“软网卡芯片”,常见的PHY功能的芯片有RTL8201BL、VT6103等等。
“软网卡”一般将网络控制芯片的运算部分交由处理器或南桥芯片处理,以简化线路设计,从而降低成本,但其多少会更多占用系统资源.
======================================================================
4.3/kernel/sound/oss:
grep -nr "attibute_dac_l_gain" ./
5.1/kernel-3.10.14/sound/soc/ingenic/icodec$:
grep -nr "2c" ./
grep -nr "DLV_REG_GCR_DACL" ./
gedit icdc_d1.c +472
5.1/kernel-3.10.14/:
grep -nr "SOC_DOUBLE_R_TLV" ./include/ | grep define
gedit ./include/sound/soc.h +123
======================================================================
0x00000000-0x00200000 : "NAND BOOT partition" 0 16
0x00200000-0x00500000 : "NAND KERNEL partition" 16 24
0x00500000-0x01900000 : "NAND ROOTFS partition" 40 160
0x01900000-0x08000000 : "NAND YAFFS partition" 200 1024-200
>>>
nerase 0 1024
fconfig 192.168.1.12 jdi.cfg
nprog 0 u-boot-nand.bin
fconfig 192.168.1.12 jdiyaffs.cfg
nprog 512 lconfig-normal.bin
fconfig 192.168.1.12 jdi.cfg
nprog 704 linuxlogo240x400.bin
nprog 1024 uImage_ZEM565-20120201
fconfig 192.168.1.12 jdiyaffs.cfg
nprog 2560 rootfsyaffs220151020
nprog 12800 mtdyaffs2tft300-20151022
======================================================================
error while loading shared libraries: libudev.so.0: cannot open shared object file: No such file or directory
locate udev.so
ln -s /lib/i386-linux-gnu/libudev.so.1 ./libudev.so.0
======================================================================
wiegand driver
device 资源定义和注册:
arch/mips/xburst/soc-x1000/chip-x1000/zlm60/common/board_base.c
driver 注册和实现:
driver/misc/wiegand_in.c
======================================================================
dd if=/dev/zero of=/dev/mtdblock5 bs=1024 count=3000
3072000 bytes (2.9MB) copied, 3.737917 seconds, 802.6KB/s
dd if=/dev/zero of=/dev/mtdblock5 bs=1M count=4
4194304 bytes (4.0MB) copied, 3.361232 seconds, 1.2MB/s
dd if=/dev/urandom of=/dev/mtdblock5 bs=1M count=4
4194304 bytes (4.0MB) copied, 6.387169 seconds, 641.3KB/s
dd if=/dev/urandom of=/dev/mtdblock5 bs=1024 count=3000
3072000 bytes (2.9MB) copied, 6.199825 seconds, 483.9KB/s
----------------------------------------------------------------------
dd if=/dev/zero of=/data/tt bs=16k count=6000 conv=fsync
98304000 bytes (93.8MB) copied, 17.804461 seconds, 5.3MB/s
dd if=/dev/zero of=/data/tt bs=16k count=6000
98304000 bytes (93.8MB) copied, 5.389757 seconds, 17.4MB/s
dd if=/data/tt of=/dev/null bs=16k count=6000
98304000 bytes (93.8MB) copied, 4.672038 seconds, 20.1MB/s
----------------------------------------------------------------------
dd if=/dev/zero of=/data/mtdblock5 bs=16k count=6000 conv=fsync
98304000 bytes (93.8MB) copied, 17.743677 seconds, 5.3MB/s
dd if=/dev/zero of=/data/mtdblock5 bs=16k count=6000
98304000 bytes (93.8MB) copied, 5.501961 seconds, 17.0MB/s
======================================================================
linux sfcnand 驱动:
1) 设备资源
>> arch/mips/xburst/soc-x1000/common/platform.c:786
#ifdef CONFIG_JZ_SFC
static struct resource jz_sfc_resources[] = {
[0] = {
.flags = IORESOURCE_MEM, // SFC's registers map base address 0x13440000
.start = SFC_IOBASE,
.end = SFC_IOBASE + 0x10000 - 1,
},
[1] = {
.flags = IORESOURCE_IRQ,
.start = IRQ_SFC, // SFC's IRQ
},
[2] = {
.start = CONFIG_SFC_SPEED,
.flags = IORESOURCE_BUS,
}
};
struct platform_device jz_sfc_device = {
.name = "jz-sfc",
.id = 0,
.resource = jz_sfc_resources,
.num_resources = ARRAY_SIZE(jz_sfc_resources),
};
#endif
>> arch/mips/xburst/soc-x1000/common/board_base.c:19
struct jz_platform_device
{
struct platform_device *pdevices;
void *pdata;
int size;
};
>> arch/mips/xburst/soc-x1000/common/board_base.c:54
定义 platform 设备资源数组
static struct jz_platform_device platform_devices_array[] __initdata = {
#define DEF_DEVICE(DEVICE, DATA, SIZE) \
{ .pdevices = DEVICE, \
.pdata = DATA, .size = SIZE,}
#ifdef CONFIG_JZ_SFC
DEF_DEVICE(&jz_sfc_device,&sfc_info_cfg, sizeof(struct jz_sfc_info)),
展开如下:
{
.pdevices = &jz_sfc_device,
.pdata = &sfc_info_cfg,
.size = sizeof(struct jz_sfc_info),
},
#endif
};
>> arch/mips/xburst/soc-x1000/include/mach/jzssi.h:187
struct jz_sfc_info {
u8 chnl; /* the chanel of SSI controller */
u16 bus_num; /* spi_master.bus_num */
unsigned is_pllclk:1; /* source clock: 1---pllclk;0---exclk */
unsigned long board_size; /* spi_master.num_chipselect */
u32 num_chipselect;
u32 allow_cs_same;
void *board_info;
u32 board_info_size;
};
>> arch/mips/xburst/soc-x1000/common/spi_bus.c:485
#elif defined(CONFIG_JZ_SFCNAND)
struct jz_sfc_info sfc_info_cfg = {
.chnl = 0,
.bus_num = 0,
.num_chipselect = 1,
.board_info = &jz_spi_nand_data,
};
#endif
>> arch/mips/xburst/soc-x1000/common/spi_bus.c:210
struct jz_spi_nand_platform_data jz_spi_nand_data = {
.jz_spi_support = jz_spi_nand_support_table, // 程序所支持的nand,spi_bus.c:110
.num_spi_flash = ARRAY_SIZE(jz_spi_nand_support_table), //
.mtd_partition = jz_mtd_spinand_partition, // nand 的分区情况,spi_bus.c:76
.num_partitions = ARRAY_SIZE(jz_mtd_spinand_partition), //
};
jz_spi_nand_support_table=((struct jz_spi_nand_platform_data *)(flash->pdata->board_info))->jz_spi_support;
>> arch/mips/xburst/soc-x1000/common/board_base.c:281
注册设备资源:
static int __init board_base_init(void)
{
。。。
pdevices_array_size = ARRAY_SIZE(platform_devices_array);
for(i = 0; i < pdevices_array_size; i++) {
if(platform_devices_array[i].size)
platform_device_add_data(platform_devices_array[i].pdevices,
platform_devices_array[i].pdata, platform_devices_array[i].size);
platform_device_register(platform_devices_array[i].pdevices);
}
。。。
}
>> 执行以下函数之后
platform_device_add_data(platform_devices_array[i].pdevices,
platform_devices_array[i].pdata, platform_devices_array[i].size);
最终结果:
platform_devices_array[i].pdevices->dev.platform_data = &sfc_info_cfg。
2) 驱动分析
>> drivers/mtd/nand/jz_sfcnand.c:1166
static int __init jz_sfc_probe(struct platform_device *pdev)
{
struct jz_sfc_nand *flash; // 非常重要的结构!
const char *jz_probe_types[] = {"cmdlinepart",NULL};
struct jz_spi_support *spi_flash; // 存放nand flash 信息,比如:id 、块大小 、页大小 、Busytime等等
int err = 0,ret = 0;
struct nand_chip *chip; // nand 操作的函数指针
struct mtd_partition *mtd_sfcnand_partition;
int num_partitions;
struct jz_spi_nand_platform_data *param;
int nand_magic= 0;
chip = kzalloc(sizeof(struct nand_chip),GFP_KERNEL); // 分配 nand _ship 空间
if(!chip)
return -ENOMEM;
flash = kzalloc(sizeof(struct jz_sfc_nand), GFP_KERNEL); // 分配 jz_sfc_nand 空间
if (!flash) {
kfree(chip);
return -ENOMEM;
}
flash->dev = &pdev->dev; // 保存 platform_device 中的struct device 结构指针
flash->pdata = pdev->dev.platform_data; // 保存指向备的私有数据结构的指针, = &sfc_info_cfg
flash->threshold = THRESHOLD; // ?
ret=sfc_nand_plat_resource_init(flash,pdev); // 获取设备资源,初始化 jz_sfc_nand 部分成员
if(ret) // 非0 则sfc_nand_plat_resource_init() 执行过程出错
{
.... // 出错处理
}
flash->chnl= flash->pdata->chnl; //the chanel of SSI controller, 这里是 0
flash->tx_addr_plus = 0;
flash->rx_addr_plus = 0;
flash->use_dma = 0; //
err=0;
/* find and map our resources */
/* SFC controller initializations for SFC */
jz_sfc_init_setup(flash); // SFC controller initializations
platform_set_drvdata(pdev, flash);
init_completion(&flash->done); // 初始化 jz_sfc_nand 中的完成量 struct completion done = 0
spin_lock_init(&flash->lock_rxtx); //初始化 jz_sfc_nand 中的 spinlock_t lock_rxtx;
spin_lock_init(&flash->lock_status); // 初始化 jz_sfc_nand 中的 spinlock_t lock_status
err = request_irq(flash->irq, jz_sfc_irq, 0, pdev->name, flash); // flash->irq 在sfc_nand_plat_resource_init() 获得
flash->column_cmdaddr_bits=24; //
jz_get_sfcnand_param(¶m,flash,&nand_magic); // 获取烧录工具传下的参数
if(nand_magic==0x6e616e64){ //如果0x6e616e64 则使用烧录工具传下来的一套参数
(flash->pdata)->board_info = (void *)param;
}else{
param=(flash->pdata)->board_info; // 使用驱动定义的参数
}
mtd_sfcnand_partition=param->mtd_partition; // nand flash 的分区信息
num_partitions=param->num_partitions; // nand flash 的分区数量
spi_flash = jz_sfc_nand_probe(flash); // 匹配具体的 nand flash,并返回存放nand flash 信息的结构指针
// 初始化jz_sfc_nand 中的 struct mtd_info mtd
flash->mtd.name = "sfc_nand";
flash->mtd.owner = THIS_MODULE;
flash->mtd.type = MTD_NANDFLASH;
flash->mtd.flags |= MTD_CAP_NANDFLASH;
flash->mtd.erasesize = spi_flash->block_size;
flash->mtd.writesize = spi_flash->page_size;
flash->mtd.size = spi_flash->size;
flash->mtd.oobsize = spi_flash->oobsize;
flash->mtd.writebufsize = flash->mtd.writesize;
flash->column_cmdaddr_bits = spi_flash->column_cmdaddr_bits;
flash->tRD = spi_flash->tRD_maxbusy;
flash->tPROG = spi_flash->tPROG_maxbusy;
flash->tBERS = spi_flash->tBERS_maxbusy;
flash->mtd.bitflip_threshold = flash->mtd.ecc_strength = 1;
// 初始化 struct nand_chip chip
chip->select_chip = NULL;
chip->badblockbits = 8;
chip->scan_bbt = nand_default_bbt;
chip->block_bad = jz_sfcnand_block_bad_check;
chip->block_markbad = jz_sfc_nandflash_block_markbad;
//chip->ecc.layout= &gd5f_ecc_layout_128; // for erase ops
chip->bbt_erase_shift = chip->phys_erase_shift = ffs(flash->mtd.erasesize) - 1;
if (!(chip->options & NAND_OWN_BUFFERS))
chip->buffers = kmalloc(sizeof(*chip->buffers), GFP_KERNEL);
/* Set the bad block position */
if (flash->mtd.writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
else
chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
flash->mtd.priv = chip; // 初始化mtd 的私有数据指针
flash->mtd._erase = jz_sfcnand_erase;
flash->mtd._read = jz_sfcnand_read;
flash->mtd._write = jz_sfcnand_write;
flash->mtd._read_oob = jz_sfcnand_read_oob;
flash->mtd._write_oob = jz_sfcnand_write_oob;
flash->mtd._block_isbad = jz_sfcnand_block_isbab;
flash->mtd._block_markbad = jz_sfcnand_block_markbad;
chip->scan_bbt(&flash->mtd); // ?
// 注册mtd 设备
ret = mtd_device_parse_register(&flash->mtd,jz_probe_types,NULL, mtd_sfcnand_partition, num_partitions);
if (ret) {
kfree(flash);
return -ENODEV;
}
}
x-loader sfcnand 驱动分析:
#define SFC_SEND_COMMAND(sfc, a, b, c, d, e, f, g) do{ \
((struct jz_sfc *)sfc)->cmd = a; \
((struct jz_sfc *)sfc)->len = b; \
((struct jz_sfc *)sfc)->addr = c; \
((struct jz_sfc *)sfc)->addr_len = d; \
((struct jz_sfc *)sfc)->addr_plus = 0; \
((struct jz_sfc *)sfc)->dummy_byte = e; \
((struct jz_sfc *)sfc)->daten = f; \
SFC_MODE_GENERATE(sfc, a); \
sfc_send_cmd(sfc, g); \
} while(0)
git checkout --track ing/sz-master
======================================================================
uboot 的 spl(second program loader)
>> arch/mips/cpu/xburst/x1000/start.S:172
j board_init_f // 跳到board_init_f 函数,C代码
>> arch/mips/cpu/xburst/x1000/soc.c :58
void board_init_f(ulong dummy)
{
....
gpio_init();
enable_uart_clk();
timer_init();
#ifndef CONFIG_FPGA
#ifdef CONFIG_SPL_CORE_VOLTAGE
debug("Set core voltage:%dmv\n", CONFIG_SPL_CORE_VOLTAGE);
spl_regulator_set_voltage(REGULATOR_CORE, CONFIG_SPL_CORE_VOLTAGE);
#endif
#ifdef CONFIG_SPL_MEM_VOLTAGE
debug("Set mem voltage:%dmv\n", CONFIG_SPL_MEM_VOLTAGE);
spl_regulator_set_voltage(REGULATOR_MEM, CONFIG_SPL_MEM_VOLTAGE);
#endif
#endif
clk_prepare();
pll_init(); // 锁相环
clk_init(); // 时钟
sdram_init(); // 内存
board_init_r(NULL, 0); // 调用board_init_r
}
>> common/spl/spl.c:149
void board_init_r(gd_t *dummy1, ulong dummy2)
{ // 这个函数主要判断是从 nand、mmc、onenand、nor等设备加载uboot代码到初始化好的内存中
....
switch (boot_device) {
....
#ifdef CONFIG_SPL_SPI_NAND
case BOOT_DEVICE_SPI_NAND:
spl_spi_nand_load_image();
break;
#endif
#ifdef CONFIG_SPL_SFC_NOR
case BOOT_DEVICE_SFC_NOR:
spl_sfc_nor_load_image();
break;
#endif
#ifdef CONFIG_SPL_SFC_NAND
case BOOT_DEVICE_SFC_NAND:
spl_sfc_nand_load_image();
break;
#endif
.....
}
jump_to_image_no_args(&spl_image);
}
mips-linux-gnu-objcopy --remove-section=.dynsym --gap-fill=0xff --pad-to=16384 \
-I binary -O binary spl/u-boot-spl.bin spl/u-boot-spl-pad.bin
选项说明:
--remove-section=.dynsym:从输出文件中去除掉由sectionname指定的section,可以多次指定,不当会导致输出文件不可用
--gap-fill=0xff:在section之间的空隙中填充0xff
--pad-to=16384
-I binary:指定输入的文件,这里是 spl/u-boot-spl.bin
-O binary:指定输出的文件,这里是 spl/u-boot-spl-pad.bin
// 连接spl/u-boot-spl-pad.bin和u-boot.bin,生存最终烧录文件 u-boot-with-spl.bin
cat spl/u-boot-spl-pad.bin u-boot.bin > u-boot-with-spl.bin
rm spl/u-boot-spl-pad.bin
======================================================================
网卡在物理上具有载波侦听的功能,当网络连接完成或者网络链接断开时,网卡芯片硬件会自动设置寄存器标志位来标识。
如网线链接断开的时候,会将LinkSts清位;重新链接网线,则硬件自动将此位置位。
这样,在网卡驱动中读写该位信息就可一判断网络是否链接通路。
网卡驱动程序通过netif_carrier_on/netif_carrier_off/netif_carrier_ok来和内核网络子系统传递信息。
1】netif_carrier_on【作用】告诉内核子系统网络链接完整。
2】netif_carrier_off【作用】告诉内核子系统网络断开。
3】netif_carrier_ok【作用】查询网络断开还是链接。
以上函数主要是改变net_device dev的state状态来告知内核链路状态的变化。
======================================================================
ubuntu下安装卸载 VMWare Player / WorkStation (.bundle文件)
比如下载下来的VMware Player文件名为
VMware-Player-3.1.0-261024.i386.bundle
在终端中转到文件放置的目录,执行
sudo sh VMware-Player-3.1.0-261024.i386.bundle
安装就开始了。
卸载方法:
在终端中输入
sudo vmware-installer -u vmware-player
就能卸载
卸载Workstation的方法相同,输入
sudo vmware-installer -u vmware-workstation
======================================================================
UBIFS 出错:
[ 3.817188] VFS: Mounted root (ubifs filesystem) on device 0:9.
[ 3.824409] Freeing unused kernel memory: 220K (80539000 - 80570000)
Starting mount /data parttion
[ 3.944590] UBIFS: background thread "ubifs_bgt1_0" started, PID 53
[ 4.009158] UBIFS error (pid 52): ubifs_check_node: bad CRC: calculated 0xe94bab05, read 0x869acbe8
[ 4.018555] UBIFS error (pid 52): ubifs_check_node: bad node at LEB 253:82976
网上的一些见解:
UBIFS本身的机制导致它会出现这种错误,可以到http://www.linux-mtd.infradead.org/faq/ubifs.html,详细了解这个文件系统的特性和它的不足之处。
以下是我对你问题的一点理解。
1.你的根文件系统是UBIFS,可写读的。
2.在你运行Linux系统时,系统的一些服务,如日志等,可能会频繁的读写你的存储器。UBIFS对掉电的容忍性我觉得是比较差的,在异常掉电或重启后,下次重启后可能导致到UBIFS文件系统记录节点CRC和实际计算的不一致,导致你的根文件系统挂载不了。
所以我有了以下直观认识:
1.UBIFS挂载速度快,存储器寿命高。
2.UBIFS对异常掉电的容忍性差,容易出现CRC错误。
所以我以下建议:
1.将你的根文件系统设置为只读,另外建立一个可读写扩展文件系统系统分区,用于其他用途。
2.如果你坚持保留根文件系统分区为可读写,则每次通过linux命令执行关机操作,尽量避免直接切断电源。
3.或者向freescale官方咨询答案,到时候大家一起讨论共享。
针对你说的不能烧写和扩展文件系统,我有以下建议给你。
1.修改你的内核NAND flash分区,增加一个扩展文件系统分区。
2.然后通过ubifs文件系统工具将你的文件打包成ubifs固有的格式(为什么?)。
3.因为上面已经将文件打包成ubifs格式了,所以直接在uboot或类似uboot的引导程序中通过nand的命令如 nand erase、nand write等将打包后的文件直接写入对应的扩展分区中。
4.修改根文件系统,在初始化脚本中mount该扩展文件系统到根文件系统下即可
以上的正确性需要再验证
======================================================================
//没bug的分支
git checkout remotes/ingenic/ingenic-master-3.10.14
gitk pm_p0.c //相关文件
/work/m200/5.1/kernel-3.10.14/drivers/char/voice_wakeup
voice_wakeup_firmware.hex 复制出来覆盖 Indroid5.1-master 分支的
//要测试的分支
git checkout remotes/ingenic/Indroid5.1-master
//跟踪 4.3 的 remotes/ing/ingenic-master 分支关于深休的修改
remotes/ing/ingenic-master
======================================================================
MII_BMSR
phy_write(phy, MII_BMCR, ctl);
val = phy_read(phy, MII_BMCR);
======================================================================
测试Audio:
1) 播放,可查看音频文件格式信息:
aplay att.wav
2) 转化音频格式:
mpg123
mpg123 -r 8000 --8bit -m -n 50 -w road_8Khz_single_mono.wav road.mp3
mpg123 -r 22050 --8bit -k 1000 -n 2000 -w 22Khz.wav paomo.mp3
3) 重要的概念:
通道数(channel):该参数为1表示单声道,2则是立体声。
桢(frame):桢记录了一个声音单元,一个时间点上所抓取的样本,其长度为样本长度与通道数的乘积。
采样率(rate):每秒钟采样次数,该次数是针对桢而言。
周期(period):音频设备一次处理所需要的桢数,对于音频设备的数据访问以及音频数据的存储,都是以此为单位。
======================================================================
efuse:
ret = jz_efuse_write(efuse->wr_info->seg_id, efuse->wr_info->data_length, efuse->wr_info->buf);
unsigned int buf[32] = {0,1,2,3,4,5};
jz_efuse_write(USER_ID, 32, buf);
printk("===========================\n");
jz_efuse_read(USER_ID, 32, buf);
printk("PROTECT_SEG: byte1 = %u, byte2 = %u byte3 = %u, byte4 = %u\n", buf[0], buf[1],buf[2], buf[3]);
======================================================================
halley2
input: gpio-keys as /devices/platform/gpio-keys/input/input1
-----------------------------------------------------------------------------------------------
如何查看 /dev/input/eventx 对应的相关设备信息:
cat /proc/bus/input/devices
I: Bus=0019 Vendor=0000 Product=0000 Version=0000
N: Name="matrix-keypad"
P: Phys=
S: Sysfs=/devices/platform/matrix-keypad.0/input/input0
U: Uniq=
H: Handlers=event0
B: PROP=0
B: EV=100013
B: KEY=40000800 1480 0 0 ffc
B: MSC=10
I: Bus=0019 Vendor=0001 Product=0001 Version=0100
N: Name="gpio-keys"
P: Phys=gpio-keys/input0
S: Sysfs=/devices/platform/gpio-keys/input/input1
U: Uniq=
H: Handlers=event1
B: PROP=0
B: EV=3
B: KEY=200 0 0 0
在上面的H:中可以看到对应的eventx
-----------------------------------------------------------------------------------------------
/etc/mdev.conf
mdev.conf写的不对
加入下面的就可以:
# Move input devices to input directory
event.* 0:0 0660 @(mkdir -p input&&mv $MDEV input)
mice 0:0 0660 @(mkdir -p input&&mv $MDEV input)
mouse.* 0:0 0660 @(mkdir -p input&&mv $MDEV input)
关于 halley2 找不到/dev/input/event文件的解决方法,修改kernel的 halley2_nor 的配置文件,过程如下:
1) make halley2_nor_v10_linux_defconfig
2) make menuconfig
A) 使能 Event interface
Device Drivers ---->
Input device support ---->
<*> Event interface
B) 去掉支持 ext4 文件系统
File systems --->
< >The Extended 4 (ext4) support
说明: 去掉支持 ext4 文件系统的原因使编译的 uImage 小于3M,否则大于3M kernel 无法启动,因为uboot 只加载3M大小到内存。
3) make uImage
4) 烧录启动即可, ls /dev :
arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/keyboard_gpio.c
arch/mips/xburst/soc-x1000/chip-x1000/halley2/halley2_v10/board.h
sudo apt-get install automake autoconf m4 libtool gettext
sudo apt-get install libncurses5-dev libslang2-dev libselinux1-dev debhelper lsb-release pkg-config po-debconf
objdump -t path-to-library.a | grep -e __isoc99_sscanf
======================================================================
halley 2 摄像头测试:
development/testsuit/camera_process/jpg_api
libjpeg.so
out/target/product/halley2/system/lib
platform/development/testsuit/grab_source/jpeg
./cimutils -I 0 -P -v -l -w 640 -h 480
./cimutils -I 0 -P -w 640 -h 480
./cimutils -I 0 -C -v -x 640 -y 480
======================================================================
halley2 蓝牙:
启动: bt_enable
hciconfig -a
hcitool scan
obex_test -b 30:45:1C:FC:03:11 1
======================================================================
linux下查看so文件的函数列表 :
方法一:
nm查看共享库so文件中导出函数列表
查看so文件中的导出函数表;
nm -D xxx.so
列出所有导出的函数,包括 xxx.so 静态链接的库中的那些导出函数。
方法二:
objdump -tT xxx.so
======================================================================
halley2_43438_cramfs_config: unconfig mozart_prepare product_canna_v2.0_ap6212_config \
wifi_ap6212_config bt_ap6212_config bt_hci_dev_ttyS0_config \
lcd_disable_config webrtc_aec_disable_config \
audio_dev_x1000_config dmr_enable_config dms_disable_config \
airplay_enable_config localplayer_enable_config song_supplyer_ximalaya_config \
mplayer_float_config vr_speech_config vr_wakeup_key_shortpress_config \
lapsule_enable_config adb_enable_config \
rootfs_cramfs_config usrdata_jffs2_config flash_spi_gd25q128c_config
@echo "Config complete sdk with cramfs for halley2 ap6212 board"
CONFIG_JZ_HIBERNATE
/home/qwwang/work/audio/org.x1000/mozart/output/host/usr/sbin/mkfs.cramfs /home/qwwang/work/audio/org.x1000/mozart/output/fs/appfs /home/qwwang/work/audio/org.x1000/mozart/output/target/appfs.cramfs >> /home/qwwang/work/audio/org.x1000/mozart/output/target/fakeroot.fs
======================================================================
audio_recorder.cpp
webrtc_watch_aec.cpp
hardware/ingenic/audio/audio-alsa$ mm -B
out/target/product/aw808/system/lib/hw/audio.primary.watch.so
root@watch:/ # ps | grep me
media 118 1 69212 7284 ffffffff 76e82674 S /system/bin/mediaserver
logcat
logcat -v time
======================================================================
adb shell 出现如下错误:
error: insufficient permissions for device
解决方法;
kill -9 <adb 进程id>
sudo adb shell
======================================================================
HUAWEI MU709s-6:
hardware/mobiled/src/modem/configure.cpp
kernel/drivers/usb/serial/option.c
编译:mobiled
cd hardware/mobiled
mm -B
代码提交:
git push ing HEAD:refs/for/分支
======================================================================
halley2 mozart:
源码获取:
repo init -u ssh://[email protected]:29418/mirror/sdk-x1000-v1.6/linux/manifest -b sz-master-mozart
>> 重启adb
./usr/fs/etc/init.d/S99adbd.sh start
1. 打开/关闭无线网卡电源
iwconfig wlan0 txpower on
iwconfig wlan0 txpower off && ifconfig wlan0 down
linux以命令行下配置连接wlan无线网卡:
工作的大体思路如下:
用iwconfig开启无线网卡的电源,并查找区域内的无线网络
连接到相应的无线网络
通过ifconfig启用无线网卡,并获取IP(如果使用DHCP的话)
注意:
假设无线被识别为wlan0,如果您的网卡没有被识别为wlan0,可以在操作时做相应的修改。
具体过程
1. 打开无线网卡电源
iwconfig wlan0 txpower on
2. 列出区域内的无线网络
iwlist wlan0 scan
3. 假设要连接到网络MyHome(即essid为MyHome的网络),那么输入命令
iwconfig wlan0 essid "MyHome"
如果网络是加密的,密码是<PASSWORD>,那么就输入命令
iwconfig wlan0 essid "MyHome" key 0123-4567-89
4. 如果正常的话,输入
iwconfig wlan0
就可以看到连接正常的各项参数了。 5. 启用无线网卡
ifconfig wlan0 up
6. 如果是用DHCP获取IP的,那么用dhclient或dhcpcd获取ip
dhclient wlan0
或
dhcpcd wlan0
7. 现在无线网卡应该可以正常使用了
注意:一定要把NetworkManager服务停掉
======================================================================
X1000 SLCD Controller
SLCD Pins Description:
SLCD_DC: Command/Data Select Signal. I/O: Output
SLCD_WR: Data Sample Signal. I/O: Output
SLCD_RD: Smart LCD read signal. I/O: Output
SLCD_CE: Smart LCD chip select. I/O: Output
SLCD_TE: Smart LCD tearing effect signal I/O: Input
SLCD_DAT: The data of SLCD I/O: Output
-----------------------------------------------
>>>> lcd-truly_tftp240240 屏:
arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/lcd/lcd-truly_tftp240240_2_e.c:
struct lcd_platform_data truly_tft240240_pdata = {
.reset = truly_tft240240_power_reset,
.power_on = truly_tft240240_power_on,
};
/* LCD Panel Device */
struct platform_device truly_tft240240_device = {
.name = "truly_tft240240_slcd",
.dev = {
.platform_data = &truly_tft240240_pdata,
},
};
arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/board_base.c:
static struct jz_platform_device platform_devices_array[] __initdata = {
#define DEF_DEVICE(DEVICE, DATA, SIZE) \
{ .pdevices = DEVICE, \
.pdata = DATA, .size = SIZE,}
。
。
#ifdef CONFIG_LCD_TRULY_TFT240240_2_E
DEF_DEVICE(&truly_tft240240_device, 0, 0),
#endif
。
。
}
>>>> 注册设备:
static int __init board_base_init(void)
{
int pdevices_array_size, i;
pdevices_array_size = ARRAY_SIZE(platform_devices_array);
for(i = 0; i < pdevices_array_size; i++) {
if(platform_devices_array[i].size)
platform_device_add_data(platform_devices_array[i].pdevices,
platform_devices_array[i].pdata, platform_devices_array[i].size);
platform_device_register(platform_devices_array[i].pdevices);
}
。
。
return 0;
}
>>>> 对应的驱动:
drivers/video/backlight/truly_tft240240_2_e.c:
static struct platform_driver truly_tft240240_driver = {
.driver = {
.name = "truly_tft240240_slcd",
.owner = THIS_MODULE,
},
.probe = truly_tft240240_probe,
.remove = truly_tft240240_remove,
.suspend = truly_tft240240_suspend,
.resume = truly_tft240240_resume,
};
static int __init truly_tft240240_init(void)
{
return platform_driver_register(&truly_tft240240_driver);
}
-----------------------------------------------
>>>>>>> fb
arch/mips/xburst/soc-x1000/common/platform.c:
#ifdef CONFIG_FB_JZ_V13
static u64 jz_fb_dmamask = ~(u64) 0;
static struct resource jz_fb_resources[] = {
[0] = {
.start = LCDC_IOBASE,
.end = LCDC_IOBASE + 0x1800 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_LCD,
.end = IRQ_LCD,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device jz_fb_device = {
.name = "jz-fb",
.id = -1,
.dev = {
.dma_mask = &jz_fb_dmamask,
.coherent_dma_mask = 0xffffffff,
},
.num_resources = ARRAY_SIZE(jz_fb_resources),
.resource = jz_fb_resources,
};
#endif
arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/board_base.c:
static struct jz_platform_device platform_devices_array[] __initdata = {
#define DEF_DEVICE(DEVICE, DATA, SIZE) \
{ .pdevices = DEVICE, \
.pdata = DATA, .size = SIZE,}
。
。
#ifdef CONFIG_FB_JZ_V13
DEF_DEVICE(&jz_fb_device, &jzfb_pdata, sizeof(struct jzfb_platform_data)),
#endif
。
。
}
>>>> 设备注册过程同上
>>>> 对应的 fb 驱动:
drivers/video/jz_fb_v13/jz_fb.c:
。。。。
static struct platform_driver jzfb_driver = {
.probe = jzfb_probe,
.remove = jzfb_remove,
.shutdown = jzfb_shutdown,
.driver = {
.name = "jz-fb",
#ifdef CONFIG_PM
.pm = &jzfb_pm_ops,
#endif
},
};
static int __init jzfb_init(void)
{
platform_driver_register(&jzfb_driver);
return 0;
}
。。。。
-----------------------------------------------
>>>>>>>> backlight
arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/lcd/lcd-truly_tftp240240_2_e.c:
static struct platform_pwm_backlight_data backlight_data = {
.pwm_id = 0,
.max_brightness = 255,
.dft_brightness = 80,
.pwm_period_ns = 30000,
.init = backlight_init,
.exit = backlight_exit,
.notify = backlight_notify,
};
struct platform_device backlight_device = {
.name = "pwm-backlight",
.dev = {
.platform_data = &backlight_data,
},
};
arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/board_base.c:
static struct jz_platform_device platform_devices_array[] __initdata = {
#define DEF_DEVICE(DEVICE, DATA, SIZE) \
{ .pdevices = DEVICE, \
.pdata = DATA, .size = SIZE,}
。
。
#ifdef CONFIG_BACKLIGHT_PWM
DEF_DEVICE(&backlight_device, 0, 0),
#endif
。
。
}
>>>> 设备注册过程同上
>>>> 对应的 backlight 驱动:
drivers/video/backlight/pwm_bl.c:
static struct platform_driver pwm_backlight_driver = {
.driver = {
.name = "pwm-backlight",
.owner = THIS_MODULE,
},
.probe = pwm_backlight_probe,
.remove = pwm_backlight_remove,
.suspend = pwm_backlight_suspend,
.resume = pwm_backlight_resume,
};
static int __init pwm_backlight_init(void)
{
return platform_driver_register(&pwm_backlight_driver);
}
======================================================================
LED 子系统
LED GPIO 的定义:
arch/mips/xburst/soc-x1000/chip-x1000/canna/common/misc.c:
static struct gpio_led gpio_leds[] = {
{
.name = "led-bt", //名称,将在/sys/class/leds/目录下出现,代表一个LED
.gpio = GPIO_PA(8), //LED 对应的GPIO
.active_low = true, //是否对.default_state状态进行翻转,比如GPIO输出0.LED亮,而LEDS_GPIO_DEFSTATE_OFF正好等于0
.default_state = LEDS_GPIO_DEFSTATE_OFF,
.retain_state_suspended = true,
.default_trigger = NULL, //触发模式:timer、ide-disk、heartbeat、backlight、gpio、default-on等
},
}
static struct gpio_led_platform_data gpio_led_info = {
.leds = gpio_leds,
.num_leds = ARRAY_SIZE(gpio_leds),
};
struct platform_device jz_leds_gpio = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = &gpio_led_info,
},
};
struct gpio_led_platform_data {
int num_leds;
const struct gpio_led *leds;
#define GPIO_LED_NO_BLINK_LOW 0 /* No blink GPIO state low */
#define GPIO_LED_NO_BLINK_HIGH 1 /* No blink GPIO state high */
#define GPIO_LED_BLINK 2 /* Please, blink */
int (*gpio_blink_set)(unsigned gpio, int state,
unsigned long *delay_on,
unsigned long *delay_off);
};
----------------------------------------
LED 子系统的驱动:
drivers/leds/
主要文件:
# LED Core
obj-$(CONFIG_NEW_LEDS) +=led-core.o
obj-$(CONFIG_LEDS_CLASS) += led-class.o
obj-$(CONFIG_LEDS_TRIGGERS) +=led-triggers.o
# LED PlatformDrivers
obj-$(CONFIG_LEDS_GPIO) += leds-gpio.o
# LED Triggers
obj-$(CONFIG_LEDS_TRIGGER_TIMER) +=ledtrig-timer.o
obj-$(CONFIG_LEDS_TRIGGER_IDE_DISK) +=ledtrig-ide-disk.o
obj-$(CONFIG_LEDS_TRIGGER_HEARTBEAT) +=ledtrig-heartbeat.o
obj-$(CONFIG_LEDS_TRIGGER_BACKLIGHT) +=ledtrig-backlight.o
obj-$(CONFIG_LEDS_TRIGGER_GPIO) +=ledtrig-gpio.o
obj-$(CONFIG_LEDS_TRIGGER_DEFAULT_ON) += ledtrig-default-on.o
drivers/leds/leds-gpio.c:
static struct platform_driver gpio_led_driver = {
.probe = gpio_led_probe,
.remove = __devexit_p(gpio_led_remove),
.driver = {
.name = "leds-gpio",
.owner = THIS_MODULE,
.of_match_table = of_gpio_leds_match,
},
};
static int __init gpio_led_init(void)
{
return platform_driver_register(&gpio_led_driver);
}
probe 函数主要流程:
static int __devinit gpio_led_probe(struct platform_device *pdev)
{
struct gpio_led_platform_data *pdata = pdev->dev.platform_data;
struct gpio_leds_priv *priv;
int i, ret = 0;
if (pdata && pdata->num_leds) {
priv = kzalloc(sizeof_gpio_leds_priv(pdata->num_leds),
GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->num_leds = pdata->num_leds;
for (i = 0; i < priv->num_leds; i++) {
//create_gpio_led,注册GPIO LED
ret = create_gpio_led(&pdata->leds[i],
&priv->leds[i],
&pdev->dev, pdata->gpio_blink_set);
if (ret < 0) {
/* On failure: unwind the led creations */
for (i = i - 1; i >= 0; i--)
delete_gpio_led(&priv->leds[i]);
kfree(priv);
return ret;
}
}
} else {
priv = gpio_leds_create_of(pdev);
if (!priv)
return -ENODEV;
}
platform_set_drvdata(pdev, priv);
}
create_gpio_led 函数主要流程:
static int __devinit create_gpio_led(const struct gpio_led *template,
struct gpio_led_data *led_dat, struct device *parent,
int (*blink_set)(unsigned, int, unsigned long *, unsigned long *))
{
int ret, state;
led_dat->gpio = -1;
/* skip leds that aren't available */
if (!gpio_is_valid(template->gpio)) {
printk(KERN_INFO "Skipping unavailable LED gpio %d (%s)\n",
template->gpio, template->name);
return 0;
}
ret = gpio_request(template->gpio, template->name);
if (ret < 0)
return ret;
// 初始化每个LED对应的 struct gpio_led_data 结构
led_dat->cdev.name = template->name;
led_dat->cdev.default_trigger = template->default_trigger;
led_dat->gpio = template->gpio;
led_dat->can_sleep = gpio_cansleep(template->gpio);
led_dat->active_low = template->active_low;
led_dat->blinking = 0;
if (blink_set) { //blink_set = NULL, if语句不会执行
led_dat->platform_gpio_blink_set = blink_set;
led_dat->cdev.blink_set = gpio_blink_set;
}
led_dat->cdev.brightness_set = gpio_led_set; // 设定 LED
if (template->default_state == LEDS_GPIO_DEFSTATE_KEEP)
state = !!gpio_get_value(led_dat->gpio) ^ led_dat->active_low;
else
state = (template->default_state == LEDS_GPIO_DEFSTATE_ON);
led_dat->cdev.brightness = state ? LED_FULL : LED_OFF;
if (!template->retain_state_suspended)
led_dat->cdev.flags |= LED_CORE_SUSPENDRESUME;
ret = gpio_direction_output(led_dat->gpio, led_dat->active_low ^ state); //设置GPIO LED 初始状态
if (ret < 0)
goto err;
INIT_WORK(&led_dat->work, gpio_led_work);
ret = led_classdev_register(parent, &led_dat->cdev); //创建classdev设备,也即leds类中实例化一个对象
if (ret < 0)
goto err;
return 0;
err:
gpio_free(led_dat->gpio);
return ret;
}
led_classdev_register 函数主要流程:
1.加到leds_list链表中,
2.初始化blinktimer,
3.指定blink_timer的function和data,
4.设置trigger,
5.然后一个新的led设备就注册好了,就可以使用了。
int led_classdev_register(struct device *parent, struct led_classdev *led_cdev)
{
led_cdev->dev = device_create(leds_class, parent, 0, led_cdev,
"%s", led_cdev->name);
if (IS_ERR(led_cdev->dev))
return PTR_ERR(led_cdev->dev);
#ifdef CONFIG_LEDS_TRIGGERS
init_rwsem(&led_cdev->trigger_lock);
#endif
/* add to the list of leds */
down_write(&leds_list_lock);
list_add_tail(&led_cdev->node, &leds_list);
up_write(&leds_list_lock);
if (!led_cdev->max_brightness)
led_cdev->max_brightness = LED_FULL;
led_update_brightness(led_cdev);
init_timer(&led_cdev->blink_timer);
led_cdev->blink_timer.function = led_timer_function;
led_cdev->blink_timer.data = (unsigned long)led_cdev;
#ifdef CONFIG_LEDS_TRIGGERS
led_trigger_set_default(led_cdev);
#endif
printk(KERN_DEBUG "Registered led device: %s\n",
led_cdev->name);
return 0;
}
/*
* PWM LED driver data - see drivers/leds/leds-pwm.c
*/
#ifndef __LINUX_LEDS_PWM_H
#define __LINUX_LEDS_PWM_H
struct led_pwm {
const char *name;
const char *default_trigger;
unsigned pwm_id;
u8 active_low;
unsigned max_brightness;
unsigned pwm_period_ns;
};
struct led_pwm_platform_data {
int num_leds;
struct led_pwm *leds;
};
#endif
======================================================================
wifi 网络测试方法:
1. 使能wlan0
2. 增加网络热点
在文件中 增加新的内容/data/misc/wifi/wpa_supplicant.conf 如下
ctrl_interface=/data/misc/wifi/sockets
update_config=1
device_name=aw808
manufacturer=Ingenic
model_name=WATCH-RDK
model_number=WATCH-RDK
serial_number=
device_type=10-0050F204-5
config_methods=physical_display virtual_push_button
external_sim=1
#----------------------以下是新增加的热点密码及优先级 ----------------------
network={
ssid="sw1"
psk="#sz@sw1^"
key_mgmt=WPA-PSK
priority=27
}
3. reboot 或手动重启wpa_supplicant 服务
4. busybox ifconfig 即可看到分配的IP地址
wpa_supplicant -Dnl80211 -iwlan0 -cwpa_supplicant.conf
udhcpc -i wlan0
======================================================================
ack的解决思路是:1)缺省就搜索子目录;2)对常用编程语言,ack里面写好了对应哪些文件扩展名,比如perl是.pl, .pm和.pod,那么你只要指定按perl这个语言搜就行了。于是上述命令可以简化为:
ack --perl pattern
如果只想排除perl类型的文件,则可以用:
ack --noperl pattern
你可以--type-add TYPE=.ext[,ext2[,...]]或者--type-set TYPE=.ext[,ext2[,...]]来临时定制文件类型(如果要长期使用,可以修改~/.ackrc。
同时,也许你已经注意到了,其实ack也可以用来替代那一大堆find命令,用来搜索指定类型的文件本身(而不是文件内容),ack当然也支持,只需要添加-f 选项就行了:
ack -f --perl
----------------------------------------------------------------------
glark
与ack关注点不一样的是,glark跟关注文件里面的内容,举两个例子说一下:
% glark --and=2 printStackTrace catch *.java
这表示在java代码中搜索printStackTrace和catch这两个词,要求这两个词出现的位置相差不超过2行;
% glark --or catch throw *.java
这表示要求搜出包含catch或者throw的行;
% glark --and=5 cout --or double float *.c
这表示要求某行包含double或者float,然后在其上下5行内有cout出现。
======================================================================
#define PXPIN 0x00 /* PIN Level Register */
#define PXINT 0x10 /* Port Interrupt Register */
#define PXINTS 0x14 /* Port Interrupt Set Register */
#define PXINTC 0x18 /* Port Interrupt Clear Register */
#define PXMSK 0x20 /* Port Interrupt Mask Reg */
#define PXMSKS 0x24 /* Port Interrupt Mask Set Reg */
#define PXMSKC 0x28 /* Port Interrupt Mask Clear Reg */
#define PXPAT1 0x30 /* Port Pattern 1 Set Reg. */
#define PXPAT1S 0x34 /* Port Pattern 1 Set Reg. */
#define PXPAT1C 0x38 /* Port Pattern 1 Clear Reg. */
#define PXPAT0 0x40 /* Port Pattern 0 Register */
#define PXPAT0S 0x44 /* Port Pattern 0 Set Register */
#define PXPAT0C 0x48 /* Port Pattern 0 Clear Register */
#define PXFLG 0x50 /* Port Flag Register */
#define PXFLGC 0x58 /* Port Flag clear Register */
#define PXOENS 0x64 /* Port Output Disable Set Register */
#define PXOENC 0x68 /* Port Output Disable Clear Register */
#define PXPEN 0x70 /* Port Pull Disable Register */
#define PXPENS 0x74 /* Port Pull Disable Set Register */
#define PXPENC 0x78 /* Port Pull Disable Clear Register */
#define PXDSS 0x84 /* Port Drive Strength set Register */
#define PXDSC 0x88 /* Port Drive Strength clear Register */
#define PZGID2LD 0xF0 /* GPIOZ Group ID to load */
#define GPIO_BASE 0xb0010000
#define GPIO_PXPIN(n) (GPIO_BASE + (PXPIN + (n)*0x100)) /* PIN Level Register */
#define GPIO_PXINT(n) (GPIO_BASE + (PXINT + (n)*0x100)) /* Port Interrupt Register */
#define GPIO_PXINTS(n) (GPIO_BASE + (PXINTS + (n)*0x100)) /* Port Interrupt Set Register */
#define GPIO_PXINTC(n) (GPIO_BASE + (PXINTC + (n)*0x100)) /* Port Interrupt Clear Register */
#define GPIO_PXMSK(n) (GPIO_BASE + (PXMSK + (n)*0x100)) /* Port Interrupt Mask Register */
#define GPIO_PXMSKS(n) (GPIO_BASE + (PXMSKS + (n)*0x100)) /* Port Interrupt Mask Set Reg */
#define GPIO_PXMSKC(n) (GPIO_BASE + (PXMSKC + (n)*0x100)) /* Port Interrupt Mask Clear Reg */
#define GPIO_PXPAT1(n) (GPIO_BASE + (PXPAT1 + (n)*0x100)) /* Port Pattern 1 Register */
#define GPIO_PXPAT1S(n) (GPIO_BASE + (PXPAT1S + (n)*0x100)) /* Port Pattern 1 Set Reg. */
#define GPIO_PXPAT1C(n) (GPIO_BASE + (PXPAT1C + (n)*0x100)) /* Port Pattern 1 Clear Reg. */
#define GPIO_PXPAT0(n) (GPIO_BASE + (PXPAT0 + (n)*0x100)) /* Port Pattern 0 Register */
#define GPIO_PXPAT0S(n) (GPIO_BASE + (PXPAT0S + (n)*0x100)) /* Port Pattern 0 Set Register */
#define GPIO_PXPAT0C(n) (GPIO_BASE + (PXPAT0C + (n)*0x100)) /* Port Pattern 0 Clear Register */
#define GPIO_PXFLG(n) (GPIO_BASE + (PXFLG + (n)*0x100)) /* Port Flag Register */
#define GPIO_PXFLGC(n) (GPIO_BASE + (PXFLGC + (n)*0x100)) /* Port Flag clear Register */
#define GPIO_PXPE(n) (GPIO_BASE + (PXPE + (n)*0x100)) /* Port Pull Disable Register */
#define GPIO_PXPES(n) (GPIO_BASE + (PXPES + (n)*0x100)) /* Port Pull Disable Set Register */
#define GPIO_PXPEC(n) (GPIO_BASE + (PXPEC + (n)*0x100)) /* Port Pull Disable Clear Register */
#define GPIO_PA(n) (0*32 + n)
#define GPIO_PB(n) (1*32 + n)
#define GPIO_PC(n) (2*32 + n)
#define GPIO_PD(n) (3*32 + n)
static void gpio_direction_output(unsigned int gpio, unsigned int value)
{
unsigned int port = gpio/32;
unsigned int pin = gpio%32;
*(volatile unsigned int *)GPIO_PXINTC(port) = 1 << pin;
*(volatile unsigned int *)GPIO_PXMSKS(port) = 1 << pin;
*(volatile unsigned int *)GPIO_PXPAT1C(port) = 1 << pin;
if(value)
*(volatile unsigned int *)GPIO_PXPAT0S(port) = 1 << pin;
else
*(volatile unsigned int *)GPIO_PXPAT0C(port) = 1 << pin;
}
void dump_gpio_status (unsigned int port, unsigned int pin)
{
unsigned pxpin = *(volatile unsigned int *) (GPIO_BASE + port * 0x100 );
unsigned pxint = *(volatile unsigned int *) (GPIO_BASE + port * 0x100 + 0x10);
unsigned pxmsk = *(volatile unsigned int *) (GPIO_BASE + port * 0x100 + 0x20);
unsigned pxpat1 = *(volatile unsigned int *) (GPIO_BASE + port * 0x100 + 0x30);
unsigned pxpat0 = *(volatile unsigned int *) (GPIO_BASE + port * 0x100 + 0x40);
//unsigned pxpen = *(volatile unsigned int *) (GPIO_BASE + port * 0x100 + 0x70);
int int_f, mask_f, pat0_f, pat1_f, pen_f;
int_f = pxint & (1<<pin);
mask_f = pxmsk & (1<<pin);
pat0_f = pxpat0 & (1<<pin);
pat1_f = pxpat1 & (1<<pin);
if (!int_f && mask_f && !pat1_f && !pat0_f)
printf(">>> port: %d, pin: %d -- output 0 <<<\n", port, pin);
else if (!int_f && mask_f && !pat1_f && pat0_f)
printf(">>> port: %d, pin: %d -- output 1 <<<\n", port, pin);
else
printf(">>> port: %d, pin: %d -- unkown status <<<\n", port, pin);
}
======================================================================
sz-mozart 摄像头 cim_core
设备:
1) arch/mips/xburst/soc-x1000/include/mach/platform.h:
#define CIM_PORTA \
{ .name = "cim", .port = GPIO_PORT_A, .func = GPIO_FUNC_2, .pins = 0xfff << 8, }
2) arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/board_base.c:
struct jz_gpio_func_def platform_devio_array[] = {
.
.
#if defined(CONFIG_VIDEO_JZ_CIM_HOST) || defined (CONFIG_JZ_CIM_CORE)
CIM_PORTA,
#endif
.
}
#if defined(CONFIG_VIDEO_JZ_CIM_HOST) || defined(CONFIG_JZ_CIM_CORE)
static struct resource jz_cim_resources[] = {
[0] = {
.flags = IORESOURCE_MEM,
.start = CIM_IOBASE,
.end = CIM_IOBASE + 0x10000 - 1,
},
[1] = {
.flags = IORESOURCE_IRQ,
.start = IRQ_CIM,
}
};
struct platform_device jz_cim_device = {
.name = "jz-cim",
.id = 0,
.resource = jz_cim_resources,
.num_resources = ARRAY_SIZE(jz_cim_resources),
};
#endif
3) arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/board_base.c:
static struct jz_platform_device platform_devices_array[] __initdata = {
#define DEF_DEVICE(DEVICE, DATA, SIZE) \
{ .pdevices = DEVICE, \
.pdata = DATA, .size = SIZE,}
#ifdef CONFIG_JZ_CIM_CORE
DEF_DEVICE(&jz_cim_device, 0, 0),
#endif
}
sensor-gc2155:
1) arch/mips/xburst/soc-x1000/chip-x1000/halley2/halley2_v20/board.h
#ifdef CONFIG_JZ_CAMERA_SENSOR
#define FRONT_CAMERA_INDEX 0
#define BACK_CAMERA_INDEX 1
#define CAMERA_SENSOR_RESET GPIO_PD(5)
#define CAMERA_FRONT_SENSOR_PWDN GPIO_PD(4)
#define CAMERA_VDD_EN GPIO_PD(3)
#endif
2) arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/i2c_bus.c
#ifdef CONFIG_JZ_CAMERA_SENSOR
static int sensor_gc2155_early_init(void)
{
int ret = -1;
if (!gpio_is_valid(CAMERA_VDD_EN)) {
pr_err("%s %d: GPIO CAMERA_VDD_EN is invalid\n", __func__, __LINE__);
return -1;
}
ret = gpio_request(CAMERA_VDD_EN, "gc2155_vdd_en");
if (ret < 0) {
pr_err("%s %d: CAMERA_VDD_EN request failed\n", __func__, __LINE__);
return -1;
}
if (!gpio_is_valid(CAMERA_FRONT_SENSOR_PWDN)) {
pr_err("%s %d: GPIO CAMERA_FRONT_SENSOR_PWDN is invalid\n", __func__, __LINE__);
return -1;
}
ret = gpio_request(CAMERA_FRONT_SENSOR_PWDN, "gc2155_front_power_pwdn");
if (ret < 0) {
pr_err("%s %d: CAMERA_FRONT_SENSOR_PWDN request failed\n", __func__, __LINE__);
return -1;
}
if (!gpio_is_valid(CAMERA_SENSOR_RESET)) {
pr_err("%s %d: GPIO CAMERA_SENSOR_RESET is invalid\n", __func__, __LINE__);
return -1;
}
ret = gpio_request(CAMERA_SENSOR_RESET, "gc2155_sensor_reset");
if (ret < 0) {
pr_err("%s %d: CAMERA_SENSOR_RESET request failed\n", __func__, __LINE__);
return -1;
}
return 0;
}
static void sensor_gc2155_reset(void)
{
gpio_direction_output(CAMERA_VDD_EN, 1);
gpio_direction_output(CAMERA_SENSOR_RESET, 0);
mdelay(250);
gpio_direction_output(CAMERA_SENSOR_RESET, 1);
mdelay(250);
}
static void sensor_gc2155_power_on(int value)
{
gpio_direction_output(CAMERA_VDD_EN, value);
/* enable or disable the camera */
gpio_direction_output(CAMERA_FRONT_SENSOR_PWDN, value ? 0 : 1);
mdelay(150);
}
static struct cim_sensor_plat_data gc2155_pdata = {
.name = "sensor-gc2155",
.gpio_en = CAMERA_VDD_EN,
.init = sensor_gc2155_early_init,
.reset = sensor_gc2155_reset,
.power_on = sensor_gc2155_power_on,
};
#endif
#if (defined(CONFIG_SOFT_I2C0_GPIO_V12_JZ) || defined(CONFIG_I2C0_V12_JZ))
struct i2c_board_info jz_i2c0_devs[] __initdata = {
....
#ifdef CONFIG_JZ_CAMERA_SENSOR
{
I2C_BOARD_INFO("sensor", 0x3c),
.platform_data = &gc2155_pdata,
},
#endif
};
int jz_i2c0_devs_size = ARRAY_SIZE(jz_i2c0_devs);
#endif
3) arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/board_base.c
static int __init board_base_init(void)
{
int pdevices_array_size, i;
。。。。
#if (defined(CONFIG_SOFT_I2C0_GPIO_V12_JZ) || defined(CONFIG_I2C0_V12_JZ))
i2c_register_board_info(0, jz_i2c0_devs, jz_i2c0_devs_size);
#endif
return 0;
}
驱动:
1) drivers/char/jz_cim_core.c:
======================================================================
sz-halley2 camera
sensor-ov7740
1)
#ifdef CONFIG_VIDEO_JZ_CIM_HOST_V13
#define FRONT_CAMERA_INDEX 0
#define BACK_CAMERA_INDEX 1
#define CAMERA_SENSOR_RESET GPIO_PD(5)
#define CAMERA_FRONT_SENSOR_PWDN GPIO_PD(4)
#define CAMERA_VDD_EN GPIO_PD(3)
#endif
struct soc_camera_desc icdesc_front = {
.host_desc = {
.bus_id = CIM0,
.board_info = &jz_i2c0_devs[FRONT_CAMERA_INDEX],
.i2c_adapter_id = 0,
},
.subdev_desc = {
.power = front_camera_sensor_power,
.reset = camera_sensor_reset_front,
.drv_priv = &ov772x_priv_front,
},
};
3) 摄像头初始化时,没有将数据写入I2C,一般问题会出现在哪里?
SENSOR的各路电源是否接好,
CMCLK是否正确
RESET sensor
I2C总线上拉电阻是否匹配正确,
访问sensor时使用的 device ID是否正确, (注意7位地址和8位地址)
I2C的时钟CLK速率是否太高,
两次I2C连续读写之间是否有spec规定的delay时间
CAMERA POWER UP 时序是否符合 SPEC。
4) 编写测试代码过程中常见的问题
● 摄像头寄存器的配置
因为摄像头有很多寄存器,可能一下无法理解里面所有的配置含义,所以开始时希望得到一份可用的配置。但往往从别人的测试代码中拿到配置后,仍然无法使用。我这里列出几个可能的原因:
(a)摄像头中的图像输出格式和你在camera控制器中设置的不一致,同一个摄像头可以设置多种输入格式,如:YCbYCr或CbYCrY。
(b)图像输出的一些时序和你的camera控制器设置不一致,摄像头可以设置一些时序,如:图像数据在CAMPCLK的上升沿有效还是下降沿有效。
(c)注意输出图像的格式和Framebuffer控制器的匹配,如字节顺序等问题
(d)图像属性设置,比如宽高是否超范围或是否为4/8 整数倍。
(e)查看图像,RGB格式的数据,可以直接丢到LCD显示,验证图像效果。YUV可以用专门的YUV工具查看,或者用Photoshop查看。
(f)camera控制器中,隔行,逐行的控制位设置。
5) Camera 测试
a)照相:cimutils -I 0 -C -v -x 320 -y 240、 cimutils -I 0 -C -v -x 640 -y 480
b)预览:cimutils -I 0 -P -w 320 -h 240
c)预览并照相:/cimutils -I 0 -P -v -l -w 320 -h 240
d)获取帮助:cimutils --help
======================================================================
VIM Ack基本使用
常用参数:
-i 忽略大小写
-v 显示不匹配行
-w 强制匹配整个单词
-l 打印匹配的文件名
-L 打印不匹配的文件名
-m 在每个文件中最多匹配多少行就停止搜索
-c 显示匹配的总行数
然后在Vim中输入 :Ack test_blah 便可以在当前项目代码中搜索 "test_blah" 了
常用快捷键如下:
? 帮助,显示所有快捷键
Enter/o 打开文件
O 打开文件并关闭Quickfix
go 预览文件,焦点仍然在Quickfix
t 新标签页打开文件
q 关闭Quickfix
可以在 ~/.vimrc 中为 :Ack 设置一个快捷键:
map <c-u> :Ack<space>
以后在普通模式下输入 Ctrl+U 便可以自动输入 :Ack 了
配置个热键:
参考 http://vim.wikia.com/wiki/Word_under_cursor_for_command
:map <F8> "zyw:exe "Ack ".@z.""<CR>
不配热键也可以:
:Ack <Ctrl + R + W> 就能把光标下的当前单词放进VIM命令行了
" 映射成<Ctrl-TAB>打开下一个TAB, <Alt-1>打开第一个TAB, <Alt-2>打开第二个, ...
if has("gui_running")
:map <silent> <C-S> :if expand("%") == ""<CR>:browse confirm w<CR>:else<CR>:confirm w<CR>:endif<CR>
noremap <M-1> 1gt
noremap <M-2> 2gt
noremap <M-3> 3gt
noremap <M-4> 4gt
noremap <M-5> 5gt
noremap <M-6> 6gt
noremap <M-7> 7gt
noremap <M-8> 8gt
noremap <M-9> 9gt
noremap <M-0> 10gt
noremap <C-TAB> gt
noremap <C-F4> <ESC>:bd<CR>
noremap qt <ESC>:bd<CR>
au BufEnter * simalt ~x "maximum the initial window
else
colorscheme desert"torte
endif
1.NERDTree与右边编辑区的Tabbar切换focus为 ctrl+w+h ctr+w+l
2.也可以直接ctr+w 多次切换
3.Tabbar切换tab esc+[Number]
4.关闭tab :bd 回车清除内容,再回车关闭tab
5.关闭所有tab :qa!
6.NERDTree与右边编辑区的Tabbar切换focus为 ctrl+h ctr+l
7.Tabbar切换 ctrl+tab 上一下,下一个tab的切换,直接鼠标双击切换tab,直接跳转到[Number]的tab上,还没有找到。。。
8.关闭同上
ctags:
找到 tag:1/3 或更多
在跳转到一个函数或者一个变量的定义处时,经常有多处地方定义了相同名字,需要定位正确的定义地方。
:ts 或 tselect 查看有相同地方的定义
:tn或tnext 查找下一个定义地方。
:tp 查找上一个地方。
:tfirst 到第一个匹配
:tlast 到最后一个匹配
:tags 查看到达当前位置所经过的标签路径
ta xxx 跳转到标签 xxx 定义的地方
:stag xxx 在分割窗口中查看包含 xxx 的文件
======================================================================
获取31服务器上的Manhhatan/halley2代码:
repo init -u ssh://[email protected]:29418/mirror/Manhhatan/halley2/platform/manifest.git -b ingenic-linux-kernel3.10.14-halley2-v2.0-20160905 -m boards/halley2.xml
----------------------------------------------------------------------
获取31服务器上的mozart代码:
repo init -u ssh://[email protected]:29418/mirror/sdk-x1000-v1.6/linux/manifest -b sz-master-mozart
repo init -u ssh://[email protected]:29418/mirror/sdk-x1000-v1.6/linux/manifest -b speaker-master-x1000
repo init -u ssh://[email protected]:29418/mirror/sdk-x1000-v1.6/linux/manifest -b speaker-master-x1000 -m master.xml
网盘下载:
链接: http://pan.baidu.com/s/1c0Dae0g 密码: <PASSWORD>
kernel:
./git/config:
[core]
repositoryformatversion = 0
filemode = true
[remote "ing"]
url = ssh://[email protected]:29418/mirror/sdk-x1000-v1.6/android/kernel/kernel-3.0.8
review = https://review.ingenic.cn/
projectname = android/kernel/kernel-3.0.8
fetch = +refs/heads/*:refs/remotes/ing/*
[remote "bj"]
url = ssh://[email protected]:29418/android/kernel/kernel-3.0.8
review = https://review.ingenic.cn/
projectname = android/kernel/kernel-3.0.8
fetch = +refs/heads/*:refs/remotes/ing/*
push = HEAD:refs/for/speaker-master-x1000
uboot:
.git/config:
[core]
repositoryformatversion = 0
filemode = true
[remote "ing"]
url = ssh://[email protected]:29418/mirror/sdk-x1000-v1.6/bootloader/u-boot
review = https://review.ingenic.cn/
projectname = bootloader/u-boot
fetch = +refs/heads/*:refs/remotes/ing/*
[remote "bj"]
url = ssh://[email protected]:29418/bootloader/u-boot
review = https://review.ingenic.cn/
projectname = bootloader/u-boot
fetch = +refs/heads/*:refs/remotes/ing/*
push = HEAD:refs/for/speaker-master-x1000
----------------------------------------------------------------------
#define CONFIG_BOOTCOMMAND "bootx sfc 0x80f00000 0xd00000" 这一行(大概在159行),
0xd00000 这个值没有修改正确,计算方法:updater分区大小 + appfs 分区起始地址
----------------------------------------------------------------------
grep 设置默认跳过的目录和文件的方法:
修改:~/.profile,添加如下一行:
export GREP_OPTIONS="--exclude-dir=\.git --exclude=.tags* --exclude=tags"
----------------------------------------------------------------------
Makefile有三个非常有用的变量。分别是$@,$^,$<代表的意义分别是:
$@--目标文件,$^--所有的依赖文件,$<--第一个依赖文件。
======================================================================
应用层:
open("/dev/dsp3", O_RDONLY);
驱动:
xb_snd_dsp_open
xb_snd_dsp_ioctl
应用层:
open("/dev/mixer3", O_RDONLY);
驱动:
xb_snd_mixer_open
xb_snd_mixer_ioctl
======================================================================
交叉编译opencv
报错解决:
Linking CXX shared library ../../lib/libopencv_core.so
/opt/toolchains/mips-gcc472-glibc216/bin/../lib/gcc/mips-linux-gnu/4.7.2/../../../../mips-linux-gnu/bin/ld: ../../3rdparty/lib/libzlib.a(gzclose.c.obj): relocation R_MIPS_26 against `gzclose_w' can not be used when making a shared object; recompile with -fPIC
../../3rdparty/lib/libzlib.a: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
make[2]: *** [lib/libopencv_core.so] 错误 1
解决方法,修改build/CmakeCache.txt, 如下:
1) CMAKE_CXX_FLAGS:STRING=-fPIC,大概163行
2) CMAKE_C_FLAGS:STRING=-fPIC , 大概183行
运行运用找不到库的问题:
error while loading shared libraries: ../../lib/libopencv_core.so的解决方法
readelf -d libopencv_highgui.so
Dynamic section at offset 0x50580 contains 30 entries:
Tag Type Name/Value
0x00000001 (NEEDED) Shared library: [../../lib/libopencv_core.so]
0x00000001 (NEEDED) Shared library: [../../lib/libopencv_imgproc.so]
0x00000001 (NEEDED) Shared library: [libstdc++.so.6]
0x00000001 (NEEDED) Shared library: [libm.so.6]
0x00000001 (NEEDED) Shared library: [libgcc_s.so.1]
0x00000001 (NEEDED) Shared library: [libc.so.6]
0x0000000c (INIT) 0xa410
0x0000000d (FINI) 0x49ed4
0x00000019 (INIT_ARRAY) 0x50000
0x0000001b (INIT_ARRAYSZ) 12 (bytes)
0x0000001a (FINI_ARRAY) 0x5000c
......
解决方法:
1) vi toolchain.cmake, 内容如下:
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR mips)
set(CMAKE_C_COMPILER mipsel-linux-gcc)
set(CMAKE_CXX_COMPILER mipsel-linux-g++)
set(CMAKE_FIND_ROOT_PATH "/opt/toolchains/mipsel-buildroot-linux-gnu/usr")
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
2) cmake -DCMAKE_TOOLCHAIN_FILE=toolchain.cmake ../opencv-2.4.13/
3) ccmake .
======================================================================
/*#define CONFIG_LCD*/
#define CONFIG_GPIO_PWR_WAKE GPIO_PB(31)
#define CONFIG_GPIO_PWR_WAKE_ENLEVEL 0
#ifdef CONFIG_LCD
#define LCD_BPP 5
#define SOC_X1000
#define CONFIG_JZ_PWM
#define CONFIG_GPIO_LCD_PWM GPIO_PC(25)
#define CONFIG_LCD_GPIO_FUNC1_SLCD
#define CONFIG_JZ_LCD_V13
#define CONFIG_SYS_WHITE_ON_BLACK
#define CONFIG_SYS_PWM_PERIOD 10000 /* Pwm period in ns */
#define CONFIG_SYS_PWM_CHN 0 /* Pwm channel ok */
#define CONFIG_SYS_PWM_FULL 255
#define CONFIG_SYS_BACKLIGHT_LEVEL 80 /* Backlight brightness is (80 / 256) */
#define CONFIG_SYS_CONSOLE_INFO_QUIET
#define CONFIG_SYS_CONSOLE_IS_IN_ENV
#define CONFIG_VIDEO_TRULY_TFT240240_2_E
#ifdef CONFIG_VIDEO_TRULY_TFT240240_2_E
#define CONFIG_GPIO_LCD_RD GPIO_PB(16)
#define CONFIG_GPIO_LCD_RST GPIO_PD(0)
#define CONFIG_GPIO_LCD_CS GPIO_PB(18)
#define CONFIG_GPIO_LCD_BL GPIO_PD(1)
#endif /* CONFIG_VIDEO_TRULY_TFT240240_2_E */
/*#define CONFIG_LCD_LOGO*/
/*#define CONFIG_RLE_LCD_LOGO*/
/*#define CONFIG_LCD_INFO_BELOW_LOGO*/ /*display the console info on lcd panel for debugg*/
#ifdef CONFIG_RLE_LCD_LOGO
#define CONFIG_CMD_BATTERYDET /*detect battery and show charge logo*/
#define CONFIG_CMD_LOGO_RLE /*display the logo using rle command*/
#endif
#endif /* CONFIG_LCD */
======================================================================
#ifndef CONFIG_LCD_DK_ST7789H2
#define SLCDC_PORTAB_8BIT \
{ .name = "slcd", .port = GPIO_PORT_A, .func = GPIO_FUNC_1, .pins = 0xff, }, \
{ .name = "slcd", .port = GPIO_PORT_B, .func = GPIO_FUNC_1, .pins = 0x1a << 16, }
#else
#define SLCDC_PORTAB_8BIT \
{ .name = "slcd", .port = GPIO_PORT_A, .func = GPIO_FUNC_1, .pins = 0xff, }, \
{ .name = "slcd", .port = GPIO_PORT_B, .func = GPIO_FUNC_1, .pins = 0x12 << 16, }
#endif
======================================================================
tar.xz 文件压缩与解压:
1) xz压缩文件方法或命令:
xz -z 要压缩的文件
如果要保留被压缩的文件加上参数 -k ,如果要设置压缩率加入参数 -0 到 -9调节压缩率。如果不设置,默认压缩等级是6.
2) xz解压文件方法或命令:
xz -d 要解压的文件
同样使用 -k 参数来保留被解压缩的文件。
3)创建或解压tar.xz文件的方法:
习惯了 tar czvf 或 tar xzvf 的人可能碰到 tar.xz也会想用单一命令搞定解压或压缩。
其实不行 tar里面没有征对 xz格式的参数, 比如 z是针对 gzip,j是针对 bzip2。
创建tar.xz文件:只要先 tar cvf xxx.tar xxx/ 这样创建xxx.tar文件先,然后使用 xz -z xxx.tar 来将 xxx.tar压缩成为 xxx.tar.xz
解压tar.xz文件:先 xz -d xxx.tar.xz 将 xxx.tar.xz解压成 xxx.tar 然后,再用 tar xvf xxx.tar来解包
======================================================================
根文件系统,网络已经连接,并且 网关、DNS 已经配置可以 ping通 域名的IP, 无法 ping通 域名的解决方法:
问题原因:
因为缺少几个必要的库和配置文件:/etc/nsswitch.conf, /lib/libnss_dns*, /lib/libnss_files*, and /lib/libresolv*
实测: /etc/nsswitch.conf 可以没有
======================================================================
配置编译strace
1) 配置:
./configure ARCH=mips CROSS_COMPILE=mips-linux-gnu- --prefix=`pwd` --host=mipsel-linux CC=mips-linux-gnu-gcc LD=mips-linux-gnu-ld CFLAGS="-EL -mabi=32 -mhard-float -march=mips32r2 -Os"
2) 编译:
make LDLIBS="-Wl -EL -W1 -start-group -lc -lnss_file -lnss_dns -lresolv -W1 -end-group"
3) 去掉符号信息
mips-linux-gnu-strip strace
======================================================================
shell 判断字符串为空
主要有以下几种方法:
echo “$str”|awk '{print length($0)}'
expr length “$str”
echo “$str”|wc -c
但是第三种得出的值会多1,可能是把结束符也计算在内了
判断字符串为空的方法有三种:
if [ "$str" = "" ]
if [ x"$str" = x ]
if [ -z "$str" ] (-n 为非空)
注意:变量都要带双引号,否则有些命令会报错,养成好习惯吧!
test或[ ]的注意事项
1、在中括号 [] 内的每个组件都需要有空白键来分隔
2、在中括号内的变量,最好都以双引号括号起来
3、在中括号内的常数,最好都以单或双引号括号起来
======================================================================
printk("### %s: %s -- %d ###\n",__FILE__, __FUNCTION__, __LINE__);
# echo 250 > brightness
[ 97.473346] ### drivers/leds/led-class.c: led_brightness_store -- 51 ###
[ 97.480682] ### brightness = 250, period = 30000, max = 255 duty = 29411 pwm->flags = 6 ###
[ 97.489358] ### drivers/leds/leds-pwm.c: __led_pwm_set -- 46 111
[ 97.495550] ### drivers/pwm/core.c: pwm_config -- 407 ###
[ 97.501156] ### drivers/pwm/pwm-jz.c: jz_pwm_config -- 100 pwm_id = 4 ###
[ 97.508240] ### tcu_device->pwm_flag = 6 ###
[ 97.512665] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_as_timer_config -- 266 ###
[ 97.520931] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_set_start_state -- 141 ###
[ 97.529196] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_set_pwm_shutdown -- 130 ###
[ 97.537534] ### arch/mips/xburst/soc-x1000/common/tcu.c: set_tcu_full_half_value -- 122 ###
[ 97.546157] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_select_division_ratio -- 153 ###
[ 97.554961] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_pwm_output_enable -- 76 ###
[ 97.563317] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_select_clk -- 170 ###
[ 97.571134] ### drivers/pwm/pwm-jz.c: jz_pwm_config -- 156 OK
[ 97.577054] ### drivers/leds/leds-pwm.c: __led_pwm_set -- 54 enable
[ 97.583528] ### drivers/pwm/pwm-jz.c: jz_pwm_disable -- 176 ###
[ 97.589643] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_disable -- 357 ###
[ 97.597175] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_shutdown_counter -- 97 ###
[ 97.605437] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_pwm_output_disable -- 90 ###
[ 97.613880] ### drivers/pwm/core.c: pwm_enable -- 440 aaa
[ 97.619456] ### drivers/pwm/pwm-jz.c: jz_pwm_enable -- 165 ###
[ 97.625467] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_enable -- 338 ###
[ 97.632925] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_pwm_output_enable -- 76 ###
[ 97.641277] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_enable -- 346 ###
--------------------------------------------------------------------------------------------
tcu_as_timer_config() {
tcu_set_start_state() {
stop conuting up;
The clock supplies to timer x is supplied;
set TCSRx = 0;
tcu_set_pwm_shutdown() {
set TCSRx.SD;
}
}
set TCNTx = 0; //Timer counter regiter
set_tcu_full_half_value() {
set TDFRx = period;
set TDHRx = duty;
}
tcu_select_division_ratio() {
tmp = regr(TCSRx);
regw((tmp | CSR_DIVx), TCSRx)
}
tcu_pwm_output_enable(id) {
if (id > 4) {
pr_err("TCU %d is not support PWM output\n", id);
dump_stack();
return -ENXIO;
}
tmp = regr(CH_TCSR(id));
regw((tmp | TCSR_PWM_EN), CH_TCSR(id));
}
tcu_select_clk(int id, int clock) {
int tmp;
tmp = regr(CH_TCSR(id));
switch (clock) {
case EXT_EN: regw((tmp | CSR_EXT_EN), CH_TCSR(id)); break;
case RTC_EN: regw((tmp | CSR_RTC_EN), CH_TCSR(id)); break;
case PCLK_EN: regw((tmp | CSR_PCK_EN), CH_TCSR(id)); break;
case CLK_MASK:
regw((tmp & (~CSR_CLK_MSK)), CH_TCSR(id));
}
}
}
pwm-beeper ===>>
#if defined(CONFIG_INPUT_PWM_BEEPER) && defined(PWM_BEEPER_PORT)
struct platform_device pwm_beeper_device = {
.name = "pwm-beeper",
.dev = {
.platform_data = (unsigned long *)PWM_BEEPER_PORT,
},
};
#endif
/* tcu->half_num = tcu->full_num, indicated duty = 0 */
if (tcu->half_num == tcu->full_num) {
if (tcu->io_func != (tcu->init_level ? GPIO_OUTPUT1 : GPIO_OUTPUT0)) {
tcu->io_func = tcu->init_level ? GPIO_OUTPUT1 : GPIO_OUTPUT0;
jzgpio_set_func(tcu->gpio_def->port, tcu->io_func, tcu->gpio_def->pins);
pr_debug("%s -- line = %d, tcu->io_func = %s\n", __FUNCTION__, __LINE__, \
tcu->io_func == GPIO_OUTPUT1 ? "GPIO_OUTPUT1" : "GPIO_OUTPUT0");
}
} else if (tcu->half_num == 0) { /* tcu->half_num = 0, indicated duty = 100% */
if (tcu->io_func != (tcu->init_level ? GPIO_OUTPUT0 : GPIO_OUTPUT1)) {
tcu->io_func = tcu->init_level ? GPIO_OUTPUT0 : GPIO_OUTPUT1;
jzgpio_set_func(tcu->gpio_def->port, tcu->io_func, tcu->gpio_def->pins);
pr_debug("%s -- line = %d, tcu->io_func = %s\n", __FUNCTION__, __LINE__, \
tcu->io_func == GPIO_OUTPUT0 ? "GPIO_OUTPUT0" : "GPIO_OUTPUT1");
}
} else {
if (tcu->io_func != tcu->gpio_def->func) {
tcu->io_func = tcu->gpio_def->func;
jzgpio_set_func(tcu->gpio_def->port, tcu->io_func, tcu->gpio_def->pins);
}
}
======================================================================
#include <soc/cpm.h>
#include <soc/base.h>
#define CPM_CLKGR_CIM (1 << 22)
unsigned int reg_clkgr = cpm_inl(CPM_CLKGR);
unsigned int gate = CPM_CLKGR_CIM;
reg_clkgr |= gate;
cpm_outl(reg_clkgr, CPM_CLKGR);
printk("CPM_CLKGR = 0x%08x\n", cpm_inl(CPM_CLKGR));
======================================================================
解压cpio文件
cpio -idmv < filename.cpio
同样可以解压img文件:
cpio -idmv < filename.img
cpio 备份命令
备份:cpio -covB > [file|device] 将数据备份到文件或设备上
还原:cpio -icduv < [file|device} 将数据还原到系统中
常用参数:
-o :将数据copy到文件或设备上
-i :将数据从文件或设备上还原到系统中
-t :查看cpio建立的文件或设备内容
-c :一种比较新的portable format方式存储
-v :在屏幕上显示备份过程中的文件名
-B :让预设的blocks可以增加到5120bytes,默认是512bytes,这样可以使备份速度加快
-d :自动建立目录,这样还原时才不会出现找不到路径的问题
-u :更新,用较新的文件覆盖旧的文件
cpio常与find 配合使用
先解开 root-nand.cpio
mkdir root-nand
cd root-nand
sudo cpio -idm < ../root-nand.cpio
cp -a ../recovery sbin/
重新打包
find ./ -print | cpio -H newc -ov > ../root-nand.cpio
======================================================================
ov5640 sysclock registers:
0x3034:
Bit[7]: Debug mode
Bit[6:4]: PLL charge pump control
Bit[3:0]:
MIPI bit mode
0x8: 8-bit mode
0xA: 10-bit mode
Others: Debug mode
0x3035:
Bit[7:4]: System clock divider
Slow down all clocks
Bit[3:0]: Scale divider for MIPI
MIPI PCLK/SERCLK can be slowed down
0x3036:
Bit[7:0]: PLL multiplier (4~252)
Can be any integer from 4~127
and only even integers from 128~252
0x3067:
Bit[7:5]: Debug mode
Bit[4]: PLL root divider
0: Bypass
1: Divided by 2
Bit[3:0]: PLL pre-divider
1,2,3,4,6,8
0x3108:
Pad Clock Divider for SCCB Clock
Bit[7:6]: Debug mode
Bit[5:4]: PCLK root divider
00: PCLK = pll_clki
01: PCLK = pll_clki/2
10: PCLK = pll_clki/4
11: PCLK = pll_clki/8
Bit[3:2]: sclk2x root divider
00: SCLK2x = pll_clki
01: SCLK2x = pll_clki/2
10: SCLK2x = pll_clki/4
11: SCLK2x = pll_clki/8
Bit[1:0]: SCLK root divider
00: SCLK = pll_clki
01: SCLK = pll_clki/2
10: SCLK = pll_clki/4
11: sclk = pll_clki/8
======================================================================
linux spi应用程序编写步骤:
第一:open
第二:ioctl ,ioctl有九种cmd,分别对应不同的arg
a、设置或获取SPI工作模式
SPI_IOC_RD_MODE //读 模式
SPI_IOC_WR_MODE //写 模式
以上两种cmd对用arg是spi_device.mode
spi_device.mode有以下几种类型
#define SPI_MODE_0 (0|0) //SCLK空闲时为低电平,串行同步时钟的前沿(上升)数据被采样
#define SPI_MODE_1 (0|SPI_CPHA)//SCLK空闲时为高电平,串行同步时钟的前沿(下降)数据被采样
#define SPI_MODE_2 (SPI_CPOL|0)//SCLK空闲时为低电平,串行同步时钟的后沿(上升)数据被采样
#define SPI_MODE_3 (SPI_CPOL|SPI_CPHA)//SCLK空闲时为高电平,串行同步时钟的后沿(下降)数据被采样
#define SPI_CS_HIGH 0x04//片选为高
#define SPI_LSB_FIRST 0x08//低位数据先传输
#define SPI_3WIRE 0x10//三线式,输入输出数据线为一条线
#define SPI_LOOP 0x20//回环模式
#define SPI_NO_CS 0x40//没有片选信号
#define SPI_READY 0x80//
用法:
mode = SPI_MODE_0 | SPI_CS_HIGH | SPI_LSB_FIRST | SPI_LOOP
ioctl(fd, SPI_IOC_WR_MODE, &mode);
注意:前面四种是对SCK时钟信号空闲时的电平,和采样时刻的选择,四个只能选择其中一种,后面的五种可以用或的形式选择任意几个,使用方法如上
b、设置或获取SPI读写是从高位还是低位开始
SPI_IOC_RD_LSB_FIRST //读 LSB
SPI_IOC_WR_LSB_FIRST //写 LSB
以上两种cmd对用arg是spi_device.mode
用法:同上,但是mode类型只有SPI_LSB_FIRST一种
c、设置或获取SPI读写数据位数
SPI_IOC_RD_BITS_PER_WORD //读 每字多少位
SPI_IOC_WR_BITS_PER_WORD //写 每字多少位
以上两种cmd对用arg是spi_device.bits_per_word
用法:
bits = 8;
ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
d、设置或获取SPI读写的最大频率
SPI_IOC_RD_MAX_SPEED_HZ //读 最大速率
SPI_IOC_WR_MAX_SPEED_HZ //写 最大速率
以上两种cmd对用arg是spi_device.max_speed_hz
用法:
speed = 50*1000;
ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
e、传输数据
SPI_IOC_MESSAGE(n) //传输n个数据包
以上一种cmd对用arg是spi_ioc_transfer
用法:全双工传输数据
struct spi_ioc_transfer tr = {
.tx_buf = (unsigned long)tx,
.rx_buf = (unsigned long)rx,
.len = ARRAY_SIZE(tx),
.delay_usecs = delay,
.speed_hz = speed,
.bits_per_word = bits,
};
ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
第三:read或write
用法:和大多数的设备read函数一样的用法,但是每次读或者写的大小不能大于4096Byte。
char* buf[n];
read(fd,buf,sizeof(buf));或者write(fd,buf,sizeof(buf));
第四:close
======================================================================
Linux下Beyond Compare4的破解使用
1.官网下载最新版 Beyond Compare 4 并安装
http://www.scootersoftware.com/download.php
2.安装后进入到bcompare目录下,输入命令破解
进入目录:
cd /usr/lib/beyondcompare/
更改权限:
sudo chmod 755 BCompare
输入破解命令:
sudo sed -i "<KEY>" BCompare
3.此时BCompare文件已被破解,打开软件会提示Trial Mode Error!表示成功,输入Team ZWT生成的密钥即可注册成功
提供Team ZWT生成密钥一枚:
--- BEGIN LICENSE KEY ---
<KEY>
--- END LICENSE KEY -----
======================================================================
0x400 1K
0x1000 4K
0x10000 64K
0x80000 512K/0.5M
0x100000 1M
======================================================================
config WKUP_PIN_RST
depends on MACH_XBURST
bool "support reset chip by press the WKUP pin judge time"
default n
config JUDGE_TIME
int "judge time lenght in second"
range 1 16
default 5
depends on WKUP_PIN_RST
======================================================================
建 repo管理的 git库
服务器:
01) cd review_site/git/mirror/
02) mkdir lrc
03) git clone [email protected]:/home/qwwang/work/github/tt/lrc --mirror
04) mkdir manifest
05) cp ../QRcode/manifest/default.xml manifest/
06) cd manifest && vim default.xml, 修改 default.xml 为:
<?xml version="1.0" encoding="UTF-8"?>
<manifest>
<remote name="linux"
fetch="."
review="https://review.ingenic.cn/" />
<default revision="master"
remote="linux"
sync-j="1" />
<project path="lrc" name="lrc" />
</manifest>
07) git init; git add .; git commit -m "init"
08) cd ..; git clone manifest/ --mirror
09) git clone [email protected]:/home/qwwang/work/github/tt/route --mirror
10) cd manifest && vim default.xml, 添加一行: <project path="route" name="route" />
11) git add .; git commit -m "add route"; git push, 如果出错继续执行下面步骤
a) cp default.xml ../; cd ..
b) rm manifest/ -rf
c) git clone manifest.git/
d) cp default.xml manifest/; cd manifest/
e) git add .; git commit -m "add route"; git push origin
客户机:
1) mkdir test; cd test
2) repo init -u ssh://[email protected]:29418/mirror/lrc/manifest
3) repo sync
建单独的git库
服务器:
1)git init --bare test (test为新建库的名称)
客户机:
1)git clone ssh://[email protected]:29418/test
Gerrit 添加一个已经有的git工程到gerrit服务器
1) ssh -p 29418 user@localhost gerrit create-project --name demo-project
2) git push ssh://user@localhost:29418/demo-project *:*
添加用户方法
服务器:
添加用户 "aaa": htpasswd etc/passwords aaa
======================================================================
ISP(Image Signal Processing 中文译为“图形信号处理”
BF3703
0x03 VHREF
VREF and HREF control.
Bit[7:6]: VREF end low 2 Bits(high 8 Bit at VSTOP[7:0])
Bit[5:4]: VREF start low 2 Bits(high 8 Bit at VSTART[7:0])
Bit[3:2]: HREF end 2 LSB(high 8 MSB at register HSTOP)
Bit[1:0]: HREF start 2 LSB(high 8 MSB at register HSTART)
0x17 HSTART
Output Format-Horizontal Frame(HREF column)start high
8-Bit(low 2Bits are at VHREF[1:0])
0x18 HSTOP
Output Format-Horizontal Frame(HREF column)end high
8-Bit(low 2 Bits are at VHREF[3:2])
0x19 VSTART
Output Format-Vertical Frame(row)start high 8-Bit(low 2 Bits are at VHREF[5:4])
0x1a VSTOP
Output Format-Vertical Frame(row)end high 8-Bit(low 2 Bits are at VHREF[7:6])
======================================================================
获取文件大小的方法:
stat -c%s filename
======================================================================
sed 是stream editor的简称,也就是流编辑器。它一次处理一行内容,处理时,把当前处理的行存储在临时缓冲区中,
称为“模式空间”(pattern space),接着用sed命令处理缓冲区中的内容,处理完成后,把缓冲区的内容送往屏幕。接
着处理下一行,这样不断重复,直到文件末尾。文件内容并没有 改变,除非你使用重定向存储输出。
sed 命令行格式为:
sed [-nefri] ‘command’ 输入文本
常用选项:
-n ∶ 使用安静(silent)模式。在一般 sed 的用法中,所有来自 STDIN的资料一般都会被列出到萤幕上。
但如果加上 -n 参数后,则只有经过 sed 特殊处理的那一行(或者动作)才会被列出来。
-e ∶ 直接在指令列模式上进行 sed 的动作编辑;
-f ∶ 直接将 sed 的动作写在一个档案内, -f filename 则可以执行 filename 内的sed 动作;
-r ∶ sed 的动作支援的是延伸型正规表示法的语法。(预设是基础正规表示法语法)
-i ∶ 直接修改读取的档案内容,而不是由萤幕输出。
常用命令:
a ∶ 新增,a 的后面可以接字串,而这些字串会在新的一行出现(目前的下一行)
c ∶ 取代,c 的后面可以接字串,这些字串可以取代 n1,n2 之间的行!
d ∶ 删除,因为是删除啊,所以 d 后面通常不接任何咚咚;
i ∶ 插入,i 的后面可以接字串,而这些字串会在新的一行出现(目前的上一行)
p ∶ 列印,亦即将某个选择的资料印出。通常 p 会与参数 sed -n 一起运作~
s ∶ 取代,可以直接进行取代的工作哩!通常这个 s 的动作可以搭配正规表示法!例如 1,20s/old/new/g 就是啦!
sed -i 's/.\/$(LOADER_NAME)[ ]\+[0-9a-z]\+[ ]\+[0-9]\+/.\/$(LOADER_NAME) $(APP_OFFSET) $(APP_SIZE)/' $(APP_SCRIPT); \
======================================================================
git clone ssh://[email protected]:29418/linux-recovery
======================================================================
安装 libffi
sed -e '/^includesdir/ s/$(libdir).*$/$(includedir)/' \
-i include/Makefile.in && sed -e '/^includedir/ s/=.*$/=@includedir@/' \
-e 's/^Cflags: -I${includedir}/Cflags:/' \
-i libffi.pc.in &&./configure --prefix=/usr --disable-static && make
======================================================================
sudo autoreconf -ivf
<file_sep>/sys_program/2nd_day/pm/raise.c
/* ************************************************************************
* Filename: raise.c
* Description:
* Version: 1.0
* Created: 2015年08月14日 15时28分59秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
sleep(3);
printf("raise\n");
raise(2);
return 0;
}
<file_sep>/network/route/src/inc/route_pthread.h
/******************************************************************************
文 件 名 : route_pthread.h
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月11日
最近修改 :
功能描述 : route_pthread.c 的头文件
******************************************************************************/
#ifndef __ROUTE_PTHREAD_H__
#define __ROUTE_PTHREAD_H__
#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */
/*----------------------------------------------*
* 函数原型说明 *
*----------------------------------------------*/
extern void create_pthread(TYPE_Route *rt);
extern void dispose_key_cmd(TYPE_Route *rt, char cmd[]);
extern void *pthread_deal_message(void *arg);
extern void *pthread_key_event(void *arg);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
#endif /* __ROUTE_PTHREAD_H__ */
<file_sep>/work/test/gpioset/Makefile
CC := mipsel-linux-gcc
TAG := gpioset gpior
INSTALL_DIR := ../../mozart/rootfs/updater/usr/bin/
all:$(TAG)
.PHONY:gpioset
gpioset:gpioset.c
$(CC) -o gpioset gpioset.c
.PHONY:gpior
gpior:
$(CC) -o gpior gpior.c
.PHONY:install
install:gpioset gpior
cp $(TAG) $(INSTALL_DIR)
.PHONY:clean
clean:
rm $(TAG) *.o -rf
<file_sep>/shell/mount_nfs.sh
#!/bin/sh
#auto get ip
#udhcpc
#config ip netmask gw
ifconfig eth0 10.221.2.112 netmask 255.255.255.0
route add default gw 10.221.2.254
serverip=10.221.2.221
serverpath=/home/edu
localpath=/mnt
echo "usage:./mount_nfs serverip serverpath localpath"
if [ -z $serverip ]; then
echo "serverip is NULL"
exit 1
fi
if [ -z $serverpath ]; then
echo "serverpath is NULL"
exit 1
fi
if [ -z $localpath ]; then
localpath=/mnt/nfs
echo "localpath default /mnt/nfs"
fi
mount -o nolock,wsize=1024,rsize=1024 $serverip:$serverpath $localpath
if [ $? = 0 ]; then
echo "nfs mount succeed!!"
echo "if you want to umount the serverpath"
echo "please input umount like this: umount /mnt"
else
echo "nfs mount failed,please check and try again!!"
fi
<file_sep>/sys_program/2nd_day/pm/signal_set.c
/* ************************************************************************
* Filename: signal_set.c
* Description:
* Version: 1.0
* Created: 2015年08月14日 17时01分27秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <signal.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
sigset_t set;
int ret = 0;
sigemptyset(&set);
ret = sigismember(&set,SIGINT);
if(ret == 0)
printf("SIG is not a member of sigpromask \nret = %d\n",ret);
sigaddset(&set,SIGINT);
sigaddset(&set,SIGQUIT);
ret = sigismember(&set,SIGINT);
if(ret == 1)
printf("SIG is a member of sigpromask \nret = %d\n",ret);
return 0;
}
<file_sep>/sys_program/6th_day/mutex.c
/* ************************************************************************
* Filename: mutex.c
* Description:
* Version: 1.0
* Created: 2015年08月20日 10时34分16秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex;
//PTHREAD_MUTEX_INITIALIZER;
void print(char *str)
{
pthread_mutex_lock(&mutex);
while(*str != '\0')
{
putchar(*str++);
fflush(stdout);
sleep(1);
}
putchar('\n');
pthread_mutex_unlock(&mutex);
}
void *fun1(void *arg)
{
char *buf = "world";
print(buf);
}
void *fun2(void *arg)
{
char *buf = "hello";
print(buf);
}
int main(int argc, char *argv[])
{
pthread_t pth1,pth2;
pthread_mutex_init(&mutex,NULL);
pthread_create(&pth1,NULL,fun1,NULL);
pthread_create(&pth2,NULL,fun2,NULL);
pthread_join(pth1,NULL);
pthread_join(pth2,NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
<file_sep>/work/test/gpioset/gpior.c
/*************************************************************************
> File Name: gpio.c
> Author:
> Mail:
> Created Time: Wed 25 May 2016 10:50:56 AM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
/*#define DEBUG*/
#define GPIO_SET_OUTPUT 1
#define GPIO_SET_INPUT 0
#define GPIO_SET_LOW 0
#define GPIO_SET_HIGH 1
static void print_help(void)
{
printf("Usage: gpior gpionum \n");
printf("Usage:\n");
printf(" eg: gpior 52\n");
}
static int gpio_read(int gpionum)
{
char path[64];
char value_str[3] = {0};
int fd, i;
snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value", gpionum);
printf("path: %s\n",path);
fd = open(path, O_RDONLY);
if(fd < 0) {
printf("Failed to open gpio value for reading!\n");
return -1;
}
for(i = 0; i < 2; i++) {
if(read(fd, value_str, sizeof(value_str)) < 0) {
printf("Failed to read gpio%d value!\n", gpionum);
return -1;
}
}
#ifdef DEBUG
printf("### read value = %s\n", value_str);
for(i = 0; i < 3; i++) {
printf("value_str[%d] = %d\t",i, value_str[i]);
}
printf("\n");
#endif
close(fd);
return atoi(value_str);
}
int main(int argc, char *argv[])
{
// Test for correct number of arguments
if(argc != 2) {
print_help();
return -1;
}
int gpionum = atoi(argv[1]);
if(gpionum < 0 || gpionum > 101) { // For Ingenic x1000 soc
printf("### gpionum: %d is invalid ###\n", gpionum);
return -1;
}
int ret = gpio_read(gpionum);
if(ret != -1)
printf("### read gpio%d ret = %d ###\n", gpionum, ret);
return 0;
}
<file_sep>/work/debug/2440/buttons/buttons_drv.c
/* ************************************************************************
* Filename: buttons_drv.c
* Description:
* Version: 1.0
* Created: 2015年08月16日 18时40分08秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/poll.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/cdev.h>
#include <linux/miscdevice.h>
#include <linux/sched.h>
#include <linux/gpio.h>
#include <linux/timer.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#include <mach/regs-gpio.h>
#include <mach/hardware.h>
#define DEVICE_NAME "buttons_drv"
#define TIME_DELAY_20MS (HZ/50) //按键按下去抖延时
#define TIME_DELAY_50MS (HZ/20) //按键松开去抖延时
#define KEY_DOWN 0 //按键按下
#define KEY_UP 1 //按键松开
#define KEY_UNCERTAIN 2 //按键不确定
#define KEY_COUNT 6
static volatile int ev_press = 0; //按键按下状态标志
static volatile int key_status[KEY_COUNT]; //记录按键的状态
static struct timer_list key_timers[KEY_COUNT];//定义6个按键去抖定时器
static DECLARE_WAIT_QUEUE_HEAD(buttons_waitq);//定义并初始化等待队列
static int majno = 0; //主设备号
static struct cdev *p_cdev = NULL;
static struct class *keys_class = NULL;
struct key_irq_desc
{
int irqno; //中断号
int pin; //引脚
int pin_cfg; //引脚配置
char *name; //中断设备名称
};
static struct key_irq_desc keys_irq[] =
{
{IRQ_EINT8 , S3C2410_GPG(0) , S3C2410_GPG0_EINT8 , "KEY0"},
{IRQ_EINT11, S3C2410_GPG(3) , S3C2410_GPG3_EINT11 , "KEY1"},
{IRQ_EINT13, S3C2410_GPG(5) , S3C2410_GPG5_EINT13 , "KEY2"},
{IRQ_EINT14, S3C2410_GPG(6) , S3C2410_GPG6_EINT14 , "KEY3"},
{IRQ_EINT15, S3C2410_GPG(7) , S3C2410_GPG7_EINT15 , "KEY4"},
{IRQ_EINT19, S3C2410_GPG(11), S3C2410_GPG11_EINT19, "KEY5"},
};
static irqreturn_t key_interrupt(int irq, void *dev_id)
{
//获取哪个按键被按下
int key_id = (int)dev_id;
if(key_status[key_id] == KEY_UP)
{
key_status[key_id] = KEY_UNCERTAIN; //设置当前按键状态为不确定
//设置去抖延时时间为20MS,并启动定时器
key_timers[key_id].expires = jiffies + TIME_DELAY_20MS;
add_timer(&key_timers[key_id]); //定时器到时之后会调用定时器的回调函数进一步处理
}
return IRQ_RETVAL(IRQ_HANDLED);
}
static void timer_callback(unsigned long arg)
{
//获取哪个按键被按下
int key_id = arg;
int status = s3c2410_gpio_getpin(keys_irq[key_id].pin); //获取按键状态
if( !status ) //低电平, 按键按下
{
if(key_status[key_id] == KEY_UNCERTAIN)
{
key_status[key_id] = KEY_DOWN;
s3c2410_gpio_setpin(keys_irq[key_id].pin, 1);
ev_press = 1; //确定有按键被按下
wake_up_interruptible(&buttons_waitq);//唤醒等待队列
}
//设置按键抬起去抖延时
key_timers[key_id].expires = jiffies + TIME_DELAY_50MS;
add_timer(&key_timers[key_id]);
}
}
static int buttons_open(struct inode *inode, struct file *file)
{
int i, ret;
for(i=0;i<KEY_COUNT;i++)
{
//配置I/O的模式为中断
s3c2410_gpio_cfgpin(keys_irq[i].pin, keys_irq[i].pin_cfg);
//配置下降沿触发中断
set_irq_type(keys_irq[i].pin, IRQ_TYPE_EDGE_FALLING);
ret = request_irq(keys_irq[i].irqno, key_interrupt, IRQF_DISABLED, keys_irq[i].name, (void *)i);
if(ret) break; //申请中断成功返回 0
key_status[i] = KEY_UP;
//初始化并设置各个按键的去抖定时器
key_timers[i].function = timer_callback; //注册定时器的到时处理函数
key_timers[i].data = i; //传递给到时处理函数的参数
init_timer(&key_timers[i]); //初始化定时器
}
if(ret) //中断申请失败
{
i--;
for(; i >= 0; i--)
{ //释放注册成功的中断
disable_irq(keys_irq[i].irqno);
free_irq(keys_irq[i].irqno, (void *)i);
}
return -EBUSY;
}
return 0;
}
static ssize_t buttons_read(struct file *filp,char __user *buf, size_t count,loff_t *ppos)
{
unsigned long ret;
if(!ev_press) //没有按键被按下
{
if(filp->f_flags & O_NONBLOCK)
{
//若应用程序采用非阻塞方式读取,则返回
return -EAGAIN; //提示用户再尝试读
}
else
{
//以阻塞方式读取且按键没被按下,则让等待队列进入休眠
wait_event_interruptible(buttons_waitq, ev_press);
}
}
ev_press = 0; //已有按键按下,重置此标志
ret = copy_to_user(buf, (void *)key_status, min(sizeof(key_status), count));
memset((void *)key_status, 0, sizeof(key_status));
return ret ? -EFAULT : min(sizeof(key_status), count); //返回用户成功读取的字节数
}
static int buttons_close(struct inode *inode,struct file *file)
{
int i;
//释放定时器和中断
for(i=0; i < KEY_COUNT; i++)
{
del_timer(&key_timers[i]);
disable_irq(keys_irq[i].irqno);
free_irq(keys_irq[i].irqno, (void *)i);
}
return 0;
}
static unsigned int buttons_poll(struct file *file, struct poll_table_struct *wait)
{
unsigned int mask = 0;
//添加 等待队列 到 等待队列表中
poll_wait(file, &buttons_waitq, wait);
if(ev_press) //按键被按下
{
mask |= POLLIN | POLLRDNORM; //表示数据可以获取
}
return mask;
}
static struct file_operations buttons_fops =
{
.owner = THIS_MODULE,
.open = buttons_open,
.read = buttons_read,
.release = buttons_close,
.poll = buttons_poll,
};
static void buttons_setup_cdev(struct cdev *dev,int index)
{
int err;
dev_t devno = MKDEV(majno, index);
cdev_init(dev, &buttons_fops);
dev->owner = THIS_MODULE;
dev->ops = &buttons_fops;
err = cdev_add(dev, devno, 1);
if(err)
{
printk(KERN_NOTICE "Error %d adding keys cdev %d",err,index);
}
}
static int __init buttons_init(void)
{
int ret;
dev_t devno = MKDEV(majno,0);
//初始化硬件I/O
if(!majno)
{
ret = alloc_chrdev_region(&devno,0,1,DEVICE_NAME);
majno = MAJOR(devno);
}
else
{
ret = register_chrdev_region(devno,1,DEVICE_NAME);
}
if(ret < 0)
{
return ret;
}
p_cdev = kmalloc(sizeof(struct cdev), GFP_KERNEL);
if(!p_cdev)
{
ret = -ENOMEM;
goto fail_malloc;
}
memset(p_cdev, 0, sizeof(struct cdev));
buttons_setup_cdev(p_cdev,0);
//注册一个类
keys_class = class_create(THIS_MODULE, DEVICE_NAME);//要添加#include <linux/device.h>
if(IS_ERR(keys_class))
{
printk("Err:failed in create keys class\n");
goto fail_add_class;
}
//创建一个设备节点
device_create(keys_class,NULL,MKDEV(devno,0),NULL,DEVICE_NAME);
return 0;
fail_malloc:
unregister_chrdev_region(devno,1);
return -1;
fail_add_class:
cdev_del(p_cdev);
kfree(p_cdev);
unregister_chrdev_region(devno,1);
return -1;
}
/*
* 设备的注销函数,在设备从内核卸载时调用
*
*/
static void __exit buttons_exit(void)
{
device_destroy(keys_class,MKDEV(majno,0)); //删除设备节点
class_destroy(keys_class); //注销类
cdev_del(p_cdev);
kfree(p_cdev); //回收设备结构的内存
unregister_chrdev_region(MKDEV(majno,0),1); //释放设备号
}
module_init(buttons_init);
module_exit(buttons_exit);
/* 描述驱动程序的一些信息,不是必须的 */
MODULE_AUTHOR("Dawei"); // 驱动程序的作者
MODULE_DESCRIPTION("A buttons Driver"); // 一些描述信息
MODULE_LICENSE("GPL"); // 遵循的协议
<file_sep>/c/practice/3rd_week/link/main.c
#include <stdio.h>
#include <string.h>
#include "link.h"
void help()
{
printf("-----------------------------------\n");
printf("->help : 帮助信息 \n");
printf("->insert: 插入一个新节点 \n");
printf("->print : 遍历整个链表 \n");
printf("->search: 查询某个节点 \n");
printf("->delete: 查删除某个节点 \n");
printf("->free : 释放整个节点 \n");
printf("->exit : 退出 \n");
printf("-----------------------------------\n");
}
int main(int argc,char *argv[])
{
char cmd[128] = "";
STU *head = NULL;
while(1)
{
scanf("%s",cmd);
if(strcmp(cmd,"help")==0)
{
help();
}
else if(strcmp(cmd,"insert")==0)
{
STU temp;
printf("please input the num,name,score:\n");
scanf("%d %s %d",&temp.num,temp.name,&temp.score);
head = insert_link(head, temp);
}
else if(strcmp(cmd,"print")==0)
{
printf("-----print-----\n");
print_link(head);
}
else if(strcmp(cmd,"search")==0)
{
char name[64] = "";
STU *ret;
printf("please input search name\n");
scanf("%s",name);
ret = search_link(head, name);
if(ret == NULL)
{
printf("not found\n");
}
else
{
printf("%d %s %d\n",ret->num,ret->name,ret->score);
}
}
else if(strcmp(cmd,"delete")==0)
{
int num = 0;
printf("Please input delete num\n");
scanf("%d",&num);
head = delete_link(head,num);
}
else if(strcmp(cmd,"free")==0)
{
printf("-----free link-----\n");
head = free_link(head);
}
else if(strcmp(cmd,"exit")==0)
{
printf("----- exit -----\n");
head = free_link(head);
break;
}
}
return 0;
}
<file_sep>/c/homework/3rd_week/atoi/Makefile
atoi:myatoi.c
gcc -o atoi myatoi.c -lm
.PHONY:clean
clean:
rm atoi
<file_sep>/work/test/cim_test-zmm220/fvjpg.c
/*
* $Id: fv.c
* $Desp: draw jpeg to framebuffer
* $Author: rockins
* $Date: Wed Jan 3 20:15:49 CST 2007
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
//#include <jpeglib.h>
//#include <jerror.h>
#include <string.h>
#define FB_DEV "/dev/fb0"
/***************** function declaration ******************/
void usage(char *msg);
unsigned short RGB888toRGB565(unsigned char red,
unsigned char green, unsigned char blue);
int fb_open(char *fb_device);
int fb_close(int fd);
int fb_stat(int fd, int *width, int *height, int *depth);
void *fb_mmap(int fd, unsigned int screensize);
int fb_munmap(void *start, size_t length);
int fb_pixel(void *fbmem, int width, int height,
int x, int y, unsigned short color);
#define TRUE 1
/************ function implementation ********************/
//int main(int argc, char **argv)
/*
* declaration for jpeg decompression
*/
static struct jpeg_decompress_struct cinfo;
static struct jpeg_error_mgr jerr;
static FILE *infile,*fp;
static unsigned char *buffer;
/*
* declaration for framebuffer device
*/
static int fbdev;
static char *fb_device;
static unsigned char *fbmem;
static unsigned int screensize;
static unsigned int fb_width;
static unsigned int fb_height;
static unsigned int fb_depth;
static unsigned int x;
static unsigned int y;
static int flag=0;
void openDev(void)
{
#if 0
if ((fp = fopen("/mnt/sdcard/main", "rb")) != NULL) {
printf("sdcard ok\n");
fclose(fp);
//return 1;
flag=1;
}
#endif
#if 0
/*
* open input jpeg file
*/
if(!flag)
{
// if ((infile = fopen(argv[1], "rb")) == NULL) {
if ((infile = fopen(path, "rb")) == NULL) {
printf("can't open jpg file\n");
// exit(-1);
return -1;
}
}
else
{
if ((infile = fopen("warning2.jpg", "rb")) == NULL) {
printf("can't open jpg file\n");
exit(-1);
}
}
#endif
/*
* open framebuffer device
*/
if ((fb_device = getenv("FRAMEBUFFER")) == NULL)
{
fb_device = FB_DEV;
printf("fb_device=/dev/fb0\n");
}
printf("fd_device:%s\n",fb_device);
fbdev = fb_open(fb_device);
/*
* get status of framebuffer device
*/
fb_stat(fbdev, &fb_width, &fb_height, &fb_depth);
/*
* map framebuffer device to shared memory
*/
screensize = fb_width * fb_height * fb_depth / 8;
fbmem = fb_mmap(fbdev, screensize);
printf("open framebuffer ok\n");
}
#if 0
int showimage(char *path)
{
if ((infile = fopen(path, "rb")) == NULL) {
printf("can't open jpg file\n");
// exit(-1);
return -1;
}
/*
* init jpeg decompress object error handler
*/
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
/*
* bind jpeg decompress object to infile
*/
jpeg_stdio_src(&cinfo, infile);
/*
* read jpeg header
*/
jpeg_read_header(&cinfo, TRUE);
/*
* decompress process.
* note: after jpeg_start_decompress() is called
* the dimension infomation will be known,
* so allocate memory buffer for scanline immediately
*/
jpeg_start_decompress(&cinfo);
if ((cinfo.output_width > fb_width) ||
(cinfo.output_height > fb_height)) {
printf("fb_width=%d\n",fb_width);
printf("fb_height=%d\n",fb_height);
printf("too large JPEG file,cannot display\n");
return (-1);
}
buffer = (unsigned char *) malloc(cinfo.output_width *
cinfo.output_components);
y = 0;
// printf("fb_depth %d\n",fb_depth);
while (cinfo.output_scanline < cinfo.output_height)
{
jpeg_read_scanlines(&cinfo, &buffer, 1);
if (fb_depth == 16)
{
unsigned short color;
for (x = 0; x < cinfo.output_width; x++)
{
color = RGB888toRGB565(buffer[x * 3], buffer[x * 3 + 1], buffer[x * 3 + 2]);
fb_pixel(fbmem, fb_width, fb_height, x, y, color);
}
}
else if (fb_depth == 24)
{
memcpy((unsigned char *) fbmem + y * fb_width * 3, buffer, cinfo.output_width * cinfo.output_components);
}
y++; // next scanline
}
/*
* finish decompress, destroy decompress object
*/
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
fclose(infile);
}
#endif
void showimg(unsigned char *buf,int x, int y, int w, int h)
{
// printf("show img ...\n");
int i;
for(i=0;i<h;i++)
memcpy((unsigned char *) fbmem + ((y+i)*fb_width+x)*2 , buf+i*w*2, w*2);
}
void closeDev(void)
{
/*
* release memory buffer
*/
free(buffer);
/*
* close jpeg inputing file
*/
// fclose(infile);
/*
* unmap framebuffer's shared memory
*/
fb_munmap(fbmem, screensize);
/*
* close framebuffer device
*/
fb_close(fbdev);
// return (0);
}
void
usage(char *msg)
{
fprintf(stderr, "%s\n", msg);
printf("Usage: fv some-jpeg-file.jpg\n");
}
/*
* convert 24bit RGB888 to 16bit RGB565 color format
*/
unsigned short
RGB888toRGB565(unsigned char red,unsigned char green, unsigned char blue)
{
unsigned short B = (blue >> 3) & 0x001F;
unsigned short G = ((green >> 2) << 5) & 0x07E0;
unsigned short R = ((red >> 3) << 11) & 0xF800;
return (unsigned short) (R | G | B);
}
void RGB565toRGB888(unsigned short rgb565, unsigned char *rgb)
{
rgb[0] = (rgb565&0xF800)>>11;
rgb[1] = (rgb565&0x0E70)>>5;
rgb[2] = (rgb565&0x001F);
return;
}
/*
* open framebuffer device.
* return positive file descriptor if success,
* else return -1.
*/
int
fb_open(char *fb_device)
{
int fd;
if ((fd = open(fb_device, O_RDWR)) < 0) {
perror(__func__);
return (-1);
}
return (fd);
}
/*
* get framebuffer's width,height,and depth.
* return 0 if success, else return -1.
*/
int
fb_stat(int fd, int *width, int *height, int *depth)
{
struct fb_fix_screeninfo fb_finfo;
struct fb_var_screeninfo fb_vinfo;
if (ioctl(fd, FBIOGET_FSCREENINFO, &fb_finfo)) {
perror(__func__);
return (-1);
}
if (ioctl(fd, FBIOGET_VSCREENINFO, &fb_vinfo)) {
perror(__func__);
return (-1);
}
*width = fb_vinfo.xres;
*height = fb_vinfo.yres;
*depth = fb_vinfo.bits_per_pixel;
return (0);
}
/*
* map shared memory to framebuffer device.
* return maped memory if success,
* else return -1, as mmap dose.
*/
void *
fb_mmap(int fd, unsigned int screensize)
{
caddr_t fbmem;
if ((fbmem = mmap(0, screensize, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0)) == MAP_FAILED) {
perror(__func__);
return NULL;
}
return (fbmem);
}
/*
* unmap map memory for framebuffer device.
*/
int
fb_munmap(void *start, size_t length)
{
return (munmap(start, length));
}
/*
* close framebuffer device
*/
int
fb_close(int fd)
{
return (close(fd));
}
/*
* display a pixel on the framebuffer device.
* fbmem is the starting memory of framebuffer,
* width and height are dimension of framebuffer,
* x and y are the coordinates to display,
* color is the pixel's color value.
* return 0 if success, otherwise return -1.
*/
int
fb_pixel(void *fbmem, int width, int height,
int x, int y, unsigned short color)
{
if ((x > width) || (y > height))
return (-1);
unsigned short *dst = ((unsigned short *) fbmem + y * width + x);
*dst = color;
return (0);
}
//modify by seven 2011-06-11
#if 1
int fb_pixelAsRow(void *fbmem, int width, int height,
int x, int y, unsigned short *rowbuf, int bufsize)
{
if ((x > width) || (y > height))
return (-1);
unsigned short *dst = ((unsigned short *) fbmem + y * width + x);
memcpy(dst, rowbuf, bufsize);
return (0);
}
#endif
/*
int main(int argc, char **argv)
{
char name[50];
int i;
for(i=0;i<10;i++)
{
sprintf(name,"image%d.jpg",i);
showimage(name);
}
return 0;
}
*/
<file_sep>/sys_program/2nd_day/pm/pause.c
/* ************************************************************************
* Filename: pause.c
* Description:
* Version: 1.0
* Created: 2015年08月14日 15时38分33秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <signal.h>
int main(int argc, char *argv[])
{
sleep(3);
printf("pause\n");
pause();
return 0;
}
<file_sep>/work/camera/bf3703/bf3703/bf3703_set_mode.c
#include <asm/jzsoc.h>
#include <linux/jz_sensor.h>
#include <linux/i2c.h>
#include "bf3703_set.h"
#define bf3703_DEBUG
#ifdef bf3703_DEBUG
#define dprintk(x...) do{printk("cm3511---\t");printk(x);printk("\n");}while(0)
#else
#define dprintk(x...)
#endif
void night_enable(struct i2c_client *client)
{
}
void de_night_disable(struct i2c_client *client)
{
}
void bf3703_night_select(struct i2c_client *client,int enable)
{
}
/*--------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------*/
/*----------------------------------set white balance------------------------------------------------*/
void bf3703_set_wb_auto_mode(struct i2c_client *client)
{
retry_write_reg(client,0x01,0x15);
retry_write_reg(client,0x02,0x24);
retry_write_reg(client,0x13,0x07); // Enable AWB
}
void bf3703_set_wb_sunny_mode(struct i2c_client *client)
{
retry_write_reg(client,0x13,0x05); // Disable AWB
retry_write_reg(client,0x01,0x13);
retry_write_reg(client,0x02,0x26);
}
void bf3703_set_wb_cloudy_mode(struct i2c_client *client)
{
retry_write_reg(client,0x13,0x05); // Disable AWB
retry_write_reg(client,0x01,0x10);
retry_write_reg(client,0x02,0x28);
}
void bf3703_set_wb_office_mode(struct i2c_client *client)
{
retry_write_reg(client,0x13,0x05); // Disable AWB
retry_write_reg(client,0x01,0x1f);
retry_write_reg(client,0x02,0x15);
}
void bf3703_set_wb_home_mode(struct i2c_client *client)
{
}
/*--------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------*/
/*---------------------------------------set banding------------------------------------------------*/
void bf3703_ab_auto(struct i2c_client *client)
{
}
void bf3703_ab_50hz(struct i2c_client *client)
{
retry_write_reg(client,0x9d,0x99);
}
void bf3703_ab_60hz(struct i2c_client *client)
{
retry_write_reg(client,0x9e,0x80);
}
void bf3703_ab_off(struct i2c_client *client)
{
}
/*--------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------*/
/*---------------------------------------set effect------------------------------------------------*/
void bf3703_set_effect_normal(struct i2c_client *client)
{
retry_write_reg(client,0x80,0x45);
retry_write_reg(client,0x76,0x00);
retry_write_reg(client,0x69,0x00);
retry_write_reg(client,0x67,0x80);
retry_write_reg(client,0x68,0x80);
}
void bf3703_set_effect_sepia(struct i2c_client *client)
{
retry_write_reg(client,0x80,0x45);
retry_write_reg(client,0x76,0x00);
retry_write_reg(client,0x69,0x20);
retry_write_reg(client,0x67,0x60);
retry_write_reg(client,0x68,0x98);
}
void bf3703_set_effect_whiteboard(struct i2c_client *client)
{
retry_write_reg(client,0x69,0x00);
retry_write_reg(client,0x80,0xc5);
retry_write_reg(client,0x76,0xf0);
retry_write_reg(client,0x67,0x80);
retry_write_reg(client,0x68,0x80);
}
void bf3703_set_effect_bluish(struct i2c_client *client)
{
}
void bf3703_set_effect_greenish(struct i2c_client *client)
{
retry_write_reg(client,0x80,0x45);
retry_write_reg(client,0x76,0x00);
retry_write_reg(client,0x69,0x20);
retry_write_reg(client,0x67,0x40);
retry_write_reg(client,0x68,0x40);
}
void bf3703_set_effect_reddish(struct i2c_client *client)
{
}
void bf3703_set_effect_yellowish(struct i2c_client *client)
{
}
void bf3703_set_effect_blackwhite(struct i2c_client *client)
{
retry_write_reg(client,0x80,0x45);
retry_write_reg(client,0x76,0x00);
retry_write_reg(client,0x69,0x20);
retry_write_reg(client,0x67,0x80);
retry_write_reg(client,0x68,0x80);
}
void bf3703_set_effect_negative(struct i2c_client *client)
{
retry_write_reg(client,0x80,0x45);
retry_write_reg(client,0x76,0x00);
retry_write_reg(client,0x69,0x40);
retry_write_reg(client,0x67,0x80);
retry_write_reg(client,0x68,0x80);
}
/*--------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------*/
<file_sep>/sys_program/4th_day/homework/chat/Makefile
.PHONY:all
all:peter lucy bob
peter:chat.c
gcc chat.c -o peter -DP
lucy:chat.c
gcc chat.c -o lucy -DL
bob:chat.c
gcc chat.c -o bob -DB
.PHONY:clean
clean:
rm peter lucy bob<file_sep>/work/shell/mksystem_img.sh
#!/bin/bash
if [ $# -gt 0 ]; then
TARGET_DEVICE=$1
fi
if [ x"$TARGET_DEVICE" = x ]; then
TARGET_DEVICE="halley2"
fi
echo "TARGET_DEVICE = $TARGET_DEVICE"
./out/host/tools/mkfs.jffs2 -e 0x8000 -p 0xc80000 -d ./out/product/$TARGET_DEVICE/system/ -o ./out/product/$TARGET_DEVICE/image/system.jffs2
<file_sep>/work/debug/a8/touchscreen/goodix_dev.c
/*
* Copyright (c) 2012 sunplusapp
* this program is free software; you can redistribute it and/or modify it
*
* this is a demo about how to create i2c_board_info dynamically; it just like
* i2c_register_device
*
* Date and Edition: 2012-11-18 v1.0
* Date and Edition: 2013-01-05 v1.1
* Author: <<EMAIL>>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/irq.h>
static struct i2c_board_info goodix_info = {
/**/
I2C_BOARD_INFO("Goodix-TS",0x55),
};
static struct i2c_client *dev_test_client;
static struct i2c_client *goodix_client;
static __init int goodix_device_init(void)
{
struct i2c_adapter *i2c_adap;
/**/
i2c_adap = i2c_get_adapter(0);
goodix_client = i2c_new_device(i2c_adap, &goodix_info);
i2c_put_adapter(i2c_adap);
printk("%s:%d\n",__FUNCTION__,__LINE__);
return 0;
}
static __exit void goodix_device_exit(void)
{
i2c_unregister_device(dev_test_client);
}
module_init(goodix_device_init);
module_exit(goodix_device_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("sunplusedu");
<file_sep>/sys_program/player/src/inc/mplayer_control.h
/* ************************************************************************
* Filename: mplayer_control.h
* Description:
* Version: 1.0
* Created: 2015年08月24日 10时05分21秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __MPLAYER_CONTROL_H__
#define __MPLAYER_CONTROL_H__
extern void send_cmd(char cmd[],MPLAYER *pm);
extern void mplayer_show_musiclist(MPLAYER *pm, SONG *ps);
//extern void mplayer_show_musiclist(MPLAYER *pm);
extern void playing_song(MPLAYER *pm, int new_song);
extern void set_playing_song(MPLAYER *pm, int step);
extern void set_lable(GtkLabel *label, char *src);
extern void set_keyflag(KEY_STATUS status);
extern void set_songname(int song_num);
extern void set_lrc_lable(MPLAYER *pm, char *pbuf[]);
extern void clear_lrc_lable(MPLAYER *pm);
#endif
<file_sep>/c/homework/2nd_week/Makefile
execute = guess_number transform year typewriting
sources = guess_number.c transform.c year.c typewriting.c
objects = guess_number.o transform.o year.o typewriting.o
.PHONY:all
all:$(subst .c,,$(sources))
#$(patsubst %.c,%,$(sources))
#$(sources:.c=)
typewriting:typewriting.c
gcc -o typewriting typewriting.c -w
guess_number:guess_number.c
@echo "making guess_number.c"
gcc -o guess_number guess_number.c -lm -w
transform:transform.c
year:year.c
.PHONY:clean
clean:
rm $(execute)
<file_sep>/c/practice/1st_week/math/mymath.h
/* ************************************************************************
* Filename: mymath.h
* Description:
* Version: 1.0
* Created: 2015年07月16日 星期四 02時22分12秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __MYMATH_H__
#define __MYMATH_H__
int sum(int a,int b);
int abs(int n);
extern void Bubbing_Methed(char *p);
#endif
<file_sep>/c/practice/sort/insertsort.c
#include "stdio.h"
//从小到大进行排序
insertsort(int k[],int n) /*直接插入排序*/
{
int i,j;
int temp;
for(i=1;i<n;i++)
{
temp = k[i]; //将要比较的值先绶存起来留出一个空位,方便移动
j = i - 1;
while(j>=0 && k[j]>temp) //比较直到出现比temp大的值,或向前找到头
{
k[j+1] = k[j]; //将前面的值往后移
j--;
}
k[j+1] = temp; //插在a[j]的后面
}
}
int main()
{
int i,a[10] = {2,5,6,3,7,8,0,9,12,1}; /*初始化序列,a[0]可任意置数*/
printf("The data array is:\n") ;
for(i=0;i<10;i++) /*输出排序前的数据*/
printf("%d ",a[i]);
insertsort(a,10); /*插入排序*/
printf("\nThe result of insertion sorting for the array is:\n");
for(i=0;i<10;i++)
printf("%d ",a[i]); /*输出排序后的数据*/
printf("\n");
return 0;
}<file_sep>/c/lrc/file.c
/* ************************************************************************
* Filename: file.c
* Description:
* Version: 1.0
* Created: 2015年07月31日 星期五 05時35分04秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include "common.h"
/**************************************************************************
*函数功能:读出文件内容
*参数:file_length 整型指针,此地址中保存文件字节数。
* lrc_src 文件名字,从此文件中读取内容。
* 返回值:读出字符串的首地址
* 函数中测文件的大小并分配空间,再把文件内容读出到分配的空间中,返回此空间首地址
**************************************************************************/
char *read_src_file(ulint *file_length, char *lrc_src)
{
FILE *fp = NULL;
char *buf = NULL;
//unsigned long int file_length = 0;
fp = fopen(lrc_src,"rb");//以只读方式打开一个二进制文件
if(fp == NULL)
{
printf("Cannot open the flie!\n");
return;
}
fseek(fp,0,SEEK_END);
*file_length = ftell(fp); //获取文件的大小
buf = (char *)malloc(*file_length); //
if(buf == NULL)
{
printf("malloc() cannot apply for memory!\n");
goto out;
}
rewind(fp); //
fread(buf,*file_length,1,fp);
out:
fclose(fp);
return buf;
}
#if 1
char *get_musiclist(char ***plist)
{
FILE *fp =NULL;
char *buf = NULL;
ulint list_length = 0;
uint lines = 0;
int part = 0;
system("ls ./music | grep .mp3 >./music/musiclist");
fp = fopen("music/musiclist","rb");
if(fp == NULL)
{
printf("Cannot open the flie!\n");
return;
}
buf = read_src_file(&list_length,"music/musiclist");
lines = check_lines(list_length, buf);
*plist = (char **)malloc((lines + 1) * sizeof(char **)); //动态分配空间存储每行的首地址
if(*plist == NULL) return NULL;
part = src_segment(buf, *plist, "\r\n"); //按行分割
plist[lines] = NULL;
#if 1
int i, len;
for(i=0;i<part-1;i++)
{
len = strlen(*(*(plist) + i));
*(*(*(plist) + i) + len -4) = '\0';
//printf("%s\n",plist[i]);
}
#endif
return buf;
}
#else
char **get_musiclist()
{
FILE *fp =NULL;
char *buf = NULL, **plist = NULL;
ulint list_length = 0;
uint lines = 0;
int part = 0;
system("ls ./music | grep .mp3 >./music/musiclist");
fp = fopen("music/musiclist","rb");
if(fp == NULL)
{
printf("Cannot open the flie!\n");
return;
}
buf = read_src_file(&list_length,"music/musiclist");
lines = check_lines(list_length, buf);
plist = (char **)malloc((lines + 1) * sizeof(char **)); //动态分配空间存储每行的首地址
if(plist == NULL) return NULL;
part = src_segment(buf, plist, "\r\n"); //按行分割
plist[lines] = NULL;
#if 1
int i, len;
for(i=0;i<part-1;i++)
{
len = strlen(*(*(plist) + i));
//printf("len =%d\n",len);
*(*(*(plist) + i) + len -1) = '\0';
//printf("%s\n",plist[i]);
}
#endif
return plist;
}
#endif
void delete_dot(char *plist[])
{
int i = 0,len = 0;
for(i=0;plist[i] != NULL;i++)
{
len = strlen(plist[i]);
plist[i][len-4] = '\0'; //减4目的是跳过歌名中的 mp3 字样
}
}
void recover_dot(char *plist[])
{
int i = 0,len = 0;
for(i=0;plist[i] != NULL;i++)
{
len = strlen(plist[i]);
plist[i][len] = '.';
}
}
int check_lines(ulint file_length, char *lrc_src)
{
uint lines = 0;
ulint i = 0;
char *p = NULL;
p = lrc_src;
#if 1
for(i = 0;i < file_length;i++)
{
if(p[i]=='\n') lines++;
}
#elif 0 //这种方法不行,因为strchr函数和strstr函数遇到 '\0' 就返回
while(p != NULL)
{
p = strchr(p,'\n');
lines++;
}
#endif
return lines;
}
int get_longestline(int lines, char *plines[])
{
int longestline = 0, temp = 0, i = 0;
for(i=0;i<lines;i++)
{
temp = strlen(plines[i]);
if(temp > longestline) longestline = i;
}
return longestline;
}
int get_longestlength(LRC *lrc_head)
{
int longest = 0, temp = 0, chrnum = 0;
if(lrc_head != NULL)
{
LRC *pb = NULL, *pf = NULL;
pb = lrc_head;
while(pb != NULL)
{
temp = strlen(pb->psrc);
if(temp > longest)
{
pf = pb;
longest = temp;
}
//printf("len=%d %s\n",temp,pb->psrc);
pb = pb->next;
}
temp = strlen(pf->psrc);
chrnum = get_chrnumber(pf->psrc,temp);
longest += chrnum/2;
}
return longest;
}
int get_showoffset(char *pbuf, int longest)
{
int len = 0, offset = 0, temp = 0;
int count = 0;
len = strlen(pbuf);
count = get_chrnumber(pbuf, len);
len += count/2;
offset = (longest - len)/3;
//printf("longest=%d len=%d offset=%d %s\n",longest,len,offset,pbuf);
if(offset < 0) offset = 0; //一定要加此判断
return offset;
}
int get_chrnumber(char *pbuf, int len)
{
int i = 0,count = 0;
for(i=0;i<len;i++)
{
if(pbuf[i] > 0 && pbuf[i] <127) count++;
}
return count;
}
<file_sep>/work/debug/pc/timer/Makefile
ifneq ($(KERNELRELEASE),)
obj-m := timer_drv.o
else
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
# KERNELDIR ?= /work/linux/linux-2.6.32.2
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
rm -rf *.o *.mod.c *.order *.symvers .*.cmd .tmp*
clean:
rm -f *.o *~ *.ko *.mod.c *.mod.o *.symvers *.order
endif
ins:
sudo insmod ./timer_dev.ko
del:
sudo rmmod timer_dev
CC := gcc
mt:
$(CC) -o test test_timer.c
.PHONY:clc
clc:
rm test
<file_sep>/work/debug/2440/keys/tiny6410_buttons.c
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/poll.h>
#include <linux/irq.h> // #define S3C_EINT(x) ((x) + S3C_IRQ_EINT_BASE) #define IRQ_EINT(x) S3C_EINT(x)
#include<linux/mm.h>
#include<linux/sched.h>
#include<asm/system.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <linux/interrupt.h>
#include <asm/uaccess.h>
#include <mach/hardware.h>
#include <linux/platform_device.h>
#include <linux/cdev.h>
#include <linux/miscdevice.h>
#include <mach/map.h>
#include <mach/regs-clock.h>
#include <mach/regs-gpio.h>
#include <plat/gpio-cfg.h>
#include <mach/gpio-bank-n.h>
#include <mach/gpio-bank-l.h> //#define S3C64XX_GPLDAT (S3C64XX_GPL_BASE + 0x08)
#define DEVICE_NAME "buttons"
struct fasync_struct *async_queue; /*异步结构体指针,用于读*/
struct button_irq_desc{
int irq;
int number;
char *name;
};
static struct button_irq_desc button_irqs[] = {
{IRQ_EINT(0), 0, "KEY0"},
{IRQ_EINT(1), 1, "KEY1"},
{IRQ_EINT(2), 2, "KEY2"},
{IRQ_EINT(3), 3, "KEY3"},
{IRQ_EINT(4), 4, "KEY4"},
{IRQ_EINT(5), 5, "KEY5"},
{IRQ_EINT(19), 6, "KEY6"},
{IRQ_EINT(20), 7, "KEY7"},
};
static volatile char key_values[] = {'0', '0', '0', '0', '0', '0', '0', '0'};
static DECLARE_WAIT_QUEUE_HEAD(button_waitq); /*定义一个新的等待队列的头*/
static volatile int ev_press = 0; /*判断是否有按键按下的标志位*/
static irqreturn_t buttons_interrupt(int irq, void *dev_id) /*中断处理函数*/
{ /*(void *)&button_irqs[i]申请中断时传进来的参数*/
struct button_irq_desc *button_irqs = (struct button_irq_desc *)dev_id;
int down;
int number;
unsigned tmp;
udelay(0);
number = button_irqs->number;
switch(number) {
case 0: case 1: case 2: case 3: case 4: case 5:
tmp = readl(S3C64XX_GPNDAT); //
down = !(tmp & (1<<number));
break;
case 6: case 7:
tmp = readl(S3C64XX_GPLDAT); /*(返回)从映射的I/O空间读取32位4字节的数值 */
down = !(tmp & (1 << (number + 5)));
break;
default:
down = 0;
}
if (down != (key_values[number] & 1)) {
key_values[number] = '0' + down;
ev_press = 1;
wake_up_interruptible(&button_waitq); /*唤醒阻塞(睡眠)的读等待队列*/
/*产生异步读信号通知相关进程 把要发送的SIGIO 信号发送出去*/
if(async_queue){
kill_fasync(&async_queue, SIGIO, POLL_IN);
#ifdef DEBUG
printk("<0>%s kill SIGIO\n", __func__);
#endif
}
}
/* //means that we did have a valid interrupt and handled it
* #define IRQ_RETVAL(x) ((x) != IRQ_NONE ) //这个宏只是返回0或非0
*/
return IRQ_RETVAL(IRQ_HANDLED);
}
static int s3c64xx_buttons_open(struct inode *inode, struct file *file)
{
int i;
int err = 0;
for (i = 0; i < sizeof(button_irqs)/sizeof(button_irqs[0]); i++) {
if (button_irqs[i].irq < 0) {
continue;
} /*中断号 处理函数 双延触发*/
err = request_irq(button_irqs[i].irq, buttons_interrupt, IRQ_TYPE_EDGE_BOTH, /*申请中断*/
button_irqs[i].name, (void *)&button_irqs[i]);
/*在proc/interrupts中显示中断拥有者 void *dev_id*/
if (err)
break;
}
if (err) { /*出错处理 把之前分配的中断释放掉*/
i--;
for (; i >= 0; i--) {
if (button_irqs[i].irq < 0){
continue;
}
disable_irq(button_irqs[i].irq);
free_irq(button_irqs[i].irq, (void *)&button_irqs[i]);
}
return -EBUSY;
}
ev_press = 1;
return 0;
}
static int s3c64xx_buttons_close(struct inode *inode, struct file *file)
{
int i;
for (i = 0; i < sizeof(button_irqs)/sizeof(button_irqs[0]); i++) {
if (button_irqs[i].irq < 0) {
continue;
}
free_irq(button_irqs[i].irq, (void *)&button_irqs[i]);
}
return 0;
}
static int s3c64xx_buttons_read(struct file *filp, char __user *buff, size_t count, loff_t *offp)
{
unsigned long err;
if (!ev_press) {
if (filp->f_flags & O_NONBLOCK)
return -EAGAIN;
else{
/*这个宏:使调用进程在等待队上睡眠,一直到修改了给定条件为止*/
wait_event_interruptible(button_waitq, ev_press); /*直到ev_press 为 1*/
}
}
ev_press = 0;
err = copy_to_user((void *)buff, (const void *)(&key_values), min(sizeof(key_values), count));
return err ? -EFAULT : min(sizeof(key_values), count);
}
static unsigned int s3c64xx_buttons_poll( struct file *file, struct poll_table_struct *wait)
{
unsigned int mask = 0;
poll_wait(file, &button_waitq, wait);
if (ev_press){
mask |= POLLIN | POLLRDNORM; //有键按下 标示数据可以读取
}
ev_press = 0;
return mask;
}
/*增加支持异步通知的函数 在release 函数中调用 */
static int misc_key_fasync(int fd, struct file *filp, int mode)
{
/*将文件从异步通知列表(相关进程列表)中删除*/
return fasync_helper(fd, filp, mode, &async_queue);
}
/*文件释放函数*/
int misc_key_release(struct inode *inode, struct file *filp)
{
/*将文件从异步通知列表中删除*/
misc_key_fasync(-1, filp, 0);
return 0;
}
static struct file_operations dev_fops = {
.owner = THIS_MODULE,
.open = s3c64xx_buttons_open,
.release = s3c64xx_buttons_close,
.read = s3c64xx_buttons_read,
.poll = s3c64xx_buttons_poll,
.fasync = misc_key_fasync, /*不要忘了在这里也要加上 与内核联系的接口*/
.release = misc_key_release,
};
static struct miscdevice misc = { /*杂项字符设备结构体*/
.minor = MISC_DYNAMIC_MINOR, /*次设备号 表示自动分配*/
.name = DEVICE_NAME, /*设备名*/
.fops = &dev_fops, /*设备操作*/
};
static int __init dev_init(void)
{
int ret;
ret = misc_register(&misc); /*注册一个混杂设备 在加载模块时会自动创建设备文件, 为主设备号为10的字符设备*/
printk(DEVICE_NAME"\tinitialized\n"); /*无需mknod指令创建设备文件。因为misc_register()会调用class_device_create()或者device_create()*/
return ret;
}
static void __exit dev_exit(void)
{
misc_deregister(&misc); /*注销混杂设备 自动删除设备文件*/
}
module_init(dev_init);
module_exit(dev_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("FriendlyARM Inc.");<file_sep>/shell/2nd_week/for.sh
#!/bin/bash
for file in $HOME/share/*.c ../homework/*
do
if [ -d "$file" ]
then
echo "$file is a directory"
elif [ -f "$file" ]
then
echo "$file is a file"
fi
done >output.txt
for ((i=0;i<4;i++))
do
echo "the number is $i"
done
for state in Shanghai Beijing Guangzhou Zhanjiang "New York"
do
echo "$state is the next place to go"
done | sort
<file_sep>/c/lrc/interface.h
/* ************************************************************************
* Filename: interface.h
* Description:
* Version: 1.0
* Created: 2015年08月03日 星期一 03時39分16秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __INTERFACE_H__
#define __INTERFACE_H__
extern char move;
void show_musicbar();
void show_interface();
void show_pattern(const char *src[], int lines, int SROW, int COL);
void show_musiclist(char *plist[]);
void show_progressbar(int time, int timelag);
void show_lrcheader(char *pheader[]);
void show_time(int time, int maxtime);
#endif
<file_sep>/c/lrc/interface.c
/* ************************************************************************
* Filename: interface.c
* Description:
* Version: 1.0
* Created: 2015年08月03日 星期一 03時39分07秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include "common.h"
#include "console.h"
#include "file.h"
#include "interface.h"
const char *logo[6] = {"..____.╭╮╭╮.____",
".._...╭-┴┴-★╮...",
".._...│◎ ︵│_...",
".... ※※※╰○--○╯※※※.",
"......★ 欢迎光临 ★...",
"......★ 无限透明 ★...",
};
const char *wave1[7] = { ".........★︵___︵★........",
"........./● ●\........",
".........︴≡ ﹏ ≡ ︴........",
".........\____ /.........",
".....╭╧╮ ╭╧╮ ╭╧╮ ╭╧╮ ╭╧╮ ╭╧╮ ╭╧╮ ...",
".....│我 |來 │幫 │你 │灌 水│ │哩....",
".....╘∞╛╘∞╛ ╘∞╛ ╘∞╛ ╘∞╛ ╘∞╛ ╘∞╛...",
};
void show_interface()
{
int i = 0;
system("clear");
set_fg_color(COLOR_GREEN);
printf("═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·");
printf("═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·");
printf("═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·\n");
//fflush(stdout);
for(i=0;i<33;i++)
{
cusor_moveto(110, i+2); //
printf("‖");
}
cusor_moveto(0, 34); //
printf("═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·");
printf("═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·");
printf("═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·\n");
set_fg_color(COLOR_WHITE);
show_musicbar();
show_pattern(logo, 6, 2, 1);
//show_pattern(wave, 7, 2, 58);
}
void show_musicbar()
{
int i = 0;
cusor_moveto(0, 9);
set_fg_color(COLOR_GREEN);
printf("·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═");
printf("·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═");
printf("·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·\n");
printf("· >> 歌曲清单 << ·\n");
printf("·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═");
printf("·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═");
printf("·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·\n");
for(i=0;i<20;i++)
{
cusor_moveto(31, 12+i);
printf("‖ ");
}
for(i=2;i<9;i++)
{
cusor_moveto(31, i);
printf("|");
}
cusor_moveto(0, 32);
printf("·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·\n");
printf("· ·\n");
set_fg_color(COLOR_RED);
cusor_moveto(3, 33);
printf("搜索:");
#if 0
printf("■□■□■□■□■□■□■□■□■□■□■□■□■□■□■□■\n");
printf("☆ >> 歌曲清单 << ★\n");
printf("■□■□■□■□■□■□■□■□■□■□■□■□■□■□■□■\n");
for(i=0;i<20;i++)
{
printf(" □\n");
printf(" ■\n");
}
printf("■□■□■□■□■□■□■□■□■□■□■□■□■□■□■□■\n");
printf("· 搜索: ·\n");
x
for(i=32;i<110;i ++)
{
cusor_moveto(i, 9);
printf("-");
//printf("☆★");
}
#endif
fflush(stdout);
set_fg_color(COLOR_WHITE);
cusor_hide(); //隐藏光标
//cusor_moveto(9, 33);
}
void show_pattern(const char *src[], int lines, int SROW, int COL)
{
int i;
for(i=0;i<lines;i++)
{
cusor_moveto(COL, SROW + i);
printf("%s",src[i]);
}
fflush(stdout);
}
void show_musiclist(char *plist[])
{
int i = 0;
set_fg_color(COLOR_BLUE);
for(i=0;plist[i] != NULL && i<20;i++)
{
cusor_moveto(0, 12+i);
printf("%d. %s",i+1,plist[i]);
}
set_fg_color(COLOR_GREEN);
for(i=0;i<20;i++)
{
cusor_moveto(31, 12+i); //为了防止歌名覆盖了原来的界面
printf("‖ ");
}
fflush(stdout);
set_fg_color(COLOR_WHITE);
}
void show_lrcheader(char *pheader[])
{
cusor_moveto(40, 3); //
printf("歌名:%s\n",pheader[0]);
cusor_moveto(40, 4); //
printf("演唱:%s\n",pheader[1]);
cusor_moveto(40, 5); //
printf("作者:%s\n",pheader[2]);
cusor_moveto(41, 14); //
printf("○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○");//
}
/*************************************************************************
* 函数名称:show_progressbar
* 功能说明:显示进度条
* 参数说明:time 歌曲从播放到当前的时间
* timelag 进度条前进的时间间隔
* 函数返回:无
*************************************************************************/
char move = 1;
void show_progressbar(int time, int timelag)
{
char *p = " ";
if(time/(timelag * move) > 0 && move <= 61)
{
cusor_moveto(40+move, 14); //
set_fg_color(COLOR_MAGENTA);
printf("●");
move++;
}
if(time%2 == 0)
{
set_fg_color(COLOR_GREEN);
}
else if(time%3 == 0)
{
set_fg_color(COLOR_RED);
}
else if(time%5 == 0)
{
set_fg_color(COLOR_CYAN);
}
else
{
set_fg_color(COLOR_YELLOW);
}
cusor_moveto(40+move, 14); //
printf("●");
set_fg_color(COLOR_WHITE);
fflush(stdout);
}
/*************************************************************************
* 函数名称:show_time
* 功能说明:显示进度条
* 参数说明:time 歌曲从播放到当前的时间
* 函数返回:无
*************************************************************************/
void show_time(int time, int maxtime)
{
int min = 0,sec = 0,time_left = 0;
time_left = maxtime - time;
if(time_left < 0) time_left = 0;
min = time_left/1000/60; //单位:秒
sec = time_left/1000%60;
if(time_left%1000 > 500)
{
sec += 1;
}
//cusor_moveto(55, 6); //
//printf("%02d:%02d\n",min,sec);
cusor_moveto(40, 6); //
printf("时间:%02d:%02d\n",min,sec);
}
<file_sep>/work/test/pwm-beeper/pwm-beeper.c
/*************************************************************************
> File Name: pwm-beeper.c
> Author: <NAME>
> Mail: <EMAIL>
> Datatime: Wed 09 Nov 2016 03:35:40 PM CST
************************************************************************/
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/input.h>
#define DEFAULT_DEV "event0"
int main(int argc, char *argv[])
{
int fd;
int i;
char dev[32] = "/dev/input/";
struct input_event event;
if(argc > 1)
strcat(dev, argv[1]);
else
strcat(dev, DEFAULT_DEV);
fd = open(dev, O_RDWR);
if(fd < 0) {
printf("Open %s failed\n", dev);
return 1;
}
event.type = EV_SND;
event.code = SND_TONE;
event.value = 0;
for(i = 1; i < 10; i++) {
event.value = i * 100;
printf("event0.value = %d\n", event.value);
write(fd, &event,sizeof(event));
//sleep(1);
}
event.value = 1004000;
write(fd, &event, sizeof(event));
while(1)
sleep(1);
close(fd);
return 0;
}
<file_sep>/sys_program/3rd_day/wfifo.c
/* ************************************************************************
* Filename: fifo.c
* Description:
* Version: 1.0
* Created: 2015年08月17日 14时26分03秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int ret, fd;
char buf[100] = "hello world";
ret = mkfifo("./myfifo",0777);
if(ret < 0) perror("");
printf("creat myfifo\n");
fd = open ("./myfifo",O_WRONLY | O_NONBLOCK);
printf("open success! fd = %d\n",fd);
while(1)
{
write(fd,buf,strlen(buf));
printf("write\n");
sleep(1);
}
return 0;
}
<file_sep>/c/homework/2nd_week/year.c
/* ************************************************************************
* Filename: year.c
* Description:
* Version: 1.0
* Created: 2015年07月16日 星期四 09時17分41秒 HKT
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
int months[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
int main(int argc, char *argv[])
{
char i = 0;
int countday = 0;
int year = 0, month = 0, day = 0;
printf("-----------------------------------------\n");
again:
printf("Please input the year, month, day.\n");
scanf("%d %d %d",&year,&month,&day);
if(year<0 || month<0 ||month >12 || day<0)
{
printf("error! input again!\n");
goto again;
}
else
{
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
checkday1:
if(day>31)
{
printf("Please input a day between 1 to 31!\n");
scanf("%d",&day);
goto checkday1;
}
break;
case 4:
case 6:
case 9:
case 11:
checkday2:
if(day>30)
{
printf("Please input a day between 1 to 30\n");
scanf("%d",&day);
goto checkday2;
}
break;
}
}
if((year%4 == 0 && year%100 != 0) || (year%400 == 0))
{
printf("%d is a leap year!\n",year);
months[1] = 29;
if((month == 2) && (day > 29))
{
printf("Please input a day between 1 to 29!\n");
scanf("%d",&day);
}
}
else
{
printf("%d is not a leap year!\n",year);
months[1] = 28;
if((month == 2) && (day > 28))
{
printf("Please input a day between 1 to 28!\n");
scanf("%d",&day);
}
}
for(i=0;i<month-1;i++)
{
countday += months[i];
}
countday += day;
printf("The day you input is the %d'th day of %d.\n",countday,year);
printf("-------------- %d.%d.%d ----------------\n",year,month,day);
return 0;
}
<file_sep>/sys_program/3rd_day/homework/expr/expr.c
/* ************************************************************************
* Filename: expr.c
* Description:
* Version: 1.0
* Created: 2015年08月17日 19时28分44秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
pid_t pid;
int fd[2];
char cmd[128] = "";
char buf[64] = "";
if(pipe(fd) < 0)
{
perror("");
}
while(1)
{
pid = vfork();
if(pid < 0) perror("");
else if(pid == 0)
{
int len = 0;
printf("Please input a cmd: ");
fgets(cmd,sizeof(cmd),stdin);
len = strlen(cmd);
if(len > 1)
cmd[len-1] = '\0'; //把获取的字符后面的\n转化成 '\0'
else
exit(0);
dup2(fd[1], 1); //
execl("/bin/sh","sh","-c",cmd,NULL);
//_exit(1);
}
else //
{
read(fd[0],buf,sizeof(buf));
printf("%s",buf);
//wait(NULL);
}
}
return 0;
}
<file_sep>/work/debug/a8/gpio_i2c/bma150_i2c.c
#include <linux/module.h>
#include <linux/ioport.h> /* resource */
#include <linux/irq.h> /* IRQ_EINT(23) */
#include <linux/gpio.h> /* S5PV210_GPH3(0) */
#include <linux/platform_device.h> /* platform_device_register() */
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <linux/miscdevice.h>
#include <linux/delay.h>
#define BMA150_ADDR 0x38
#define BMA150_WRITE 0x00
#define BMA150_READ 0x01
#define clk_out() s3c_gpio_cfgpin(S5PV210_GPD1(5),S3C_GPIO_OUTPUT)
#define dat_out() s3c_gpio_cfgpin(S5PV210_GPD1(4),S3C_GPIO_OUTPUT)
#define dat_in() s3c_gpio_cfgpin(S5PV210_GPD1(4),S3C_GPIO_INPUT)
#define clk_clear() gpio_set_value(S5PV210_GPD1(5), 0)
#define clk_set() gpio_set_value(S5PV210_GPD1(5), 1)
#define dat_clear() gpio_set_value(S5PV210_GPD1(4), 0)
#define dat_set() gpio_set_value(S5PV210_GPD1(4), 1)
#define get_data_in() gpio_get_value(S5PV210_GPD1(4))
#define demo_i2c_delay() udelay(50)
static void demo_i2c_send_byte(unsigned char data)
{
signed char i;
dat_out();
clk_clear();
for(i=7;i>=0;i--){
if(data&(1<<i))
dat_set();
else
dat_clear();
demo_i2c_delay();
clk_set();
demo_i2c_delay();/* 对方读取数据 */
clk_clear();
}
}
static unsigned char demo_i2c_receive_byte(void)
{
signed char i;
unsigned char data = 0;
dat_in();
clk_clear();
for(i=7;i>=0;i--){
demo_i2c_delay();
clk_set();
demo_i2c_delay();
// data = data<<1;
data |= get_data_in()<<i;
clk_clear();
}
return data;
}
static void demo_i2c_send_ack(unsigned char ack)
{
dat_out();
clk_clear();
if(ack)
dat_set();
else
dat_clear();
demo_i2c_delay();
clk_set();
demo_i2c_delay();/* 对方读取应答 */
clk_clear();
}
static unsigned char demo_i2c_receive_ack(void)
{
unsigned char ack = 0;
dat_in();
clk_clear();
demo_i2c_delay();
clk_set();
demo_i2c_delay();
ack = get_data_in();
clk_clear();
return ack;
}
static void demo_i2c_start(void)
{
dat_out();
dat_set();
clk_set();
demo_i2c_delay();
dat_clear();
demo_i2c_delay();
clk_clear();
}
static void demo_i2c_stop(void)
{
dat_out();
dat_clear();
clk_set();
demo_i2c_delay();
dat_set();
demo_i2c_delay();
clk_clear();
}
static void demo_i2c_init(void)
{
clk_out();
dat_out();
clk_clear();
dat_clear();
}
static void demo_i2c_send(unsigned char reg,unsigned char *buff,int len)
{
int i = 0;
demo_i2c_start();
demo_i2c_send_byte((BMA150_ADDR<<1)|BMA150_WRITE);/* 发送地址 */
demo_i2c_receive_ack();
demo_i2c_send_byte(reg);
demo_i2c_receive_ack();
while(len--){
demo_i2c_send_byte(buff[i++]);
demo_i2c_receive_ack();
}
demo_i2c_stop();
}
static void demo_i2c_receive(unsigned char reg,unsigned char *buff,int len)
{
int i = 0;
demo_i2c_start();
demo_i2c_send_byte((BMA150_ADDR<<1)|BMA150_WRITE);/* 发送地址 */
demo_i2c_receive_ack();
demo_i2c_send_byte(reg);
demo_i2c_receive_ack();
demo_i2c_stop();
demo_i2c_start();
demo_i2c_send_byte((BMA150_ADDR<<1)|BMA150_READ);/* 发送地址 */
demo_i2c_receive_ack();
while(len--){
buff[i++] = demo_i2c_receive_byte();
if(len == 0)
demo_i2c_send_ack(1);
else
demo_i2c_send_ack(0);
}
demo_i2c_stop();
}
static int demo_bma150_open(struct inode *pinode, struct file *pfile)
{
unsigned char chip_id;
demo_i2c_receive(0x00,&chip_id,1);
printk("%s,%d,id = %d\n",__FUNCTION__,__LINE__,chip_id);
return 0;
}
static ssize_t demo_bma150_read(struct file *pfile, char __user *buffer, size_t count, loff_t *offset)
{
unsigned char data[6];
signed short x,y,z;
demo_i2c_receive(0x02,data,6);
x = (data[0]>>6)|(data[1]<<2);
y = (data[2]>>6)|(data[3]<<2);
z = (data[4]>>6)|(data[5]<<2);
x = (signed short)(x<<6)>>6;/* 符号位扩展 */
y = (signed short)(y<<6)>>6;
z = (signed short)(z<<6)>>6;
printk("x=%d,y=%d,z=%d\n",x,y,z);
return 1;
}
static struct file_operations bma150_fops = {
.owner = THIS_MODULE,
.open = demo_bma150_open,
.read = demo_bma150_read,
};
static struct miscdevice bma150_ops = {
.minor = MISC_DYNAMIC_MINOR,
.name = "bma150_dev",
.fops = &bma150_fops,
};
static int __init demo_bma150_init(void)
{
printk("%s,%d\n",__FUNCTION__,__LINE__);
demo_i2c_init();
return misc_register(&bma150_ops);
}
static void __exit demo_bma150_exit(void)
{
printk("%s,%d\n",__FUNCTION__,__LINE__);
misc_deregister(&bma150_ops);
}
module_init(demo_bma150_init);
module_exit(demo_bma150_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/debug/ingenic/pe10/test_pe10.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#define PE10_IOC_MAGIC 'p'
#define PE10_SET_ON_TIMER _IO(PE10_IOC_MAGIC, 1)
#define PE10_SET_OFF_TIMER _IO(PE10_IOC_MAGIC, 2)
int main(int argc, char *argv[])
{
char cmd[64] = {0};
char *pcmd[5] = {NULL};
int fd = 0, arg = 0, i = 0;
fd = open("/dev/pe10_gpio", O_RDWR);
if(fd <0){
printf("open '/dev/pe10_gpio' failed\n");
return -1;
}
while(1) {
bzero(cmd, sizeof(cmd));
printf("\033[31mCMD: \033[0m");
fflush(stdout);
fgets(cmd, sizeof(cmd), stdin);
cmd[strlen(cmd) - 1] = 0;
if(strlen(cmd) == 0)
continue;
i = 0;
pcmd[i++] = strtok(cmd, " ");
if(pcmd[0] != NULL) {
pcmd[i++] = strtok(NULL, " ");
}
if(strcmp(pcmd[0], "on") == 0) {
if(pcmd[1] != NULL) {
arg = atoi(pcmd[1]);
printf("set on time as %d\n", arg);
ioctl(fd, PE10_SET_ON_TIMER, arg);
}
else
printf("set on time : on <value>\n");
}
else if(strcmp(pcmd[0], "off") == 0) {
if(pcmd[1] != NULL) {
arg = atoi(pcmd[1]);
printf("set off time as %d\n", arg);
ioctl(fd, PE10_SET_OFF_TIMER, arg);
}
else
printf("set off time: off <value>\n");
}
else if(strcmp(pcmd[0], "help") == 0) {
printf("\033[34mset on time : on <value>\033[0m\n");
printf("\033[34mset off time: off <value>\033[0m\n");
printf("\033[34msetting exit: q\n");
}
else if(strcmp(pcmd[0], "q") == 0) {
break;
}
else {
printf("wrong cmd, input 'help' to get help.\n");
}
}
close(fd);
return 0;
}
<file_sep>/java/Test.java
/*
public class Test {
void max(int a , int b) {
System.out.println( a > b ? a : b );
}
void max(short a , short b) {
System.out.println("short");
System.out.println( a > b ? a : b );
}
void max(float a, float b) {
System.out.println( a > b ? a : b );
}
public static void main(String[] args) {
Test t = new Test();
t.max(3, 4);
//short a = 3;
//short b = 4;
t.max((short)3, (short)4);
}
}*/
public class Test {
public static void main(String[] args) {
int i,j;
int a[][]={{1,2},{3,4,5},{6},{7,8,9,0,}};
String s[][];
s = new String[3][];
s[0] = new String[2];
s[1] = new String[3];
s[2] = new String[4];
for(i=0;i < a.length;i++) {
for(j=0; j < a[i].length;j++) {
System.out.print("a["+i+"]["+j+"] = "+a[i][j]+" ");
}
System.out.println();
}
for(i=0;i < s.length;i++) {
for(j=0; j < s[i].length;j++) {
s[i][j] = new String("ÎÒµÄλÖÃÊÇ£º"+i+","+j+" ");
}
}
for(i=0;i < s.length;i++) {
for(j=0; j < s[i].length;j++) {
System.out.print(s[i][j]+" ");
}
System.out.println();
}
}
}<file_sep>/gtk/1. base/02_image/demo.c
#include <gtk/gtk.h>
typedef struct _Window
{
GtkWidget *main_window;
GtkWidget *table;
GtkWidget *image;
GtkWidget *button_previous;
GtkWidget *button_next;
}WINDOW;
// 给创建好的image重新设计一张图片
void load_image(GtkWidget *image, const char *file_path, const int w, const int h )
{
gtk_image_clear( GTK_IMAGE(image) ); // 清除图像
GdkPixbuf *src_pixbuf = gdk_pixbuf_new_from_file(file_path, NULL); // 创建图片资源
GdkPixbuf *dest_pixbuf = gdk_pixbuf_scale_simple(src_pixbuf, w, h, GDK_INTERP_BILINEAR); // 指定大小
gtk_image_set_from_pixbuf(GTK_IMAGE(image), dest_pixbuf); // 图片控件重新设置一张图片(pixbuf)
g_object_unref(src_pixbuf); // 释放资源
g_object_unref(dest_pixbuf); // 释放资源
}
// 根据图片路径创建一个新按钮,同时指定图片大小
GtkWidget *create_button_from_file(const char *file_path, const int w, const int h)
{
GtkWidget *temp_image = gtk_image_new_from_pixbuf(NULL);
load_image(temp_image, file_path, w, h);
GtkWidget *button = gtk_button_new(); // 先创建空按钮
gtk_button_set_image(GTK_BUTTON(button), temp_image); // 给按钮设置图标
gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE); // 按钮背景色透明
return button;
}
// 按钮的回调函数
void deal_switch_image(GtkWidget *button, gpointer data)
{
WINDOW *p_temp = (WINDOW *)data;
if(button == p_temp->button_previous){ // 上一张
printf("p_temp->button_previous\n");
}else if(button == p_temp->button_next ){ // 下一张
printf("p_temp->button_next\n");
}
}
void window_demo(gpointer data)
{
WINDOW *p_temp = (WINDOW *)data;
// 主窗口
p_temp->main_window = gtk_window_new(GTK_WINDOW_TOPLEVEL); // 创建主窗口
gtk_window_set_title(GTK_WINDOW(p_temp->main_window), "image"); // 设置窗口标题
gtk_window_set_position(GTK_WINDOW(p_temp->main_window), GTK_WIN_POS_CENTER); // 设置窗口在显示器中的位置为居中
gtk_widget_set_size_request(p_temp->main_window, 800, 480); // 设置窗口的最小大小
gtk_window_set_resizable(GTK_WINDOW(p_temp->main_window), FALSE); // 固定窗口的大小
g_signal_connect(p_temp->main_window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
// 表格布局
p_temp->table = gtk_table_new(7, 7, TRUE); // 表格布局容器
gtk_container_add(GTK_CONTAINER(p_temp->main_window), p_temp->table); // 容器加入窗口
// 图片控件
p_temp->image = gtk_image_new_from_pixbuf(NULL); // 创建图片控件
load_image(p_temp->image, "./image/1.jpg", 500, 450);
gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->image, 1, 6, 1, 6); // 把图片控件加入布局
// 按钮
p_temp->button_previous = create_button_from_file("./image/previous.bmp", 80, 80);
gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_previous, 1, 2, 6, 7);
g_signal_connect(p_temp->button_previous, "clicked", G_CALLBACK(deal_switch_image), p_temp);
p_temp->button_next = create_button_from_file("./image/next.bmp", 80, 80);
gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_next, 5, 6, 6, 7);
g_signal_connect(p_temp->button_next, "clicked", G_CALLBACK(deal_switch_image), p_temp);
gtk_widget_show_all(p_temp->main_window);
}
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv); // 初始化
WINDOW window;
window_demo(&window);
gtk_main(); // 主事件循环
return 0;
}<file_sep>/work/test/cim_test-zmm220/cim.c
#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/fb.h>
#include <asm/mman.h>
#include <sys/mman.h>
#include <string.h>
#include "cim.h"
#include "arca.h"
#define CIM0308DEV "/dev/cim0"
#define CIM367DEV "/dev/cim1"
#define GC0308 1
#define MT367 2
/*
* IOCTL_XXX commands
*/
#define IOCTL_READ_REG 0 /* read sensor registers */
#define IOCTL_WRITE_REG 1 /* write sensor registers */
#define IOCTL_READ_EEPROM 2 /* read sensor eeprom */
#define IOCTL_WRITE_EEPROM 3 /* write sensor eeprom */
#define IOCTL_SET_IMG_FORMAT 8 //arg type:enum imgformat
#define IOCTL_SET_TIMING_PARAM 9 // arg type: timing_param_t *
#define IOCTL_SET_IMG_PARAM 10 // arg type: img_param_t *
#define IOCTL_CIM_READ_REG 211
static int cim0308_fd=-1;
static int cim367_fd=-1;
int set_timing_param(int id,TIMING_PARAM *timing)
{
printf(" %s %d \n",__func__,__LINE__);
switch(id)
{
case GC0308:
if (ioctl(cim0308_fd, IOCTL_SET_TIMING_PARAM, (unsigned long)timing) < 0){
printf("set_timing_param failed!\n");
return 0;
}
break;
case MT367:
if (ioctl(cim367_fd, IOCTL_SET_TIMING_PARAM, (unsigned long)timing) < 0){
printf("set_timing_param failed!\n");
return 0;
}
break;
default:
return 0;
}
return 1;
}
int set_img_format(int fd, img_format_t format)
{
if (ioctl(fd, IOCTL_SET_IMG_FORMAT, &format) < 0) {
printf("set_img_format failed!\n");
return 0;
}
return 1;
}
int set_img_param(int fd,IMG_PARAM *img)
{
printf(" %s %d \n",__func__,__LINE__);
if (ioctl(fd, IOCTL_SET_IMG_PARAM, (unsigned long)img) < 0) {
printf("set_img_param failed!\n");
return 0;
}
return 1;
}
int cim_open(int id,int width, int height, int bpp)
{
IMG_PARAM param;
printf(" %s %d \n",__func__,__LINE__);
switch(id)
{
case GC0308:
{
if(cim0308_fd>0) cim_close(GC0308);
cim0308_fd = open(CIM0308DEV, O_RDWR);
if(cim0308_fd < 0)
{
printf("Error opening %s \n",CIM0308DEV);
return -1;
}
printf("open %s success \n",CIM0308DEV);
if (set_img_format(cim0308_fd, RGB565) == 0)
return -1;
param.width = width;
param.height = height;
param.bpp = bpp;
if (set_img_param(cim0308_fd,¶m) == 0)
return -1;
return cim0308_fd;
}
case MT367:
{
if(cim367_fd>0) cim_close(MT367);
cim367_fd = open(CIM367DEV, O_RDWR);
if(cim367_fd < 0)
{
printf("Error opening %s \n",CIM367DEV);
return -1;
}
if (set_img_format(cim367_fd, YUV422_SEP) == 0)
return -1;
param.width = width;
param.height = height;
param.bpp = bpp;
if (set_img_param(cim367_fd,¶m) == 0)
return -1;
return cim367_fd;
}
}
return -1;
}
/* Read a frame of image */
int cim_read(unsigned char id,unsigned char *buf, int frame_size)
{
switch(id)
{
case GC0308:
return read(cim0308_fd, buf, frame_size);
case MT367:
return read(cim367_fd, buf, frame_size);
default:
return 0;
}
}
void cim_close(int id)
{
switch(id)
{
case GC0308:
close(cim0308_fd);
cim0308_fd = -1;
break;
case MT367:
close(cim367_fd);
cim367_fd = -1;
break;
default:
break;
}
}
void *cim_mmap(int id, unsigned int size)
{
caddr_t mem;
switch(id){
case GC0308:
if ((mem = mmap(0, size, PROT_READ | PROT_WRITE,
MAP_SHARED, cim0308_fd, 0)) == MAP_FAILED) {
perror(__func__);
return NULL;
}
break;
case MT367:
if ((mem = mmap(0, size, PROT_READ | PROT_WRITE,
MAP_SHARED, cim367_fd, 0)) == MAP_FAILED) {
perror(__func__);
return NULL;
}
break;
default:
return NULL;
}
return (mem);
}
<file_sep>/network/2nd_day/tftp_pull.c
/******************************************************************************
文 件 名 : tftp_client.c
版 本 号 :
作 者 :
生成日期 : 2015年9月1日
最近修改 :
功能描述 : TFTP 客户端
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
typedef enum _mode
{
pull = 0,
push = 1,
}MODE;
int main(int argc, char *argv[])
{
fd_set rfds;
MODE flag;
struct timeval tv;
FILE *fp = NULL;
char file_name[128] = "";
char server_ip[16] = "10.221.2.12";
unsigned char cmd[128] = "", msg[1024] = "";
int sockfd = 0, ask = 0, ret = 0;
int cmd_len = 0, msg_len = 0, snd_len = 0;
unsigned short port = 69; // TFTP服务器的固定端口
if(argc < 2)
{
printf("parameter too little!\n");
printf("please run again: ./elf pull/push filename\n");
exit(-1);
}
strcpy(file_name, argv[2]);
printf("file_name = %s\n",file_name);
//创建一个套接字
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
//配置服务器的地址
struct sockaddr_in server_addr;
socklen_t server_len = sizeof(server_addr);
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);//服务器的端口
inet_pton(AF_INET, server_ip ,&server_addr.sin_addr.s_addr);//服务器的IP
if(strcmp("pull", argv[1]) == 0) //下载
{
flag = pull;
printf("pull>>>\n");
cmd_len = sprintf(cmd, "%c%c%s%c%s%c", 0, 1, file_name, 0, "octet", 0); //octet: 二进制模式;netascii: 文本模式
sendto(sockfd, cmd, cmd_len, 0,\
(struct sockaddr *)&server_addr, sizeof(server_addr));
fp = fopen(file_name, "wb");
if(fp == NULL)
{
printf("%s is not exist!!\n", file_name);
exit(-1);
}
}
else if(strcmp("push", argv[1]) == 0) //上传
{
flag = push;
printf("push>>>\n");
cmd_len = sprintf(cmd, "%c%c%s%c%s%c", 0, 2, file_name, 0, "octet", 0);
sendto(sockfd, cmd, cmd_len, 0,\
(struct sockaddr *)&server_addr, sizeof(server_addr));
fp = fopen(file_name, "rb");
if(fp == NULL)
{
printf("%s is not exist!!\n", file_name);
exit(-1);
}
}
else
{
printf("Err: argv[1] != pull/push\n");
exit(-1);
}
while(1)
{
bzero(msg, sizeof(msg));
bzero(&server_addr, sizeof(server_addr));
FD_ZERO(&rfds);
FD_SET(sockfd, &rfds);
/* Wait up to one second. */
tv.tv_sec = 1;
tv.tv_usec = 0;
ret = select(FD_SETSIZE, &rfds, NULL, NULL, &tv);
if(ret < 0) perror("");
if(FD_ISSET(sockfd, &rfds))
{
msg_len = recvfrom(sockfd, msg, sizeof(msg), 0, \
(struct sockaddr *)&server_addr, &server_len);
}
else
{
printf("time out, continue!\n");
continue;
}
if(flag == pull) //下载
{
if(msg[1] == 3) //数据确认
{
//printf("ask_no = %d&&&&&&&&&\n",msg[3]);
if(ask != msg[3])
{
ask = msg[3];
//把接收的数据写入文件
fwrite((msg+4), msg_len - 4, 1, fp);
}
if(msg_len < 516)
{
//fclose(fp);
break;
}
msg[1] = 4; //数据确认操作码
//发送确认信号
sendto(sockfd, msg, 4, 0,\
(struct sockaddr *)&server_addr, sizeof(server_addr));
printf("ask_no = %d&&&&&&&&&\n",msg[3]);
}
}
else if(flag == push)
{
if(msg_len == 4)
{
//bzero(msg, sizeof(msg));
msg_len = fread((msg+4), 1, 512, fp);//用fread((msg+4), 512, 1, fp);只能读到一个字节
//printf("read_len = %d\n",msg_len);
if(msg_len == 0)
{
printf("push %s finish!\n",file_name);
break;
}
ask++;
msg[0] = 0;
msg[1] = 3;
msg[2] = ask/256;
msg[3] = ask%256;
printf("msg[1]=%d msg[2~3]=%d\n",msg[1], msg[2] * 256 + msg[3]);
//发送数据
snd_len = sendto(sockfd, msg, msg_len+4, 0,\
(struct sockaddr *)&server_addr, sizeof(server_addr));
if(snd_len != msg_len+4)
{
printf("Err: send msg to server error!\n");
}
}
}
}
fclose(fp);
close(sockfd);
return 0;
}
<file_sep>/sys_program/3rd_day/pipe.c
/* ************************************************************************
* Filename: pipe.c
* Description:
* Version: 1.0
* Created: 2015年08月17日 10时18分41秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd[2];
char buf[100] = "Hello world";
pid_t pid;
if(pipe(fd) < 0)
{
perror("");
}
printf("fd[0] = %d fd[1] = %d\n",fd[0],fd[1]);
pid = fork();
if(pid <0 )
{
perror("");
}
else if(pid == 0)
{
write(fd[1],buf,strlen(buf));
exit(1);
}
else
{
wait(NULL);
memset(buf,0,sizeof(buf));
read(fd[0],buf,sizeof(buf));
printf("buf = %s\n",buf);
}
return 0;
}
<file_sep>/sys_program/player/src/inc/mplayer_ui.h
#ifndef __MPLAYER_UI_H__
#define __MPLAYER_UI_H__
//extern MPLAYER mplayer;
extern SunGtkCList *musiclist;
extern void window_init(MPLAYER *pm);
extern void mplayer_ui_show(int argc, char *argv[], MPLAYER *pm);
#endif
<file_sep>/c/practice/sort/quicksort.c
#include <stdio.h>
void swap(int *a,int *b)
{ /*序列中元素位置的交换*/
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void print(int k[])
{
int i;
static int cont = 0;
cont++;
printf("\n第 %d 次: ",cont);
for(i=0;i<10;i++)
{
printf("%d ",k[i]);
}
printf("\n");
}
void quicksort(int k[], int start_num, int end_num)
{ /*快速排序*/
int i, j;
if(start_num < end_num)
{
i = start_num;
j = end_num + 1;
while(1)
{
do{
i++;
}while( !(k[i] >= k[start_num] || i == end_num)); //从第一个开始求出第一个大于基准值的元素位置i
do{
j--;
}while( !(k[j] <= k[start_num] || j == start_num)); //从最后开始求出第一个小于基准值的元素位置j
if(i < j) swap(&k[i], &k[j]);
else break;
}
swap(&k[start_num], &k[j]);
quicksort(k, start_num, j-1); /*递归排序基准元素前面的子序列*/
quicksort(k, j+1, end_num); /*递归排序基准元素后面的子序列*/
}
}
int main()
{
int k[10]={2,5,6,3,7,8,1,9,12,0} , i;
printf("The data array is\n") ;
for(i=0;i<10;i++) /*显示原序列之中的元素*/
printf("%d ",k[i]);
printf("\n");
quicksort(k,0,9); /*快速排序*/
printf("\nThe result of quick sorting for the array is\n");
for(i=0;i<10;i++) /*显示排序后的结果*/
printf("%d ",k[i]);
printf("\n");
return 0;
}
<file_sep>/work/test/pwm-led/pwm-led.sh
#!/bin/sh
cd /sys/class/leds/led_state/
val=`cat brightness`
for i in $(seq $val 254)
do
echo $i
echo $i > brightness
usleep 20000
done
for i in $(seq 254 0)
do
echo $i
echo $i > brightness
usleep 20000
done
<file_sep>/work/test/netlink/Makefile
ifneq ($(KERNELRELEASE),)
obj-m := netlink_kernel.o
else
CC=mips-linux-gnu-gcc
KERNELDIR ?= ~/work/sz-halley2/kernel
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
rm -rf *.o *.mod.c *.order *.symvers .*.cmd .tmp*
clean:
rm -f *.o *~ *.ko *.mod.c *.mod.o *.symvers *.order
endif
<file_sep>/network/sockets/UDPEchoServer.c
/*************************************************************************
> File Name: UDPEchoServer.c
> Author:
> Mail:
> Created Time: Mon 16 May 2016 06:09:10 PM CST
************************************************************************/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include "Practical.h"
int main(int argc, char *argv[])
{
if(argc != 2)
DieWithUserMessage("Parameter(s)", "<Server Port/Service>");
char *service = argv[1];
}
<file_sep>/c/practice/3rd_week/mylink/Makefile
link: main.c link.c
gcc -o link main.c link.c
clean:
rm link
<file_sep>/gtk/1. base/06_timeout/timeout.c
#include <gtk/gtk.h>
#include <stdlib.h>
#include <string.h>
guint timer; // 定时器id
/* 功能: 设置控件字体大小
* widget: 需要改变字体的控件
* size: 字体大小
* is_button: TRUE代表控件为按钮,FALSE为其它控件
*/
void set_widget_font_size(GtkWidget *widget, int size, int is_button)
{
GtkWidget *labelChild;
PangoFontDescription *font;
gint fontSize = size;
font = pango_font_description_from_string("Sans");//"Sans"字体名
pango_font_description_set_size(font, fontSize*PANGO_SCALE);//设置字体大小
if(is_button){
labelChild = gtk_bin_get_child(GTK_BIN(widget));//取出GtkButton里的label
}else{
labelChild = widget;
}
//设置label的字体,这样这个GtkButton上面显示的字体就变了
gtk_widget_modify_font(GTK_WIDGET(labelChild), font);
pango_font_description_free(font);
}
/* 功能: 定时器处理函数
* label: 主要用于显示数字
*/
gboolean deal_time( GtkWidget* label )
{
char buf[5] = "";
static int num = 10;
num--;
sprintf(buf, "%d", num);
gtk_label_set_text(GTK_LABEL(label), buf);
if(0 == num){
num = 11;
//g_source_remove(timer); // 移除定时器
}
return TRUE;
}
int main( int argc, char *argv[])
{
gtk_init(&argc, &argv);
/////////////////主窗口操作
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "倒计时");
gtk_container_set_border_width(GTK_CONTAINER(window), 0);
//设置窗口默认大小,设置一个最小大小
gtk_window_set_default_size(GTK_WINDOW(window), 320, 400);
//设置窗口在显示器中的位置为居中。
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
g_signal_connect( G_OBJECT(window), "destroy",
G_CALLBACK(gtk_main_quit), NULL ); //按关闭按钮可以把程序中断
// 倒计时显示区域
GtkWidget *label = gtk_label_new("10"); // label的创建
set_widget_font_size(label, 230, FALSE); // 设置label的字体大小
gtk_container_add(GTK_CONTAINER(window), label);
// 定时器的创建
timer = g_timeout_add(500, (GSourceFunc)deal_time, (gpointer)label);
gtk_widget_show_all(window); // 显示所有部件
gtk_main();
return 0;
}<file_sep>/sys_program/player/src/mplayer_pthread.c
/* ************************************************************************
* Filename: mplayer_process.c
* Description:
* Version: 1.0
* Created: 2015年08月23日 18时05分21秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include "common.h"
#include "file.h"
#include "link.h"
#include "process_lrc.h"
#include "mplayer_control.h"
#include "mplayer_pthread.h"
SONG song;
void mplayer_init(MPLAYER *pm)
{
FILE *fp = NULL;
int i = 0, ret = 0;
char buf[128];
song.song_src = (char *)get_musiclist(&song.psong_list, &song.count);
if(song.count > 0)
{
song.search = NULL;
song.search = (char *)malloc(song.count + 1);
if(song.search == NULL) perror("");
bzero(song.search, song.count+1);
}
pm->playflag = playing; //暂停
pm->playmode = list_loop;//列表顺序播放模式
pm->soundflag = beam; //播音
bzero(song.name, sizeof(song.name));
fp = fopen(".song", "r");
if(fp != NULL)
{
fread(buf, sizeof(buf), 1, fp);
if(get_songname(song.name,buf) == 0)
{
printf("get_songname = %s\n",song.name);
for(i = 0;i < song.count; i++)
{
if(strcmp(song.name,song.psong_list[i]) == 0)
{
song.now = i;
song.old = i;
break;
}
}
if(i == song.count)
{
song.now = 0;
song.old = 0;
strcpy(song.name, song.psong_list[0]);
}
}
}
else
{
song.now = 6;
song.old = 6;
strcpy(song.name, song.psong_list[6]);
}
song.keyflag = init;
song.endflag = FALSE;
//?
ret = pipe(pm->fd);
if(ret < 0) perror("pipe");
unlink("./.cmd_fifo"); //
mkfifo("./.cmd_fifo",0666); //
pm->fd_pipe = open("./.cmd_fifo", O_RDWR);
//write(pm->fd_pipe, "pause\n", strlen("pause\n"));//
//??
sem_init(&song.sem_keyflag, 0, 1);
sem_init(&song.sem_setsong, 0, 1);
//?
pthread_mutex_init(&pm->mutex, NULL);
}
int mplayer_process(MPLAYER *pm)
{
pm->pid = fork();//
if(pm->pid < 0)
{
perror("fork:");
return(-1);
}
if(pm->pid == 0)
{
//char buf[256] = "./music/";
//printf("in son process >> song_name = %s\n",song.name);
//strcat(buf,song.name);
if( dup2(pm->fd[1], 1) < 0) perror("dup2");//??
printf("start mplayer now!\n");
//启动mplayer
execlp("mplayer",
"mplayer",
"-slave", "-quiet","-idle",
"-input", "file=./.cmd_fifo",
"./music/login.wav", NULL);
exit(0);
}
return 0;
}
void gtk_thread_init(void)
{
if( FALSE == g_thread_supported() )
{
g_thread_init(NULL);
}
gdk_threads_init();
}
void *pthread_show_lrc(void *agr)
{
MPLAYER *pm = (MPLAYER *)agr;
LRC *pb = NULL;
char buf[256];
char lrc_path[] = "./music/lyric/";
while(1)
{
usleep(500*MS);
if(pm->playflag == playing)
{
if(song.keyflag != quiet)
{
set_keyflag(quiet);
free_link(song.lrc_head);
bzero(buf,sizeof(buf));
strcat(buf,lrc_path);
strcat(buf,song.name);
get_lrcname(buf);
dispose_lrc(pm, buf);
playing_song(pm, song.now);
song.cur_time = 0;
song.end_time = 0;
song.endflag = FALSE;
}
if(song.pnode != NULL && song.cur_time >= song.pnode->time) //
{
pb = NULL;
pb = (LRC *)search_link(song.pnode, song.pnode->time); //song.pnode???????
mplayer_show_lyric(pm, pb);
if(pb != NULL) song.pnode = song.pnode->next;
}
if((song.rate/100.0) >= 0.99) //
{
song.endflag = TRUE;
set_playing_song(pm, 1);
set_keyflag(init);
song.rate = 0;
}
}
}
}
void *pthread_send_cmd(void *agr)
{
MPLAYER *pm = (MPLAYER *)agr;
char *cmd[]={ "get_percent_pos\n", "get_time_pos\n","get_time_length\n", "get_file_name\n", "get_meta_artist\n"};
int i = 0;
while(1)
{
for(i=0; i < 5; i++)
{
if((pm->playflag == playing) && (song.endflag == FALSE))
{
send_cmd(cmd[i], pm);
usleep(100*MS);
}
}
}
}
void *pthread_rcv_msg(void *agr)
{
MPLAYER *pm = (MPLAYER *)agr;
float temp = 0.0;
char msg[256];
char *p = NULL, buf[16];
while(1)
{
usleep(80*MS);
if(pm->playflag == playing)
{
bzero(msg,sizeof(msg));
read(pm->fd[0], msg, sizeof(msg));
//printf(">>>>>pthread_rcv_msg = %s\n",msg);
if((p = strstr(msg, "ANS_PERCENT_POSITION=")) != NULL)
{
sscanf(p,"ANS_PERCENT_POSITION=%f",&song.rate);
gdk_threads_enter();
gtk_progress_bar_set_fraction(pm->ui.hbox_right.progress_bar, song.rate/100.0);
gdk_threads_leave(); }
if((p = strstr(msg,"ANS_TIME_POSITION=")) != NULL)
{
sscanf(msg,"ANS_TIME_POSITION=%f\n",&temp);
bzero(buf,sizeof(buf));
sprintf(buf,"%02d:%02d", (int)temp/60, (int)temp%60);
set_lable(pm->ui.hbox_right.label_cur_time, buf);
song.cur_time = (int)(temp * 1000);
//printf("music cur_time = %d ms\n",song.cur_time);
}
if((p = strstr(msg,"ANS_LENGTH=")) !=NULL)
{
sscanf(p,"ANS_LENGTH=%f",&temp);
bzero(buf,sizeof(buf));
sprintf(buf,"%02d:%02d", (int)temp/60, (int)temp%60);
set_lable(pm->ui.hbox_right.label_end_time, buf);
song.end_time = (int)(temp * 1000);
//printf("music end_time = %d ms\n",song.end_time);
}
#if 1
if((p = strstr(msg, "ANS_FILENAME=")) != NULL)
{
char buf[128] = {0};
sscanf(p,"ANS_FILENAME='%[^']",buf);
set_lable(pm->ui.hbox_right.label_title1, buf);
}
if((p = strstr(msg, "ANS_META_ARTIST=")) != NULL)
{
char buf[128] = {0};
char utf8[128] = {0};
sscanf(p,"ANS_META_ARTIST='%[^']",buf);
gb2312_to_utf8(buf, utf8);
set_lable(pm->ui.hbox_right.label_title2, utf8);
}
#endif
}
}
}
void create_pthread(MPLAYER *pm)
{
pthread_create(&pm->pth_sendcmd,NULL,pthread_send_cmd,(void *)pm);
pthread_create(&pm->pth_rcvmsg, NULL,pthread_rcv_msg, (void *)pm);
pthread_create(&pm->pth_showlrc,NULL,pthread_show_lrc,(void *)pm);
pthread_detach(pm->pth_showlrc);
pthread_detach(pm->pth_rcvmsg);
pthread_detach(pm->pth_sendcmd);
}
<file_sep>/c/practice/2nd_week/fun_pointer/Makefile
fun_pointer:fun_pointer.c fun.c
.PHONY:clean
clean:
rm fun_pointer
<file_sep>/gtk/2. configure/03. vim_gtk自动补全/readme.txt
1) 把文件夹《vim_configure》拷贝到虚拟机任意目录
2) 进入此文件夹,sudo运行copy_con.sh脚本<file_sep>/gtk/4st_week/gtk_calculator.c
/* ************************************************************************
* Filename: gtk_calculator.c
* Description:
* Version: 1.0
* Created: 2015年08月10日 19时59分35秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <gtk/gtk.h>
int main(int argc, char *argv[])
{
gtk_init(&argc,&argv);
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window),"GTK entry");
gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER);//设置窗口的位置
gtk_widget_set_size_request(window, 500, 300); //设置窗口的大小
gtk_window_set_resizable(GTK_WINDOW(window),FALSE); //设置窗口是否可以改变大小
GtkWidget *entry = gtk_entry_new(); //创建行编辑
gtk_entry_set_max_length(GTK_ENTRY(entry), 100); //设置行编辑显示最大字符的长度
gtk_entry_set_text(GTK_ENTRY(entry), "1+2=3"); //设置显示内容
gtk_entry_set_editable(GTK_EDITABLE(entry),FALSE); //设置行编辑不予许编辑,只能显示
<file_sep>/work/test/fb_test/fb_test.c
/*************************************************************************
> File Name: fb_test.c
> Author:
> Mail:
> Created Time: Mon 30 May 2016 04:06:45 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#define RED_COLOR565 0x0f100
#define GREEN_COLOR565 0x007e0
#define BLUE_COLOR565 0x0001f
#define RED_COLOR888 0xff0000
#define GREEN_COLOR888 0x00ff00
#define BLUE_COLOR888 0x0000ff
int main()
{
int fd = 0;
int x = 0, y = 0;
int div = 0;
char *fbp = NULL;
struct fb_var_screeninfo vinfo;
struct fb_fix_screeninfo finfo;
struct fb_cmap cmapinfo;
long int screensize = 0;
long int location = 0;
//Open the file for reading and writing
fd = open("/dev/fb0", O_RDWR);
if(fd < 0) {
printf("ERROR: cannot open framebuffer device. %d\n", fd);
exit(1);
}
printf("The framebuffer device was opened successfully!\n");
//Get fixed screen infomation
if(ioctl(fd, FBIOGET_FSCREENINFO, &finfo)) { //
printf("ERROR: cannot get fixed infomation!\n ");
exit(2);
}
printf(finfo.id);
printf("\ntype: 0x%x\n", finfo.type);
printf("visual: %d\n", finfo.visual);
printf("line_length: %d\n", finfo.line_length);
printf("smem_start: 0x%x, smem_len: %d\n", finfo.smem_start, finfo.smem_len);
printf("mmio_start: 0x%x, mmio_len: %d\n", finfo.mmio_start, finfo.mmio_len);
// Get variable screen infomation
if(ioctl(fd, FBIOGET_VSCREENINFO, &vinfo)) {
printf("ERROR: cannot get variable infomation!\n");
exit(3);
}
printf("%d x %d, %dbpp\n", vinfo.xres, vinfo.yres, vinfo.bits_per_pixel);
//Figure out the size of the screen in bytes
screensize = vinfo.xres * vinfo.yres * vinfo.bits_per_pixel/8;
//Map the device to memory
fbp = (char *)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if((int)fbp == -1) {
printf("ERROR: failed to map framebuffer device to memory!\n");
exit(4);
}
printf("The framebuffer device was mapped to memory successfully!\n");
//Figure out where in memory to put the pixel
#if 0
int r, b, g;
b = 0x10; //blue:0000 0010
g = 0x100; //green: 0000 0100
r = 0x100; //red: 0000 0100
//vinfo.xoffset = (240-160)/2;
//vinfo.yoffset = (240-160)/2;
for(y = 80; y < 160; y++) {
for(x = 80; x < 160; x++) {
location = (x + vinfo.xoffset) * (vinfo.bits_per_pixel/8) +
(y + vinfo.yoffset) * finfo.line_length;
#if 0
if(vinfo.bits_per_pixel == 32) {
*(fbp + location) = b;
*(fbp + location + 1) = g;
*(fbp + location + 2) = r;
*(fbp + location + 3) = 0;
} else { //16bpp: r:g:b = 5:6:6
unsigned short int t = r << 11 | g << 5 | b;
*((unsigned short int *)(fbp + location)) = t;
}
#else
/* 简单处理,假定是32位或者是16位 565模式*/
if (vinfo.bits_per_pixel == 32) {
*(fbp + location) = 100; // Some blue
*(fbp + location + 1) = 15+(x-100)/2; // A little green
*(fbp + location + 2) = 200-(y-100)/5;// A lot of red
*(fbp + location + 3) = 0xff; // No transparency
} else { //assume 16bpp
unsigned short b = 10;
unsigned short g = (x-100)/6;
unsigned short r = 31-(y-100)/16; // A lot of red
unsigned short t = r << 11 | g << 5 | b;
*((unsigned short *)(fbp + location)) = t;
}
#endif
}
}
#else
switch(vinfo.bits_per_pixel) {
case 16:
div = vinfo.yres/3;
for(y = 0; y < vinfo.yres; y++) {
for(x = 0; x < vinfo.xres; x++) {
location = (x + vinfo.xoffset) * (vinfo.bits_per_pixel/8) +
(y + vinfo.yoffset) * finfo.line_length;
switch(y/div) {
case 0: //Red screen
*((unsigned short *)(fbp + location)) = RED_COLOR565;
break;
case 1: //Green screen
*((unsigned short *)(fbp + location)) = GREEN_COLOR565;
break;
case 2: //Blue screen
*((unsigned short *)(fbp + location)) = BLUE_COLOR565;
break;
}
}
}
break;
case 32:
div = vinfo.yres/3;
for(y = 0; y < vinfo.yres; y++) {
for(x = 0; x < vinfo.xres; x++) {
location = (x + vinfo.xoffset) * (vinfo.bits_per_pixel/8) +
(y + vinfo.yoffset) * finfo.line_length;
switch(y/div) {
case 0: //Red screen
*((unsigned int *)(fbp + location)) = RED_COLOR888 - ((y%div)/(div/4) * 0x20 << 16);
break;
case 1: //Green screen
*((unsigned int *)(fbp + location)) = GREEN_COLOR888 - ((y%div)/(div/4) * 0x20 << 8);
break;
case 2: //Blue screen
*((unsigned int *)(fbp + location)) = BLUE_COLOR888 - ((y%div)/(div/4) * 0x20 << 0);
break;
}
}
}
break;
default:
printf("WARNNING: bpp if not %d\n", vinfo.bits_per_pixel);
}
#endif
munmap(fbp, screensize);
close(fd);
return 0;
}
<file_sep>/network/route/src/inc/print.h
/******************************************************************************
文 件 名 : print.h
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月14日
最近修改 :
功能描述 : print.c 的头文件
******************************************************************************/
#ifndef __PRINT_H__
#define __PRINT_H__
#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */
/*----------------------------------------------*
* 外部函数原型说明 *
*----------------------------------------------*/
extern void firewall_rule_set_help(void);
extern void show_help(void);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
#endif /* __PRINT_H__ */
<file_sep>/gtk/4st_week/picture_browse/image.h
/* ************************************************************************
* Filename: image.h
* Description:
* Version: 1.0
* Created: 2015年08月11日 14时47分43秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#ifndef __IMAGE_H__
#define __IMAGE_H__
void load_image(GtkWidget *image, const char *file_path, const int w, const int h );
GtkWidget *create_button_from_file(const char *file_path, const int w, const int h);
void chang_background(GtkWidget *widget, int w, int h, const gchar *path);
#endif
<file_sep>/network/route/src/tcp_server.c
/******************************************************************************
文 件 名 : tcp_server.c
版 本 号 : 初稿
作 者 : if
生成日期 : 2015年9月16日
最近修改 :
功能描述 : tcp 服务器 调用函数
函数列表 :
tcp_send_arp_table
tcp_send_firewall_rules
tcp_send_port_info
dispose_tcp_cmd
修改历史 :
1.日 期 : 2015年9月16日
作 者 : if
修改内容 : 创建文件
******************************************************************************/
#include "common.h"
/*****************************************************************************
函 数 名 : tcp_send_arp_table()
功能描述 : 给TCP客户端发送ARP表的信息
输入参数 : rt TYPE_Route类型结构体
connfd 监听套接字
返 回 值 : NULL
修改日期 : 2015年9月16日
*****************************************************************************/
void tcp_send_arp_table(TYPE_Route *rt, int connfd)
{
uchar ip[16] = "";
uchar mac[18]= "";
uchar msg[50]= "";
ARP_Table *pb = NULL;
pb = rt->arp_head;
send(connfd, "_____IP________________MAC_______\n", \
strlen("_____IP________________MAC_______\n"), 0);
while(pb != NULL) {
//bzero(ip, sizeof(ip));
//bzero(mac, sizeof(mac));
//bzero(msg, sizeof(msg));
sprintf(ip,"%d.%d.%d.%d",\
pb->ip[0],pb->ip[1],pb->ip[2],pb->ip[3]);
sprintf(mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
pb->mac[0],pb->mac[1],pb->mac[2],pb->mac[3],pb->mac[4],pb->mac[5]);
sprintf(msg, "-%-12s -- %s\n", ip, mac);
send(connfd, msg, strlen(msg), 0);
pb = pb->next;
}
send(connfd, "_________________________________\n", \
strlen("_________________________________\n"), 0);
send(connfd, "#end#", strlen("#end#"), 0);
}
/*****************************************************************************
函 数 名 : tcp_send_firewall_rules()
功能描述 : 给TCP客户端发送防火墙的设定规则
输入参数 : rt TYPE_Route类型结构体
connfd 监听套接字
返 回 值 : NULL
修改日期 : 2015年9月16日
*****************************************************************************/
void tcp_send_firewall_rules(TYPE_Route *rt, int connfd)
{
FIRE_Wall *pnode = NULL;
FIRE_Wall *pbuf[4] = {rt->mac_head,rt->ip_head,rt->port_head,rt->pro_head};
char rule[RULE_LEN] = "";
int i = 0;
send(connfd,"\n------firewall rules-------\n", \
strlen("\n------firewall rules-------\n"), 0);
for(i=0; i<4; i++) {
pnode = pbuf[i];
while(pnode != NULL) {
strcpy(rule, pnode->rule);
strcat(rule,"\n");
send(connfd, rule, strlen(rule), 0);
pnode = pnode->next;
}
}
send(connfd,"---------------------------\n\n", \
strlen("---------------------------\n\n"), 0);
send(connfd, "#end#", strlen("#end#"), 0);
}
/*****************************************************************************
函 数 名 : tcp_send_port_info()
功能描述 : 给TCP客户端发送接口信息
输入参数 : rt TYPE_Route类型结构体
connfd 监听套接字
返 回 值 : NULL
修改日期 : 2015年9月16日
*****************************************************************************/
void tcp_send_port_info(TYPE_Route *rt, int connfd)
{
int i = 0;
char name[64];
char ip[16];
char mask[16];
char b_ip[16];
char mac[18];
char msg[200];
for(i=0;i<rt->port_num;i++)
{
sprintf(name, "___________%s___________", rt->eth_port[i].name);
//ip
sprintf(ip, "%d.%d.%d.%d",\
rt->eth_port[i].ip[0],rt->eth_port[i].ip[1],\
rt->eth_port[i].ip[2],rt->eth_port[i].ip[3]);
//mac
sprintf(mac, "%02x:%02x:%02x:%02x:%02x:%02x",\
rt->eth_port[i].mac[0],rt->eth_port[i].mac[1],\
rt->eth_port[i].mac[2],rt->eth_port[i].mac[3],\
rt->eth_port[i].mac[4],rt->eth_port[i].mac[5]);
//netmask
printf(mask, "%d.%d.%d.%d",\
rt->eth_port[i].netmask[0],rt->eth_port[i].netmask[1],\
rt->eth_port[i].netmask[2],rt->eth_port[i].netmask[3]);
//broadcast ip
sprintf(b_ip, "%d.%d.%d.%d",\
rt->eth_port[i].bc_ip[0],rt->eth_port[i].bc_ip[1],\
rt->eth_port[i].bc_ip[2],rt->eth_port[i].bc_ip[3]);
sprintf(msg, "%s\n%s\n%s\n%s\n%s\n", name, ip, mac, mask, b_ip);
send(connfd, msg, strlen(msg), 0);
send(connfd, "__________________________\n", \
strlen("__________________________\n"), 0);
send(connfd, "#end#", strlen("#end#"), 0);
}
}
/*****************************************************************************
函 数 名 : dispose_cmd()
功能描述 : 处理命令,并执行相应的动作
输入参数 : rt TYPE_Route类型结构体
cmd 待处理、执行的命令
返 回 值 : NULL
修改日期 : 2015年9月16日
*****************************************************************************/
void dispose_tcp_cmd(TYPE_Route *rt, int connfd, char cmd[])
{
pthread_mutex_lock(&rt->mutex); // 上锁
if(strcmp(cmd, "help") == 0){
char route_help[] = {
"***************************************************\n\
- help: 查看帮助信息 *\n\
- arp: 查看 ARP 表 *\n\
- ifconfig: 查看网卡信息 *\n\
- fire on: 开启防火墙 *\n\
- fire off: 关闭防火墙 *\n\
- lsfire: 查看防火墙规则 *\n\
- setfire: 设置防火墙规则 *\n\
***************************************************\n"
};
send(connfd, route_help, strlen(route_help), 0);
send(connfd, "#end#", strlen("#end#"), 0);
}
else if(strcmp(cmd,"arp") == 0){
tcp_send_arp_table(rt, connfd);
}
else if(strcmp(cmd,"ifconfig") == 0){
tcp_send_port_info(rt, connfd);
}
else if(strcmp(cmd,"lsfire") == 0){
tcp_send_firewall_rules(rt, connfd);
}
else if(strcmp(cmd,"setfire") == 0){
int i, len;
char rule[RULE_LEN] = "";
char passwd[PASSWD_LEN] = "";
for(i=0; i<2; i++) {
send(connfd, "passwd: ", strlen("passwd: "), 0);
send(connfd, "#end#", strlen("#end#"), 0);
len = recv(connfd, passwd, sizeof(passwd), 0);
if(len == 0) goto out;
if(strcmp(passwd, rt->passwd) == 0){
send(connfd, "passed", strlen("passed"), 0);
send(connfd, "#end#", strlen("#end#"), 0);
break;
}
else {
send(connfd, "\nerror, try again!\n", strlen("\nerror, try again!\n"), 0);
send(connfd, "#end#", strlen("#end#"), 0);
}
}
if(i == 2) goto out;
char fire_help[] = {
"*************************************************************************\n\
- >>> 温馨提示: ()是可选选项 <<< *\n\
-设置 ip 过滤规则,格式: ip (opt) <ip> -> ip (src) 192.168.1.1 *\n\
-设置 mac过滤规则,格式: mac (opt) <mac> -> mac (dst) 192.168.1.1 *\n\
-设置端口过滤规则,格式: port (opt) <port> -> port (host) 8000 *\n\
-设置协议过滤规则,格式: <pro> (type) (opt) (type_val) -> udp port 8000 *\n\
-删除已设置的规则,输入: -d <要删除的规则> *\n\
-查看设置规则帮助,输入: -h *\n\
-查看已设置的规则,输入: ls *\n\
-退出防火墙设置, 输入: esc *\n\
*************************************************************************\n"
};
send(connfd, fire_help, strlen(fire_help), 0);
send(connfd, "#end#", strlen("#end#"), 0);
while(1) {
bzero(rule, RULE_LEN);
send(connfd, "entry: ", strlen("entry: "), 0);
send(connfd, "#end#", strlen("#end#"), 0);
len = recv(connfd, rule, RULE_LEN, 0);
if(len == 0) goto out;
if(strcmp(rule,"ls") == 0){
tcp_send_firewall_rules(rt, connfd);
}
else if(strcmp(rule,"-h") == 0) {
send(connfd, fire_help, strlen(fire_help), 0);
send(connfd, "#end#", strlen("#end#"), 0);
}
else if(strncmp(rule,"-d",2) == 0) {
char *prule = NULL;
prule = rule+3; //跳过 "-d "
delete_firewall_rule(rt, prule);
firewall_save_all_rules(rt);
}
else if(strcmp(rule,"passwd") == 0) {
send(connfd, "new passwd: ", strlen("new passwd: "), 0);
send(connfd, "#end#", strlen("#end#"), 0);
len = recv(connfd, passwd, sizeof(passwd), 0);
if(len == 0) goto out;
get_passwd(rt->passwd, PASSWD_LEN-1);
firewall_save_passwd(rt->passwd);
}
else if(strcmp(rule,"esc") == 0){
send(connfd, "exitting set firewall...\n",
strlen("exitting set firewall...\n"), 0);
send(connfd, "#end#", strlen("#end#"), 0);
break;
}
else {
firewall_build_rule(rt, rule, 1);
}
}
}
out:
pthread_mutex_unlock(&rt->mutex);// 解锁
}
<file_sep>/network/2nd_day/Makefile
tftp_client:tftp_client.c
gcc -o tftp_client tftp_client.c
.PHONY:clean
clean:
rm tftp_client
<file_sep>/sys_program/2nd_day/pm/sigpromask.c
/* ************************************************************************
* Filename: sigpromask.c
* Description:
* Version: 1.0
* Created: 2015年08月14日 17时22分34秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
int main(int argc, char *argv[])
{
sigset_t set;
int i = 0;
sigemptyset(&set);
sigaddset(&set,SIGINT);
while(1)
{
sigprocmask(SIG_BLOCK, &set, NULL);
for(i=0;i<5;i++)
{
printf("SIGINT signal is blocked\n");
sleep(1);
}
sigprocmask(SIG_UNBLOCK, &set, NULL);
for(i=0;i<5;i++)
{
printf("SIGINT signal unblocked\n");
sleep(1);
}
}
return 0;
}
<file_sep>/work/debug/ingenic/pe10/pe10_drv.c
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/pm.h>
#include <linux/slab.h>
#include <linux/sysctl.h>
#include <linux/proc_fs.h>
#include <linux/delay.h>
#include <linux/gpio_keys.h>
#include <linux/gpio.h>
#include <linux/miscdevice.h> /* struct miscdevice */
#include <jz_notifier.h>
#define PE10_PORT (GPIO_PE(10))
#define DEVICE_NAME "pe10_gpio"
#define PE10_IOC_MAGIC 'p'
#define PE10_SET_ON_TIMER _IO(PE10_IOC_MAGIC, 1)
#define PE10_SET_OFF_TIMER _IO(PE10_IOC_MAGIC, 2)
static int flag = 0;
static int on_time = 180 * HZ;
static int off_time = 3 * HZ;
static struct timer_list pe10_timer;
static void pe10_timer_handle(unsigned long arg)
{
if(flag == 0) {
flag = 1;
gpio_direction_output(PE10_PORT, 0);
mod_timer(&pe10_timer,jiffies+off_time);
printk(KERN_WARNING "[msg]: output 0 %s\n",__FUNCTION__);
}
else {
flag = 0;
gpio_direction_output(PE10_PORT, 1);
mod_timer(&pe10_timer,jiffies+on_time);
printk(KERN_WARNING "[msg]: output 1 %s\n",__FUNCTION__);
}
//printk(KERN_WARNING "[msg]: %s\n",__FUNCTION__);
}
static int pe10_drv_open(struct inode *inode, struct file *filp)
{
//pe10_timer.expires = jiffies+on_time; // 设置定时器的定时时间为on_time秒
//add_timer(&pe10_timer); // 注册定时器
printk(KERN_WARNING "[msg]: %s\n",__FUNCTION__);
return 0;
}
static long pe10_drv_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
int ret = 0;
printk(KERN_WARNING "[msg]: %s\n",__FUNCTION__);
switch(cmd) {
case PE10_SET_ON_TIMER:
if(arg < 1 || arg > 2000)
ret = EINVAL;
else {
on_time = arg * HZ;
mod_timer(&pe10_timer,jiffies+on_time);
}
break;
case PE10_SET_OFF_TIMER:
if(arg < 1 || arg > 60)
ret = EINVAL;
else {
off_time = arg * HZ;
mod_timer(&pe10_timer,jiffies+off_time);
}
break;
default:
ret = -EINVAL;
}
return ret;
}
static int pe10_drv_release(struct inode *inode, struct file *filp)
{
//del_timer(&pe10_timer);
printk(KERN_WARNING "[msg]: %s\n",__FUNCTION__);
return 0;
}
static struct file_operations pe10_fops = {
.owner = THIS_MODULE,
.open = pe10_drv_open,
.release = pe10_drv_release,
.unlocked_ioctl = pe10_drv_ioctl,
};
static struct miscdevice pe10_misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = DEVICE_NAME,
.fops = &pe10_fops,
};
static __init int pe10_drv_init(void)
{
int ret;
ret = misc_register(&pe10_misc);
init_timer(&pe10_timer);
pe10_timer.data = 0;
pe10_timer.function = pe10_timer_handle;
// GPIO 申请及初始化
ret = gpio_request(PE10_PORT, "PE10_DRV PORT");
if (ret < 0) {
printk("Failed to request GPIO:%d, ERRNO:%d\n",(int)PE10_PORT, ret);
goto err1;
}
gpio_direction_output(PE10_PORT, 1);
pe10_timer.expires = jiffies+on_time;
add_timer(&pe10_timer);
printk (DEVICE_NAME"\tinitialized\n");
return 0;
err1:
misc_deregister(&pe10_misc);
return ret;
}
static __exit void pe10_drv_exit(void)
{
del_timer_sync(&pe10_timer);
misc_deregister(&pe10_misc);
printk(KERN_WARNING "[msg]: %s\n",__FUNCTION__);
}
module_init(pe10_drv_init);
module_exit(pe10_drv_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/debug/2440/leds/leds_drv.c
/* ************************************************************************
* Filename: leds_drv.c
* Description:
* Version: 1.0
* Created: 2015年08月09日 22时26分14秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/delay.h>
#include <linux/ioctl.h>
#include <linux/cdev.h>
#include <linux/gpio.h>
#include <linux/device.h>
#include <asm/irq.h>
#include <mach/regs-gpio.h>
#include <mach/hardware.h>
#define DEVICE_NAME "leds_drv"
#define LED_ON 0
#define LED_OFF 1
static int majno = 0; //
static struct cdev *p_cdev = NULL;
static struct class *leds_class = NULL;
static unsigned long led_table[] = {
S3C2410_GPB(5),
S3C2410_GPB(6),
S3C2410_GPB(7),
S3C2410_GPB(8),
};
static unsigned int led_cfg_table[] =
{
S3C2410_GPIO_OUTPUT,
S3C2410_GPIO_OUTPUT,
S3C2410_GPIO_OUTPUT,
S3C2410_GPIO_OUTPUT,
//S3C2410_GPB5_OUTP,
//S3C2410_GPB6_OUTP,
//S3C2410_GPB7_OUTP,
//S3C2410_GPB8_OUTP,
};
static int leds_open(struct inode *inode, struct file *filp)
{
int i;
for(i=0;i<4;i++)
{
s3c2410_gpio_cfgpin(led_table[i], led_cfg_table[i]); //要添加#include <linux/gpio.h>
}
return 0;
}
static int leds_ioctl(struct inode * inode, struct file *file, unsigned int cmd, unsigned long arg)
{
if(arg >= 4)
{
return -EINVAL;
}
switch(cmd)
{
case LED_ON:
{
s3c2410_gpio_setpin(led_table[arg], 0);
return 0;
}
case LED_OFF:
{
s3c2410_gpio_setpin(led_table[arg], 1);
return 0;
}
default:
return -EINVAL;
}
}
static struct file_operations leds_fops =
{
.owner = THIS_MODULE,
.open = leds_open,
.ioctl = leds_ioctl,
};
static void leds_setup_cdev(struct cdev *dev,int index)
{
int err;
dev_t devno = MKDEV(majno, index);
cdev_init(dev, &leds_fops);
dev->owner = THIS_MODULE;
dev->ops = &leds_fops;
err = cdev_add(dev, devno, 1);
if(err)
{
printk(KERN_NOTICE "Error %d adding leds cdev %d",err,index);
}
}
/*
* 设备初始化函数,在设备加载到内核时调用
*/
static int __init leds_drv_init(void)
{
int ret;
dev_t devno = MKDEV(majno,0);
if(!majno)
{
ret = alloc_chrdev_region(&devno,0,1,DEVICE_NAME);
majno = MAJOR(devno);
}
else
{
ret = register_chrdev_region(devno,1,DEVICE_NAME);
}
if(ret < 0)
{
return ret;
}
p_cdev = kmalloc(sizeof(struct cdev), GFP_KERNEL);
if(!p_cdev)
{
ret = -ENOMEM;
goto fail_malloc;
}
memset(p_cdev, 0, sizeof(struct cdev));
leds_setup_cdev(p_cdev,0);
//注册一个类
leds_class = class_create(THIS_MODULE, DEVICE_NAME);//要添加#include <linux/device.h>
if(IS_ERR(leds_class))
{
printk("Err:failed in create leds class\n");
goto fail_add_class;
}
//创建一个设备节点
device_create(leds_class,NULL,MKDEV(devno,0),NULL,DEVICE_NAME);
return 0;
fail_malloc:
unregister_chrdev_region(devno,1);
return -1;
fail_add_class:
cdev_del(p_cdev);
kfree(p_cdev);
unregister_chrdev_region(devno,1);
return -1;
}
/*
* 设备的注销函数,在设备从内核卸载时调用
*
*/
static void __exit leds_drv_exit(void)
{
cdev_del(p_cdev);
kfree(p_cdev); //回收设备结构的内存
device_destroy(leds_class,MKDEV(majno,0)); //删除设备节点
class_destroy(leds_class); //注销类
unregister_chrdev_region(MKDEV(majno,0),1); //释放设备号
}
module_init(leds_drv_init);
module_exit(leds_drv_exit);
/* 描述驱动程序的一些信息,不是必须的 */
MODULE_AUTHOR("Dawei"); // 驱动程序的作者
MODULE_DESCRIPTION("A Leds Driver"); // 一些描述信息
MODULE_LICENSE("GPL"); // 遵循的协议
<file_sep>/c/homework/3rd_week/message/Makefile
msg:main.c msg.c
.PHONY:clean
clean:
rm msg
<file_sep>/work/camera/bf3703/BF3703.c
#include "bf3703.h"
#include "twi_s.h"
#include "system_gpio.h"
#define BF3703_ADDRESS 0x6e
#define BF3703_IMG_WIDTH 640
#define BF3703_IMG_HEIGHT 480
#define BF3703_IMG_WIDTH_WITH_DATA (0+BF3703_IMG_WIDTH)
#define BF3703_IMG_HEIGHT_WITH_DATA (0+BF3703_IMG_HEIGHT)
#define BF3703_IMG_SIZE (BF3703_IMG_WIDTH*BF3703_IMG_HEIGHT)
#define BF3703_IMG_SIZE_WITH_DATA (BF3703_IMG_WIDTH_WITH_DATA*BF3703_IMG_HEIGHT_WITH_DATA)
#define RegTable_size(table) (sizeof(table)/sizeof(table[0]))
typedef struct sensor_conf{
u8 reg;
u8 value;
u8 delay_ms;
}sensor_conf;
static const struct sensor_conf BF3703_reg[] =
{
{0x15,0x22},//VSYNC = VSYNC_DAT 0x15[5] = 1
{0x09,0x01},//0x01 ,standby
{0x12,0x01},//0x01 VGA RAW Bayer RGB mode
{0x3a,0x00},//0x00
//{0x1e,0x10},//Vertically flip
{0xf1,0x28},
{0x13,0x00},//关闭AEC和AGC
{0x01,0x00},
{0x02,0x00},
//{0x8c,0x01},
//{0x8d,0x32},
{0x8c,0x00},
{0x8d,0x2D},//曝光时间约3ms
{0x87,0x20},//模拟增益设置到32
//{0x13,0x05},
{0x05,0x1f},
{0x06,0x60},
{0x14,0x20},
{0x27,0x03},
{0x06,0xe0},
{0x11,0x40},//MCLK=XCLK
{0x2a,0x00},//0x2a和0x2b是设置dummy pix。设置为16,是为了把每一行的pix设置到800。
{0x2b,0x10},//这样一来,MCLK为24MHz时,每一行的时间就为1/15ms,方便计算。
{0x9e,0x4c},
{0x9e,0x3f},
{0x92,225},//0x92和0x93,设置VSYNC后插入行。,这里设置为225行,也就是15ms
{0x93,0x00},
{0xe3,0x2D},//0x92和0x93,设置VSYNC前插入行。这里保持与初次设置的曝光时间一样。
{0xe4,0x00},
{0xeb,0x30},
{0xbb,0x20},
{0Xf5,0x21},
{0Xe1,0X3c},
{0X16,0x03},
{0X2f,0Xf6},
{0x33,0x20},
{0x34,0x08},
{0x35,0x56},
{0x65,0x58},
{0x66,0x52},
{0x36,0x05},
{0x37,0xc0},
{0x38,0x46},
{0x9b,0xf6},
{0x9c,0x46},
{0xbc,0x01},
{0xbd,0xf6},
{0xbe,0x46},
{0x82,0x14},
{0x83,0x23},
{0x9a,0x23},
{0x70,0x6f},
{0x72,0x2f},
{0x73,0x2f},
{0x74,0x29},
{0x77,0x90},
{0x7a,0x26},
{0x7b,0x30},
{0x84,0x1a},
{0x85,0x20},
{0x89,0x02},
{0x8a,0x64},
{0x86,0x30},
{0x96,0xa6},
{0x97,0x0c},
{0x98,0x18},
{0x80,0x54},
{0x24,0x88},
{0x25,0x78},
{0x69,0x20},
{0x94,0x0a},
{0X1F,0x20},
{0X22,0x20},
{0X26,0x20},
{0x56,0x40},
{0x61,0xd3},
{0x79,0x48},
{0x3b,0x60},
{0x3c,0x28},
{0x39,0x80},
{0x3f,0xc0},
{0x40,0X60},
{0x41,0X60},
{0x42,0X66},
{0x43,0X57},
{0x44,0X4c},
{0x45,0X43},
{0x46,0X3c},
{0x47,0X37},
{0x48,0X33},
{0x49,0X2f},
{0x4b,0X2c},
{0x4c,0X29},
{0x4e,0X25},
{0x4f,0X22},
{0x50,0X20},
{0x6a,0x00},
{0x23,0x00},
{0xa0,0x03},
{0x06,0xe0},
{0x8e,0x01},
{0x8f,0xfe},//{0xb6,0x20},//{0xb7,0x20},//{0xb8,0x20},{0xb9,0xc0}
//{0xb9,0x80}
};
//设置图像传感器曝光时间
void BF3703_SetExposure(u16 exposure)
{
u8 reg_val=0;
// Integration time MSB 0x8c, stores the higher 8 bits of exposure time.
// Integration time LSB 0x8d, stores the lower 8 bits of exposure time.
reg_val=(u8)(exposure>>8);
TWI_Write(TWI1, 0x6e, 0x8c, 1, ®_val, 1);
reg_val=(u8)(exposure&0xff);
TWI_Write(TWI1, 0x6e, 0x8d, 1, ®_val, 1);
}
void BF3703_SetAnalogGain(u16 gain) //set global gain register
{
u8 reg_val=0;
reg_val=(u8)MIN(0x3F,MAX(0x00,gain)); // Limit the value between 0 ~ 63
TWI_Write(TWI1, 0x6e, 0x87, 1, ®_val, 1);
}
//设置图像传感器帧率
void BF3703_SetDummyLine(u16 dummy_lines)
{
u8 reg_val=0;
// Dummy lines insert before active line MSB 0xe4, stores the higher 8 bits of dummy lines.
// Dummy lines insert before active line LSB 0xe3, stores the lower 8 bits of dummy lines.
reg_val=(u8)(dummy_lines>>8);
TWI_Write(TWI1, 0x6e, 0xe4, 1, ®_val, 1);
reg_val=(u8)(dummy_lines&0xff);
TWI_Write(TWI1, 0x6e, 0xe3, 1, ®_val, 1);
}
u32 BF3703_GetExposure(void)
{
u8 string[2]={0};
u16 reg_val=0;
TWI_Read(TWI1, 0x6e, 0x8c, 1, &(string[0]), 1);
TWI_Read(TWI1, 0x6e, 0x8d, 1, &(string[1]), 1);
reg_val = string[1]; //lsb 8bit
reg_val |= ((string[0]<<8)); //hsb
return (u32)reg_val;
}
u32 BF3703_GetAnalogGain(void)
{
u8 reg_val=0;
TWI_Read(TWI1, 0x6e, 0x87, 1, ®_val, 1);
return (u32)reg_val;
}
//u32 BF3703_GetCurrentBin(void)
//{
// u8 reg_val=0;
//
// TWI_Read(TWI1, 0x6e, 0x88, 1, ®_val, 1);
// return (u32)reg_val;
//}
u32 BF3703_GetCurrentBin(u8* p_data)
{
u32 BIN_NUM=256;
u32 GREY_LEVEL=256;
u32 IMG_STEP=4;
u32 HIST_STEP=GREY_LEVEL/BIN_NUM;
u32 width=0;
u32 height=0;
u32 w_offset=0;
u32 h_offset=0;
u32 w_start=0;
u32 w_end=0;
u32 h_start=0;
u32 h_end=0;
u8* data_addr=p_data;
u32 hist_temp[256]={0};
u32 sum=0;
u32 pix_num=0;
u32 i=0,j=0;
width=BF3703_IMG_WIDTH;
height=BF3703_IMG_HEIGHT;
w_offset=0;
h_offset=0;
w_start=0;
w_end=width;
h_start=0;
h_end=height;
// 1. 先创建一个256级的histogram,并对原图像下采样1/4 * 1/4 统计。
memset(hist_temp,0,GREY_LEVEL*sizeof(u32));
for(j=h_start;j<h_end;j+=IMG_STEP)
for(i=w_start;i<w_end;i+=IMG_STEP)
hist_temp[data_addr[i+j*width]]++;
// 计算当前256级别下的Bin值
for(i=0;i<GREY_LEVEL;i++)
{
sum+=(hist_temp[i]*i); // 计算total sum的直方图。
pix_num+=hist_temp[i]; // 计算pixel计入计算的总数。
}
sum=(sum/pix_num);
// // 计算64级别下的Bin值
// sum=(sum>>2);//((sum/GREY_LEVEL)*BIN_NUM)
// 返回量程为256的图像bin值
return sum;
}
u32 BF3703_GetCurrentBin_80Per(u8* p_data)
{
u32 BIN_NUM=256;
u32 GREY_LEVEL=256;
u32 IMG_STEP=4;
u32 HIST_STEP=GREY_LEVEL/BIN_NUM;
u32 width=0;
u32 height=0;
u32 w_offset=0;
u32 h_offset=0;
u32 w_start=0;
u32 w_end=0;
u32 h_start=0;
u32 h_end=0;
u8* data_addr=p_data;
u32 hist_temp[256]={0};
u32 sum=0;
u32 pix_num=0;
u32 i=0,j=0;
width=BF3703_IMG_WIDTH;
height=BF3703_IMG_HEIGHT;
w_offset=width*(20-19)/20;
h_offset=height*(20-19)/20;
w_start=w_offset;
w_end=width-w_offset;
h_start=h_offset;
h_end=height-h_offset;
// 1. 先创建一个256级的histogram,并对原图像下采样1/4 * 1/4 统计。
memset(hist_temp,0,GREY_LEVEL*sizeof(u32));
for(j=h_start;j<h_end;j+=IMG_STEP)
for(i=w_start;i<w_end;i+=IMG_STEP)
hist_temp[data_addr[i+j*width]]++;
// 计算当前256级别下的Bin值
for(i=0;i<GREY_LEVEL;i++)
{
sum+=(hist_temp[i]*i); // 计算total sum的直方图。
pix_num+=hist_temp[i]; // 计算pixel计入计算的总数。
}
sum=(sum/pix_num);
// // 计算64级别下的Bin值
// sum=(sum>>2);//((sum/GREY_LEVEL)*BIN_NUM)
// 返回量程为256的图像bin值
return sum;
}
void BF3703_AE_Enable(void)
{
u8 reg_val=0;
reg_val = 0x05;
TWI_Write(TWI1, 0x6e, 0x13, 1, ®_val, 1);
}
void BF3703_AE_Disable(void)
{
u8 reg_val=0;
reg_val = 0x00;
TWI_Write(TWI1, 0x6e, 0x13, 1, ®_val, 1);
}
void BF3703_ExitStandby(void)
{
// u8 reg_val=0;
// u32 delay=0;
// // Software Power Down
// reg_val = 0x01;
// TWI_Write(TWI1, 0x6e, 0x09, 1, ®_val, 1);
// Hardware Power Down
PIO_Clear(&Pin_ISI_PWDN);// 1:pwdn mode
}
void BF3703_EnterStandby(void)
{
// u8 reg_val=0;
// u32 delay=0;
// // Software Power Up
// reg_val = 0x11;
// TWI_Write(TWI1, 0x6e, 0x09, 1, ®_val, 1);
// Hardware Power Up
PIO_Set(&Pin_ISI_PWDN);// 0:normal mode
}
/*********************************************************************************
Function: BF3703_GetHistogram()
Description: Fetch Histogram based on the image info area and loaded into a
existing histo array
Input: u32 bin_num
u8* pImgData
Output: u32* _hist
Return: None
Create Date: 2014/09/09
Last Update: None
**********************************************************************************/
void BF3703_GetHistogram(u32* _hist, u32 bin_num, u8* pImgData)
{
u32 BIN_NUM=bin_num;
u32 GREY_LEVEL=256;
u32 IMG_STEP=4;
u32 HIST_STEP=GREY_LEVEL/BIN_NUM;
u32 width=BF3703_IMG_WIDTH;
u32 height=BF3703_IMG_HEIGHT;
u8* data_addr=pImgData;
u32 hist_temp[256]={0};
u32 temp=0;
u32 i=0,j=0;
// 1. 先创建一个256级的histogram,并对原图像下采样1/4 * 1/4 统计。
memset(hist_temp,0,GREY_LEVEL*sizeof(u32));
for(j=0;j<height;j+=IMG_STEP)
for(i=0;i<width;i+=IMG_STEP)
hist_temp[data_addr[i+j*width]]++;
// 2. 将256级的临时histogram降入64级
for(i=0;i<BIN_NUM;i++)
{
temp=0;
for(j=0;j<HIST_STEP;j++)
temp+=hist_temp[i*HIST_STEP+j];
// 每4个256级的元素,组成一个64级元素
_hist[i]=temp;
}
return;
}
void BF3703_Init(void)
{
uint32_t i;
uint8_t tmp_val;// read for check
volatile uint32_t delay;//need use volatile?
for (i = 0; i < RegTable_size(BF3703_reg); i++)
{
//TWI_Write(Twi *pTwi, uint8_t address, uint32_t iaddress, uint8_t isize, uint8_t *pData, uint32_t num)
TWI_Write(TWI1, 0x6e, BF3703_reg[i].reg, 1, (u8*)&(BF3703_reg[i].value), 1);
}
}
void BF3703_WriteRegister(u8 reg_addr,u8 reg_val)
{
TWI_Write(TWI1, 0x6e, reg_addr, 1, ®_val, 1);
}
void BF3703_Reset(void)
{
u8 reg_val=0;
u32 delay=0;
reg_val = 0x10;
TWI_Write(TWI1, 0x6e, 0x12, 1, ®_val, 1);
}
| a027f58a6f329768800eedf66c35c62c2cfeaba5 | [
"Markdown",
"Makefile",
"Java",
"Text",
"C",
"Shell"
] | 324 | C | weimingtom/learn | f70dca6bd9ac0f078986fcff90fa13e9ee099901 | ddf61784b8abf4caf99df826709bb4c3d11de632 | |
refs/heads/master | <repo_name>timleschinsky/se-server<file_sep>/settings.gradle
rootProject.name = 'se_spring_demo'
<file_sep>/src/main/java/com/ovgu/se/openapispringboot/demo/model/ItemDbo.java
package com.ovgu.se.openapispringboot.demo.model;
import io.swagger.models.auth.In;
import lombok.*;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.math.BigDecimal;
import java.time.LocalDate;
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Data
@Builder
public class ItemDbo {
@Id
@GeneratedValue
private Integer id;
@Column(unique = true)
private String name;
private String description;
private Double price;
private Double tax;
private LocalDate listedSince;
private String manufacturer;
public Item toItem() {
return new Item()
.id(id)
.name(name)
.price(price)
.tax(tax)
.listedSince(listedSince)
.manufacturer(manufacturer)
.description(description);
}
public ItemDbo(Item item) {
name = item.getName();
description = item.getDescription();
price = item.getPrice();
tax = item.getTax();
listedSince = LocalDate.now();
manufacturer = item.getManufacturer();
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
<file_sep>/src/main/java/com/ovgu/se/openapispringboot/demo/data/ItemRepository.java
package com.ovgu.se.openapispringboot.demo.data;
import com.ovgu.se.openapispringboot.demo.model.ItemDbo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.List;
@Transactional
public interface ItemRepository extends JpaRepository<ItemDbo, Integer> {
@Query("SELECT i FROM ItemDbo i WHERE (:name is null or i.name = :name) and (:manufacturer is null"
+ " or i.manufacturer = :manufacturer) and (:description is null or i.description = :description)" +
"and (:priceGe is null or i.price > :priceGe) and (:priceLe is null or i.price < :priceLe)")
List<ItemDbo> findByNameAndManufacturerAndDescriptionAndPriceIsBetween(
@Param("name") String name,
@Param("manufacturer") String manufacturer,
@Param("description") String description,
@Param("priceGe") Double priceGe,
@Param("priceLe") Double priceLe);
}
<file_sep>/Dockerfile
FROM openjdk:11.0.8-slim
VOLUME /tmp
COPY / /build/
RUN cd /build && ./gradlew bootJar && cp build/libs/*.jar /app.jar && cd .. && rm -rf /build
ENTRYPOINT ["java","-jar","/app.jar"]
EXPOSE 8080
<file_sep>/src/main/java/com/ovgu/se/openapispringboot/demo/service/ItemApiImpl.java
package com.ovgu.se.openapispringboot.demo.service;
import com.ovgu.se.openapispringboot.demo.data.ItemRepository;
import com.ovgu.se.openapispringboot.demo.api.ItemApiDelegate;
import com.ovgu.se.openapispringboot.demo.model.Item;
import com.ovgu.se.openapispringboot.demo.model.ItemDbo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class ItemApiImpl implements ItemApiDelegate {
private final ItemRepository itemRepository;
private final Logger log = LoggerFactory.getLogger(ItemApiImpl.class);
@Autowired
public ItemApiImpl(ItemRepository itemRepository) {
this.itemRepository = itemRepository;
}
@Override
public ResponseEntity<Item> createItem(Item item) {
ItemDbo savedItem = new ItemDbo(item);
savedItem = itemRepository.save(savedItem);
log.info("Item posted");
return ResponseEntity.ok(savedItem.toItem());
}
@Override
public ResponseEntity<Void> deleteItem(Integer id) {
log.info("ID: {} will be deleted", id);
ItemDbo itemDbo = itemRepository.findById(id).orElseThrow();
itemRepository.delete(itemDbo);
log.info("Item deleted");
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<Item> getItem(Integer id) {
log.info("Item {} get", id);
ItemDbo itemDbo = itemRepository.findById(id).orElseThrow();
return ResponseEntity.ok(itemDbo.toItem());
}
@Override
public ResponseEntity<List<Item>> getItems(String name, String manufacturer, String description, Double priceGe, Double priceLe) {
log.info("Items get");
List<Item> itemList = itemRepository
.findByNameAndManufacturerAndDescriptionAndPriceIsBetween(name, manufacturer, description, priceGe, priceLe)
.parallelStream()
.map(ItemDbo::toItem).collect(Collectors.toUnmodifiableList());
return ResponseEntity.ok(itemList);
}
@Override
public ResponseEntity<Item> updateItem(Integer id, Item item) {
log.info("Item {} updating", id);
ItemDbo itemDbo = itemRepository.findById(id).orElseThrow();
itemDbo.setDescription(item.getDescription());
itemDbo.setManufacturer(item.getManufacturer());
itemDbo.setName(item.getName());
itemDbo.setTax(item.getTax());
itemDbo.setPrice(item.getPrice());
itemDbo = itemRepository.save(itemDbo);
log.info("Item updated");
return ResponseEntity.ok(itemDbo.toItem());
}
}
<file_sep>/build.gradle
plugins {
id 'java'
id "org.openapi.generator" version "4.3.1"
id 'org.springframework.boot' version '2.3.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
}
group = 'com.ovgu.se.openapispringboot.demo'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
jcenter()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa:2.0.1.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-web:2.0.1.RELEASE'
runtimeOnly 'com.h2database:h2'
implementation "io.springfox:springfox-swagger2:2.8.0"
implementation "io.springfox:springfox-swagger-ui:2.8.0"
implementation "org.openapitools:jackson-databind-nullable:0.1.0"
implementation "javax.validation:validation-api"
implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
openApiGenerate {
generatorName = "spring"
inputSpec = "openapi.json"
outputDir = "$buildDir/generated"
configOptions = [
basePackage : "com.ovgu.se.openapispringboot.demo",
apiPackage : "com.ovgu.se.openapispringboot.demo.api",
configPackage : "com.ovgu.se.openapispringboot.demo.config",
modelPackage : "com.ovgu.se.openapispringboot.demo.model",
hideGenerationTimestamp: "true",
dateLibrary : "java8",
delegatePattern : "true"
]
systemProperties = [
modelTests : "false",
modelDocs : "false",
apiTests : "false",
apiDocs : "false"
]
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn tasks.openApiGenerate
}
sourceSets.main.java.srcDirs += "$buildDir/generated/src/main/java"
<file_sep>/README.md
# Spring Demo Server for SE Summer term 2020
## Build
- Build by `gradle build`.
- Create JAR by `gradle build bootJar`
## Build Docker
- Build this app to a Docker container with the included Dockerfile
- This is done automatically with the Docker automated build as image `tbd`.
## Run
- Run by `gradle bootRun`
<file_sep>/src/main/resources/application.properties
springfox.documentation.swagger.v2.path=/api-docs
server.port=8080
spring.jackson.date-format=com.ovgu.se.openapispringboot.demo.RFC3339DateFormat
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
server.servlet.contextPath=/api/spring
spring.profiles.active=development
| 922b9346c5a3a44c46a5d8ea71e982ae1474b1ce | [
"Markdown",
"INI",
"Gradle",
"Java",
"Dockerfile"
] | 8 | Gradle | timleschinsky/se-server | ef7a347c9fa8c4ed0dbc1d855de99fc69efd399a | e77ec0d7cc3d6aa83e346d904a0a7478bf7db0d5 | |
refs/heads/main | <file_sep>import { draw } from "wasm-game-of-life";
const canvas = document.getElementById('drawing');
const ctx = canvas.getContext('2d');
const realInput = document.getElementById('real');
const imaginaryInput = document.getElementById('imaginary');
const renderBtn = document.getElementById('render');
renderBtn.addEventListener('click', () => {
const real = parseFloat(realInput.value) || 0;
const imaginary = parseFloat(imaginaryInput.value) || 0;
draw(ctx, 600, 600, real, imaginary);
});
draw(ctx, 600, 600, -0.15, 0.65);<file_sep>pub struct BasicPoint {
x: u32,
y: u32,
time: u32,
}
<file_sep>// A dependency graph that contains any wasm must all be imported
// asynchronously. This `bootstrap.js` file does the single async import, so
// that no one else needs to worry about it again.
// import("./js/index.js")
// .catch(e => console.error("Error importing `index.js`:", e));
// import("./js/julia.js")
// .catch(e => console.error("Error importing `index.js`:", e));
import("./js/paint.js")
.catch(e => console.error("Error importing `paint.js`:", e));
<file_sep>// mod Julia;
mod paint;
// mod universe;
// mod utils;
<file_sep>import { run, Paint, Rect } from "wasm-game-of-life";
// run()
const paint = Paint.new()
console.log(paint)<file_sep>use std::cell::Cell;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::HtmlCanvasElement;
use web_sys::canvas;
fn window() -> web_sys::Window {
web_sys::window().expect("no global `window` exist ")
}
fn document() -> web_sys::Document {
window().document().expect("should have document on window")
}
fn body() -> web_sys::HtmlElement {
document().body().expect("document should have body")
}
fn request_frame_animation(f: &Closure<dyn FnMut()>) {
window()
.request_animation_frame(f.as_ref().unchecked_ref())
.expect("should register `requestAnimationFrame` OK");
}
// Called by our JS entry point to run the example
// #[wasm_bindgen(start)]
#[wasm_bindgen]
pub fn run() -> Result<(), JsValue> {
let canvas = document()
.create_element("canvas")?
.dyn_into::<web_sys::HtmlCanvasElement>()?;
canvas.set_width(640);
canvas.set_height(480);
canvas.style().set_property("border", "solid")?;
body().append_child(&canvas)?;
let context = canvas
.get_context("2d")
.unwrap()
.unwrap()
.dyn_into::<web_sys::CanvasRenderingContext2d>()
.unwrap();
let context = Rc::new(context);
let pressed = Rc::new(Cell::new(false));
{
let context = context.clone();
let pressed = pressed.clone();
let closure = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {
context.set_stroke_style(&"rgb(80,80,80)".into());
context.set_line_width(8.0);
// ctx.lineJoin = "bevel" || "round" || "miter";
// 不生效
context.set_line_join("bevel");
context.begin_path();
context.move_to(event.offset_x() as f64, event.offset_y() as f64);
pressed.set(true);
}) as Box<dyn FnMut(_)>);
canvas.add_event_listener_with_callback("mousedown", closure.as_ref().unchecked_ref())?;
closure.forget();
}
{
let context = context.clone();
let pressed = pressed.clone();
let closure = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {
if pressed.get() {
context.line_to(event.offset_x() as f64, event.offset_y() as f64);
context.set_line_join("bevel");
context.stroke();
context.begin_path();
context.move_to(event.offset_x() as f64, event.offset_y() as f64);
}
}) as Box<dyn FnMut(_)>);
canvas.add_event_listener_with_callback("mousemove", closure.as_ref().unchecked_ref())?;
closure.forget();
}
{
let context = context.clone();
let pressed = pressed.clone();
let closure = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {
pressed.set(false);
context.line_to(event.offset_x() as f64, event.offset_y() as f64);
context.stroke();
}) as Box<dyn FnMut(_)>);
canvas.add_event_listener_with_callback("mouseup", closure.as_ref().unchecked_ref())?;
closure.forget();
}
Ok(())
}
#[wasm_bindgen]
#[derive(Debug)]
pub struct Paint {
canvas: web_sys::HtmlCanvasElement,
context: web_sys::CanvasRenderingContext2d,
pressed: Rc<Cell<bool>>,
}
#[wasm_bindgen]
impl Paint {
pub fn new() -> Paint {
// self.pressed = Rc::new(Cell::new(false));
let canvasVal = Self::init_canvas();
let context = Self::init_context(canvasVal);
Paint {
canvas: canvasVal,
context: context,
pressed: Rc::new(Cell::new(false)),
}
}
pub fn init_canvas() -> web_sys::HtmlCanvasElement {
let canvas = document()
.create_element("canvas")
.expect("create canvas fail")
.dyn_into::<web_sys::HtmlCanvasElement>()
.expect(" create canvas fail");
canvas.set_width(640);
canvas.set_height(480);
canvas
.style()
.set_property("border", "solid")
.expect("set property fail");
canvas
}
pub fn init_context(canvas: HtmlCanvasElement) -> web_sys::CanvasRenderingContext2d {
let context =
canvas
.get_context("2d")
.unwrap()
.unwrap()
.dyn_into::<web_sys::CanvasRenderingContext2d>()
.unwrap();
context
}
} | 0eb5e1c5aab5a7e75d328ec84fdb59d6212cc017 | [
"JavaScript",
"Rust"
] | 6 | JavaScript | JunaYa/rust-wasm-game-of-life | e67c142eef5fa0cd6bb101e75c91ea02f8743688 | f066a49f06b2a7d6bd078c5cdda92cd4d01f8bbc | |
refs/heads/master | <file_sep>'use strict';
// brings in the assert module for unit testing
const assert = require('assert');
// brings in the readline module to access the command line
const readline = require('readline');
// use the readline module to print out to the command line
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const pigLatin = (word) => {
//array of vowels to check against
const vowels = ["a","e","i","o","u"];
// trim & lowercase word
word = word.toLowerCase().trim();
let startsWithVowel;
let firstVowel;
let slicedCharacters;
if (word[0] == 'a' || word[0] == 'e' || word[0] == 'i' || word[0] == 'o' || word[0] == 'u') {
startsWithVowel = true;
}
else {
startsWithVowel = false;
}
// if word starts with vowel
if (startsWithVowel == true) {
word += "yay";
console.log(word);
return word;
}
//if word doesn't start with a vowel
else {
//find index of first vowel
for (let i=0; i<=word.length-1; i++) {
if (word[i] !== "a" && word[i] !== "e" && word[i] !== "i" && word[i] !== "o" && word[i] !== "u") {
}
else {
firstVowel = i;
break;
}
}
// copy characters up until first vowel
slicedCharacters = word.slice(0, firstVowel);
// cut off characters before first vowel
word = word.slice(firstVowel, word.length);
// add sliced portion to end
word = word + slicedCharacters;
// add 'ay' to end of word
word += "ay";
console.log(word);
return word;
}
}
// the first function called in the program to get an input from the user
// to run the function use the command: node main.js
// to close it ctrl + C
const getPrompt = () => {
rl.question('word ', (answer) => {
console.log( pigLatin(answer) );
getPrompt();
});
}
// Unit Tests
// You use them run the command: npm test main.js
// to close them ctrl + C
if (typeof describe === 'function') {
describe('#pigLatin()', () => {
it('should translate a simple word', () => {
assert.equal(pigLatin('car'), 'arcay');
assert.equal(pigLatin('dog'), 'ogday');
});
it('should translate a complex word', () => {
assert.equal(pigLatin('create'), 'eatecray');
assert.equal(pigLatin('valley'), 'alleyvay');
});
it('should attach "yay" if word begins with vowel', () => {
assert.equal(pigLatin('egg'), 'eggyay');
assert.equal(pigLatin('emission'), 'emissionyay');
});
it('should lowercase and trim word before translation', () => {
assert.equal(pigLatin('HeLlO '), 'ellohay');
assert.equal(pigLatin(' RoCkEt'), 'ocketray');
});
it('Should separate two words and return them together', () => {
assert.equal(pigLatin('Hop Fest '), 'Ophay Estfay');
});
});
} else {
getPrompt();
}
// **********
// HINTS
// **********
// break your code into pieces and focus on one piece at a time...
// 1. if word begins with a vowel send to one function: adds "yay"
// 2. if word begins in with a consonant send to another function: splices off beginning, returns word with new ending.
// 3. if multiple words, create array of words, loop over them, sending them to different functions and creating a new array with the new words. | 11e0c386ecba548e0c40d578ac2322b8412baf22 | [
"JavaScript"
] | 1 | JavaScript | laavang/JS211_PigLatinProject | d624234243a4947cefd7e1e3643df124ec8eb241 | 9f24a621ecfa9c6e0d9219806f332224133a05a0 | |
refs/heads/master | <repo_name>kgt15/FarmFriend-app<file_sep>/app/src/main/java/gino/farmfriend/banana.java
package gino.farmfriend;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.prefs.AbstractPreferences;
/**
* Created by Gino on 19-02-2016.
*/
import android.content.Context;
import android.net.ConnectivityManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.net.NetworkInfo;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class banana extends AppCompatActivity {
TextView uid1;
TextView name11;
TextView email11;
TextView pre1;
//JSON Node Names
private static final String TAG_USER = "weather";
private static final String TAG_USER1 = "main";
private static final String TAG_ID = "temp_min";
private static final String TAG_EMAIL = "description";
private static final String TAG_ID1 = "temp_max";
private static final String TAG_NAME1 = "humidity";
int flag = 0;
private static final String TAG_USER11 = "main";
JSONArray user = null;
JSONObject d = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.banana);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor ed = sp.edit();
ed.putString("track", "0");
ed.apply();
if (isonline()==true)
new JSONParse().execute();
}
@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_home, menu);
return true;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
uid1 = (TextView) findViewById(R.id.textView);
name11 = (TextView) findViewById(R.id.textView2);
email11 = (TextView) findViewById(R.id.textView3);
pre1 = (TextView) findViewById(R.id.textView4);
pDialog = new ProgressDialog(banana.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
ServiceHandler jParser = new ServiceHandler();
// Getting JSON from URL
String url2 = "http://usehumzz.site88.net/banana.json";
JSONObject json = jParser.getJSONFromUrl(url2);
System.out.println(json);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {System.out.println("secomd"+json);
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
System.out.println("user "+user);
JSONObject c = user.getJSONObject(0);
d = json.getJSONObject(TAG_USER1);
System.out.println("d "+d);
// Storing JSON item in a Variable
//String name = c.getString(TAG_NAME);
String email1 = c.getString(TAG_EMAIL);
String a1 = d.getString(TAG_ID1);
String b1 = d.getString(TAG_NAME1);
String id1 = d.getString(TAG_ID);
System.out.println("stuff "+email1+" "+a1+ " "+ b1 +" "+ id1+" ");
uid1.setText(id1);
// name1.setText(name);
email11.setText(email1);
pre1.setText(a1);
name11.setText(b1);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public boolean isonline()
{
ConnectivityManager cm=(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info=cm.getActiveNetworkInfo();
if (info!= null) {
return true;
}
else {
return false;
}
}
}
<file_sep>/app/src/main/java/gino/farmfriend/new_policies.java
package gino.farmfriend;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Created by Gino on 18-02-2016.
*/
public class new_policies extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_policies);
listView=(ListView)findViewById(R.id.listView);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("New Policies");
String[] values = new String[] { "Over 4 per cent annual growth rate aimed over next two decades",
"Greater private sector participation through contract farming",
"Price protection for farmers",
"National agricultural insurance scheme to be launched"
,"Dismantling of restrictions on movement of agricultural commodities throughout the country",
"Rational utilisation of country's water resources for optimum use of irrigation potential",
"High priority to development of animal husbandry, poultry, dairy and aquaculture",
"Capital inflow and assured markets for crop production",
"Exemption from payment of capital gains tax on compulsory acquisition of agricultural land",
"Minimise fluctuations in commodity prices",
"Continuous monitoring of international prices",
"Plant varieties to be protected through a legislation.",
"Adequate and timely supply of quality inputs to farmers",
"High priority to rural electrification",
"Setting up of agro-processing units and creation of off-farm employment in rural areas"
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
}
}
| 25d0d94d9cc1cf33057f6605b13268b183c87418 | [
"Java"
] | 2 | Java | kgt15/FarmFriend-app | d21866a1465492f9e572384d51f8a61de1b4e355 | 6be8b329e0e5ea9870e11d6e52414487f31f22e4 | |
refs/heads/master | <repo_name>GorNishanov/ipr<file_sep>/tests/unit-tests/simple.cpp
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest/doctest.h"
#include <ipr/impl>
#include <ipr/io>
#include <sstream>
TEST_CASE("global constant variable can be printed") {
using namespace ipr;
impl::Lexicon lexicon{};
impl::Module m{lexicon};
impl::Interface_unit unit{lexicon, m};
impl::Scope* global_scope = unit.global_scope();
const Name* name = lexicon.make_identifier("bufsz");
auto& type = lexicon.get_qualified(Type_qualifier::Const, lexicon.int_type());
impl::Var* var = global_scope->make_var(*name, type);
var->init = lexicon.make_literal(lexicon.int_type(), "1024");
std::stringstream ss;
Printer pp{ss};
pp << unit;
CHECK(!ss.str().empty());
}
| fb18439a7ed628bce85c0113a0409d9b264258a9 | [
"C++"
] | 1 | C++ | GorNishanov/ipr | 34dce3817bf533b83005ae62d7f9e6b2c5532b05 | 0d0a8399faf647e13f6f6357bb9ec4bc6152fb15 | |
refs/heads/master | <repo_name>moniir/StrategyPatternExample<file_sep>/src/ShoppingCart.java
import java.util.ArrayList;
import java.util.List;
public class ShoppingCart {
List<Product> productList;
public ShoppingCart() {
this.productList = new ArrayList<>();
}
public void addProduct(Product product){
productList.add(product);
}
public void repoveProduct(Product product){
productList.remove(product);
}
public int calculateTotal(){
int sum = 0;
for(Product product: productList){
sum+=product.getPrice();
}
return sum;
}
public void pay(Payment payment){
int amount = calculateTotal();
payment.pay(amount);
}
}
| 2b4205f0f42d0d9a1b93349bce027a3154fb4099 | [
"Java"
] | 1 | Java | moniir/StrategyPatternExample | 512753d5f819e94404f3d5d7258c51ad3f4f46be | 36662b9571aa17f497e4e6798718ec9ab15f60d6 | |
refs/heads/master | <repo_name>levi1913/Portafolio<file_sep>/index.php
<?php include('header.php')?>
<section>
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg"><defs></defs><path id="myID" d=""/></svg>
</section>
<div class="bienvenida">
<div class="hello">
<div class="banner">
<span>He</span><span class="blanco">llo.</span></div>
<div class="nombre">
<span>I'm <NAME>, web developer and this is my website.</span>
</div>
</div>
</div>
</div>
<div class="container home" id="home">
<div class="row">
<div class="col-lg-12">
<center><img src="img/uaeh.jpg"></center><br>
<p>Mi nombre es <NAME>, soy Licenciado en Ciencias Computacionales
egresado de la Universidad Autónoma del Estado de Hidalgo.
</p>
<p>
Durante mi vida académica y laboral me he enfocado y desempeñado, principalmente en el desarrollo web, especialmente
en el Front-end, aunque también he trabajo en desarrollo back end , gracias a esto, he aprendido diversos lenguajes, tanto de programación como de marcado.
</p>
<p>
Me concidero a mi mismo como una persona trabajadora, que le gusta mucho aprender y le apasiona su trabajo.
Soy bueno adaptandome a grupos de trabajo o desarrollando como freelance.
</p>
</div>
</div>
</div>
<div class="proyectos" id="proyectos">
<br><h2>Proyectos realizados</h2><br>
<div class="carrusel">
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<img class="d-block w-100" src="img/imagen1.png" alt="First slide">
<div class="carousel-caption d-none d-md-block">
<a href="http://revalidacion.uaeh.edu.mx/SistemaRevalidacionUAEHOficial/login.php"><h5>Sistema de revalidación</h5>
<p>Sistema realizado para la Universidad Autónoma del Estado de Hidalgo</p></a>
</div>
</div>
<div class="carousel-item">
<img class="d-block w-100" src="img/imagen2.png" alt="Second slide">
<div class="carousel-caption d-none d-md-block corona">
<a href="https://levi1913.github.io/Covid-19/"><h5>CoronaNews</h5>
<p>Aplicación que muestra todas las estadísticas del COVID-19</p></a>
</div>
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div><br>
<center>
<h3>¿Sobre que proyecto te interesa conocer?</h3>
<select id="proyecto" onchange="selecionar();">
<option value="vacio">Seleccione una opción...</option>
<option value="revalidacion">Sistema de revalidación</option>
<option value="Covid">CoronaNEWS</option>
</select>
<div class="div_revalidacion" style="display: none">
<select id="revalidacion" onchange="opciones1();">
<option value="vacio">Seleccione una opción...</option>
<option value="todo">Todo :)</option>
<option value="conte">Contexto</option>
<option value="herra">Herramientas usadas</option>
<option value="link">Link</option>
</select>
</div>
<div class="div_covid" style="display: none">
<select id="covid" onchange="opciones2();">
<option value="vacio">Seleccione una opción...</option>
<option value="todo">Todo :)</option>
<option value="conte">Contexto</option>
<option value="herra">Herramientas usadas</option>
<option value="link">Link</option>
</select>
</div>
<br>
<div id="infocaja" class="infocaja"></div>
</center>
</div>
<div class="atributos" id="aptitudes">
<br>
<div class="container">
<div class="row">
<div class="col-lg-12">
<br>
<p>A lo largo de mi carrera como estudiante y como profesional, he aprendido una serie de características que pueden
resultar útiles para la realización de todo tipo de proyectos de desarrollo web. </p>
<p>Soy licenciado en Ciencias Computacionales egresado de la Universidad Autónoma del Estado de Hidalgo.</p>
<br>
</div>
<div class="col-lg-6 col-sm-12 listas">
<h3>Lenguajes</h3>
<ul>
<li><img src="img/html.png" class="icon">HTML 5</li>
<li><img src="img/css.png" class="icon">CSS 3</li>
<li><img src="img/javascript.png" class="icon">JAVASCRIPT</li>
<li><img src="img/c++.png" class="icon">C++</li>
<li><img src="img/java.png" class="icon">JAVA</li>
<li><img src="img/cs.png" class="icon">C#</li>
<li><img src="img/sql.png" class="icon">SQL</li>
</ul>
</div>
<div class="col-lg-6 col-sm-12 listas">
<h3>Frameworks</h3>
<ul>
<li><img src="img/boot.png" class="icon">Bootstrap 4</li>
<li><img src="img/react.png" class="icon-mas">React.js</li>
<li><img src="img/angular.png" class="icon">Angular</li>
<li><img src="img/node.png" class="icon-mas">NodeJs</li>
</ul>
</div>
<div class="col-lg-12 col-sm-12 listas">
<h3>Herramientas</h3>
<ul>
<li><img src="img/sass.png" class="icon">SASS</li>
<LI><img src="img/git.png" class="icon">GIT</LI>
<LI><img src="img/github.png" class="icon">GITHUB (repositorios)</LI>
<LI><img src="img/npm.png" class="icon">npm</LI>
</ul>
</div>
</div>
</div>
</div>
<div class="contacto" id="contacto">
<br>
<div class="container">
<div class="row">
<div class="col-lg-6">
<div class="email">
<form action="enviar.php" method="POST" onsubmit="return lleno();">
<h2>¡Contáctame!</h2>
<input type="text" placeholder="Tu nombre..." name="nombre" id="nombre"><br>
<input type="text" placeholder="Tu Asunto..." name="asunto" id="asunto"><br>
<input type="email" placeholder="Tu email..." name="email" id="email"><br>
<input type="number" placeholder="Tu teléfono..." name="telefono" id="telefono"><br><br>
<textarea name="mensaje" placeholder="Escriba aquí su mensaje..." name="mensaje" id="mensaje"></textarea>
<input type="submit" value="Enviar" class="boton">
</form>
</div>
</div>
<div class="col-lg-6 col-sm-12">
<div class="redes">
<ul>
<li><img src="img/gmail.png" class="img_conta"><a href="mailto:<EMAIL>?Subject=Contacto%20páginaweb"><EMAIL></a></li>
<li><img src="img/linkedin.png" class="img_conta"><a href="https://www.linkedin.com/in/levi-torres-2b4587188/">linkedin.com/in/levi-torres-2b4587188</a></li>
<li><img src="img/gitblanco.png" class="img_conta"><a href="https://github.com/levi1913">https://github.com/levi1913</a></li>
<li><img src="img/whatss.png" class="img_conta"><a href=" https://wa.me/527713967763">771 396 7763</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<?php include('footer.php')?>
| 75697423078e491d6460ec862a3150bdea6a7f53 | [
"PHP"
] | 1 | PHP | levi1913/Portafolio | 35b0d2e91cc16470ba15cbaaf1e051a327519393 | d7a8b2fb9db307cbd42a83519f1773e78c70dfb4 | |
refs/heads/main | <file_sep># -*- coding: utf-8 -*-
"""
@Time : 2020/12/16 15:19
@Author : <EMAIL>
@File : docxParser.py
@ Software : PyCharm
@Desc : 获取word文档内容及图片
"""
import xml.dom.minidom
import zipfile
import os
import sys
class DocxParser:
def get_content(self,file_path):
if not os.path.exists(file_path):
print('文件不存在,请检查后重试~')
sys.exit()
if '.docx' not in file_path:
print('仅能处理docx后缀的文件,请检查后重试')
sys.exit()
article_content = self.__read_resource(file_path)
print(article_content)
return article_content
def __read_resource(self,file_path):
content = ''
rels = {}
with zipfile.ZipFile(file_path, 'r') as zip_file:
file_list = zip_file.namelist()
document_xml_name = '' # 段落文件
document_xml_rels = '' # media文件
for i in file_list:
if 'document.xml' in i :
document_xml_name = i
if 'document.xml.rels' in i :
document_xml_rels = i
with zip_file.open(document_xml_name, mode='r') as resource_document:
DOMTree = xml.dom.minidom.parseString(resource_document.read())
collection = DOMTree.documentElement
wp = collection.getElementsByTagName('w:p')
for item in wp:
section = ''
p = ''
picture_id = ''
for i in item.childNodes:
wt = i.getElementsByTagName('w:t')
pic = i.getElementsByTagName('pic:blipFill')
if len(wt) == 0 and len(pic) == 0:
continue
if len(wt) > 0:
p = p + wt[0].childNodes[0].data # 获取段落
if len(pic) > 0:
picture_id = picture_id + ' {' + pic[0].getElementsByTagName('a:blip')[0].attributes[
'r:embed'].value + '} ' # 获取图片资源位
if p != '':
section = '<p>' + p + '</p>'
if len(picture_id) > 0:
section = section + picture_id
content = content + section
with zip_file.open(document_xml_rels, mode='r') as resource_rels:
DOMTree = xml.dom.minidom.parseString(resource_rels.read())
collection = DOMTree.documentElement
wp = collection.getElementsByTagName('Relationship')
for i in wp:
id = i.attributes['Id'].value
target = i.attributes['Target'].value
if 'media/' in target:
rels[id] = target.split('/')[-1].split('.')[0]
for k,v in rels.items():
if '{' + k + '}' in content:
content = content.replace('{' + k + '}','{'+ v +'}')
return content
def __parser_content(self,element):
DOMTree = xml.dom.minidom.parseString(element)
collection = DOMTree.documentElement
content = ''
wp = collection.getElementsByTagName('w:p')
for item in wp:
section = ''
p = ''
picture_id = ''
for i in item.childNodes:
wt = i.getElementsByTagName('w:t')
pic = i.getElementsByTagName('pic:blipFill')
if len(wt) == 0 and len(pic) == 0:
continue
if len(wt) > 0:
p = p + wt[0].childNodes[0].data # 获取段落
if len(pic) > 0:
picture_id = picture_id + ' {' + pic[0].getElementsByTagName('a:blip')[0].attributes['r:embed'].value + '} ' # 获取图片资源位
if p != '':
section = '<p>' + p + '</p>'
if len(picture_id) > 0:
section = section + picture_id
content = content + section
return content
def __parse_rels(self,element):
DOMTree = xml.dom.minidom.parse(element)
collection = DOMTree.documentElement
wp = collection.getElementsByTagName('Relationship')
rels = {}
for i in wp:
id = i.attributes['Id'].value
target = i.attributes['Target'].value
if 'media' in target:
rels[id] = target
return rels
def get_media(self,file_path,save_path):
with zipfile.ZipFile(file_path) as zip_file:
file_list = zip_file.namelist()
media = []
for i in file_list:
if 'word' in i and 'media' in i:
media.append(i)
if media != '':
for i in media:
zip_file.extract(i, save_path)
print('文件已保存在' + os.path.join(save_path,'word','media') + '中!')<file_sep># docxParser
解析docx文档,输出文章内容及图片(图片默认输出图片位置~)
#### 方案
1. 使用 zipfile 获取 docx文档中的 document.xml 数据
2. 使用 xml.dom.minidom.parseString() 解析文档,取出docx文档中的段落内容
3. 读取document.xml.rels 文件,匹配 图片资源的位置
#### 用法
##### 获取word文档内容,包含文字及图片所在位置(图片以 {image1} 表示)
```python
# params: file_path word文档绝对路径
# return: <p>文字</p>{image1}<p>文字</p>
DocxParser().get_content(file_path)
```
---
##### 导出文档图片
```python
# params: file_path word文档绝对路径
# params: save_path 图片保存地址
# return: 最终图片地址:图片保存地址/word/media/
DocxParser().get_media(file_path,save_path)
```
| 4a661ce24bed2fcd1dc2dad76fa3262e8ab6ade3 | [
"Markdown",
"Python"
] | 2 | Python | william-sv/docxParser | 61a01fb5826d2e88c14344214cbce6a2e9fb6da6 | 8975d79d98c44263e95c5be39350e39b6f1b7456 | |
refs/heads/master | <repo_name>DipeshYogi/api_jobseeker<file_sep>/jobseeker_api/api/views.py
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
import psycopg2
from api.serializers import recomm_serializer
from rest_framework import status
from rest_framework.renderers import JSONRenderer
import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import linear_kernel,cosine_similarity
from sklearn.feature_extraction.text import CountVectorizer
try:
conn = psycopg2.connect( user='lvdbzgnnnthckg',
password= '<PASSWORD>',
host = 'ec2-184-72-237-95.compute-1.amazonaws.com',
port = '5432',
database = 'd32b9rckhe5166',
)
cursor = conn.cursor()
print ('Connected')
except (Exception, psycopg2.Error) as error:
print ("error while connecting to postgres")
class GetConn(APIView):
def get(self,request):
cursor.execute('Select * from portal_jobs where owner_id=1')
rec = cursor.fetchall()
cursor.execute('select username from auth_user where id=1')
usr_name = cursor.fetchone()
return Response ({'user':usr_name,'Jobs posted':rec})
class GetRecomm(APIView):
"""Get recommendation for a Profile"""
serializer_class = recomm_serializer
renderer_classes = [JSONRenderer]
def get(self,request):
n1 = self.serializer_class(data=request.data)
if n1.is_valid():
n1 = n1.validated_data.get('n1')
cursor.execute('select p_skills, s_skills, img, exp from users_profile where user_id = %s', (n1,))
rec = cursor.fetchall()
rec = pd.DataFrame(rec, columns=['p_skills','s_skills','img','exp'])
rec['id'] = n1
cursor.execute('select id, title, req_skills, exp from portal_jobs where owner_id <> %s', (n1,))
jobs = cursor.fetchall()
jobs = pd.DataFrame(jobs, columns=['id', 'title', 'req_skills', 'exp'])
users_dta = rec['p_skills']+ ' '+rec['s_skills']
jobs_dta = jobs['title']+ ' '+jobs['req_skills']
jobid = jobs['id']
data1 = pd.concat([users_dta, jobs_dta]).reset_index(drop=True)
count = CountVectorizer(stop_words='english', ngram_range=(1, 2))
count = CountVectorizer(stop_words='english', ngram_range=(1, 2))
mat = count.fit_transform(data1)
score = linear_kernel(mat,mat)
req_score = score[0]
req1_score = list(enumerate(req_score))
req1_score = req1_score[1:]
req1_score = pd.DataFrame(req1_score,columns=['index','score'])
req1_score['JobId'] = jobid
req1_score = req1_score.sort_values(by='score', ascending=False)
req1_score = req1_score[req1_score['score']>=1]['JobId']
req1_score = tuple(req1_score)
#print(req1_score)
cursor.execute('select * from portal_jobs where id in %s',(req1_score,))
recomm_jobs = cursor.fetchall()
cursor.execute('select username from auth_user where id = %s', (n1,))
name = cursor.fetchall()
return Response(recomm_jobs)
else:
return Response(n1.errors, status = status.HTTP_400_BAD_REQUEST)
<file_sep>/requirements.txt
boto==2.49.0
boto3==1.9.236
botocore==1.12.236
dj-database-url==0.5.0
Django==2.1
django-crispy-forms==1.7.2
django-heroku==0.3.1
django-storages==1.7.2
docutils==0.15.2
gunicorn==19.9.0
jmespath==0.9.4
joblib==0.13.2
numpy==1.17.2
pandas==0.25.1
Pillow==6.1.0
psycopg2==2.8.3
python-dateutil==2.8.0
pytz==2019.2
s3transfer==0.2.1
scikit-learn==0.21.3
scipy==1.3.1
six==1.12.0
sklearn==0.0
urllib3==1.25.6
whitenoise==4.1.4
djangorestframework==3.11.0
<file_sep>/api_env/Scripts/django-admin.py
#!c:\users\slappy1012\desktop\2020\api_jobseeker\api_env\scripts\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
<file_sep>/jobseeker_api/api/serializers.py
from rest_framework import serializers
class recomm_serializer(serializers.Serializer):
""" Get recommendations for a Profile"""
n1 = serializers.IntegerField()
<file_sep>/jobseeker_api/api/urls.py
from django.urls import path
from api import views
urlpatterns = [
path('', views.GetConn.as_view(), name = 'test-conn'),
path('recommend/', views.GetRecomm.as_view(), name = 'recommend'),
]
| 7bfc65d93bdfc3b563fd8afcf84a259c4d941fc3 | [
"Python",
"Text"
] | 5 | Python | DipeshYogi/api_jobseeker | 892f096b66956977888f8a41d772951d729c1bad | 65eda8ab540ba2fb6f27b59e4f8544320b769180 | |
refs/heads/master | <file_sep>const express = require('express');
const cors = require('cors')
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const mongoose = require('mongoose');
const app = express();
app.use(cors())
var config = require('./config');
mongoose.connect(config.database);
require('./server/models/db.js')
// API file for interacting with MongoDB
const api = require('./server/routes/api');
// On Connection
mongoose.connection.on('connected', () => {
console.log('Connected to database '+config.database);
});
// On Error
mongoose.connection.on('error', (err) => {
console.log('Database error: '+err);
});
// const users = require('./routes/users');
// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
//
// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));
// API location
app.use('/api', api);
// Send all other requests to the Angular app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
//Set Port
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));
<file_sep>import { Component, ViewChild, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router'
import { OrderService } from '../services/order.service'
import { OrderFormComponent } from '../order-form/order-form.component'
@Component({
selector: 'app-place-order',
templateUrl: './place-order.component.html',
styleUrls: ['./place-order.component.css']
})
export class PlaceOrderComponent implements OnInit {
@ViewChild(OrderFormComponent) private orderFormComponent: OrderFormComponent;
items: any[] = []
constructor(
private orderService: OrderService,
private location: Location,
private router: Router
) {
this.items = this.orderService.items
}
ngOnInit() {
}
decQty(item: any) {
this.items[this.items.indexOf(item)].qty--
if (this.items[this.items.indexOf(item)].qty == 0) {
this.items.splice(this.items.indexOf(item), 1)
}
// (+item.qty)--
}
incQty(item: any) {
this.items[this.items.indexOf(item)].qty++
//(+item.qty)++
}
getItemCount() {
if (this.items) { // for testing
return this.items.length
} else {
return 2
}
}
getTotalPrice() {
if (this.items) { // for testing
var total = 0;
for (let item of this.items) {
total = total + item.price * item.qty
}
return total
} else {
return 11.25
}
}
goBack() {
this.location.back()
}
placeOrder() {
var valid = this.orderFormComponent.validateInfo()
console.log(valid)
if (valid) {
var order: any = {}
console.log(valid)
order.deliveryOrPickup = valid.deliveryOrPickup
console.log(order.deliveryOrPickup)
if (valid.deliveryOrPickup == 'delivery') {
order.address = {}
order.firstName = valid.firstName
order.lastName = valid.lastName
order.address.address = valid.address
order.address.city = valid.city
order.address.zip = valid.zip
} else {
order.firstName = valid.firstName
order.lastName = valid.lastName
}
var items = []
var total = 0
for (let item of this.items) {
var itemWithoutQty = Object.assign({}, item);
var quantity = itemWithoutQty.qty
delete itemWithoutQty.qty
for (var i = 0; i < quantity; i++) {
items.push(itemWithoutQty)
total += itemWithoutQty.price
}
}
order.items = items
order.total = total
console.log(order)
this.orderService.placeOrder(order).subscribe((data) => {
if (data.success) {
this.orderService.items = []
this.router.navigate([''])
}
})
console.log('submitting form...')
} else {
console.log('invalid form')
}
}
}
<file_sep>const mongoose = require('mongoose')
const Category = mongoose.model('Category')
const Location = mongoose.model('Location')
const Item = mongoose.model('Item')
// make sure name and size are unique
module.exports.addItem = function(req, res) {
var name = req.body.name
var price = parseFloat(req.body.price)
var calories = parseInt(req.body.calories)
var size = req.body.size
var categoryName = req.body.category
var locationName = req.body.location
Category.findOne({"name": categoryName}).exec((err, category) => {
if (err) {
res.status(500).json(err)
} else {
item = {
category: category,
name: name,
price: price,
calories: calories,
size: size
// location: locationName
}
if (locationName == 'All') {
Location.update({}, {
$push : { 'items' : item }
}, {
multi : true
}, (err, locations) => {
if (err) {
res.status(500).json(err)
} else {
res.status(201).json({success: true, item: item})
}
});
} else {
Location.findOneAndUpdate(
{'city': locationName},
{$push : {'items': item}},
{'new': true}, (err, location) => {
if (err) {
res.status(500).json(err)
} else {
console.log({success: true, item: item})
res.status(201).json({success: true, item: item})
}
}
)
}
}
})
}
module.exports.getItems = function(req, res) {
Location.find().exec((err, locations) => {
if (err) {
res.status(500).json(err)
} else {
var items = []
for (var location of locations) {
for (var item of location.items) {
if (items.findIndex(i => (i.name == item.name && i.size == item.size)) != -1) {
console.log('item = ' + item.name)
items[items.findIndex(i => (i.name == item.name && i.size == item.size))].location = 'all'
} else {
item.location = location.city
items.push(item)
}
}
}
console.log(items)
// console.log(items)
// var reducedItems = items.reduce(function (allItems, item) {
// console.log('item=', item)
// console.log(allItems.findIndex(i => i.name == item.name)
// if (allItems.findIndex(i => i.name == item.name) != -1) {
// allItems[allItems.findIndex(i => i.name == item.name)].location = 'all'
// } else {
// allItems.push(item)
// }
// return allItems;
// }, []);
// console.log(reducedItems)
res.status(200).json({success: true})
// var dups = [];
// var arr = items.filter(function(el) {
// // If it is not a duplicate, return true
// if (dups.indexOf(el.ID) == -1) {
// dups.push(el.ID);
// return true;
// }
//
// return false;
//
// });
// res.status(200).json(locations)
}
})
}
module.exports.deleteItem = function(req, res) {
const deleteLocation = req.body.location;
const itemId = req.body._id
if ("all" || deleteLocation == "All") {
Location.find().exec((err, locations) => {
if (err) {
res.status(500).json(err)
} else {
for (var location of locations) {
location.items.splice(location.items.findIndex(i => (i._id == itemId)), 1 )
location.save()
}
res.status(201).json({success: true })
// locations.save(function(err, deleted) {
// if (err) {
// res.status(500).json(err)
// } else {
// res.status(201).json({success: true })
// }
// })
}
})
} else {
Location.find({"city": deleteLocation}).exec((err, location) => {
if (err) {
res.status(500).json(err)
} else {
console.log("location = " + location)
console.log('items')
console.log(location[0].items)
location[0].items.splice(location[0].items.findIndex(i => (i._id == itemId)), 1 )
location[0].save(function(err, deleted) {
if (err) {
res.status(500).json(err)
} else {
res.status(201).json({success: true })
}
})
}
})
}
}
module.exports.editItem = function(req, res) {
const editLocation = req.body.location;
const itemId = req.body._id;
if (editLocation == "All") {
Location.find().exec((err, locations) => {
if (err) {
res.status(500).json(err)
} else {
delete req.body.location
for (var location of locations) {
location.items.splice(location.items.findIndex(i => (i._id == itemId)), 1, req.body)
location.save()
}
res.status(201).json({success: true })
}
})
} else {
Location.find({"city": editLocation}).exec((err, location) => {
if (err) {
res.status(500).json(err)
} else {
delete req.body.location
location[0].items.splice(location[0].items.findIndex(i => (i._id == itemId)), 1, req.body)
location[0].save(function(err, deleted) {
if (err) {
res.status(500).json(err)
} else {
res.status(201).json({success: true })
}
})
}
})
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http'
import 'rxjs/add/operator/map'
@Injectable()
export class AdminService {
constructor(private http: Http) { }
addCategory(name: String) {
// let headers = new Headers();
// this.loadToken()
// headers.append('Authorization', 'JWT ' + this.authToken)
// headers.append('Content-Type', 'application/json')
return this.http.post('http://localhost:3000/api/category', { name: name }/*, { headers: headers }*/)
.map(res => res.json())
}
deleteCategory(categoryName: String) {
// let headers = new Headers();
// this.loadToken()
// headers.append('Authorization', 'JWT ' + this.authToken)
// headers.append('Content-Type', 'application/json')
return this.http.delete('http://localhost:3000/api/category', new RequestOptions({ body: { "categoryName": categoryName } }))
.map(res => res.json())
}
editCategory(oldAndNewCategories: Object) {
// let headers = new Headers();
// this.loadToken()
// headers.append('Authorization', 'JWT ' + this.authToken)
// headers.append('Content-Type', 'application/json')
return this.http.put('http://localhost:3000/api/category', oldAndNewCategories)
.map(res => res.json())
}
addItem(item: Object) {
// let headers = new Headers();
// this.loadToken()
// headers.append('Authorization', 'JWT ' + this.authToken)
// headers.append('Content-Type', 'application/json')
return this.http.post('http://localhost:3000/api/items', item/*, { headers: headers }*/)
.map(res => res.json())
}
deleteItem(item: Object) {
// let headers = new Headers();
// this.loadToken()
// headers.append('Authorization', 'JWT ' + this.authToken)
// headers.append('Content-Type', 'application/json')
return this.http.delete('http://localhost:3000/api/items', new RequestOptions({ body: item })).map(res => res.json())
}
editItem(item: Object) {
// let headers = new Headers();
// this.loadToken()
// headers.append('Authorization', 'JWT ' + this.authToken)
// headers.append('Content-Type', 'application/json')
return this.http.put('http://localhost:3000/api/items', item).map(res => res.json())
}
}
<file_sep>var mongoose = require('mongoose')
var Location = mongoose.model('Location')
var config = require('../../config')
// name: type: String,required: true
// address: {type: String,required: true},
// coordinates: {type: [Number],required: true},
// hours: {type: [OpeningTimeSchema],required: true},
// wifi: {type: Boolean},
// menu: {type: MenuSchema}
// days: {type: String,required: true},
// opening: String,
// closing: String,
// closed: {type: Boolean,required: true}
module.exports.addLocation = function(req, res) {
const street = req.body.street
const city = req.body.city
const state = req.body.state
const zip = req.body.zip
const slug = city.replace(/\./, "").replace(/\s/g, '-').toLowerCase()
const lat = req.body.lat
const lng = req.body.lng
const coordinates = [parseFloat(lat), parseFloat(lng)]
const hours =
[
{
days: 'Monday-Friday',
opening: "10:00",
closing: "10:00",
closed: false
},
{
days: 'Saturday',
opening: "10:00",
closing: "12:00",
closed: false
},
{
days: 'Sunday',
closed: true
}
]
const wifi = (req.body.wifi == 'true')
Location.create({
street: street,
city: city,
state: state,
zip: zip,
slug: slug,
coordinates: coordinates,
hours: hours,
wifi: wifi
}, (err, location) => {
if (err) {
res.status(400).json(err)
} else {
res.status(201).json(location)
}
})
}
module.exports.getLocation = function(req, res) {
var city = req.params.location
// var city = req.params.location.replace(/-/, " ").toLowerCase()
// city = city.indexOf('st') != -1 ? city.replace(/st/, 'st.') : city
// console.log(city)
// res.status(200).json({success: true})
Location.find({"slug": city}).exec((err, location) => {
var categoryNameHolder = []
var categoryArr = []
var pizzaSizes = []
var specialPizzas = []
var toppings = []
location[0].items.forEach(function(item) {
if (item.name == "Custom Pizza") {
pizzaSizes.push(item)
}
else if (item.category.name == "Pizza") {
specialPizzas.push(item)
}
else if (item.category.name == "Topping") {
toppings.push(item)
} else {
categoryNameHolder[item.category.name] = categoryNameHolder[item.category.name] || {}
var obj = categoryNameHolder[item.category.name]
if (Object.keys(obj).length == 0)
categoryArr.push(obj)
obj.categoryName = item.category.name
obj.items = obj.items || []
obj.items.push(item)
}
})
var pizza = {
categoryName: "Pizza",
pizzaSizes: pizzaSizes,
specialPizzas: specialPizzas,
toppings: toppings
}
// var locationAndSortedItems = {
// location: location[0],
// sortedItems: groupedItems
// }
var locationSortedItemsAndPizza = {
location: location[0],
sortedItems: categoryArr,
pizza: pizza
}
if (err) {
res.status(400).json(err)
} else {
res.status(200).json(locationSortedItemsAndPizza)
}
})
}
<file_sep>const mongoose = require('mongoose');
const AddressSchema = mongoose.Schema({
address: {
type: String
},
city: {
type: String
},
zip: {
type: Number
}
});
module.exports = mongoose.model('Address', AddressSchema);
<file_sep>const mongoose = require('mongoose');
const OpeningTimeSchema = mongoose.Schema({
days: {
type: String,
required: true
},
opening: String,
closing: String,
closed: {
type: Boolean,
required: true
}
});
module.exports = mongoose.model('OpeningTime', OpeningTimeSchema);
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'
import { Subscription } from 'rxjs/Subscription';
import { OrderService } from '../services/order.service'
@Component({
selector: 'app-order-summary',
templateUrl: './order-summary.component.html',
styleUrls: ['./order-summary.component.css']
})
export class OrderSummaryComponent implements OnInit {
items: any[] = []
subscription: Subscription;
orderCount: number = 0
constructor(
private orderService: OrderService,
private router: Router
) {
this.subscription = orderService.itemAdded$.subscribe(
item => {
this.orderCount++
var ordered = false;
for (let orderItem of this.items) {
if (orderItem._id == item._id) {
if (orderItem.name == 'Custom Pizza') {
if (orderItem.toppings.length == item.toppings.length) {
var toppingsDontMatch = false
orderItem.toppings.sort(function(a, b) {
var nameA = a.name.toUpperCase(); // ignore upper and lowercase
var nameB = b.name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
})
item.toppings.sort(function(a, b) {
var nameA = a.name.toUpperCase(); // ignore upper and lowercase
var nameB = b.name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
})
for (var i = 0; i < orderItem.toppings.length; i++) {
if (item.toppings[i]._id == orderItem.toppings[i]._id) {
continue
} else {
console.log('print unequal')
toppingsDontMatch = true
}
}
if (!toppingsDontMatch) {
orderItem.qty++
ordered = true
}
}
} else {
orderItem.qty++
ordered = true
}
}
}
if (!ordered) {
item.qty = 1;
this.items.push(item)
}
}
)
this.items = this.orderService.items
}
ngOnInit() {
}
ngOnDestroy() {
// prevent memory leak when component destroyed
this.subscription.unsubscribe();
}
removeItem(item: any) {
this.items = this.items.filter((orderItem) => {
if (item.name == "Custom Pizza" && orderItem._id == item._id) {
if (item.toppings.length == orderItem.toppings.length) {
for (var i = 0; i < item.toppings.length; i++) {
if (item.toppings[i] != orderItem.toppings[i])
return orderItem;
}
} else {
return orderItem
}
} else {
if (orderItem._id != item._id)
return orderItem
else
this.orderCount = this.orderCount - orderItem.qty
}
})
this.orderService.removeItem(this.orderCount)
}
getTotal() {
return this.items
.reduce((sum, value) => sum + (value.price * value.qty), 0);
}
placeOrder() {
this.orderService.placeOrder(this.items)
this.router.navigate(['place-order'])
}
}
<file_sep>import { Component, OnInit, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
@Output() showCat = new EventEmitter<boolean>()
@Output() showIt = new EventEmitter<boolean>()
@Output() logout = new EventEmitter<boolean>();
constructor() { }
showCategory = false
showItem = false
ngOnInit() {
}
showAddCategory() {
this.showCategory = !this.showCategory
this.showCat.emit(this.showCategory)
}
showAddItem() {
this.showItem = !this.showItem
this.showIt.emit(this.showItem)
}
logoutAdmin() {
this.logout.emit(true)
}
}
<file_sep>var mongoose = require('mongoose')
var User = mongoose.model('User')
var bcrypt = require('bcrypt-nodejs')
var jwt = require('jsonwebtoken')
var config = require('../../config')
module.exports.authenticate = function(req, res, next) {
var headerExists = req.headers.authorization
if (headerExists) {
var token = req.headers.authorization.split(' ')[1]
jwt.verify(token, config.secret, function(error, decoded) {
if (error) {
console.log(error)
res.status(401).json('Unauthorized')
} else {
req.user = decoded.username
next()
}
})
} else {
res.status(403).json('No token provided')
}
}
module.exports.login = function(req, res) {
var username = req.body.username
var password = <PASSWORD>
User.findOne({
username: username
}).exec(function(err, user) {
if (err) {
console.log(err)
res.status(400).json(err)
} else {
if (bcrypt.compareSync(password, user.password)) {
var token = jwt.sign({ username: user.username }, config.secret)
res.status(200).json({success: true, token: token, user: user.username})
} else {
res.status(401).json('Unauthorized')
}
}
})
}
// module.exports.addUser = function(req, res) {
// var username = req.body.username;
// var password = <PASSWORD>;
//
// User.create({
// username: username,
// password: <PASSWORD>.hashSync(password, bcrypt.genSaltSync(10))
// }, function(err, user) {
// if (err) {
// console.log(err)
// res.status(400).json(err)
// } else {
// console.log('user created', user)
// // var token = jwt.sign({ username: user.username }, '<PASSWORD>', { expiresIn: 3600 })
// res.status(201).json({success: true})
// }
// })
// }
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-order-form',
templateUrl: './order-form.component.html',
styleUrls: ['./order-form.component.css']
})
export class OrderFormComponent implements OnInit {
delivery: boolean = true
submitted: boolean = false
orderForm: FormGroup
// orderInfo = {
// deliveryOrPickup: this.delivery ? "delivery" : "Pickup",
// firstName: "",
// lastName: "",
// address: "",
// city: "",
// zip: ""
// }
// orderForm = new FormGroup({
// firstName: new FormControl(),
// lastName: new FormControl(),
// address: new FormControl(),
// city: new FormControl(),
// zip: new FormControl(),
// });
constructor(private fb: FormBuilder) {
this.createForm()
}
createForm() {
this.orderForm = this.fb.group({
deliveryOrPickup: "delivery",
firstName: ["", Validators.compose([
Validators.minLength(2),
Validators.required
])],
lastName: ["", Validators.compose([
Validators.minLength(2),
Validators.required
])],
address: ["", Validators.compose([
Validators.minLength(4),
Validators.required
])],
city: ["", Validators.compose([
Validators.minLength(4),
Validators.required
])],
zip: ["", Validators.compose([
Validators.pattern(/^\d{5}$/),
Validators.required
])]
});
}
ngOnInit() {
this.orderForm.get('deliveryOrPickup').valueChanges.subscribe((deliveryOrPickup: string) => {
// console.log(deliveryOrPickup)
if (deliveryOrPickup == "delivery") {
this.orderForm.get('address').setValidators([Validators.required, Validators.minLength(4)]);
this.orderForm.get('city').setValidators([Validators.required, Validators.minLength(4)]);
this.orderForm.get('zip').setValidators([Validators.required, Validators.pattern(/^\d{5}$/)]);
}
if (deliveryOrPickup == "pickup") {
// this.orderForm.get('address').setValue("")
this.orderForm.get('address').setValidators(null);
this.orderForm.get('address').updateValueAndValidity();
// this.orderForm.get('city').setValue("")
this.orderForm.get('city').setValidators(null);
this.orderForm.get('city').updateValueAndValidity();
// this.orderForm.get('zip').setValue("")
this.orderForm.get('zip').setValidators(null);
this.orderForm.get('zip').updateValueAndValidity();
}
})
}
get firstName() { return this.orderForm.get('firstName'); }
get lastName() { return this.orderForm.get('lastName'); }
get address() { return this.orderForm.get('address'); }
get city() { return this.orderForm.get('city'); }
get zip() { return this.orderForm.get('zip'); }
validateInfo() {
if (this.orderForm.status == 'VALID') {
// Submit
return this.orderForm.value
} else {
this.submitted = true
return false
}
}
deliverySelected() {
this.delivery = true;
this.orderForm.get('deliveryOrPickup').setValue("delivery")
}
pickUpSelected() {
this.delivery = false;
this.orderForm.get('deliveryOrPickup').setValue("pickup")
}
}
<file_sep>const mongoose = require('mongoose');
const Item = require('./item.js')
const ItemSchema = mongoose.model('Item').schema
const AddressSchema = mongoose.model('Address').schema
const OrderSchema = mongoose.Schema({
items: {
type: [ItemSchema],
required: true
},
timePlaced: {
type: Date,
"default": Date.now
},
paid: {
type: Boolean,
"default": false
},
deliveryOrPickup: {
type: String,
required: true
},
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
total: {
type: Number,
required: true
},
address: AddressSchema
});
module.exports = mongoose.model('Order', OrderSchema);
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';
import { AgmCoreModule } from '@agm/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { LocationsComponent } from './locations/locations.component';
import { LoginComponent } from './login/login.component';
import { DashboardComponent } from './dashboard/dashboard.component'
import { NavbarComponent } from './navbar/navbar.component';
import { MenuComponent } from './menu/menu.component'
import { AdminService } from './services/admin.service';
import { AuthService } from './services/auth.service';
import { MenuService } from './services/menu.service';
import { OrderService } from './services/order.service';
import { AuthGuard } from './guards/auth.guard';
import { DialogComponent } from './dialog/dialog.component';
import { UserMenuComponent } from './user-menu/user-menu.component';
import { OrderSummaryComponent } from './order-summary/order-summary.component';
import { PlaceOrderComponent } from './place-order/place-order.component';
import { OrderFormComponent } from './order-form/order-form.component';
const routes: Routes = [
{ path: '', component: HomeComponent, pathMatch: 'full' },
{ path: 'about', component: AboutComponent },
{ path: 'locations', component: LocationsComponent },
{ path: 'order-form', component: OrderFormComponent },
{ path: 'menu/:location', component: UserMenuComponent },
{ path: 'place-order', component: PlaceOrderComponent },
{ path: 'admin/login', component: LoginComponent },
{ path: 'admin/dashboard', component: DashboardComponent/*, canActivate: [AuthGuard]*/ }
];
@NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutComponent,
LocationsComponent,
LoginComponent,
DashboardComponent,
NavbarComponent,
MenuComponent,
DialogComponent,
UserMenuComponent,
OrderSummaryComponent,
PlaceOrderComponent,
OrderFormComponent,
],
imports: [
BrowserModule,
HttpModule,
FormsModule,
ReactiveFormsModule,
BrowserAnimationsModule,
RouterModule.forRoot(routes),
AgmCoreModule.forRoot({
apiKey: '<KEY>'
})
],
providers: [
AdminService,
AuthService,
MenuService,
OrderService,
AuthGuard
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http'
import 'rxjs/add/operator/map'
import { Subject } from 'rxjs/Subject';
@Injectable()
export class OrderService {
items: Object[] = []
constructor(private http: Http) { }
// Observable string sources
private itemAddedSource = new Subject<any>();
private itemRemovedSource = new Subject<number>();
// Observable string streams
itemAdded$ = this.itemAddedSource.asObservable();
itemRemoved$ = this.itemRemovedSource.asObservable();
// missionConfirmed$ = this.missionConfirmedSource.asObservable();
// Service message commands
addItem(item: any) {
this.itemAddedSource.next(item);
}
removeItem(newQty: number) {
this.itemRemovedSource.next(newQty)
}
placeOrder(order: any) {
return this.http.post('http://localhost:3000/api/order', order)
.map(res => res.json())
}
retrieveOrder() {
return this.items
}
//
// confirmMission(astronaut: string) {
// this.missionConfirmedSource.next(astronaut);
// }
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { trigger, state, style, transition, animate } from '@angular/animations';
import 'rxjs/add/operator/switchMap';
import { Subscription } from 'rxjs/Subscription';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MenuService } from '../services/menu.service'
import { OrderService } from '../services/order.service';
@Component({
selector: 'app-user-menu',
templateUrl: './user-menu.component.html',
styleUrls: ['./user-menu.component.css'],
animations: [
trigger('slideInOut', [
state('in', style({
transform: 'translate3d(0, 0, 0)'
})),
state('out', style({
transform: 'translate3d(100%, 0, 0)'
})),
transition('in => out', animate('400ms ease-in-out')),
transition('out => in', animate('400ms ease-in-out'))
]),
]
// providers: [OrderService]
})
export class UserMenuComponent implements OnInit {
location: Object
sortedItems: Object[]
pizza: any
menuState: String = 'out';
orderQty: number = 0;
subscription: Subscription;
showDialog: boolean = false;
customPizzaForm: FormGroup
toppings: any
constructor(
private route: ActivatedRoute,
private menuService: MenuService,
private orderService: OrderService,
private fb: FormBuilder
) {
this.route.params
.switchMap((params: Params) => this.menuService.getLocationInfo(params['location']))
.subscribe(data => {
console.log(data)
this.location = data.location
this.sortedItems = data.sortedItems
this.pizza = data.pizza
this.toppings = data.pizza.toppings
console.log(this.toppings)
// console.log(this.location)
// console.log('sortedItems')
// console.log(this.sortedItems)
// console.log(this.pizza.items[this.pizza.items.findIndex(i => i.size == "Medium")])
this.customPizzaForm
.patchValue({
pizzaSize: this.pizza.pizzaSizes[this.pizza.pizzaSizes.findIndex(i => i.size == "Medium")]
})
});
this.subscription = orderService.itemRemoved$.subscribe(
newQty => {
this.orderQty = newQty
});
this.orderQty = this.orderService.items.length
}
addTopping() {
const control = <FormArray>this.customPizzaForm.controls['toppings'];
const addrCtrl = this.initTopping();
control.push(addrCtrl);
}
removeTopping(i: number) {
const control = <FormArray>this.customPizzaForm.controls['toppings'];
control.removeAt(i);
}
initTopping() {
return this.fb.group({
topping: {}
});
}
ngOnInit() {
// call from ngOnInit
this.customPizzaForm = this.fb.group({
pizzaSize: [{}, Validators.required],
// pizzaSize: this.fb.group(new Item())
toppings: this.fb.array([])
});
this.addTopping()
}
ngOnDestroy() {
// prevent memory leak when component destroyed
this.subscription.unsubscribe();
}
toggleOrder() {
this.menuState = this.menuState === 'out' ? 'in' : 'out';
}
addItemToOrder(product: Object) {
this.orderQty++;
this.orderService.addItem(product)
}
addPizzaToOrder() {
var pizza = Object.assign({}, this.customPizzaForm.value.pizzaSize);
var toppings = []
var size = pizza.size
var toppingsArr = this.customPizzaForm.value.toppings.slice(0)
for (let topping of toppingsArr) {
if (Object.keys(topping.topping).length !== 0) {
var newTopping = Object.assign({}, topping.topping)
switch (size) {
case ("Small"):
newTopping.calories = parseInt((newTopping.calories * 0.8).toFixed(0))
newTopping.price = parseFloat((newTopping.price * 0.8).toFixed(1))
pizza.calories += parseInt(newTopping.calories.toFixed(0))
pizza.price = parseFloat((pizza.price + newTopping.price).toFixed(1))
break;
case ("Large"):
newTopping.calories = parseInt((newTopping.calories * 1.2).toFixed(0))
newTopping.price = parseFloat((newTopping.price * 1.2).toFixed(1))
pizza.calories += parseInt((newTopping.calories).toFixed(0))
pizza.price = parseFloat((pizza.price + newTopping.price).toFixed(1))
break;
default:
pizza.calories += newTopping.calories
pizza.price = parseFloat((pizza.price + newTopping.price).toFixed(1))
}
toppings.push(newTopping)
}
}
// console.log('pizzaPrice')
// console.log(pizza.price)
// console.log("toppings")
// console.log(toppings)
pizza.toppings = toppings
// console.log(pizza)
this.orderService.addItem(pizza)
this.orderQty++
this.showDialog = !this.showDialog
this.customPizzaForm = this.fb.group({
pizzaSize: [{}, Validators.required],
// pizzaSize: this.fb.group(new Item())
toppings: this.fb.array([])
});
this.addTopping()
this.customPizzaForm
.patchValue({
pizzaSize: this.pizza.pizzaSizes[this.pizza.pizzaSizes.findIndex(i => i.size == "Medium")]
})
}
toppingPrice(topping: any) {
switch (this.customPizzaForm.value.pizzaSize.size) {
case ("Small"):
return topping.price * 0.8
case ("Large"):
return topping.price * 1.2
default:
return topping.price
}
}
createPizza() {
this.showDialog = !this.showDialog
}
}
<file_sep>var mongoose = require('mongoose')
var Category = mongoose.model('Category')
var Location = mongoose.model('Location')
module.exports.getAdminInfo = function(req, res) {
Category.find().exec((err, categories) => {
if (err) {
res.status(500).json(err)
} else {
Location.find().exec((err, locations) => {
if (err) {
res.status(500).json(err)
} else {
var items = []
var locationNames = []
for (var location of locations) {
locationNames.push(location.city)
for (var item of location.items) {
if (items.findIndex(i => (i.name == item.name && i.size == item.size)) != -1) {
items[items.findIndex(i => (i.name == item.name && i.size == item.size))].location = 'All'
} else {
item.location = location.city
items.push(item)
}
}
}
// var reducedItems = items.sort(function(a, b) {
// var catA = a.category.name.toUpperCase()
// var catB = b.category.name.toUpperCase()
// if (catA < catB) {
// return -1;
// }
// if (catA > catB) {
// return 1;
// }
// return 0;
// }).reduce(function(acc, item) {
// if (acc.length) {
// if (acc[acc.length - 1][0].name.category = item.category) {
// acc[acc.length-1].push(item)
// } else {
// acc.push([item])
// }
// } else {
// acc.push([item])
// }
// }, [])
var categoryNameHolder = []
var categoryArr = []
items.forEach(function(item) {
categoryNameHolder[item.category.name] = categoryNameHolder[item.category.name] || {}
var obj = categoryNameHolder[item.category.name]
if (Object.keys(obj).length == 0)
categoryArr.push(obj)
obj.categoryName = item.category.name
obj.items = obj.items || []
obj.items.push(item)
})
// var groupedItems = items.reduce(function(arr, item) {
// arr.findIndex(i => (i.category.name == i.category.name))
// obj[item.category.name] = obj[item.category.name] || []
// obj[item.category.name].push(item)
// return obj;
// }, [])
// var result = Object.keys(groupedItems).map(function(key) {
// return groupedItems[key];
// });
locationNames.push('All')
var categoriesAndGroupedItems = {
locations: locationNames,
categories: categories,
items: categoryArr
}
// console.log(categoriesAndLocations)
res.status(200).json(categoriesAndGroupedItems)
}
})
//res.status(200).json(categories)
}
})
}
<file_sep>const mongoose = require('mongoose');
const Category = require('./category.js')
const CategorySchema = mongoose.model('Category').schema
const ItemSchema = mongoose.Schema({
category: {
type: CategorySchema,
required: true
},
name: {
type: String,
required: true
},
size: {
type: String
},
calories: {
type: Number,
required: true
},
price: {
type: Number,
required: true
},
location: String,
toppings: [this]
});
module.exports = mongoose.model('Item', ItemSchema);
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-locations',
templateUrl: './locations.component.html',
styleUrls: ['./locations.component.css']
})
export class LocationsComponent implements OnInit {
coords: any;
lat: number;
lng: number;
constructor() {
this.coords = [
[44.9695247, -93.1064527],
[44.9744402, -93.2732667]
];
this.lat = (this.coords[0][0] + this.coords[1][0]) / 2;
this.lng = (this.coords[0][1] + this.coords[1][1]) / 2;
}
ngOnInit() {
}
}
<file_sep>const mongoose = require('mongoose');
const OpeningTime = require('./openingTime.js')
const OpeningTimeSchema = mongoose.model('OpeningTime').schema
const Item = require('./item.js')
const ItemSchema = mongoose.model('Item').schema
const LocationSchema = mongoose.Schema({
street: {
type: String,
required: true
},
city: {
type: String,
required: true
},
state: {
type: String,
required: true
},
zip: {
type: String,
required: true
},
slug: {
type: String,
required: true
},
coordinates: {
type: [Number],
required: true
},
hours: {
type: [OpeningTimeSchema],
// required: true
},
wifi: {
type: Boolean,
required: true
},
items: {
type: [ItemSchema]
}
});
// Note: Virtuals aren't able to be queried
// LocationSchema.virtual('slug').get(function() {
// return this.city.replace(/\./, "").replace('\s', '-').toLowerCase();
// });
module.exports = mongoose.model('Location', LocationSchema);
<file_sep>import { Component, OnInit, Pipe, PipeTransform } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations'
import {trigger, transition, style, animate, state} from '@angular/animations'
import { NgForm } from '@angular/forms'
import { AdminService } from '../services/admin.service'
import { AuthService } from '../services/auth.service'
@Pipe({ name: 'keys', pure: false })
export class KeysPipe implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value)//.map(key => value[key]);
}
}
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css'],
animations: [
trigger(
'myAnimation',
[
transition(
':enter', [
style({ transform: 'translateY(-100%)', opacity: 0 }),
animate('500ms', style({ transform: 'translateY(0)', 'opacity': 1 }))
]
),
transition(
':leave', [
style({ transform: 'translateY(0)', 'opacity': 1 }),
animate('500ms', style({ transform: 'translateY(-100%)', 'opacity': 0 }))
]
)
]
)
]
})
export class DashboardComponent implements OnInit {
categories: Object[]
items: any//Object[]
locationNames: Object[]
showCategory: boolean = false;
showItem: boolean = false;
catName: String;
addCatSubmitted: boolean = false;
addItemSubmitted: boolean = false;
item = {
name: "",
category: "",
price: "",
location: "",
calories: "",
size: ""
}
constructor(
private adminService: AdminService,
private authService: AuthService,
private router: Router
) { }
ngOnInit() {
this.authService.getInfo().subscribe(data => {
this.categories = data.categories
this.items = data.items
this.locationNames = data.locations
// console.log(this.items)
}, err => {
console.log(err)
return false
})
}
logout(value: boolean) {
// this.authService.logout()
this.router.navigate(['admin/login'])
}
showCat(show: boolean) {
// if (this.showItem) {
// this.showItem = !this.showItem
// setTimeout(function() {
// this.showCategory = !this.showCategory
// }, 1000)
// } else {
// this.showCategory = !this.showCategory
// }
this.showCategory = !this.showCategory
}
showIt(show: boolean) {
// if (this.showCategory) {
// console.log('print')
// this.showCategory = !this.showCategory
// setTimeout(function() {
// this.showItem = !this.showItem
// }, 500)
// } else {
// this.showItem = !this.showItem
// }
this.showItem = !this.showItem
}
addCategory(form: NgForm) {
if (form.valid) {
this.addCatSubmitted = false
this.adminService.addCategory(this.catName).subscribe((data) => {
this.categories.push(data);
this.showCategory = !this.showCategory
})
} else {
this.addCatSubmitted = true
}
}
addItem(form: NgForm) {
if (form.valid) {
console.log(this.item)
this.addItemSubmitted = false
this.adminService.addItem(this.item).subscribe((data) => {
if (data.success) {
var addedToExistingCategory: boolean = false;
this.items.forEach((definedItem) => {
if (definedItem.categoryName == data.item.category.name) {
data.item.location = this.item.location
definedItem.items.push(data.item)
addedToExistingCategory = true
}
})
if (!addedToExistingCategory) {
var obj = {}
obj["categoryName"] = data.item.category.name
obj["items"] = [data.item]
this.items.push(obj)
}
this.item = {
name: "",
category: "",
price: "",
location: "",
calories: "",
size: ""
}
console.log(this.items)
}
})
} else {
this.addItemSubmitted = true
}
}
}
<file_sep>import { Component, OnInit, OnChanges, Input, SimpleChanges } from '@angular/core';
import { NgForm } from '@angular/forms'
import { AdminService } from '../services/admin.service'
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit, OnChanges {
@Input() items: any;
@Input() categories: any;
@Input() locations: any;
selectedItem: any;
selectedCategory: String;
showDialog: boolean = false;
showCategoryDialog: boolean = false;
editProduct: any;
editSubmitted: boolean = false;
editCat: String;
newCatName: String;
editCatSubmitted: boolean = false;
constructor(private adminService: AdminService) { }
ngOnInit() {
}
ngOnChanges(changes: SimpleChanges) {
console.log('changes')
console.log(changes['items'])
// if (changes['items']) {
// this.items = changes['items'];
// }
console.log('items')
console.log(this.items)
console.log('editProduct')
console.log(this.editProduct)
}
// Delete category from dashboard
deleteCategory() {
this.adminService.deleteCategory(this.selectedCategory).subscribe((data) => {
if (data.success) {
// console.log(this.items.findIndex(i => (i.categoryName == this.selectedItem.category)))
this.items.splice(this.items.findIndex(i => (i.categoryName == this.selectedCategory)), 1)
this.selectedCategory = ""
}
})
this.showCategoryDialog = !this.showCategoryDialog
}
editCategory(catName: String) {
if (this.editCat == catName) {
this.editCat = ""
this.newCatName = ""
} else {
this.editCat = catName
this.newCatName = catName
}
}
editCategorySubmit(form: NgForm) {
var obj = {}
obj["oldCategoryName"] = this.editCat
obj["newCategoryName"] = this.newCatName
if (form.valid) {
this.adminService.editCategory(obj).subscribe((data) => {
if (data.success) {
this.items[this.items.findIndex(i => (i.categoryName == this.editCat))]["categoryName"] = this.newCatName
this.editCat = ""
this.newCatName = ""
}
})
} else {
this.editCatSubmitted = true;
}
}
deleteItem() {
this.adminService.deleteItem(this.selectedItem).subscribe((data) => {
if (data.success) {
// console.log(this.items.findIndex(i => (i.categoryName == this.selectedItem.category)))
var item = this.items[this.items.findIndex(i => (i.categoryName == this.selectedItem.category.name))]
item.items.splice(item.items.findIndex(i => (i._id == this.selectedItem._id)), 1)
this.selectedItem = {}
}
})
this.showDialog = !this.showDialog
}
setSelected(product: Object) {
this.selectedItem = product
this.showDialog = !this.showDialog
}
setSelectedCategory(category: String) {
this.selectedCategory = category
this.showCategoryDialog = !this.showCategoryDialog
}
edit(product: any) {
if (this.editProduct && this.editProduct._id == product._id) {
this.editProduct = {}
} else {
this.editProduct = Object.assign({}, product)
console.log(this.editProduct)
}
}
editItem(form: NgForm) {
if (form.valid) {
this.adminService.editItem(this.editProduct).subscribe((data) => {
if (data.success) {
// console.log(this.items.findIndex(i => (i.categoryName == this.selectedItem.category)))
var item = this.items[this.items.findIndex(i => (i.categoryName == this.editProduct.category.name))]
item.items.splice(item.items.findIndex(i => (i._id == this.editProduct._id)), 1, this.editProduct)
this.editProduct = {}
}
})
} else {
this.editSubmitted = true;
}
}
}
| 27191e22df0490ac0c2363a9d3ea33a9514177c7 | [
"JavaScript",
"TypeScript"
] | 21 | JavaScript | EisenEgan/BellicciPizza | fc9c5c2ef3801c6dd711cf7d2c54c36b065ccc80 | f912277f4532414bae02f8048bd85baf36c86fb7 | |
refs/heads/master | <repo_name>rrosenblum/rails-footnotes<file_sep>/lib/rails-footnotes/extension.rb
require 'active_support/concern'
module Footnotes
module RailsFootnotesExtension
extend ActiveSupport::Concern
included do
prepend_before_action :rails_footnotes_before_action
after_action :rails_footnotes_after_action
end
def rails_footnotes_before_action
if Footnotes.enabled?(self)
Footnotes::Filter.start!(self)
end
end
def rails_footnotes_after_action
if Footnotes.enabled?(self)
filter = Footnotes::Filter.new(self)
filter.add_footnotes!
filter.close!(self)
end
end
end
end
| edda201e0a8542e7c2aba048499b607c674b4a3f | [
"Ruby"
] | 1 | Ruby | rrosenblum/rails-footnotes | 2cac543d747873070495e6dc45effa97728e6abf | 681e385953b78b95a648e093ac9724d1240552ce | |
refs/heads/master | <repo_name>Assumeru/CMIBOD023T<file_sep>/src/main/java/nl/hro/cmibod023t/classification/Classifier.java
package nl.hro.cmibod023t.classification;
public interface Classifier<T> extends Trainable<T> {
Result<T> test(Object... features);
default Result<T> test(Classifiable object) {
return test(object.getFeatures());
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/classification/DecisionTree.java
package nl.hro.cmibod023t.classification;
import nl.hro.cmibod023t.classification.tree.Node;
public class DecisionTree<T> implements Classifier<T> {
private final FeatureTable<T> table;
private Node<T> tree;
public DecisionTree(Class<?>... columns) {
table = new FeatureTable<>(columns);
}
@Override
public DecisionTree<T> train(T result, Object... features) {
table.train(result, features);
tree = null;
return this;
}
@Override
public Result<T> test(Object... features) {
table.checkFeatureLength(features);
if(tree == null) {
tree = Node.build(table);
}
return tree.getValue(features);
}
@Override
public String toString() {
if(tree == null) {
tree = Node.build(table);
}
return tree.toString();
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/classification/Trainable.java
package nl.hro.cmibod023t.classification;
public interface Trainable<T> {
Trainable<T> train(T result, Object... features);
default Trainable<T> train(Testable<T> object) {
return train(object.getTargetClass(), object.getFeatures());
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/exercises/Star.java
package nl.hro.cmibod023t.exercises;
import nl.hro.cmibod023t.cluster.points.EuclidianDoublePoint;
public class Star extends EuclidianDoublePoint {
private final int id;
public Star(double x, double y, double z, int id) {
super(x, y, z);
this.id = id;
}
public int getId() {
return id;
}
public double getX() {
return dimensions[0];
}
public double getY() {
return dimensions[1];
}
public double getZ() {
return dimensions[2];
}
@Override
public String toString() {
return "<Star " + id + " (" + getX() + ", " + getY() + ", " + getZ() + ")>";
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/classification/columns/Column.java
package nl.hro.cmibod023t.classification.columns;
import java.util.Collection;
import java.util.Set;
public interface Column<T> {
void add(Object feature);
Collection<Integer> getRowsMatching(Object feature);
Set<Object> getFeatures();
Column<?> copy(Iterable<Integer> indices);
int getIndex();
boolean matches(Object external, T internal);
static Column<?> create(Class<?> type, int index) {
if(type == String.class) {
return new StringColumn(index);
} else if(type == boolean.class || type == Boolean.class) {
return new BooleanColumn(index);
} else if(type == int.class || type == Integer.class) {
return new IntColumn(index);
} else if(Enum.class.isAssignableFrom(type)) {
return new EnumColumn(type, index);
}
throw new UnsupportedOperationException("Unsupported type: " + type);
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/classification/tree/ValueNode.java
package nl.hro.cmibod023t.classification.tree;
import nl.hro.cmibod023t.classification.Result;
public class ValueNode<T> implements Node<T> {
private final Result<T> result;
public ValueNode(T value, double probability) {
this.result = new Result<>(value, probability);
}
@Override
public Result<T> getValue(Object... values) {
return result;
}
@Override
public String toString(int indent) {
StringBuilder sb = new StringBuilder();
while(indent > 0) {
sb.append('\t');
indent--;
}
return sb.append("Value<").append(result).append('>').toString();
}
@Override
public String toString() {
return toString(0);
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/classification/NaiveClassifier.java
package nl.hro.cmibod023t.classification;
import java.util.Map;
import java.util.Map.Entry;
import nl.hro.cmibod023t.collection.DoubleCountMap;
public class NaiveClassifier<T> implements Classifier<T> {
private final FeatureTable<T> table;
public NaiveClassifier(Class<?>... columns) {
table = new CachingFeatureTable<>(columns);
}
@Override
public NaiveClassifier<T> train(T result, Object... features) {
table.train(result, features);
return this;
}
@Override
public Result<T> test(Object... features) {
table.checkFeatureLength(features);
Map<T, Integer> results = table.countResults();
DoubleCountMap<T> probabilities = initMap(results);
for(int i = 0; i < features.length; i++) {
Iterable<Integer> indices = table.getColumn(i).getRowsMatching(features[i]);
Map<T, Integer> featureCount = table.countResults(indices);
for(Entry<T, Integer> entry : featureCount.entrySet()) {
double p = entry.getValue();
probabilities.add(entry.getKey(), Math.log(p / results.get(entry.getKey())));
}
}
return getBest(probabilities);
}
private DoubleCountMap<T> initMap(Map<T, Integer> results) {
DoubleCountMap<T> probabilities = new DoubleCountMap<>();
for(Entry<T, Integer> entry : results.entrySet()) {
probabilities.put(entry.getKey(), Math.log(entry.getValue() / (double) table.size()));
}
return probabilities;
}
private Result<T> getBest(Map<T, Double> probabilities) {
Entry<T, Double> best = probabilities.entrySet().iterator().next();
for(Entry<T, Double> entry : probabilities.entrySet()) {
if(entry.getValue() > best.getValue()) {
best = entry;
}
}
return new Result<>(best.getKey(), Math.exp(best.getValue()));
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/classification/Testable.java
package nl.hro.cmibod023t.classification;
public interface Testable<T> extends Classifiable {
T getTargetClass();
}
<file_sep>/src/main/java/nl/hro/cmibod023t/classification/CachingFeatureTable.java
package nl.hro.cmibod023t.classification;
import java.util.Collections;
import java.util.Map;
import nl.hro.cmibod023t.collection.IntCountMap;
public class CachingFeatureTable<T> extends FeatureTable<T> {
private final IntCountMap<T> resultCount;
private final Map<T, Integer> resultCountWrapper;
public CachingFeatureTable(Class<?>... columns) {
super(columns);
resultCount = new IntCountMap<>();
resultCountWrapper = Collections.unmodifiableMap(resultCount);
}
@Override
public FeatureTable<T> train(T result, Object... features) {
resultCount.increment(result);
return super.train(result, features);
}
@Override
public Map<T, Integer> countResults() {
return resultCountWrapper;
}
@Override
protected IntCountMap<T> buildResultCounter() {
IntCountMap<T> count = new IntCountMap<>();
for(T result : resultCount.keySet()) {
count.add(result, 0);
}
return count;
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/classification/tree/Node.java
package nl.hro.cmibod023t.classification.tree;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import nl.hro.cmibod023t.classification.FeatureTable;
import nl.hro.cmibod023t.classification.Result;
import nl.hro.cmibod023t.classification.columns.Column;
public interface Node<T> {
Result<T> getValue(Object... values);
String toString(int indent);
static <T> Node<T> build(FeatureTable<T> table) {
Map<T, Integer> results = table.countResults();
if(results.keySet().size() == 1) {
return new ValueNode<>(results.keySet().iterator().next(), 1);
}
Column<?> column;
if(table.columns().isEmpty()) {
return getLeaf(results);
} else if(table.columns().size() == 1) {
column = table.getColumn(0);
} else {
column = table.getColumnWithLargestGain();
}
Set<Object> features = column.getFeatures();
if(features.size() == 1) {
return getLeaf(results);
}
Map<Object, Node<T>> children = new HashMap<>();
for(Object feature : features) {
Node<T> child = build(table.subset(column, feature));
children.put(feature, child);
}
return new BranchNode<>(children, column);
}
static <T> Node<T> getLeaf(Map<T, Integer> results) {
int max = Integer.MIN_VALUE;
T result = null;
double total = 0;
for(Entry<T, Integer> entry : results.entrySet()) {
int value = entry.getValue();
total += value;
if(value > max) {
max = value;
result = entry.getKey();
}
}
return new ValueNode<>(result, max / total);
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/exercises/Mushroom.java
package nl.hro.cmibod023t.exercises;
import nl.hro.cmibod023t.classification.Classifier;
import nl.hro.cmibod023t.classification.DecisionTree;
import nl.hro.cmibod023t.classification.NaiveClassifier;
import nl.hro.cmibod023t.classification.Testable;
public class Mushroom implements Testable<Mushroom.Class> {
private final Class type;
private final CapShape capShape;
private final Surface capSurface;
private final Color capColor;
private final boolean bruised;
private final Odor odor;
private final GillAttachment gillAttachment;
private final GillSpacing gillSpacing;
private final GillSize gillSize;
private final Color gillColor;
private final StalkShape stalkShape;
private final StalkRoot stalkRoot;
private final Surface stalkSurfaceAboveRing;
private final Surface stalkSurfaceBelowRing;
private final Color stalkColorAboveRing;
private final Color stalkColorBelowRing;
private final VeilType veilType;
private final Color veilColor;
private final RingNumber ringNumber;
private final RingType ringType;
private final Color sporePrintColor;
private final Population population;
private final Habitat habitat;
public Mushroom(Class type, CapShape capShape, Surface capSurface, Color capColor, boolean bruised, Odor odor, GillAttachment gillAttachment, GillSpacing gillSpacing, GillSize gillSize, Color gillColor, StalkShape stalkShape, StalkRoot stalkRoot, Surface stalkSurfaceAboveRing, Surface stalkSurfaceBelowRing, Color stalkColorAboveRing, Color stalkColorBelowRing, VeilType veilType, Color veilColor, RingNumber ringNumber, RingType ringType, Color sporePrintColor, Population population, Habitat habitat) {
this.type = type;
this.capShape = capShape;
this.capSurface = capSurface;
this.capColor = capColor;
this.bruised = bruised;
this.odor = odor;
this.gillAttachment = gillAttachment;
this.gillSpacing = gillSpacing;
this.gillSize = gillSize;
this.gillColor = gillColor;
this.stalkShape = stalkShape;
this.stalkRoot = stalkRoot;
this.stalkSurfaceAboveRing = stalkSurfaceAboveRing;
this.stalkSurfaceBelowRing = stalkSurfaceBelowRing;
this.stalkColorAboveRing = stalkColorAboveRing;
this.stalkColorBelowRing = stalkColorBelowRing;
this.veilType = veilType;
this.veilColor = veilColor;
this.ringNumber = ringNumber;
this.ringType = ringType;
this.sporePrintColor = sporePrintColor;
this.population = population;
this.habitat = habitat;
}
public Class getType() {
return type;
}
public CapShape getCapShape() {
return capShape;
}
public Surface getCapSurface() {
return capSurface;
}
public Color getCapColor() {
return capColor;
}
public boolean isBruised() {
return bruised;
}
public Odor getOdor() {
return odor;
}
public GillAttachment getGillAttachment() {
return gillAttachment;
}
public GillSpacing getGillSpacing() {
return gillSpacing;
}
public GillSize getGillSize() {
return gillSize;
}
public Color getGillColor() {
return gillColor;
}
public StalkShape getStalkShape() {
return stalkShape;
}
public StalkRoot getStalkRoot() {
return stalkRoot;
}
public Surface getStalkSurfaceAboveRing() {
return stalkSurfaceAboveRing;
}
public Surface getStalkSurfaceBelowRing() {
return stalkSurfaceBelowRing;
}
public Color getStalkColorAboveRing() {
return stalkColorAboveRing;
}
public Color getStalkColorBelowRing() {
return stalkColorBelowRing;
}
public VeilType getVeilType() {
return veilType;
}
public Color getVeilColor() {
return veilColor;
}
public RingNumber getRingNumber() {
return ringNumber;
}
public RingType getRingType() {
return ringType;
}
public Color getSporePrintColor() {
return sporePrintColor;
}
public Population getPopulation() {
return population;
}
public Habitat getHabitat() {
return habitat;
}
public interface CharEnum {
char getChar();
}
public enum Class implements CharEnum {
POISONOUS('p'), EDIBLE('e');
private final char character;
private Class(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public enum CapShape implements CharEnum {
BELL('b'), CONICAL('c'), CONVEX('x'), FLAT('f'), KNOBBED('k'), SUNKEN('s');
private final char character;
private CapShape(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public enum Surface implements CharEnum {
FIBROUS('f'), GROOVES('g'), SCALY('y'), SMOOTH('s'), SILKY('k');
private final char character;
private Surface(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public enum Color implements CharEnum {
BLACK('k'), BROWN('n'), BUFF('b'), CHOCOLATE('h'), GRAY('g'), GREEN('r'), ORANGE('o'), PINK('p'), PURPLE('u'), RED('e'), WHITE('w'), YELLOW('y'), CINNAMON('c');
private final char character;
private Color(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public enum Odor implements CharEnum {
ALMOND('a'), ANISE('l'), CREOSOTE('c'), FISHY('y'), FOUL('f'), MUSTY('m'), NONE('n'), PUNGENT('p'), SPICY('s');
private final char character;
private Odor(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public enum GillAttachment implements CharEnum {
ATTACHED('a'), DESCENDING('l'), FREE('f'), NOTCHED('n');
private final char character;
private GillAttachment(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public enum GillSpacing implements CharEnum {
CLOSE('c'), CROWDED('w'), DISTANT('d');
private final char character;
private GillSpacing(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public enum GillSize implements CharEnum {
BROAD('b'), NARROW('n');
private final char character;
private GillSize(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public enum StalkShape implements CharEnum {
ENLARGING('e'), TAPERING('t');
private final char character;
private StalkShape(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public enum StalkRoot implements CharEnum {
BULBOUS('b'), CLUB('c'), CUP('u'), EQUAL('e'), RHIZOMORPHS('z'), ROOTED('r'), MISSING('?');
private final char character;
private StalkRoot(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public enum VeilType implements CharEnum {
PARTIAL('p'), UNIVERSAL('u');
private final char character;
private VeilType(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public enum RingNumber implements CharEnum {
NONE('n'), ONE('o'), TWO('t');
private final char character;
private RingNumber(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public enum RingType implements CharEnum {
COBWEBBY('c'), EVANESCENT('e'), FLARING('f'), LARGE('l'), NONE('n'), PENDANT('p'), SHEATHING('s'), ZONE('z');
private final char character;
private RingType(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public enum Population implements CharEnum {
ABUNDANT('a'), CLUSTERED('c'), NUMEROUS('n'), SCATTERED('s'), SEVERAL('v'), SOLIDARY('y');
private final char character;
private Population(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public enum Habitat implements CharEnum {
GRASSES('g'), LEAVES('l'), MEADOWS('m'), PATHS('p'), URBAN('u'), WASTE('w'), WOODS('d');
private final char character;
private Habitat(char character) {
this.character = character;
}
@Override
public char getChar() {
return character;
}
}
public static Classifier<Mushroom.Class> createNaiveBayesianClassifier() {
return new NaiveClassifier<>(CapShape.class, Surface.class, Color.class, boolean.class, Odor.class, GillAttachment.class, GillSpacing.class, GillSize.class, Color.class, StalkShape.class, StalkRoot.class, Surface.class, Surface.class, Color.class, Color.class, VeilType.class, Color.class, RingNumber.class, RingType.class, Color.class, Population.class, Habitat.class);
}
public static Classifier<Mushroom.Class> createDecisionTree() {
return new DecisionTree<>(CapShape.class, Surface.class, Color.class, boolean.class, Odor.class, GillAttachment.class, GillSpacing.class, GillSize.class, Color.class, StalkShape.class, StalkRoot.class, Surface.class, Surface.class, Color.class, Color.class, VeilType.class, Color.class, RingNumber.class, RingType.class, Color.class, Population.class, Habitat.class);
}
@Override
public Object[] getFeatures() {
return new Object[] {
getCapShape(), getCapSurface(), getCapColor(),
isBruised(), getOdor(), getGillAttachment(),
getGillSpacing(), getGillSize(), getGillColor(),
getStalkShape(), getStalkRoot(), getStalkSurfaceAboveRing(),
getStalkSurfaceBelowRing(), getStalkColorAboveRing(), getStalkColorBelowRing(),
getVeilType(), getVeilColor(), getRingNumber(),
getRingType(), getSporePrintColor(), getPopulation(), getHabitat()
};
}
@Override
public Class getTargetClass() {
return type;
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/classification/continuous/Range.java
package nl.hro.cmibod023t.classification.continuous;
public interface Range<T extends Number> {
boolean inRange(T value);
Class<T> getType();
public static Range<Integer> lessThan(int value) {
return new IntRange.LessThan(value);
}
public static Range<Integer> moreThan(int value) {
return new IntRange.MoreThan(value);
}
public static Range<Integer> create(int min, int max) {
return new IntRange.InRange(min, max);
}
public static Range<Integer> is(int value) {
return new IntRange.EqualTo(value);
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/cluster/balltree/Node.java
package nl.hro.cmibod023t.cluster.balltree;
import java.util.Arrays;
import nl.hro.cmibod023t.cluster.points.KDPoint;
interface Node<E extends KDPoint> {
Node<E> getRight();
Node<E> getLeft();
E getValue();
static <E extends KDPoint> Node<E> build(E[] points, int dimension) {
if(points.length == 1) {
return new Leaf<>((E) points[0]);
}
Arrays.sort(points, KDPoint.getComparator(dimension));
int median = points.length / 2;
E point = points[median];
dimension = (dimension + 1) % point.getDimensions();
E[] leftP = Arrays.copyOfRange(points, 0, median);
Node<E> left = leftP.length > 0 ? build(leftP, dimension) : null;
E[] rightP = Arrays.copyOfRange(points, median + 1, points.length);
Node<E> right = rightP.length > 0 ? build(rightP, dimension) : null;
return new Branch<>(point, left, right);
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/cluster/balltree/BallTree.java
package nl.hro.cmibod023t.cluster.balltree;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import nl.hro.cmibod023t.cluster.points.KDPoint;
public class BallTree<E extends KDPoint> {
private final Node<E> root;
@SuppressWarnings("unchecked")
public BallTree(Collection<E> collection) {
root = (Node<E>) Node.build(collection.toArray(new KDPoint[collection.size()]), 0);
}
public Collection<E> getNeighbours(E point, double epsilon, double epsilonSq) {
return getNeighbours(root, point, epsilon, epsilonSq, 0);
}
private Collection<E> getNeighbours(Node<E> node, E point, double epsilon, double epsilonSq, int dimension) {
List<E> neighbours = new ArrayList<>();
while(node != null) {
double dimN = node.getValue().getDimension(dimension);
double dimP = point.getDimension(dimension);
dimension = (dimension + 1) % point.getDimensions();
if(dimN + epsilon >= dimP && dimN - epsilon <= dimP) {
if(node.getValue().getDistance(point) <= epsilonSq) {
neighbours.add(node.getValue());
}
neighbours.addAll(getNeighbours(node.getLeft(), point, epsilon, epsilonSq, dimension));
node = node.getRight();
} else if(dimN < dimP) {
node = node.getRight();
} else {
node = node.getLeft();
}
}
return neighbours;
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/exercises/MushroomParser.java
package nl.hro.cmibod023t.exercises;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class MushroomParser {
private static final Map<String, CharColumnParser> COLUMNS = new HashMap<>();
static {
COLUMNS.put("class", c -> getEnum(c, Mushroom.Class.values()));
COLUMNS.put("cap-shape", c -> getEnum(c, Mushroom.CapShape.values()));
COLUMNS.put("cap-surface", c -> getEnum(c, Mushroom.Surface.values()));
COLUMNS.put("cap-color", c -> getEnum(c, Mushroom.Color.values()));
COLUMNS.put("bruises", c -> c == 't');
COLUMNS.put("odor", c -> getEnum(c, Mushroom.Odor.values()));
COLUMNS.put("gill-attachment", c -> getEnum(c, Mushroom.GillAttachment.values()));
COLUMNS.put("gill-spacing", c -> getEnum(c, Mushroom.GillSpacing.values()));
COLUMNS.put("gill-size", c -> getEnum(c, Mushroom.GillSize.values()));
COLUMNS.put("gill-color", c -> getEnum(c, Mushroom.Color.values()));
COLUMNS.put("stalk-shape", c -> getEnum(c, Mushroom.StalkShape.values()));
COLUMNS.put("stalk-root", c -> getEnum(c, Mushroom.StalkRoot.values()));
COLUMNS.put("stalk-surface-above-ring", c -> getEnum(c, Mushroom.Surface.values()));
COLUMNS.put("stalk-surface-below-ring", c -> getEnum(c, Mushroom.Surface.values()));
COLUMNS.put("stalk-color-above-ring", c -> getEnum(c, Mushroom.Color.values()));
COLUMNS.put("stalk-color-below-ring", c -> getEnum(c, Mushroom.Color.values()));
COLUMNS.put("veil-type", c -> getEnum(c, Mushroom.VeilType.values()));
COLUMNS.put("veil-color", c -> getEnum(c, Mushroom.Color.values()));
COLUMNS.put("ring-number", c -> getEnum(c, Mushroom.RingNumber.values()));
COLUMNS.put("ring-type", c -> getEnum(c, Mushroom.RingType.values()));
COLUMNS.put("spore-print-color", c -> getEnum(c, Mushroom.Color.values()));
COLUMNS.put("population", c -> getEnum(c, Mushroom.Population.values()));
COLUMNS.put("habitat", c -> getEnum(c, Mushroom.Habitat.values()));
}
private final File file;
public MushroomParser(File file) {
this.file = file;
}
public List<Mushroom> parseMushrooms() throws IOException, InstantiationException, IllegalAccessException, InvocationTargetException {
List<Mushroom> mushrooms = new ArrayList<>();
@SuppressWarnings("unchecked")
Constructor<Mushroom> constructor = (Constructor<Mushroom>) Mushroom.class.getConstructors()[0];
try(Scanner sc = new Scanner(file)) {
String[] header = sc.nextLine().split(",");
if(constructor.getParameterCount() != header.length) {
throw new IllegalArgumentException("File need " + constructor.getParameterCount() + " headers");
}
while(sc.hasNextLine()) {
String[] chars = sc.nextLine().split(",");
Object[] params = new Object[header.length];
for(int i = 0; i < params.length; i++) {
CharColumnParser column = COLUMNS.get(header[i]);
if(column == null) {
throw new IllegalArgumentException("Unexpected header " + header[i]);
}
params[i] = column.getValue(chars[i].charAt(0));
}
mushrooms.add(constructor.newInstance(params));
}
}
return mushrooms;
}
private static <E extends Mushroom.CharEnum> E getEnum(char c, E[] values) {
for(E value : values) {
if(value.getChar() == c) {
return value;
}
}
throw new IllegalArgumentException("Unexpected value " + c + " for " + values[0].getClass());
}
@FunctionalInterface
private interface CharColumnParser {
Object getValue(char c);
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/exercises/Assignment2.java
package nl.hro.cmibod023t.exercises;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import org.jzy3d.analysis.AbstractAnalysis;
import org.jzy3d.analysis.AnalysisLauncher;
import org.jzy3d.chart.factories.AWTChartComponentFactory;
import org.jzy3d.colors.Color;
import org.jzy3d.maths.Coord3d;
import org.jzy3d.plot3d.primitives.Scatter;
import org.jzy3d.plot3d.rendering.canvas.Quality;
import nl.hro.cmibod023t.cluster.Cluster;
import nl.hro.cmibod023t.cluster.KDPointCollection;
import nl.hro.cmibod023t.cluster.dbscan.Dbscan;
public class Assignment2 {
private static final long SEED = 0;
private static final double EPSILON = 0.5;
private static final int MIN_POINTS = 10;
public static void main(String[] args) throws Exception {
if(args.length == 0) {
System.err.println("Missing file path argument");
System.exit(1);
}
File file = new File(args[0]);
List<Star> stars = parseStars(file);
Dbscan<Star> dbscan = new Dbscan<>(MIN_POINTS, new KDPointCollection<>(EPSILON));
dbscan.addPoints(stars);
Collection<Cluster<Star>> clusters = dbscan.cluster();
System.out.println("Clusters: " + clusters.size());
for(Cluster<Star> c : clusters) {
System.out.println(c.size());
}
draw(stars, clusters);
}
private static List<Star> parseStars(File file) throws IOException {
List<Star> stars = new ArrayList<>(64000);
try(Scanner sc = new Scanner(file)) {
sc.nextLine();
while(sc.hasNextLine()) {
String[] values = sc.nextLine().split(",");
stars.add(new Star(Double.parseDouble(values[0]), Double.parseDouble(values[1]), Double.parseDouble(values[2]), Integer.parseInt(values[7])));
}
}
return stars;
}
private static void draw(List<Star> stars, Collection<Cluster<Star>> clusters) throws Exception {
Coord3d[] points = new Coord3d[stars.size()];
Color[] colors = new Color[stars.size()];
Map<Cluster<Star>, Color> colorMap = getColors(clusters);
for(int i = 0; i < points.length; i++) {
Star star = stars.get(i);
points[i] = new Coord3d(star.getX(), star.getY(), star.getZ());
colors[i] = colorMap.get(star.getCluster());
}
Scatter scatter = new Scatter(points, colors);
AnalysisLauncher.open(new AbstractAnalysis() {
@Override
public void init() throws Exception {
chart = AWTChartComponentFactory.chart(Quality.Fastest);
chart.getScene().add(scatter);
}
});
}
private static Map<Cluster<Star>, Color> getColors(Collection<Cluster<Star>> clusters) {
Map<Cluster<Star>, Color> colorMap = new HashMap<>();
colorMap.put(null, new Color(0, 0, 0));
Random random = new Random(SEED);
for(Cluster<Star> cluster : clusters) {
float r = random.nextFloat();
float g = random.nextFloat();
float b = random.nextFloat();
colorMap.put(cluster, new Color(r, g, b));
}
return colorMap;
}
private Assignment2() {
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/collection/IntCountMap.java
package nl.hro.cmibod023t.collection;
import java.util.HashMap;
public class IntCountMap<T> extends MapWrapper<T, Integer> {
public IntCountMap() {
super(new HashMap<>());
}
public void add(T key, int amount) {
Integer value = get(key);
if(value == null) {
put(key, amount);
} else {
put(key, value + amount);
}
}
public void increment(T key) {
add(key, 1);
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/classification/columns/BooleanColumn.java
package nl.hro.cmibod023t.classification.columns;
public class BooleanColumn extends AbstractColumn<Boolean> {
public BooleanColumn(int index) {
super(Boolean.class, index);
}
}
<file_sep>/src/main/java/nl/hro/cmibod023t/cluster/DefaultPointCollection.java
package nl.hro.cmibod023t.cluster;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import nl.hro.cmibod023t.cluster.points.Point;
import nl.hro.cmibod023t.collection.CollectionWrapper;
public class DefaultPointCollection<E extends Point> extends CollectionWrapper<E> implements PointCollection<E> {
private final double epsilon;
public DefaultPointCollection(double epsilon) {
super(new ArrayList<>());
this.epsilon = epsilon * epsilon;
}
@Override
public Collection<E> getNeighbours(E p) {
List<E> neighbours = new ArrayList<>();
for(E neighbour : collection) {
if(p.getDistance(neighbour) <= epsilon) {
neighbours.add(neighbour);
}
}
return neighbours;
}
}
| d8b80f4fbc6f1daeb6216cf3d2c4568e4056feab | [
"Java"
] | 19 | Java | Assumeru/CMIBOD023T | af02b88d8fd29dc0c7cfacf5f4d56e5759ba34cc | 430bc3af74b4764a21321dd88b0154cb648925a5 | |
refs/heads/master | <file_sep>#load large file
data <- read.table( "household_power_consumption.txt", sep=";", header=TRUE, na.strings='?',
colClasses=c(rep('character', 2),
rep('numeric', 7)))
#filter the target date
data<-data[data["Date"]=="1/2/2007"|data["Date"]=="2/2/2007",]
#convert date DateTime
data$Date <- as.Date(data$Date , "%d/%m/%Y")
data$DateTime <- paste(data$Date, data$Time, sep=" ")
data$DateTime <- strptime(data$DateTime, "%Y-%m-%d %H:%M:%S")
png("plot4.png", width = 480, height = 480)
par(mfrow = c(2, 2))
with(data, {
plot(DateTime, Global_active_power, type = "l", xlab = "", ylab = "Global Active Power")
plot(DateTime, Voltage, xlab = "DateTime", type = "l", ylab = "Voltage")
ylimits = range(c(data$Sub_metering_1, data$Sub_metering_2, data$Sub_metering_3))
plot(DateTime, Sub_metering_1, xlab = "", ylab = "Energy sub metering", type = "l", ylim = ylimits, col = "black")
par(new = TRUE)
plot(DateTime, Sub_metering_2, xlab = "", axes = FALSE, ylab = "", type = "l", ylim = ylimits, col = "red")
par(new = TRUE)
plot(DateTime, Sub_metering_3, xlab = "", axes = FALSE, ylab = "", type = "l", ylim = ylimits, col = "blue")
legend("topright",
legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),
bg = "transparent",
bty = "n",
lty = c(1,1,1),
col = c("black", "red", "blue")
)
plot(DateTime, Global_reactive_power, type = "l", xlab = "DateTime", ylab = "Global_reactive_power")
})
dev.off
<file_sep>#load large file
data <- read.table( "household_power_consumption.txt", sep=";", header=TRUE, na.strings='?',
colClasses=c(rep('character', 2),
rep('numeric', 7)))
#filter the target date
data<-data[data["Date"]=="1/2/2007"|data["Date"]=="2/2/2007",]
#convert date DateTime
data$Date <- as.Date(data$Date , "%d/%m/%Y")
data$DateTime <- paste(data$Date, data$Time, sep=" ")
data$DateTime <- strptime(data$DateTime, "%Y-%m-%d %H:%M:%S")
png("plot1.png")
hist(data$Global_active_power, main = "Global Active power", col = "red", xlab = "Global Active Power (kilowatts)", )
dev.off()
<file_sep>#load large file
data <- read.table( "household_power_consumption.txt", sep=";", header=TRUE, na.strings='?',
colClasses=c(rep('character', 2),
rep('numeric', 7)))
#filter the target date
data<-data[data["Date"]=="1/2/2007"|data["Date"]=="2/2/2007",]
#convert date DateTime
data$Date <- as.Date(data$Date , "%d/%m/%Y")
data$DateTime <- paste(data$Date, data$Time, sep=" ")
data$DateTime <- strptime(data$DateTime, "%Y-%m-%d %H:%M:%S")
png("plot3.png")
plot(x=(data$DateTime),y=data$Sub_metering_1,type="l",ylab="Energy sub metering",xlab="")
lines(x=(data$DateTime),y=data$Sub_metering_2,col="red")
lines(x=(data$DateTime),y=data$Sub_metering_3,col="blue")
legend("topright",c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),bty="l",col=c("black","red","blue"),lwd=2,cex=0.7)
dev.off()
| a163712fc9abc27e5ef4bef60b1da4ff39bf1f39 | [
"R"
] | 3 | R | voltain/plotCourseraOrg | bd7fd24cd24b7df554e50f68d2b2420d11dc6d87 | 1c0335228272d98751bf2456e511b5e339d67eff | |
refs/heads/master | <repo_name>marcopandolfo/He4rt-Cup<file_sep>/src/app/Dao/ChallengesDAO.js
/* eslint-disable no-underscore-dangle */
function challengeDAO(connection) {
this._connection = connection;
}
challengeDAO.prototype.create = function create(gameId) {
return new Promise((resolve, reject) => {
this._connection.query('INSERT INTO challenges (game_id) VALUES (?)', [gameId], (err, result) => {
if (err) return reject(err);
return resolve(result);
});
});
};
challengeDAO.prototype.setTitle = function setTitle(gameId, title) {
return new Promise((resolve, reject) => {
this._connection.query('UPDATE challenges SET challenge_title = ? WHERE game_id = ?', [title, gameId], (err, result) => {
if (err) return reject(err);
return resolve(result);
});
});
};
// eslint-disable-next-line func-names
module.exports = function () {
return challengeDAO;
};
<file_sep>/src/app/Dao/VotesDAO.js
/* eslint-disable no-underscore-dangle */
function VotesDAO(connection) {
this._connection = connection;
}
VotesDAO.prototype.incrementVotes = function incrementVote(team, gameId) {
return new Promise((resolve, reject) => {
const aux = `${team}_votes`;
this._connection.query(`UPDATE game SET ${aux} = ${aux} + 1 WHERE game_id = ?`, [gameId], (err, result) => {
if (err) return reject(err);
return resolve(result);
});
});
};
VotesDAO.prototype.getVotes = function getVotes(gameId) {
return new Promise((resolve, reject) => {
this._connection.query('SELECT red_votes, blue_votes from game WHERE game_id = ?', [gameId], (err, result) => {
if (err) return reject(err);
return resolve(result[0]);
});
});
};
VotesDAO.prototype.savePlayerVote = function savePlayerVote(gameId, nick, amount, team) {
return new Promise((resolve, reject) => {
this._connection.query('INSERT INTO votes (game_id, nick, amount, team) VALUES (?, ?, ?, ?)', [gameId, nick, amount, team], (err, result) => {
if (err) return reject(err);
return resolve(result);
});
});
};
VotesDAO.prototype.getPlayersVotes = function getPlayersVotes(gameId) {
return new Promise((resolve, reject) => {
this._connection.query('SELECT * FROM votes WHERE game_id = ?', [gameId], (err, result) => {
if (err) return reject(err);
return resolve(result);
});
});
};
// eslint-disable-next-line func-names
module.exports = function () {
return VotesDAO;
};
<file_sep>/src/app/controllers/challenges.js
/* eslint-disable camelcase */
module.exports = (app) => {
const connection = app.infra.connectionFactory();
const challengesDao = new app.Dao.ChallengesDAO(connection);
app.post('/challenges/title', (req, res) => {
const { challenge_title, game_id } = req.body;
challengesDao
.setTitle(game_id, challenge_title)
.then(() => res.status(200).send())
.catch(err => res.status(400).json(err));
});
};
<file_sep>/src/twitchService/index.js
const tmi = require('tmi.js');
const client = new tmi.Client({
options: {
debug: JSON.parse(process.env.npm_config_argv).original[1] === 'dev',
},
connection: {
secure: true,
reconnect: true,
},
identity: {
username: 'he4rtdevs',
password: process.env.TWITCH_TOKEN,
},
});
client.on('connected', () => {
console.log('> Twitch Connected');
});
client.connect();
module.exports = client;
<file_sep>/src/config/custom-express.js
const express = require('express');
const consign = require('consign');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
// App
const app = express();
// CORS
app.use(cors());
// BodyParser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Define path
let rootPath = 'src\\app';
if (process.platform === 'linux') rootPath = 'src/app';
// Consign
consign({ cwd: rootPath })
.include('infra')
.then('Dao')
.then('controllers')
.into(app);
module.exports = app;
<file_sep>/src/server.js
const app = require('./config/custom-express');
// Port
const port = process.env.PORT || 3000;
// Auto create mysql tables
const connection = app.infra.connectionFactory();
app.infra.createTables(connection);
app.listen(port, () => {
console.log(`> Servidor rodando na porta [${port}]`);
});
<file_sep>/README.md
<h1 align="center">
He4rt Cup - API
</h1>
<h3 align="center">
<img src="https://heartdevs.com/wp-content/uploads/2018/12/logo.png" width="215"><br>
He4rt Cup API made in NodeJS
<br>
<br>
<a href="https://discord.gg/J78z3FV" target="_blank">
<img src="https://discordapp.com/api/guilds/452926217558163456/embed.png" alt="Discord server"/></a><br>
</h3>
## :rocket: 5 minutes quick start
:bulb: Install all packages of the `package.json` on your Node project. This will download everything you need.
```
npm install
```
:gear: Configure the file `.env-example` and rename to `.env`
:bulb: If you want to run this on `development` mode (recommended):
```
npm run dev
```
:bulb: Or run this on `production` mode:
```
npm start
```
<br>
## :book: API Doc:
- Check the API <a href="https://documenter.getpostman.com/view/6227429/SVYouezy?version=latest#intro">Documentation:</a>
## :pushpin: Tips:
- Install the extensions `editorconfig` and `eslint` in your IDE for make a better code
## ✌️ Contributions
Contributions are 100% welcome, just make a PR or ISSUE :)
## :mailbox_with_mail: License
This software was created for study purposes only. Feel free to try it out.
<file_sep>/src/app/controllers/votes.js
/* eslint-disable camelcase */
/* eslint-disable object-curly-newline */
module.exports = (app) => {
const connection = app.infra.connectionFactory();
const votesDao = new app.Dao.VotesDAO(connection);
// POST
app.post('/votes', async (req, res) => {
const { nick, team, amount, game_id } = req.body;
// TODO: validate
await votesDao.incrementVotes(team, game_id);
votesDao.savePlayerVote(game_id, nick, amount, team);
const votes = await votesDao.getVotes(game_id);
votes.game_id = game_id;
return res.status(201).json(votes);
});
// GET
app.get('/votes/:gameId', async (req, res) => {
const { gameId } = req.params;
const votes = await votesDao.getVotes(gameId);
return res.status(200).json(votes);
});
// GET
app.get('/votes/players/:gameId', (req, res) => {
const { gameId } = req.params;
votesDao
.getPlayersVotes(gameId)
.then(result => res.status(200).json(result))
.catch(err => res.status(400).json(err));
});
};
<file_sep>/src/app/models/game.js
class Game {
constructor(body) {
this.timer = body.timer;
this.state = body.state;
this.description = body.description;
this.blueVotes = '';
this.redVotes = '';
// challenges for default is none
// Players
this.playerCSSRed = body.player_css_red;
this.playerCSSBlue = body.player_css_blue;
this.playerHTMLRed = body.player_html_red;
this.playerHTMLBlue = body.player_html_blue;
this.playerJSRed = body.player_js_red;
this.playerJSBlue = body.player_js_blue;
}
}
module.exports = Game;
<file_sep>/src/app/infra/connectionFactory.js
/* eslint-disable func-names */
const mysql = require('mysql');
function createDBConnection() {
return mysql.createConnection({
multipleStatements: true,
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DB_NAME,
});
}
module.exports = function () {
return createDBConnection;
};
<file_sep>/src/app/controllers/game.js
/* eslint-disable camelcase */
const Game = require('../models/game');
module.exports = (app) => {
const connection = app.infra.connectionFactory();
const gameDao = new app.Dao.GameDAO(connection);
const challengesDao = new app.Dao.ChallengesDAO(connection);
// POST: Create new Game
app.post('/game/create', (req, res) => {
req.body.state = 'waiting';
// TODO: validate
const game = new Game(req.body);
gameDao
.create(game)
.then((result) => {
challengesDao.create(result.insertId);
return res.status(201).json({ game_id: result.insertId });
})
.catch(err => res.status(400).json(err));
});
// PUT: Att Description
app.put('/game/description', (req, res) => {
const { game_id, description } = req.body;
// TOOD: validate
gameDao
.updateDescription(description, game_id)
.then(() => res.status(200).send())
.catch(err => res.status(400).json(err));
});
app.put('/game/updatePlayer', (req, res) => {
const {
game_id,
team, lang,
player,
} = req.body;
// TOOD: validate
gameDao
.updatePlayer(game_id, team, lang, player)
.then(() => res.status(200).send())
.catch(err => res.status(400).json(err));
});
// GET
app.get('/game/:gameId', (req, res) => {
const { gameId } = req.params;
gameDao
.getGame(gameId)
.then((game) => {
console.log('[GET GAME]');
return res.status(200).json(game);
})
.catch(err => res.status(400).json(err));
});
app.put('/game/updateState', (req, res) => {
const { game_id, state } = req.body;
// TOOD: validate
gameDao
.updateState(game_id, state)
.then(() => res.status(200).send())
.catch(err => res.status(400).json(err));
});
};
<file_sep>/src/twitchService/commands/sendWhisper.js
const client = require('../index');
module.exports = (nick, msg) => {
client.whisper(nick, msg)
.catch(() => {
console.log(`Não foi possivel enviar whipser para o usuario ${nick}`);
});
};
<file_sep>/src/app/Dao/GameDAO.js
/* eslint-disable no-underscore-dangle */
function GameDAO(connection) {
this._connection = connection;
}
GameDAO.prototype.create = function create(game) {
return new Promise((resolve, reject) => {
this._connection.query(`
INSERT INTO game
(state, player_css_blue, player_css_red, player_html_blue, player_html_red, player_js_blue, player_js_red, description, timer)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[game.state, game.playerCSSBlue, game.playerCSSRed,
game.playerHTMLBlue, game.playerHTMLRed, game.playerJSBlue,
game.playerJSRed, game.description, game.timer],
(err, result) => {
if (err) return reject(err);
return resolve(result);
});
});
};
GameDAO.prototype.updateDescription = function updateDescription(description, gameId) {
return new Promise((resolve, reject) => {
this._connection.query('UPDATE game SET description = ? WHERE game_id = ?', [description, gameId], (err, result) => {
if (err) return reject(err);
return resolve(result);
});
});
};
GameDAO.prototype.updatePlayer = function updatePlayer(gameId, team, lang, player) {
return new Promise((resolve, reject) => {
this._connection.query(`UPDATE game SET player_${lang}_${team} = ? WHERE game_id = ?`, [player, gameId], (err, result) => {
if (err) return reject(err);
return resolve(result);
});
});
};
GameDAO.prototype.updateState = function updateState(gameId, state) {
return new Promise((resolve, reject) => {
this._connection.query('UPDATE game SET state = ? WHERE game_id = ?', [state, gameId], (err, result) => {
if (err) return reject(err);
return resolve(result);
});
});
};
GameDAO.prototype.getGame = function getGame(gameId) {
return new Promise((resolve, reject) => {
this._connection.query('SELECT * FROM game WHERE game_id = ?', [gameId], (err, result) => {
if (err) return reject(err);
return resolve(result[0]);
});
});
};
// eslint-disable-next-line func-names
module.exports = function () {
return GameDAO;
};
| 8801ca5043d157e94618a2e0ac0be1ddf02de7ce | [
"JavaScript",
"Markdown"
] | 13 | JavaScript | marcopandolfo/He4rt-Cup | fc81bb8b05bffb43a5d2ab30b68e2f934ccb2476 | 98ed4322588b7dd581012f044838de1757e86c14 | |
refs/heads/main | <file_sep>package com.k8s.kubernetsk8s.ws;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class KubeController {
@GetMapping("/hello")
public String hello() {
return "Welcome - suresh-k8s";
}
}
<file_sep>rootProject.name = 'kubernets-k8s'
| ec499ea307f67b67d694cf7bb6c980f5da5aefc4 | [
"Java",
"Gradle"
] | 2 | Java | kulaalasuresh/kubernets-k8s | ab1b70454b5f3fab6291ef89144486eeacc87e29 | e3fb6dfee382aa1978908f817e57cb2b2b1b5595 | |
refs/heads/master | <repo_name>alex-andres/week-4-game<file_sep>/README.md
# week-4-game
This game is an RPG that allows the user to start the game with the start prompt
The user then is prompted to choose their character
Once the character has been chosen the remaining character options shift into the choose opponent container
The user is then prompted to choose their opponent
Once an opponent has been chosen the opponent character shifts into the opponent container
The user then has an option of attack 1 or attack 2
Once the attack has been chosen the HP values for each character update, as the opponent automatically counterattacks
When an opponent is defeated the user is prompted to choose a new opponent and the previous protocol is repeated until there are no opponents left
If the user is defeated before this, then the user is prompted to reset the game with a button and the game resets.
<file_sep>/assets/javascript/script1.js
// Javascript file for Mario Game
// Code contained in this function will run as soon as the page loads.
// window.onload =function(){
// }
// Global Variables
var selectedCharacter = "";
var selectedOpponent = "";
var indexSelectedCharacter = 0;
var indexSeletedOpponent = 0;
var arrAllCharactersList = ["mario", "luigi", "bowser", "toad"];
var arrAllCharacters = [];
var arrAllOpponents = [];
var arrLowerCaseCharacters = [];
var arrRemainingCharacters =[];
var arrRemainingCharacterIDs = [];
var arrAllOpponentsIDs = [];
var bolStart = true;
var bolCharSelect = false;
var bolOppSelect = false;
var bolAttack = false;
var bolGameOver = false;
var bolOpponentDefeated = false;
var characterHp = 0;
var opponentHp = 0;
var characterAttack1 = 0;
var characterAttack2 = 0;
var opponentCounterAttack = 0;
var character;
var opponent;
// object with character objects
var characters = {
mario : { name: "Mario", id: '"#mario"', hpId: "#hpMario", hp: 100, attack1: 10, attack2: 15, counterAttack: 9},
luigi : { name: "Luigi", id: '"#luigi"', hpId: "#hpLuigi", hp: 90, attack1: 8, attack2: 12, counterAttack: 4},
bowser : { name: "Bowser", id: '"#bowser"', hpId: "#hpBowser", hp: 130, attack1: 6, attack2: 20, counterAttack: 18},
toad : { name: "Toad", id: '"#toad"', hpId: "#hpToad", hp: 85, attack1: 9, attack2: 7, counterAttack: 13}
};
//for loop that creates an array out of characters object to be able to iterate over
for (var key in characters){
arrAllCharacters.push(characters[key]);
arrRemainingCharacters.push(characters[key]);
}
// for loop that creates a lower case array and id array
for (var i = 0; i < arrAllCharacters.length; i++) {
arrLowerCaseCharacters[i] = arrAllCharacters[i].name.toLowerCase();
arrRemainingCharacterIDs[i] = "#" + arrLowerCaseCharacters[i]
}
var marioGame = {
moveOpponents: function() {
//A function that takes the buttons that were not clicked on and appends them to the opponents row
indexSelectedCharacter = arrRemainingCharacterIDs.indexOf("#" + selectedCharacter);
arrRemainingCharacterIDs.splice(indexSelectedCharacter, 1);
arrRemainingCharacters.splice(indexSelectedCharacter, 1);
$(arrRemainingCharacterIDs.toString()).appendTo("#opponentChoicesRow").addClass("inOpponentChoices opponent").removeClass("inCharacterChoices");
},
displayOpponentsChoices: function() {
$("#selectedOpponent, #opponentChoices").removeClass("hide");
$("#selectCharacter, #selectedCharacter").addClass("hide");
$("#characterChoices").html("Your Character");
},
moveSelectedOpponent: function() {
indexSelectedOpponent = arrRemainingCharacterIDs.indexOf("#" + selectedOpponent);
$("#" +selectedOpponent).appendTo("#opponentRow")
},
displayOpponentSelection: function(){
$("#opponentContainer").removeClass("hide");
$("#selectedOpponent").addClass("hide");
$("#opponent").html("Your Opponent");
$("#attackContainer").removeClass("hide");
},
attack1: function(){
console.log(arrAllCharacters);
var character = arrAllCharacters[indexSelectedCharacter];
var opponent = arrRemainingCharacters[indexSelectedOpponent];
character.hp -= opponent.counterAttack;
opponent.hp -= Math.floor(1.2 * character.attack1);
$(character.hpId).text("HP: " + character.hp);
$(opponent.hpId).text("HP: " + opponent.hp);
},
attack2: function(){
console.log(arrAllCharacters);
character.hp -= opponent.counterAttack;
opponent.hp -= Math.floor(1.5 * character.attack2);
$(character.hpId).text("HP: " + character.hp);
$(opponent.hpId).text("HP: " + opponent.hp);
},
chooseNewOpponent: function(){
$(eval(opponent.id)).addClass("hide");
$("#selectedOpponent, #opponentChoices").removeClass("hide");
selectedOpponent = "";
indexSeletedOpponent = 0;
bolOppSelect = true;
this.moveSelectedOpponent();
this.displayOpponentSelection();
},
reset: function(){
$("#reset").removeClass("hide");
$("#reset").on("click", function(){
selectedCharacter = "";
selectedOpponent = "";
indexSelectedCharacter = 0;
indexSeletedOpponent = 0;
arrAllCharactersList = ["mario", "luigi", "bowser", "toad"];
arrAllCharacters = [];
arrAllOpponents = [];
arrLowerCaseCharacters = [];
arrRemainingCharacters =[];
arrRemainingCharacterIDs = [];
arrAllOpponentsIDs = [];
bolStart = true;
bolCharSelect = false;
bolOppSelect = false;
bolAttack = false;
bolGameOver = false;
bolOpponentDefeated = false;
characterHp = 0;
opponentHp = 0;
characterAttack1 = 0;
characterAttack2 = 0;
opponentCounterAttack = 0;
character;
opponent;
// object with character objects
var characters = {
mario : { name: "Mario", id: '"#mario"', hpId: "#hpMario", hp: 100, attack1: 10, attack2: 15, counterAttack: 9},
luigi : { name: "Luigi", id: '"#luigi"', hpId: "#hpLuigi", hp: 90, attack1: 8, attack2: 12, counterAttack: 4},
bowser : { name: "Bowser", id: '"#bowser"', hpId: "#hpBowser", hp: 130, attack1: 6, attack2: 20, counterAttack: 18},
toad : { name: "Toad", id: '"#toad"', hpId: "#hpToad", hp: 85, attack1: 9, attack2: 7, counterAttack: 13}
};
//for loop that creates an array out of characters object to be able to iterate over
for (var key in characters){
arrAllCharacters.push(characters[key]);
arrRemainingCharacters.push(characters[key]);
}
// for loop that creates a lower case array and id array
for (var i = 0; i < arrAllCharacters.length; i++) {
arrLowerCaseCharacters[i] = arrAllCharacters[i].name.toLowerCase();
arrRemainingCharacterIDs[i] = "#" + arrLowerCaseCharacters[i]
}
// for loop that generates text for a character name for each button using jquery selectors and methods
for (var i = 0; i < 4; i++) {
$("#" + arrLowerCaseCharacters[i] + "Name").text(arrAllCharacters[i].name);
};
// for loop that genererates text a character name for each button using jquery selectors and methods
for (var i = 0; i < 4; i++) {
$("#hp" + arrAllCharacters[i].name).text("HP: " + arrAllCharacters[i].hp);
};
$("#mario").appendTo("#characterChoicesRow").removeClass("hide");
$("#luigi").appendTo("#characterChoicesRow").removeClass("hide");
$("#bowser").appendTo("#characterChoicesRow").removeClass("hide");
$("#toad").appendTo("#characterChoicesRow");
$("#opponentChoices").addClass("hide");
$("#opponentContainer").addClass("hide");
$("#attackContainer").addClass("hide");
$("#reset").addClass("hide");
$("#mainContainer").addClass("hide");
$("#startContainer").removeClass("hide");
});
}
};
// for loop that generates text for a character name for each button using jquery selectors and methods
for (var i = 0; i < 4; i++) {
$("#" + arrLowerCaseCharacters[i] + "Name").text(arrAllCharacters[i].name);
};
// for loop that genererates text a character name for each button using jquery selectors and methods
for (var i = 0; i < 4; i++) {
$("#hp" + arrAllCharacters[i].name).text("HP: " + arrAllCharacters[i].hp);
};
//Input
//function that starts game by calling function once start button is click
$("#start").on("click", function(){
if(bolStart === true){
bolCharSelect = true;
// method that removes hide class from the main container, displaying contents of game
$("#mainContainer").removeClass("hide");
// method that adds hide class to start container, to hide start button
$("#startContainer").addClass("hide");
}
});
//Receives click input from user, while user is choosing his/her character
$("#characterChoicesRow").on("click", (".character"), function(){
if (bolCharSelect === true) {
selectedCharacter = this.id;
marioGame.moveOpponents();
marioGame.displayOpponentsChoices();
bolOppSelect = true;
bolCharSelect = false;
}
});
//Receives click input from user, while user is choosing his/her opponent
$("#opponentChoicesRow").on("click", (".opponent"), function(){
if(bolOppSelect === true) {
selectedOpponent = this.id;
marioGame.moveSelectedOpponent();
marioGame.displayOpponentSelection();
bolAttack = true;
bolOppSelect = false;
character = arrAllCharacters[indexSelectedCharacter];
opponent = arrRemainingCharacters[indexSelectedOpponent];
console.log(opponent.hp);
}
});
// Receives click input from user, while user is selecting attack1
$("#attack1").on("click", function(){
if (bolAttack === true && opponent.hp >= 0 ) {
marioGame.attack1();
if (character.hp <= 0) {
$(character.hpId).text("HP: 0");
bolGameOver = true;
marioGame.reset();
}
if (opponent.hp <= 0) {
$(opponent.hpId).text("HP: 0");
bolOpponentDefeated = true;
marioGame.chooseNewOpponent();
}
}
});
// Receives click input from user, while user is selecting attack2
$("#attack2").on("click", function(){
if (bolAttack === true) {
marioGame.attack2();
if (character.hp <= 0) {
$(character.hpId).text("HP: 0");
bolGameOver = true;
marioGame.reset();
}
if (opponent.hp <= 0) {
$(opponent.hpId).text("HP: 0");
marioGame.chooseNewOpponent();
}
}
});
| 0b0533a6d8d8b16f0bcbb638c8d1cfe7d152a3a3 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | alex-andres/week-4-game | 605929ff5916830f90757e4566475a82967da3e3 | 02e017f4057eb726355be08c0deca2b958faab4c | |
refs/heads/master | <file_sep>/**
* Copyright 2016 Daniel "Dadie" Korner
*
* 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
*
* distributed under the License is distributed on an "AS IS" BASIS,
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package com.grimgal.android.gpio;
import android.net.Uri;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ScrollView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.List;
import java.util.ArrayList;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import com.grimgal.android.framework.*;
public class GPIOActivity extends Activity {
List<Button> buttons = new ArrayList<Button>();
ScrollView scroll;
LinearLayout layout;
LayoutParams layoutParams;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
// ###### Layout [BEGIN] ######
this.layout = new LinearLayout(this);
{
this.layout.setOrientation(LinearLayout.VERTICAL);
}
this.scroll = new ScrollView(this);
{
this.scroll.addView(this.layout);
}
this.setContentView(this.scroll);
int[] gpios = {33, 23, 29, 30, 22, 18, 21, 190, 191, 192, 174, 173, 171, 172, 189, 210, 209, 19, 28, 31, 25, 24};
Arrays.sort(gpios);
for (final int gpio : gpios) {
final Button button = new Button(this);
{
button.setHeight(20);
button.setWidth(200);
//button.setTag(this.buttons.size());
String direction;
if (GPIO.create(gpio).isIn()) {
direction = "in";
}
else {
direction = "out";
}
String value = "" + GPIO.create(gpio).getValue();
button.setText("GPIO " + gpio + " D("+direction+") V("+value+")");
OnClickListener buttonClicked = new OnClickListener() {
@Override
public void onClick(View v) {
GPIO g = GPIO.create(gpio);
if (g.isIn()) {
g.setOut();
}
if (!g.getValue()) {
g.setValue(true);
}
else {
g.setValue(false);
}
String direction;
if (GPIO.create(gpio).isIn()) {
direction = "in";
}
else {
direction = "out";
}
String value = "" + GPIO.create(gpio).getValue();
button.setText("GPIO " + gpio + " D("+direction+") V("+value+")");
}
};
button.setOnClickListener(buttonClicked);
}
this.layout.addView(button);
this.buttons.add(button);
}
// ###### Layout [END] ######
}
}
| 806dcc4a62853de51f0e7911ba8f19d71b96f891 | [
"Java"
] | 1 | Java | MeasureTools/android.gpio_app | e921f07deb7e512a400b83f6d3565af624b5e0c0 | c870fb1f3a9f908513a9eb11af1de1afe4dd98d7 | |
refs/heads/master | <file_sep>import stackTrace from 'stacktrace-js';
let order = 0;
const sendMessageToExtension = (identifier, data, trace) => {
window.postMessage({
spit_event: true,
identifier,
data,
trace,
order: order++,
}, '*');
};
const getStackTrace = (identifier, data, debugError) => {
if (debugError) {
stackTrace.fromError(debugError).then(trace => {
sendMessageToExtension(identifier, data, trace);
});
} else {
sendMessageToExtension(identifier, data, []);
}
}
const Communicator = class Communicator {
onChange(spitEvent, data, debugError) {
getStackTrace(spitEvent.getIdentifier(), data, debugError);
}
set(data, ev, debugError) {
this.onChange(ev, data, debugError);
}
onAddEvent(ev) {
ev.addListener(this);
}
}
Communicator.prototype.debug = true;
const registerStore = store => {
window.postMessage({
spit_event: true,
page_init: true,
}, '*');
const communicator = new Communicator();
store.addListener(communicator);
store.getEvents().forEach(ev => {
ev.addListener(communicator);
communicator.onChange(ev, ev.get())
});
}
window.__REACT_SPIT_DEV_TOOLS__ = registerStore;
<file_sep>/* global chrome */
const s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.extension.getURL('/js/injected_file.js');
s.onload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
window.addEventListener('message', function(event) {
// Only accept messages from same frame
if (event.source !== window) {
return;
}
const message = event.data;
// Only accept messages that we know are ours
if (typeof message !== 'object' || message === null || !message.spit_event) {
return;
}
chrome.runtime.sendMessage(message);
});
<file_sep>import React from 'react';
export default class TraceView extends React.Component {
render() {
const { traces } = this.props;
if (traces.length) {
return (
<div>
{traces.slice(2).map(line => (
<div>
{line.fileName}:{line.lineNumber}:{line.functionName}
</div>
))}
</div>
);
}
return <div>Initial data</div>;
}
}
| 5af103617575148c27a872c432d5b8ebb96ab5a2 | [
"JavaScript"
] | 3 | JavaScript | phzimmermann/react-spit-chrome-extension | 533c554b07498c6838e64857956ee9eea60336a5 | 0cc0b82409cf895c5624335ee9c19a7f438af150 | |
refs/heads/master | <file_sep>//
// TaskDetailProtocols.swift
// TaskLogger
//
// Created by <NAME> on 30/9/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
protocol TaskDetailViewProtocol: class {
var presenter: TaskDetailPresenterProtocol? { get set }
func showTask(_ task: TaskItem)
}
protocol TaskDetailPresenterProtocol: class {
var view: TaskDetailViewProtocol? { get set }
var interactor: TaskDetailPresenterToInteractorProtocol? { get set }
func showDetail()
}
protocol TaskDetailPresenterToInteractorProtocol: class {
var taskItem: TaskItem? { get set }
}
protocol TaskDetailRouterProtocol: class {
static func getTaskDetailRouter(with task: TaskItem) -> UIViewController?
}
<file_sep>//
// TaskDetailViewController.swift
// TaskLogger
//
// Created by <NAME> on 23/9/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class TaskDetailViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
}
}
<file_sep>//
// TaskDetailPresenter.swift
// TaskLogger
//
// Created by <NAME> on 30/9/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class TaskDetailPresenter: TaskDetailPresenterProtocol {
var view: TaskDetailViewProtocol?
var interactor: TaskDetailPresenterToInteractorProtocol?
func showDetail() {
guard let task = interactor?.taskItem else { return }
view?.showTask(task)
}
}
<file_sep>//
// TaskItem.swift
// TaskLogger
//
// Created by <NAME> on 30/9/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
struct TaskItem {
let title: String
let description: String?
}
<file_sep>//
// TasksManager.swift
// TaskLogger
//
// Created by <NAME> on 30/9/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class TasksManager: NSObject {
private override init() { }
static let shared = TasksManager()
var tasks: [TaskItem] = []
}
<file_sep>//
// TaskDetailViewController.swift
// TaskLogger
//
// Created by <NAME> on 23/9/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class TaskDetailViewController: UIViewController {
var presenter: TaskDetailPresenterProtocol?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
presenter?.showDetail()
}
}
extension TaskDetailViewController: TaskDetailViewProtocol {
func showTask(_ task: TaskItem) {
titleLabel.text = task.title
descriptionTextView.text = task.description
}
}
<file_sep>//
// TaskListViewController.swift
// TaskLogger
//
// Created by <NAME> on 23/9/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class TaskListViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: TableView Datasource
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UITableViewCell.self), for: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
//MARK: TableView Delegate
//MARK: Functions
@IBAction func addTask(_ sender: UIBarButtonItem) {
}
}
<file_sep>//
// TaskDetailInteractor.swift
// TaskLogger
//
// Created by <NAME> on 30/9/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class TaskDetailInteractor: TaskDetailPresenterToInteractorProtocol {
var taskItem: TaskItem?
}
<file_sep>//
// TaskListInteractor.swift
// TaskLogger
//
// Created by <NAME> on 30/9/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class TaskListInteractor: TaskListPresenterToInteractorProtocol {
var presenter: TaskListInteractorToPresenterProtocol?
var tasksManager = TasksManager.shared
var tasks: [TaskItem] {
return tasksManager.tasks
}
func fetchTasks() {
presenter?.didFetchTasks(tasks)
}
func saveTask(_ task: TaskItem) {
if task.title.isEmpty {
presenter?.onError(message: "Title cannot be empty")
} else {
tasksManager.tasks.append(task)
presenter?.didAddTask(task)
}
}
func updateTask(_ index: Int, title: String, description: String?) {
if title.isEmpty {
presenter?.onError(message: "Title cannot be empty")
} else {
let task = TaskItem(title: title, description: description)
tasksManager.tasks[index] = task
presenter?.didEditTasks()
}
}
func deleteTask(_ index: Int) {
tasksManager.tasks.remove(at: index)
presenter?.didRemoveTask(index)
}
}
<file_sep># TaskLogger
A sample app written in Swift, showing the use of VIPER
Read tutorial:
https://kodesnippets.com/charming-the-viper/
<file_sep>//
// TaskDetailRouter.swift
// TaskLogger
//
// Created by <NAME> on 30/9/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class TaskDetailRouter: TaskDetailRouterProtocol {
static func getTaskDetailRouter(with task: TaskItem) -> UIViewController? {
guard let taskDetailViewController = storyboard.instantiateViewController(withIdentifier: String(describing: TaskDetailViewController.self)) as? TaskDetailViewController else {
return nil
}
let presenter = TaskDetailPresenter()
taskDetailViewController.presenter = presenter
presenter.view = taskDetailViewController
let interactor = TaskDetailInteractor()
interactor.taskItem = task
presenter.interactor = interactor
return taskDetailViewController
}
static var storyboard: UIStoryboard {
return UIStoryboard(name: "Main", bundle: Bundle.main)
}
}
<file_sep>//
// TaskListProtocols.swift
// TaskLogger
//
// Created by <NAME> on 30/9/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
// MARK: VIEW
protocol TaskListViewProtocol: class {
var presenter: TaskListPresenterProtocol? { get set }
func showTasks(_ tasks: [TaskItem])
func showMessage(_ message: String)
}
// MARK: PRESENTER
protocol TaskListPresenterProtocol: class {
var view: TaskListViewProtocol? { get set }
var interactor: TaskListPresenterToInteractorProtocol? { get set }
var router: TaskListRouterProtocol? { get set }
func getTasks()
func showTaskDetail(_ task: TaskItem)
func addTask(_ task: TaskItem)
func editTask(_ index: Int, title: String, description: String?)
func removeTask(_ index: Int)
}
// MARK: INTERACTOR
protocol TaskListPresenterToInteractorProtocol: class {
var presenter: TaskListInteractorToPresenterProtocol? { get set }
func fetchTasks()
func saveTask(_ task: TaskItem)
func updateTask(_ index: Int, title: String, description: String?)
func deleteTask(_ index: Int)
}
protocol TaskListInteractorToPresenterProtocol: class {
func didAddTask(_ task: TaskItem)
func didRemoveTask(_ index: Int)
func didFetchTasks(_ tasks: [TaskItem])
func didEditTasks()
func onError(message: String)
}
// MARK: ROUTER
protocol TaskListRouterProtocol: class {
func presentTaskListDetail(from view: TaskListViewProtocol, for task: TaskItem)
}
<file_sep>//
// TaskListViewController.swift
// TaskLogger
//
// Created by <NAME> on 23/9/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class TaskListViewController: UITableViewController {
var presenter: TaskListPresenterProtocol?
var tasks: [TaskItem] = []
override func viewDidLoad() {
super.viewDidLoad()
setupPresenter()
presenter?.getTasks()
}
//MARK: TableView Datasource
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UITableViewCell.self), for: indexPath)
let tasks = self.tasks[indexPath.row]
cell.textLabel?.text = tasks.title
cell.detailTextLabel?.text = tasks.description
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
//MARK: TableView Delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let task = tasks[indexPath.row]
presenter?.showTaskDetail(task)
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in
self.presenter?.removeTask(indexPath.row)
}
let edit = UITableViewRowAction(style: .default, title: "Edit") { (action, indexPath) in
let task = self.tasks[indexPath.row]
self.updateTask(index: indexPath.row, task: task)
}
edit.backgroundColor = UIColor.lightGray
return [edit, delete]
}
//MARK: Functions
private func setupPresenter() {
let presenter: TaskListPresenter & TaskListInteractorToPresenterProtocol = TaskListPresenter()
self.presenter = presenter
let interactor = TaskListInteractor()
self.presenter?.interactor = interactor
interactor.presenter = presenter
self.presenter?.router = TaskListRouter()
self.presenter?.view = self
}
private func addTask() {
let alertController = UIAlertController(title: "Add Task", message: "", preferredStyle: .alert)
alertController.addTextField(configurationHandler: nil)
alertController.addTextField(configurationHandler: nil)
let saveAction = UIAlertAction(title: "Save", style: .default, handler: { [weak self] alert in
let titleText = alertController.textFields![0].text ?? ""
let descriptionText = alertController.textFields![1].text ?? "NA"
let taskItem = TaskItem(title: titleText, description: descriptionText)
self?.presenter?.addTask(taskItem)
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
private func updateTask(index: Int, task: TaskItem) {
let alertController = UIAlertController(title: "Update Task", message: "", preferredStyle: .alert)
alertController.addTextField { $0.text = task.title }
alertController.addTextField { $0.text = task.description }
let updateAction = UIAlertAction(title: "Update", style: .default, handler: { [weak self] alert in
let titleText = alertController.textFields![0].text ?? ""
let descriptionText = alertController.textFields![1].text ?? "NA"
self?.presenter?.editTask(index, title: titleText, description: descriptionText)
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(updateAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
private func showAlert(_ message: String) {
let alertController = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
@IBAction func addTask(_ sender: UIBarButtonItem) {
addTask()
}
}
extension TaskListViewController: TaskListViewProtocol {
func showTasks(_ tasks: [TaskItem]) {
self.tasks = tasks
tableView.reloadData()
}
func showMessage(_ message: String) {
showAlert(message)
}
}
<file_sep>//
// TaskListRouter.swift
// TaskLogger
//
// Created by <NAME> on 30/9/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class TaskListRouter: TaskListRouterProtocol {
func presentTaskListDetail(from view: TaskListViewProtocol, for task: TaskItem) {
guard
let tasklistViewController = view as? UIViewController,
let taskDetail = TaskDetailRouter.getTaskDetailRouter(with: task) else {
return
}
tasklistViewController.navigationController?.pushViewController(taskDetail, animated: true)
}
}
<file_sep>//
// TaskListPresenter.swift
// TaskLogger
//
// Created by <NAME> on 30/9/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class TaskListPresenter: TaskListPresenterProtocol {
var view: TaskListViewProtocol?
var interactor: TaskListPresenterToInteractorProtocol?
var router: TaskListRouterProtocol?
func getTasks() {
interactor?.fetchTasks()
}
func showTaskDetail(_ task: TaskItem) {
guard let view = view else { return }
router?.presentTaskListDetail(from: view, for: task)
}
func addTask(_ task: TaskItem) {
interactor?.saveTask(task)
}
func editTask(_ index: Int, title: String, description: String?) {
interactor?.updateTask(index, title: title, description: description)
}
func removeTask(_ index: Int) {
interactor?.deleteTask(index)
}
}
extension TaskListPresenter: TaskListInteractorToPresenterProtocol {
func didAddTask(_ task: TaskItem) {
interactor?.fetchTasks()
}
func didEditTasks() {
interactor?.fetchTasks()
}
func didRemoveTask(_ index: Int) {
interactor?.fetchTasks()
}
func didFetchTasks(_ tasks: [TaskItem]) {
view?.showTasks(tasks)
}
func onError(message: String) {
view?.showMessage(message)
}
}
| 282ececf182e9cb334270b1e4320ad4877f4d4b4 | [
"Swift",
"Markdown"
] | 15 | Swift | iaaqibhussain/TaskLogger | 07614cbd2a58dd15f3c09348ef6f651ad25ff469 | 7408767b6622129a949ed7fec98765b674d7d0b2 | |
refs/heads/master | <file_sep>#!/bin/bash
# IMDSv2
# Get the Token
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` && curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/
# Get the AMI id of this instance
curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/ami-id
### Version 1
# Get public ip address
public_ip=$(curl http://169.254.169.254/latest/meta-data/public-ipv4)
### Version 2
public_ip=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/public-ipv4)
# Get AMI Id
## Version 1
ami-id=$(curl http://169.254.169.254/latest/meta-data/ami-id)
### Version2
ami-id=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/ami-id)
### Get VPC-id
### Version 1
vpc-id=$(curl http://169.254.169.254/latest/meta-data/network/interfaces/macs/02:fa:6a:3b:76:e0/vpc-id)
### Version2
vpc-id=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/network/interfaces/macs/02:fa:6a:3b:76:e0/vpc-id)
### Get Subnet-id
### Version 1
subnet-id=$(curl http://169.254.169.254/latest/meta-data/network/interfaces/macs/02:fa:6a:3b:76:e0/subnet-id)
### Version
subnet-id=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/network/interfaces/macs/02:fa:6a:3b:76:e0/subnet-id)<file_sep>#!/bin/bash
# Create a bucket in us-east-1
aws s3 mb --region us-west-2 s3://qts3fromcliorig
# Create a bucket in different region
aws s3 mb --region us-west-1 s3://qts3fromclicopy
# Lets enable versioning
aws s3api put-bucket-versioning --bucket qts3fromcliorig --versioning-configuration Status=Enabled
aws s3api put-bucket-versioning --bucket qts3fromclicopy --versioning-configuration Status=Enabled
# Create a role to allow copy of the s3 bucket objects
# Attach the policy to role
# Enable put-bucket replication<file_sep>#!/bin/bash
remove_trails() {
echo $(echo $1 | tr -d '"')
}
# create_subnet 192.168.0.0/24 $VPC_ID 'tag'
create_subnet() {
ID=$(aws ec2 create-subnet --cidr-block "$1" --tag-specifications "ResourceType=subnet,Tags=[{Key=Name, Value=$3}]" --vpc-id $2 --query "Subnet.SubnetId")
ID=$(remove_trails $ID)
echo $ID
}
# create_routetable $VPC_ID 'public'
create_routetable() {
ROUTE_TABLE_ID=$(aws ec2 create-route-table --vpc-id "$1" --tag-specifications "ResourceType=route-table,Tags=[{Key=Name, Value=$2}]" --query "RouteTable.RouteTableId")
ROUTE_TABLE_ID=$(remove_trails $ROUTE_TABLE_ID)
echo $ROUTE_TABLE_ID
}
VPC_ID=$(aws ec2 create-vpc --cidr-block '192.168.0.0/16' --tag-specifications "ResourceType=vpc,Tags=[{Key=Name, Value=vpcfromcli}]" --query "Vpc.VpcId")
VPC_ID=$(remove_trails $VPC_ID)
echo "Created VPC with id: ${VPC_ID}"
# Create subnets
SUBNET1_ID=$(create_subnet '192.168.0.0/24' $VPC_ID 'subnet1')
echo "Created Subnet1 with Subnetid $SUBNET1_ID"
SUBNET2_ID=$(create_subnet '192.168.1.0/24' $VPC_ID 'subnet2')
echo "Created Subnet2 with Subnetid $SUBNET2_ID"
SUBNET3_ID=$(create_subnet '192.168.2.0/24' $VPC_ID 'subnet3')
echo "Created Subnet3 with Subnetid $SUBNET3_ID"
SUBNET4_ID=$(create_subnet '192.168.3.0/24' $VPC_ID 'subnet4')
echo "Created Subnet4 with Subnetid $SUBNET4_ID"
# CREATE Route tables
PUBLIC_RT=$(create_routetable $VPC_ID 'public')
echo "Created Routetable public with Id $PUBLIC_RT"
PRIVATE_RT=$(create_routetable $VPC_ID 'private')
echo "Created Routetable private with Id $PRIVATE_RT"
<file_sep>#!/bin/bash
# query using aws cli to fetch database instance identifiers
aws rds describe-db-instances --query "DBInstances[*].DBInstanceIdentifier"
# to fetch database instance id and masterusername
aws rds describe-db-instances --query "DBInstances[*].[DBInstanceIdentifier, MasterUsername]"
aws rds describe-db-instances --query "DBInstances[*].{ID: DBInstanceIdentifier, Username:MasterUsername}"
aws rds describe-db-instances --query "DBInstances[*].{ID: DBInstanceIdentifier, Username:MasterUsername}" --output table
aws rds describe-db-instances --query "DBInstances[*].{ID: DBInstanceIdentifier, Username:MasterUsername}" --output text
aws rds describe-db-instances --query "DBInstances[*].{ID: DBInstanceIdentifier, Username:MasterUsername}" --output yaml
# to fetch endpoint address for all mysql database instances
aws rds describe-db-instances --query "DBInstances[?Engine=='mysql'].Endpoint.Address"
#to fetch all the database snapshot identifiers and Status
aws rds describe-db-snapshots --query "DBSnapshots[*].{Id: DBSnapshotIdentifier, DBId: DBInstanceIdentifier, Status: Status}"
aws rds describe-db-snapshots --query "DBSnapshots[*].{Id: DBSnapshotIdentifier, DBId: DBInstanceIdentifier, Status: Status}" --output table
# to fetch all the database snapshot identifiers and Snapshot Creation time for mysql engine
aws rds describe-db-snapshots --query "DBSnapshots[?Engine=='mysql'].{Id: DBSnapshotIdentifier, DBId: DBInstanceIdentifier, CreationTime: SnapshotCreateTime}"
# to fetch all the db subnet group names other than default
aws rds describe-db-subnet-groups --query "DBSubnetGroups[?DBSubnetGroupName != 'default'].DBSubnetGroupName"
<file_sep>#!/bin/bash
# This file will contain simple commands that can be executed to create rds
# instances and configuring them
aws rds create-db-instance --db-instance-identifier 'qtrdsfromcli' --allocated-storage 20 --db-instance-class 'db.t2.micro' --engine 'mysql' --master-username 'admin' --master-user-password '<PASSWORD>' --vpc-security-group-ids "sg-075892da85bd09fc0" --backup-retention-period 7 --port 3306 --no-multi-az --no-auto-minor-version-upgrade
aws rds describe-db-instances
aws rds describe-db-instances --db-instance-identifier 'qtrdsfromcli'
# Create a db snapshot
aws rds create-db-snapshot --db-instance-identifier 'qtrdsfromcli' --db-snapshot-identifier 'snapshotfromcli'
aws rds describe-db-snapshots
aws rds describe-db-snapshots --query "DBSnapshots[*].{Snapshot:DBSnapshotIdentifier,InstanceID:DBInstanceIdentifier,Status:Status}"
aws rds describe-db-snapshots --query "DBSnapshots[*].{Snapshot:DBSnapshotIdentifier,InstanceID:DBInstanceIdentifier,Status:Status}" --output yaml
aws rds describe-db-snapshots --query "DBSnapshots[*].{Snapshot:DBSnapshotIdentifier,InstanceID:DBInstanceIdentifier,Status:Status}" --output table
# Create read replica
aws rds create-db-instance-read-replica --db-instance-identifier 'qtrdsreplicafromcli' --source-db-instance-identifier 'qtrdsfromcli' --db-instance-class 'db.t2.micro' --publicly-accessible --no-multi-az --no-auto-minor-version-upgrade --vpc-security-group-ids "sg-075892da85bd09fc0"
aws rds describe-db-instances --query "DBInstances[*].{DBID: DBInstanceIdentifier, Status: DBInstanceStatus}" --output table
# promote read replica
aws rds promote-read-replica --db-instance-identifier 'qtrdsreplicafromcli'
aws rds delete-db-instance --db-instance-identifier 'qtrdsfromcli' --skip-final-snapshot <file_sep>#!/bin/bash
# basic info
aws s3 ls
# human readable format
aws s3 ls --human-readable
aws s3 ls s3://qts3tbddocs --human-readable
# human readable format with summary
aws s3 ls s3://qts3tbddocs --human-readable --summarize
# remove buckets
aws s3 rb s3://qts3tbddocs
aws s3 rb s3://qts3tbddocs --force
# Create an s3 bucket with 3 folders
# images
# documents
# videos
aws s3 mb s3://qts3inclass
# Upload one object per folder from your local machine to s3 bucket
aws s3 cp ./contents/content.txt s3://qts3inclass/documents/content.txt
aws s3 cp ./contents/test.jpg s3://qts3inclass/images/test.jpg
aws s3 cp ./contents/one.mp4 s3://qts3inclass/videos/one.mp4
# Create a new bucket
aws s3 mb s3://qts3inclasscopy
# syncronize the contents of one bucket to another
aws s3 sync s3://qts3inclass s3://qts3inclasscopy
# Summarize the contents
aws s3 ls s3://qts3inclass --human-readable --summarize
aws s3 ls s3://qts3inclass --recursive --human-readable --summarize
aws s3 ls s3://qts3inclasscopy --human-readable --summarize
aws s3 ls s3://qts3inclasscopy --recursive --human-readable --summarize
# Delete the objects
aws s3 rm --recursive s3://qts3inclasscopy
# Sync the contents from local machine to s3 bukcet
aws s3 sync ./contents s3://qts3inclass/contents
aws s3 ls s3://qts3inclass --recursive --human-readable
<file_sep>#!/bin/bash
# In this we will try to create ec2 instance
aws ec2 run-instances --image-id "ami-0a4a70bd98c6d6441" --instance-type "t2.micro" --key-name "climumbai" --security-group-ids "sg-09856719dfb1ab869"
# To Remove ec2 instance make a note of instance id
aws ec2 terminate-instances --instance-ids i-0bd538d74168d4e42<file_sep>#!/bin/bash
aws autoscaling create-launch-configuration \
--launch-configuration-name 'lcfromcli' --image-id 'ami-03d5c68bab01f3496' \
--key-name 'ansible' --security-groups 'sg-0eb0f3fca6c9a45a8' \
--instance-type 't2.micro' --associate-public-ip-address
aws autoscaling describe-launch-configurations --query "LaunchConfigurations[*].LaunchConfigurationName"
aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name 'asgfromcli' --launch-configuration-name 'lcfromcli' \
--min-size 1 --max-size 5 --desired-capacity 2 \
--availability-zones "us-west-2a" "us-west-2b" "us-west-2c"
aws autoscaling describe-auto-scaling-groups
aws autoscaling put-scaling-policy \
--auto-scaling-group-name 'asgfromcli' --policy-name 'mytargetrackingpolicy' \
--policy-type 'TargetTrackingScaling' \
--target-tracking-configuration 'file://config.json'
<file_sep>#!/bin/bash
# Creating a vpc with aws cli
aws ec2 create-vpc --cidr-block '10.100.0.0/16' --tag-specifications 'ResourceType=vpc,Tags=[{Key="Name",Value="ntier"}]'
#vpc-id =vpc-0f229c2da7f5e512d
#vpcid=$(aws ec2 describe-vpcs --filter 'Name=cidr,Values=10.100.0.0/16' --query 'Vpcs[0].VpcId')
# Create web subnet
aws ec2 create-subnet --cidr-block '10.100.0.0/24' --vpc-id $vpc_id --tag-specifications 'ResourceType=subnet,Tags=[{Key="Name",Value="web"}]' --availability-zone "us-west-2a"
# Create app subnet
aws ec2 create-subnet --cidr-block '10.100.1.0/24' --vpc-id $vpc_id --tag-specifications 'ResourceType=subnet,Tags=[{Key="Name",Value="app"}]' --availability-zone "us-west-2b"
# Create db subnet
aws ec2 create-subnet --cidr-block '10.100.2.0/24' --vpc-id $vpc_id --tag-specifications 'ResourceType=subnet,Tags=[{Key="Name",Value="db"}]' --availability-zone "us-west-2c"
# Create mgmt subnet
aws ec2 create-subnet --cidr-block '10.100.3.0/24' --vpc-id $vpc_id --tag-specifications 'ResourceType=subnet,Tags=[{Key="Name",Value="mgmt"}]' --availability-zone "us-west-2a"
# Create internet gateway
aws ec2 create-internet-gateway --tag-specifications 'ResourceType=internet-gateway,Tags=[{Key="Name",Value="ntierigw"}]'
# attach interet-gateway with vpc
aws ec2 attach-internet-gateway --vpc-id $vpc_id --internet-gateway-id $igw_id
# Create public route table
aws ec2 create-route-table --vpc-id $vpc_id --tag-specifications 'ResourceType=route-table,Tags=[{Key="Name",Value="public"}]'
# Create private route table
aws ec2 create-route-table --vpc-id $vpc_id --tag-specifications 'ResourceType=route-table,Tags=[{Key="Name",Value="private"}]'
# Create a route to igw for public route table
aws ec2 create-route --destination-cidr-block 0.0.0.0/0 --gateway-id $igw_id --route-table-id $pub_rt_id
aws ec2 associate-route-table --route-table-id $pub_rt_id --subnet-id 'subnet-0372a28adcf6a733b'
aws ec2 associate-route-table --route-table-id $pub_rt_id --subnet-id 'subnet-0456e0afc23996728'
aws ec2 associate-route-table --route-table-id $pri_rt_id --subnet-id 'subnet-085e842b0137a2308'
aws ec2 associate-route-table --route-table-id $pri_rt_id --subnet-id 'subnet-0dbc628a0a5daa03f'
# web Security Group
aws ec2 create-security-group --description 'web sg' --group-name 'web' --vpc-id $vpc_id --tag-specifications 'ResourceType=security-group,Tags=[{Key="Name",Value="web"}]'
aws ec2 authorize-security-group-ingress --group-id sg-0b16a13e9892355a1 --protocol tcp --port 80 --cidr 0.0.0.0/0
# network acl
aws ec2 create-network-acl --vpc $vpc_id --tag-specifications 'ResourceType=network-acl,Tags=[{Key="Name",Value="web-acl"}]'
#nacl_id=acl-04d687ee59684f6ee
aws ec2 create-network-acl-entry --network-acl-id acl-04d687ee59684f6ee --ingress --port-range From=80,To=80 --cidr-block 0.0.0.0/0 --rule-action allow --rule-number 100 --protocol tcp<file_sep>#!/bin/bash
aws ec2 create-vpc --cidr-block '192.168.0.0/16' --tag-specifications "ResourceType=vpc,Tags=[{Key=Name,Value=ntier}]"
# "VpcId": "vpc-04acb61dbc8b814c7"
aws ec2 create-subnet --cidr-block '192.168.0.0/24' --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=web1}]" --vpc-id "vpc-04acb61dbc8b814c7" --availability-zone "us-west-2a"
# "SubnetId": "subnet-0b8b36e0ae7a2b040"
aws ec2 create-subnet --cidr-block '192.168.1.0/24' --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=web2}]" --vpc-id "vpc-04acb61dbc8b814c7" --availability-zone "us-west-2b"
#"SubnetId": "subnet-0157da4c7a92eb1d9"
aws ec2 create-subnet --cidr-block '192.168.2.0/24' --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=app1}]" --vpc-id "vpc-04acb61dbc8b814c7" --availability-zone "us-west-2a"
# "SubnetId": "subnet-063a24cd079bc5ff6"
aws ec2 create-subnet --cidr-block '192.168.3.0/24' --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=app2}]" --vpc-id "vpc-04acb61dbc8b814c7" --availability-zone "us-west-2b"
# "SubnetId": "subnet-0f50fceb36b1c4833"
aws ec2 create-subnet --cidr-block '192.168.4.0/24' --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=db1}]" --vpc-id "vpc-04acb61dbc8b814c7" --availability-zone "us-west-2a"
# "SubnetId": "subnet-014b090887965363c"
aws ec2 create-subnet --cidr-block '192.168.5.0/24' --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=db2}]" --vpc-id "vpc-04acb61dbc8b814c7" --availability-zone "us-west-2b"
# "SubnetId": "subnet-0ecd212a19a0427ae"
aws ec2 create-internet-gateway --tag-specifications "ResourceType=internet-gateway,Tags=[{Key=Name,Value=ntierigw}]"
# "InternetGatewayId": "igw-09baaac90b9e1aaf6"
aws ec2 attach-internet-gateway --internet-gateway-id "igw-09baaac90b9e1aaf6" --vpc-id "vpc-04acb61dbc8b814c7"
<file_sep>#!/bin/bash
### usage is get_access_key username
get_access_key() {
access_key=$(aws iam list-access-keys --user-name $user --query "AccessKeyMetadata[0].AccessKeyId"|tr -d '"')
echo $access_key
}
send_email() {
echo "Sending email with json attached"
}
#users=$(aws iam list-users --query "Users[].UserName")
users=(testuser1 testuser2)
for user in ${users[@]}; do
echo "rotating credentials for $user"
current_access_key=$(get_access_key $user)
aws iam create-access-key --user-name $user > $user.json
send_email
echo "deleting current access key $current_access_key"
aws iam delete-access-key --access-key-id $current_access_key --user-name $user
new_access_key=$(get_access_key $user)
echo "New access key is $new_access_key"
done<file_sep>#!/bin/bash
current_region="ap-south-1"
ubuntu_20_amiid="ami-0a4a70bd98c6d6441"
windows_2019_amid="ami-0994975f92b8520bc"
echo "fetching the aws default vpc id"
# find default vpc id in your region
vpc_id=$(aws ec2 describe-vpcs --query "Vpcs[?IsDefault].VpcId" --output text)
echo "created the vpc with id ${vpc_id}"
# Create a security group
sgroupname='openforgol'
echo "Creating the security group with name ${sgroupname}"
aws ec2 create-security-group --description "open 22 80 and 8080 port" --group-name ${sgroupname} --vpc-id $vpc_id
# store security group id into some variable
sg_id=$(aws ec2 describe-security-groups --group-names ${sgroupname} --query "SecurityGroups[0].GroupId" --output text)
echo "Created security group with id ${sg_id}"
# openports
for port_number in 22 80 8080
do
echo "Creating a security group ingress rule for ${port_number}"
aws ec2 authorize-security-group-ingress --group-name ${sgroupname} --protocol tcp --port "$port_number" --cidr 0.0.0.0/0
done
key_name="my-key"
# if you dont have a key use ssh-keygen
echo "importing key pair"
aws ec2 import-key-pair --key-name $key_name --public-key-material fileb://~/.ssh/id_rsa.pub
az_a="${current_region}a"
az_b="${current_region}b"
#subnet id in az -a
subnet_a=$(aws ec2 describe-subnets --filters "Name=availability-zone,Values=${az_a}" "Name=vpc-id,Values=$vpc_id" --query "Subnets[0].SubnetId" --output text)
echo "subnet in ${az_a} is ${subnet_a}"
#subnet id in az-b
subnet_b=$(aws ec2 describe-subnets --filters "Name=availability-zone,Values=${az_b}" "Name=vpc-id,Values=$vpc_id" --query "Subnets[0].SubnetId" --output text)
echo "subnet in ${az_b} is ${subnet_b}"
default_instance_type='t2.micro'
aws ec2 run-instances --image-id $ubuntu_20_amiid --instance-type $default_instance_type --key-name $key_name --security-group-ids $sg_id --subnet-id $subnet_a --count 1
aws ec2 run-instances --image-id $windows_2019_amid --instance-type $default_instance_type --key-name $key_name --security-group-ids $sg_id --subnet-id $subnet_b --count 1
# fetch ubuntu instance ami id
ubuntu_20_instance_id=$(aws ec2 describe-instances --filter "Name=image-id,Values=${ubuntu_20_amiid}" --query "Reservations[].Instances[0].InstanceId" --output text)
# fetch ubuntu instance public ip address
ubuntu_20_public_ip=$(aws ec2 describe-instances --filter "Name=instance-id,Values=${ubuntu_20_instance_id}" --query "Reservations[].Instances[0].PublicIpAddress" --output text)
echo "preparing login command"
# login into ec2 instance
echo "ssh -i ~/.ssh/id_rsa ubuntu@${ubuntu_20_public_ip}"
# Lets get Windows instance id and windows public ip address
windows_2019_instance_id=$(aws ec2 describe-instances --filter "Name=image-id,Values=${windows_2019_amid}" --query "Reservations[].Instances[0].InstanceId" --output text)
windows_2019_public_ip=$(aws ec2 describe-instances --filter "Name=instance-id,Values=${windows_2019_instance_id}" --query "Reservations[].Instances[0].PublicIpAddress" --output text)
aws ec2 get-password-data --instance-id "${windows_2019_instance_id}" --priv-launch-key "~/.ssh/id_rsa"
## Deleting ec2 instance
aws ec2 terminate-instances --instance-ids "${windows_2019_instance_id}" "${ubuntu_20_instance_id}"
aws ec2 delete-key-pair --key-name $key_name
aws ec2 delete-security-group --group-id $sg_id<file_sep>#!/bin/bash
aws s3api list-objects --bucket qts3apidemo<file_sep>#!/bin/bash
aws iam create-group --group-name 'avengers'
for name in Ironman Gamora BlackPanther CaptianAmerica Thor Hulk BlackWidow groot nebula spiderman
do
aws iam create-user --user-name $name
aws iam create-login-profile --user-name $name --password-reset-required --password '<PASSWORD>'
aws iam add-user-to-group --group-name 'avengers' --user-name $name
done
<file_sep>#!/bin/bash
aws iam create-group --group-name 'justiceleague'
for name in superman batman aquaman wonderwomen
do
aws iam create-user --user-name $name
aws iam create-login-profile --user-name $name --password-reset-required --password '<PASSWORD>'
aws iam add-user-to-group --group-name 'justiceleague' --user-name $name
done
<file_sep>#!/bin/bash
# Lets get all the security group names
groupnames=$(aws ec2 describe-security-groups --query "SecurityGroups[*].GroupName")
for group in ${groupnames}
do
echo "${group}"
done
# Lets get all the security group ids
groupids=$(aws ec2 describe-security-groups --query "SecurityGroups[*].GroupId")
# find the ip address of the instances
publicips=$(aws ec2 describe-instances --query "Reservations[*].Instances[*].PublicIpAddress" --text)
# find the ipaddress of specific instance
publicip=$(aws ec2 describe-instances --instance-ids i-0d97976949ae63a82 --query "Reservations[*].Instances[*].PublicIpAddress" --text)
# Write a aws cli query to print the key pair names
aws ec2 describe-key-pairs --query "KeyPairs[*].KeyName" --output text
<file_sep>aws rds create-db-instance --db-instance-identifier 'qtrdsfromcli' \
--db-instance-class 'db.t2.micro' --engine 'mysql' \
--master-username 'root' --master-user-password '<PASSWORD>' \
--publicly-accessible --db-name 'qtecommerce' \
--db-subnet-group-name 'qtsubnetgroup' --allocated-storage 20
aws rds describe-db-instances --db-instance-identifier 'qtrdsfromcli'
aws rds describe-db-instances --db-instance-identifier 'qtrdsfromcli'\
--query 'DBInstances[0].DBInstanceStatus'
aws rds describe-db-instances --db-instance-identifier 'qtrdsfromcli' \
--query 'DBInstances[0].Endpoint'
aws rds delete-db-instance --db-instance-identifier 'qtrdsfromcli'\
--skip-final-snapshot --delete-automated-backups
aws rds create-db-instance --db-instance-identifier 'qtrdsfromclimulti' \
--db-instance-class 'db.t2.micro' --engine 'mysql' \
--master-username 'root' --master-user-password '<PASSWORD>' \
--publicly-accessible --db-name 'qtecommerce' \
--db-subnet-group-name 'qtsubnetgroup' --allocated-storage 20 \
--multi-az --vpc-security-group-ids 'sg-0c8eee8f2fbefd89e'
aws rds create-db-instance-read-replica --db-instance-identifier 'qtrdsreplica' \
--source-db-instance-identifier 'qtrdsfromclimulti' --publicly-accessible \
--source-region 'us-west-2'
# Create db snapshot
aws rds create-db-snapshot --db-instance-identifier 'qtrdsfromclimulti' \
--db-snapshot-identifier 'snapshotfromcli'
# Delete db snapshot
aws rds delete-db-snapshot --db-snapshot-identifier 'snapshotfromcli'
# Promote read replica
aws rds promote-read-replica --db-instance-identifier 'qtrdsreplica'
# Delete the db-instance
aws rds delete-db-instance --db-instance-identifier 'qtrdsreplica'\
--skip-final-snapshot --delete-automated-backups
# Create a read replica in different region
# ARN: arn:aws:rds:<region>:<account number>:<resourcetype>:<name>
aws rds create-db-instance-read-replica --db-instance-identifier 'qtrdsreplica' \
--source-db-instance-identifier 'arn:aws:rds:us-west-2:678879106782:db:qtrdsfromclimulti' \
--publicly-accessible \
--source-region 'us-west-2' --region 'ap-south-1'
aws rds delete-db-instance --db-instance-identifier 'qtrdsreplica'\
--skip-final-snapshot --delete-automated-backups --region 'ap-south-1'
aws rds delete-db-instance --db-instance-identifier 'qtrdsfromclimulti'\
--skip-final-snapshot --delete-automated-backups
<file_sep>#!/bin/bash
# Create an AWS S3 Glacier vault
aws glacier create-vault --account-id - --vault-name 'docsvault'
#
# {
# "location": "/678879106782/vaults/docsvault"
# }
#
# Prepare a large file 10 MB
dd if=/dev/urandom of=largefile bs=10485760 count=1
# Split the files into 1 MB
split -b 1048576 --verbose largefile chunk
# lets upload file directly to the archive
aws glacier upload-archive --account-id - --vault-name 'docsvault' --body awscliv2.zip
# Generally we upload large files where we upload parts of the file
# Lets initiate multipart upload
aws glacier initiate-multipart-upload --account-id - --archive-description "multipart upload demo" --part-size 1048576 --vault-name 'docsvault'
# {
# "location": "/678879106782/vaults/docsvault/multipart-uploads/<KEY>",
# "uploadId": "<KEY>"
# }
UPLOADID='<KEY>'
aws glacier upload-multipart-part --upload-id $UPLOADID --account-id - --vault-name 'docsvault' --body chunkaa --range 'bytes 0-1048575/*'
# {
# "checksum": "67793b16e2bb560d78b31a04ed25c543f40f23c9db2dc07f2bd8152b9281c41a"
# }
aws glacier upload-multipart-part --upload-id $UPLOADID --account-id - --vault-name 'docsvault' --body chunkab --range 'bytes 1048576-2097151/*'
# {
# "checksum": "9157be17875e70f7c2172fc78ae52f82e27e3b921499ca76527de54e72122253"
# }
aws glacier upload-multipart-part --upload-id $UPLOADID --account-id - --vault-name 'docsvault' --body chunkac --range 'bytes 2097152-3145727/*'
# {
# "checksum": "4b234d66bbafbe590e2d11f854937a9f2db1d3efc1e97d781bd4b650524fdb76"
# }
aws glacier upload-multipart-part --upload-id $UPLOADID --account-id - --vault-name 'docsvault' --body chunkad --range 'bytes 3145728-4194303/*'
# {
# "checksum": "389bda6a3bf4e353d7bad29b42458212b5108504620ff4d7f67224c00196e533"
# }
aws glacier upload-multipart-part --upload-id $UPLOADID --account-id - --vault-name 'docsvault' --body chunkae --range 'bytes 4194304-5242879/*'
# {
# "checksum": "43dc081cce7630950c0df124eb14576ca8c731549ad87bcbf729fa4d458e9927"
# }
aws glacier upload-multipart-part --upload-id $UPLOADID --account-id - --vault-name 'docsvault' --body chunkaf --range 'bytes 5242880-6291455/*'
# {
# "checksum": "6adaec6095b75dfdbb4b01955e592f5751f8cf3900022dbfe917888456773983"
# }
aws glacier upload-multipart-part --upload-id $UPLOADID --account-id - --vault-name 'docsvault' --body chunkag --range 'bytes 6291456-7340031/*'
# {
# "checksum": "6f741bf13f6571f14449a68ff9faf72e8d2ee15d38bb87f50674ebb9848dfd61"
# }
aws glacier upload-multipart-part --upload-id $UPLOADID --account-id - --vault-name 'docsvault' --body chunkah --range 'bytes 7340032-8388607/*'
# {
# "checksum": "c32c2e938d6634fe9a494e1738b04db3c813f7498d9386e61433637223806b02"
# }
aws glacier upload-multipart-part --upload-id $UPLOADID --account-id - --vault-name 'docsvault' --body chunkai --range 'bytes 8388608-9437183/*'
# {
# "checksum": "f28d377947e57d6e78595d50b1353f16f663832f210c00bf0f82f55dc2a2183d"
# }
aws glacier upload-multipart-part --upload-id $UPLOADID --account-id - --vault-name 'docsvault' --body chunkaj --range 'bytes 9437184-10485759/*'
# {
# "checksum": "afeafaef8a5a7f15f4fd1a00b36d380a4a80680f4079f2341c851e14fba2cf69"
# }
# Calculate tree hash
openssl dgst -sha256 -binary chunkaa > hash1
openssl dgst -sha256 -binary chunkab > hash2
openssl dgst -sha256 -binary chunkac > hash3
openssl dgst -sha256 -binary chunkad > hash4
openssl dgst -sha256 -binary chunkae > hash5
openssl dgst -sha256 -binary chunkaf > hash6
openssl dgst -sha256 -binary chunkag > hash7
openssl dgst -sha256 -binary chunkah > hash8
openssl dgst -sha256 -binary chunkai > hash9
openssl dgst -sha256 -binary chunkaj > hash10
<file_sep>#!/bin/bash
aws ec2 run-instances --image-id 'ami-0cf6f5c8a62fa5da6' --instance-type 't2.micro' --key-name 'cheflearning' --security-groups 'openallports' --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=fromcli1}]'
# fetchin information about the ec2 instance created by us
aws ec2 describe-instances --filters 'Name=image-id,Values=ami-0cf6f5c8a62fa5da6' --query "Reservations[*].Instances[*].PublicIpAddress" --output text
aws ec2 run-instances --image-id 'ami-03d5c68bab01f3496' --instance-type 't2.micro' --key-name 'cheflearning' --security-groups 'openallports' --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=fromcli2}]'
# fetchin information about the ec2 instance created by us
aws ec2 describe-instances --filters 'Name=tag:Name,Values=fromcli2' --query "Reservations[*].Instances[*].PublicIpAddress" --output text
# Stop the ec2 instace with tag Name: fromcli2
instaceid=$(aws ec2 describe-instances --filters 'Name=tag:Name,Values=fromcli2' --query "Reservations[0].Instances[0].InstanceId" --output text)
aws ec2 stop-instances --instance-ids ${instaceid}
# Terminate the ec2 instance with tag Name: fromcli1
aws ec2 describe-instances --filters 'Name=tag:Name,Values=fromcli1' --query "Reservations[0].Instances[0].InstanceId" --output text
<file_sep>#!/bin/bash
aws s3api create-bucket --acl 'public-read' --bucket 'qts3apidemo' --region 'us-east-1'
aws s3api put-object --bucket 'qts3apidemo' --key 'videos/one.mp4' --body './contents/one.mp4'
# Create the similar structure like what we have done with basic s3 commands<file_sep>#!/bin/bash
# get default vpc
vpc_id=$(aws ec2 describe-vpcs --query 'Vpcs[?IsDefault].VpcId[]' --output text)
# Create a security group
aws ec2 create-security-group --description "open 22 80 and 8080 port" --group-name 'openfortomcat' --vpc-id $vpc_id
# store security group id into some variable
sg_id=$(aws ec2 describe-security-groups --group-names "openfortomcat" --query "SecurityGroups[0].GroupId" --output text)
# openports
for port_number in 22 80 8080
do
aws ec2 authorize-security-group-ingress --group-name "openfortomcat" --protocol tcp --port "$port_number" --cidr 0.0.0.0/0
done
# get the first subnet
subnet_id=$(aws ec2 describe-subnets --filters "Name=vpc-id,Values=$vpc_id" --query "Subnets[0].SubnetId" --output text)
# Create a public key if required
# ssh-keygen
aws ec2 import-key-pair --key-name "my-key" --public-key-material fileb://~/.ssh/id_rsa.pub
# Create an ec2 instance with the security group and key created over here
| 8bce28a16c716b795ddccbb3d9b18a543f322557 | [
"Shell"
] | 21 | Shell | AbhiWarzone/awsadministration | b1d065443b26b600e01def4607480b36b6115729 | f93a3dd0bbad29da6d2cafcca68d326de4dfbfb4 | |
refs/heads/master | <repo_name>GiaGenae/calendoc<file_sep>/README.md
# CalenDOC
CalenDOC is an app created for a user to manage all his or her medical appointments, by date or by physician.
## Installation
Start this application by running `bundle` then `rails s`. After, open localhost:3000 in your browser and enjoy!
## License
MIT License <file_sep>/db/migrate/20210701023258_add_user_and_doctor_id.rb
class AddUserAndDoctorId < ActiveRecord::Migration[6.1]
def change
add_column :appointments, :user_id, :integer
add_column :appointments, :doctor_id, :integer
end
end
<file_sep>/db/migrate/20210701004802_drop_appointments.rb
class DropAppointments < ActiveRecord::Migration[6.1]
def change
drop_table :appointments
end
end
| fea84372727f51faee8389ea37b2c79c13ac6b02 | [
"Markdown",
"Ruby"
] | 3 | Markdown | GiaGenae/calendoc | 97e155fa51a86e5a3456f4f83f3a3302e25021c8 | e550f80e78bca51f24a841011563016a56272a87 | |
refs/heads/master | <repo_name>NatalieShostak/HomeWork4Back<file_sep>/Task2.java
public class Task2 {
public static void drawRectangle(int width, int height) {
for (int j = 0; j <= height - 1; j++) {
for (int i = 0; i <= width - 1; i++) {
System.out.print("+");
}
System.out.println();
}
}
public static void drawRectangle(int width) {
drawRectangle(width, width);
}
public static void main(String[] args) {
drawRectangle(3, 2);
drawRectangle(5);
}
}
<file_sep>/Task4.java
public class Task4 {
public static void getMax(int a, int b) {
int max;
if (a > b) max = a;
else max = b;
System.out.println("Max value of two int's is " + max);
}
public static void getMax(float a, float b) {
float max;
if (a > b) max = a;
else max = b;
System.out.println("Max value of two float's is " + max);
}
public static void main(String[] args) {
getMax(6, 25);
getMax(8.5f, 125.8f);
}
}
<file_sep>/Task7.java
import java.util.Scanner;
public class Task7 {
public static void count(int x) {
for (int i = 0; i < x; i++) {
System.out.println(i + 1);
}
}
public static void drawRectangle(int width, int height) {
for (int j = 1; j <= height; j++) {
for (int i = 1; i <= width; i++) {
System.out.print("+");
}
System.out.println();
}
}
public static void drawRectangle(int width) {
drawRectangle(width, width);
}
public static void getMax(int a, int b) {
int max = Math.max(a, b);
System.out.println("Max value of two int's is " + max);
}
public static void getMax(float a, float b) {
float max = Math.max(a, b);
System.out.println("Max value of two float's is " + max);
}
public static void countRecursion(int x) {
if (x == 0) return;
else {
countRecursion(x - 1);
System.out.println(x);
}
}
public static void drawPartOfRectangleRecursion(int a) {
if (a == 0) return;
else {
drawPartOfRectangleRecursion(a - 1);
System.out.print("+");
}
}
public static void drawRectangleRecursion(int width, int height) {
if (height == 0) return;
else {
drawPartOfRectangleRecursion(width);
System.out.println();
drawRectangleRecursion(width, height - 1);
}
}
public static void whichTask() {
Scanner sc = new Scanner(System.in);
System.out.println("Which task should I do?\n(input number 1 - 6)");
int taskNumber = sc.nextInt();
switch (taskNumber) {
case 1:
System.out.println("Enter number to count");
int value = sc.nextInt();
count(value);
break;
case 2:
System.out.println("Enter the width of rectangle");
int width = sc.nextInt();
System.out.println("Enter the height of rectangle");
int height = sc.nextInt();
drawRectangle(width, height);
break;
case 3:
System.out.println("Enter the width of the square");
int widthOfSquare = sc.nextInt();
drawRectangle(widthOfSquare);
break;
case 4:
getMax(2, 93);
break;
case 5:
countRecursion(8);
break;
case 6:
drawRectangleRecursion(2, 4);
break;
default:
System.out.println("incorrect number");
}
}
public static void again() {
Scanner sc = new Scanner(System.in);
System.out.println("Do you want to do another task?\n(yes/no)");
String answer = sc.nextLine();
if (answer.equals("yes")) {
whichTask();
again();
} else System.out.println("as you wish");
}
public static void main(String[] args) {
whichTask();
again();
}
}
<file_sep>/Task6.java
public class Task6 {
public static void drawPartOfRectangleRecursion(int a) {
if (a == 0) return;
else {
drawPartOfRectangleRecursion(a - 1);
System.out.print("+");
}
}
public static void drawRectangleRecursion(int width, int height) {
if (height == 0) return;
else {
drawPartOfRectangleRecursion(width);
System.out.println();
drawRectangleRecursion(width, height - 1);
}
}
public static void main(String[] args) {
drawRectangleRecursion(40, 4);
}
}
| ce2af0e903dfdd50ee100f8a328c15f474c84178 | [
"Java"
] | 4 | Java | NatalieShostak/HomeWork4Back | 593707563673647fc2c3d45a0505a2688b4a531d | cce5b0eea7c10682691a3adfbf33f8a8d5b711fe | |
refs/heads/develop | <repo_name>official-frandly/frandly-market-landing<file_sep>/src/components/header/PlainHeader.js
import React from "react";
import styled from "styled-components";
function PlainHeader(props) {
return <div>PlainHeader</div>;
}
export default PlainHeader;
<file_sep>/src/components/cards/EducationCard.js
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Card from "@material-ui/core/Card";
import CardActionArea from "@material-ui/core/CardActionArea";
import CardActions from "@material-ui/core/CardActions";
import CardContent from "@material-ui/core/CardContent";
import CardMedia from "@material-ui/core/CardMedia";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
import styled from "styled-components";
const useStyles = makeStyles({
media: {
height: 240,
},
});
export default function MediaCard(props) {
const classes = useStyles();
return (
<Styled.MediaCard>
<Card className="card__item">
<CardActionArea>
<CardMedia
className={classes.media}
image={props.image || ""}
title="Contemplative Reptile"
/>
<CardContent>
<Typography gutterBottom variant="h5" component="h2">
{props.title}
</Typography>
<Typography variant="body2" color="textSecondary" component="p">
{props.subtitle}
</Typography>
</CardContent>
</CardActionArea>
<CardActions>
{/* <Button size="small" color="primary">
Share
</Button> */}
<Button size="small" color="primary">
더 보기
</Button>
</CardActions>
</Card>
</Styled.MediaCard>
);
}
const Styled = {
MediaCard: styled.div`
.card__item {
/* float: left; */
/* max-width: 360px; */
width: 100%;
margin-right: 10px;
margin-bottom: 15px;
/* &:last-child {
margin-right: 0;
} */
}
`,
};
<file_sep>/next.config.js
const withPlugins = require("next-compose-plugins");
const optimizedImages = require("next-optimized-images");
const withCSS = require("@zeit/next-css");
const withSass = require("@zeit/next-sass");
const nextConfiguration = {
target: "serverless", //will output independent pages that don't require a monolithic server. It's only compatible with next start or Serverless deployment platforms (like ZEIT Now) — you cannot use the custom server API.
};
module.exports = withPlugins([optimizedImages], nextConfiguration);
<file_sep>/src/components/cards/index.js
export { default as EducationCard } from "./EducationCard";
<file_sep>/src/components/modal/index.js
export { default as EducationModal } from "./EducationModal";
export { default as QuestionModal } from "./QuestionModal";
<file_sep>/src/components/modal/EducationModal.js
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Modal from "@material-ui/core/Modal";
import Backdrop from "@material-ui/core/Backdrop";
import Fade from "@material-ui/core/Fade";
import styled, { createGlobalStyle } from "styled-components";
import { EducationCard } from "components/cards";
const useStyles = makeStyles((theme) => ({
modal: {
display: "flex",
alignItems: "center",
justifyContent: "center",
},
paper: {
width: "90%",
height: "90%",
overflow: "auto",
backgroundColor: theme.palette.background.paper,
border: "2px solid #000",
boxShadow: theme.shadows[5],
padding: theme.spacing(2, 4, 3),
},
}));
const educationItems = [
{
id: 1,
image: "https://t1.daumcdn.net/cfile/tistory/994BEF355CD0313D05",
href:
"https://www.hanwhawm.com/main/common/common_file/fileView.cmd?category=2&depth3_id=anls5&key1=51501&key2=1&bldid=bbs10031",
title: "프랜들리 입점 프로세스",
subtitle:
"프랜들리 입점 신청은 1분이면 끝입니다. 쉽고 간단한 프랜들리 입점 방법을 확인해보세요! 입점 프로세스 프랜들리 입점을... ",
},
{
id: 12,
image: "https://t1.daumcdn.net/cfile/tistory/994BEF355CD0313D05",
href:
"https://www.hanwhawm.com/main/common/common_file/fileView.cmd?category=2&depth3_id=anls5&key1=51501&key2=1&bldid=bbs10031",
title: "프랜들리 입점 프로세스",
subtitle:
"프랜들리 입점 신청은 1분이면 끝입니다. 쉽고 간단한 프랜들리 입점 방법을 확인해보세요! 입점 프로세스 프랜들리 입점을... ",
},
{
id: 13,
image: "https://t1.daumcdn.net/cfile/tistory/994BEF355CD0313D05",
href:
"https://www.hanwhawm.com/main/common/common_file/fileView.cmd?category=2&depth3_id=anls5&key1=51501&key2=1&bldid=bbs10031",
title: "프랜들리 입점 프로세스",
subtitle:
"프랜들리 입점 신청은 1분이면 끝입니다. 쉽고 간단한 프랜들리 입점 방법을 확인해보세요! 입점 프로세스 프랜들리 입점을... ",
},
{
id: 14,
image: "https://t1.daumcdn.net/cfile/tistory/994BEF355CD0313D05",
href:
"https://www.hanwhawm.com/main/common/common_file/fileView.cmd?category=2&depth3_id=anls5&key1=51501&key2=1&bldid=bbs10031",
title: "프랜들리 입점 프로세스",
subtitle:
"프랜들리 입점 신청은 1분이면 끝입니다. 쉽고 간단한 프랜들리 입점 방법을 확인해보세요! 입점 프로세스 프랜들리 입점을... ",
},
{
id: 15,
image: "https://t1.daumcdn.net/cfile/tistory/994BEF355CD0313D05",
href:
"https://www.hanwhawm.com/main/common/common_file/fileView.cmd?category=2&depth3_id=anls5&key1=51501&key2=1&bldid=bbs10031",
title: "프랜들리 입점 프로세스",
subtitle:
"프랜들리 입점 신청은 1분이면 끝입니다. 쉽고 간단한 프랜들리 입점 방법을 확인해보세요! 입점 프로세스 프랜들리 입점을... ",
},
{
id: 16,
image: "https://t1.daumcdn.net/cfile/tistory/994BEF355CD0313D05",
href:
"https://www.hanwhawm.com/main/common/common_file/fileView.cmd?category=2&depth3_id=anls5&key1=51501&key2=1&bldid=bbs10031",
title: "프랜들리 입점 프로세스",
subtitle:
"프랜들리 입점 신청은 1분이면 끝입니다. 쉽고 간단한 프랜들리 입점 방법을 확인해보세요! 입점 프로세스 프랜들리 입점을... ",
},
{
id: 17,
image: "https://t1.daumcdn.net/cfile/tistory/994BEF355CD0313D05",
href:
"https://www.hanwhawm.com/main/common/common_file/fileView.cmd?category=2&depth3_id=anls5&key1=51501&key2=1&bldid=bbs10031",
title: "프랜들리 입점 프로세스",
subtitle:
"프랜들리 입점 신청은 1분이면 끝입니다. 쉽고 간단한 프랜들리 입점 방법을 확인해보세요! 입점 프로세스 프랜들리 입점을... ",
},
{
id: 18,
image: "https://t1.daumcdn.net/cfile/tistory/994BEF355CD0313D05",
href:
"https://www.hanwhawm.com/main/common/common_file/fileView.cmd?category=2&depth3_id=anls5&key1=51501&key2=1&bldid=bbs10031",
title: "프랜들리 입점 프로세스",
subtitle:
"프랜들리 입점 신청은 1분이면 끝입니다. 쉽고 간단한 프랜들리 입점 방법을 확인해보세요! 입점 프로세스 프랜들리 입점을... ",
},
{
id: 19,
image: "https://t1.daumcdn.net/cfile/tistory/994BEF355CD0313D05",
href:
"https://www.hanwhawm.com/main/common/common_file/fileView.cmd?category=2&depth3_id=anls5&key1=51501&key2=1&bldid=bbs10031",
title: "프랜들리 입점 프로세스",
subtitle:
"프랜들리 입점 신청은 1분이면 끝입니다. 쉽고 간단한 프랜들리 입점 방법을 확인해보세요! 입점 프로세스 프랜들리 입점을... ",
},
{
id: 10,
image: "https://t1.daumcdn.net/cfile/tistory/994BEF355CD0313D05",
href:
"https://www.hanwhawm.com/main/common/common_file/fileView.cmd?category=2&depth3_id=anls5&key1=51501&key2=1&bldid=bbs10031",
title: "프랜들리 입점 프로세스",
subtitle:
"프랜들리 입점 신청은 1분이면 끝입니다. 쉽고 간단한 프랜들리 입점 방법을 확인해보세요! 입점 프로세스 프랜들리 입점을... ",
},
{
id: 21,
href:
"https://www.hanwhawm.com/main/common/common_file/fileView.cmd?category=2&depth3_id=anls5&key1=51501&key2=1&bldid=bbs10031",
image: "https://t1.daumcdn.net/cfile/tistory/994BEF355CD0313D05",
title: "프랜들리 입점 프로세스",
subtitle:
"프랜들리 입점 신청은 1분이면 끝입니다. 쉽고 간단한 프랜들리 입점 방법을 확인해보세요! 입점 프로세스 프랜들리 입점을... ",
},
];
export default function EducationModal() {
const classes = useStyles();
const [open, setOpen] = React.useState(false);
const handleOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<Styled.EducationModal className="education__modal">
<button
type="button"
onClick={handleOpen}
className="educationModal__btn"
>
모두 보기
</button>
<Modal
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className={classes.modal}
open={open}
onClose={handleClose}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500,
}}
>
<Fade in={open}>
<div className={classes.paper}>
<h2 id="transition-modal-title" className="education__modal_title">
교육 자료
</h2>
<div id="transition-modal-description">
<div className="education__card_box">
{educationItems.map((item) => {
return (
<div className="education__card_col" key={item.id}>
<a href={item.href} target="_blank">
<EducationCard
className="education__card"
image={item.image}
title={item.title}
subtitle={item.subtitle}
/>
</a>
</div>
);
})}
</div>
</div>
</div>
</Fade>
</Modal>
<ModalStyle />
</Styled.EducationModal>
);
}
const ModalStyle = createGlobalStyle`
.education__modal_title{
font-size:25px;
font-weight:bold;
border-bottom:1px solid #ececec;
margin-bottom:20px;
}
.education__card_box {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
max-width:1400px;
margin:auto;
&:after {
display: block;
clear: both;
content: "";
}
}
.education__card_col{
flex-basis: 33% ;
padding:10px;
max-width:360px;
}
.education__card{
}
`;
const Styled = {
EducationModal: styled.div`
text-align: right;
.educationModal__btn {
background: transparent;
color: #4f96ff;
border-radius: 5px;
border: 0;
&:hover {
color: #2e7cf1;
}
}
`,
};
<file_sep>/src/lib/config.js
export const setting = {
importPointNumber: "02-651-5513",
importPointAddress: "https://www.google.com",
questionEmail: "<EMAIL>",
brandName_en: "frandly",
brandName_ko: "프랜들리",
partnerNickname: "프랜더",
};
<file_sep>/src/components/sections/faq.js
import React from "react";
import { Box, Container, Flex, Text, Heading } from "theme-ui";
import { Link } from "components/link";
import BlockTitle from "components/block-title";
import Accordion from "components/accordion/accordion";
import styled from "styled-components";
import { QuestionModal } from "components/modal";
import { data } from "lib/config";
const accordionData = [
{
isExpanded: false,
title: "입점 신청을 하려면 어떻게 해야하나요?",
contents: (
<div>
For our recent trip to S.A. I booked several accommodation thru SA
Places. I just wanted to tell you that everything worked out perfectly
with all the bookings and also your booking was very quick and
professional. I hope I have the opportunity to re-visit South Africa
soon, I will then make my bookings with your company again. I will also
recommend
</div>
),
},
{
isExpanded: true,
title:
"저희 상점도 프랜들리에 올라가는 사진들 처럼 이쁘게 찍고싶은데 어떻게 해야하나요?",
contents: (
<div>
For our recent trip to S.A. I booked several accommodation thru SA
Places. I just wanted to tell you that everything worked out perfectly
with all the bookings and also your booking was very quick and
professional. I hope I have the opportunity to re-visit South Africa
soon, I will then make my bookings with your company again. I will also
recommend
</div>
),
},
{
isExpanded: false,
title: "입점할 때 주의 사항이 있나요?",
contents: (
<div>
For our recent trip to S.A. I booked several accommodation thru SA
Places. I just wanted to tell you that everything worked out perfectly
with all the bookings and also your booking was very quick and
professional. I hope I have the opportunity to re-visit South Africa
soon, I will then make my bookings with your company again. I will also
recommend
</div>
),
},
{
isExpanded: false,
title: "프랜들리 박스를 구매하고싶은데 어떻게 해야하나요?",
contents: (
<div>
For our recent trip to S.A. I booked several accommodation thru SA
Places. I just wanted to tell you that everything worked out perfectly
with all the bookings and also your booking was very quick and
professional. I hope I have the opportunity to re-visit South Africa
soon, I will then make my bookings with your company again. I will also
recommend
</div>
),
},
{
isExpanded: false,
title: "상점 결산은 어디서 하나요?",
contents: (
<div>
For our recent trip to S.A. I booked several accommodation thru SA
Places. I just wanted to tell you that everything worked out perfectly
with all the bookings and also your booking was very quick and
professional. I hope I have the opportunity to re-visit South Africa
soon, I will then make my bookings with your company again. I will also
recommend
</div>
),
},
];
const FAQ = () => {
return (
<Styled.FAQ id="faq">
<Box as="section">
<Container>
<BlockTitle title="자주묻는 질문" text="Ask your question and meet" />
<Flex sx={styles.flex}>
<Box sx={styles.faqWrapper}>
<Accordion items={accordionData} />
</Box>
<Box sx={styles.content}>
<Heading as="h3">
추가적인 질문이 더 남았나요? <br /> 문의하기 버튼을 눌러 질문을
남겨주세요.
</Heading>
<Text as="p" className="faq__subtitle">
If your question is not list here, please feel free to make a
manual support.
</Text>
{/* <Link sx={styles.askButton} path="#">
문의하기
</Link> */}
<QuestionModal />
</Box>
</Flex>
</Container>
</Box>
</Styled.FAQ>
);
};
export default FAQ;
const Styled = {
FAQ: styled.div`
padding-top: 61px;
.faq__subtitle {
margin-bottom: 30px;
}
`,
};
const styles = {
flex: {
flexWrap: "wrap",
flexDirection: ["column", null, null, null, null, "row-reverse"],
pb: ["70px", null, null, null, "90px", null, "130px"],
},
content: {
flex: ["0 0 100%", null, null, null, "0 0 33.333%"],
maxWidth: ["100%", null, null, "450px", "100%"],
mx: ["auto", null, null, null, "0"],
mb: ["0px", null, null, null, "0"],
textAlign: ["center", null, null, null, null, "left"],
mt: ["40px", null, null, null, null, "0"],
h3: {
fontSize: ["23px", null, null, null, "24px"],
lineHeight: [1.5, null, null, null, 1.67],
color: "black",
fontWeight: 700,
letterSpacing: "-1.5px",
mt: "-5px",
pr: ["0", null, null, null, null, "30px"],
},
p: {
fontSize: "16px",
lineHeight: 1.87,
color: "#343D48",
opacity: 0.7,
mt: "10px",
pr: ["0", null, null, null, null, "80px"],
},
},
askButton: {
display: "inline-block",
verticalAlign: "middle",
backgroundColor: "#02073E",
color: "#fff",
borderRadius: "5px",
fontSize: "16px",
fontWeight: 700,
p: "6.5px 19px",
letterSpacing: "-0.16px",
mt: "25px",
transition: "all 500ms ease",
"&:hover": {
opacity: 0.8,
},
},
faqWrapper: {
flex: ["0 0 100%", null, null, null, "0 0 66.666%"],
},
};
<file_sep>/src/components/sections/contact.js
import React from "react";
import { Button, Input, Box, Container, Heading, Text } from "theme-ui";
import styled from "styled-components";
import { setting } from "lib/config";
const Contact = () => {
return (
<Styled.Contact>
<Box as="section" sx={styles.subscribe}>
<Container>
<Heading as="h3">{setting.brandName_ko}를 구독하세요!</Heading>
<Text as="p">
구독하기를 통해 {setting.brandName_ko}의 최신 이벤트와 정보를 받아볼
수 있습니다.
</Text>
{/* <Box as="form" sx={styles.form}>
<Box as="label" htmlFor="subscribeEmail" variant="styles.srOnly">
Email
</Box>
<Input
placeholder="Enter your email"
type="email"
id="subscribeEmail"
className="contact__email"
// sx={styles.input}
value="<EMAIL>"
readOnly
/>
</Box> */}
<Box as="form" sx={styles.form}>
<Box as="label" htmlFor="subscribeEmail" variant="styles.srOnly">
Email
</Box>
<Input
placeholder="Enter your email"
type="email"
id="subscribeEmail"
sx={styles.input}
/>
<Button type="submit" sx={styles.button}>
구독하기
</Button>
</Box>
</Container>
</Box>
</Styled.Contact>
);
};
export default Contact;
const Styled = {
Contact: styled.div`
.contact__email {
text-align: center;
background: rgba(255, 255, 255, 0.08);
color: rgba(255, 255, 255, 0.8);
}
`,
};
const styles = {
subscribe: {
py: ["80px", null, null, null, "80px", "100px", "140px"],
backgroundColor: "#020718",
h3: {
textAlign: "center",
fontSize: ["23px", null, null, null, null, "30px", "36px"],
lineHeight: [1.5, null, null, "1"],
color: "#fff",
letterSpacing: ["-0.5px"],
mb: ["0px", null, null, "15px"],
width: ["70%", null, null, "auto"],
mx: ["auto", null, null, "0"],
},
p: {
fontSize: ["16px"],
color: "#fff",
opacity: ".6",
letterSpacing: ["-0.5px"],
textAlign: "center",
width: ["70%", null, null, "auto"],
mx: ["auto", null, null, "0"],
mt: ["10px", null, null, "0"],
},
},
form: {
width: ["100%"],
maxWidth: ["555px"],
mx: ["auto"],
display: ["flex"],
flexWrap: ["wrap"],
mt: ["30px", null, null, null, "60px"],
},
input: {
width: ["100%"],
maxWidth: ["100%", null, "370px", "380px"],
borderRadius: "5px",
border: "none",
backgroundColor: "rgba(255,255,255, .08)",
outline: "none",
color: "rgba(255,255,255, .8)",
fontSize: "16px",
pl: ["0px", null, null, "30px"],
height: ["50px", null, null, "60px"],
mr: ["0px", null, null, "15px"],
textAlign: ["center", null, null, "left"],
},
button: {
backgroundColor: "#fff",
borderRadius: "5px",
fontWeight: "500",
fontSize: ["18px"],
color: "#020718",
letterSpacing: "-0.5px",
outline: "none",
padding: ["0px 30.75px"],
minHeight: ["50px", null, null, "60px"],
width: ["100%", null, null, "auto"],
mt: ["10px", null, null, "0"],
mx: ["auto", null, null, "0"],
"&:hover": {
backgroundColor: "#fff",
opacity: "0.8",
},
},
};
<file_sep>/src/components/header/header.js
/** @jsx jsx */
import { jsx, Container, Flex, Image } from "theme-ui";
import { Link } from "components/link";
import { Link as ScrollLink } from "react-scroll";
import Logo from "components/logo";
import logoImage from "assets/banner-logo.png";
import { DrawerProvider } from "contexts/drawer/drawer.provider";
import MobileDrawer from "./mobileDrawer";
import menuItems from "./header.data";
import logoDark from "assets/logo-dark.svg";
import styled from "styled-components";
import { setting } from "lib/config";
import { capitalize } from "lib/utils";
export default function Header({ className }) {
return (
<DrawerProvider>
<Styled.Header sx={styles.header} className={className}>
{/* <header > */}
<Container sx={styles.container}>
{/* <Logo image={logoDark} /> */}
<ScrollLink
activeClass="active"
sx={styles.nav.navLink}
to={"banner"}
spy={true}
smooth={true}
offset={-70}
duration={500}
>
<div>
<span className="title__logo">
<Image className="logo" src={logoImage} alt="logo image" />
{capitalize(setting.brandName_en)} market
</span>
{/* <h2>Frandly</h2> */}
</div>
</ScrollLink>
<Flex as="nav" sx={styles.nav}>
{menuItems.map(({ path, label }, i) => (
<ScrollLink
activeClass="active"
sx={styles.nav.navLink}
to={path}
spy={true}
smooth={true}
offset={-70}
duration={500}
key={i}
>
{label}
</ScrollLink>
))}
{/* <Link path="/" ml={2} label="서비스" sx={styles.nav.navLink} /> */}
{/* <Link
path="/education"
ml={2}
label="교육자료"
sx={styles.nav.navLink}
/> */}
{/* <Link path="/news" ml={2} label="뉴스" sx={styles.nav.navLink} /> */}
</Flex>
<span className="qa__number">
입점 문의 {setting.importPointNumber}
</span>
{/* <Link
path="/"
ml={2}
label="입점 신청하기"
sx={styles.headerBtn}
variant="buttons.primary"
/> */}
<a
href={setting.importPointAddress}
target="_blank"
sx={styles.headerBtn}
>
입점 신청하기
</a>
<MobileDrawer />
</Container>
{/* </header> */}
</Styled.Header>
</DrawerProvider>
);
}
const Styled = {
Header: styled.header`
.title__logo {
position: relative;
font-size: 30px;
font-weight: bold;
top: 2px;
}
.qa__number {
display: inline-block;
margin-right: 10px;
color: #103d4b;
font-size: 14px;
}
.logo {
position: relative;
width: 40px;
top: -3px;
margin-right: 7px;
}
`,
};
const styles = {
headerBtn: {
backgroundColor: "black",
fontSize: "16px",
fontWeight: "bold",
letterSpacing: "-0.16px",
borderRadius: "5px",
color: "#ffffff",
padding: "6.5px 24px",
display: ["none", null, null, null, "inline-block"],
ml: ["0", null, null, "auto", "0"],
mr: ["0", null, null, "20px", "0"],
"&:hover": {
color: "#fff",
},
},
header: {
color: "text_white",
fontWeight: "normal",
py: "25px",
width: "100%",
position: "fixed",
top: 0,
left: 0,
backgroundColor: "transparent",
transition: "all 0.4s ease",
"&.sticky": {
backgroundColor: "background",
color: "text",
py: "15px",
boxShadow: "0 1px 2px rgba(0, 0, 0, 0.06)",
},
},
container: {
display: "flex",
alignItems: "center",
width: [null, null, null, null, null, null, "1420px"],
"@media screen and (max-width: 960px)": {
justifyContent: "space-between",
},
},
nav: {
mx: "auto",
"@media screen and (max-width: 960px)": {
display: "none",
},
navLink: {
fontSize: "16px",
color: "#02073E",
fontWeight: "400",
cursor: "pointer",
lineHeight: "1.2",
mr: "48px",
transition: "500ms",
":last-child": {
mr: "0",
},
"&:hover": {
color: "#0066C5",
},
// "&:hover, &.active": {
// color: "#0066C5",
// },
},
},
};
| 336afc25f9af654ae4e4dbac731948a51e7e0558 | [
"JavaScript"
] | 10 | JavaScript | official-frandly/frandly-market-landing | 9aac474670101e2f0769846be9c133bca1857bf2 | 5c08c4aceb4ccda18a6467135caaa8c70aaa6296 |