repo
stringlengths 5
121
| content
stringlengths 35
2.09M
|
|---|---|
704266213/ComponentApp
|
704266213/ComponentApp
FastJsonConverterFactory.java
```/*******************************************************************************
* Copyright 2017 Yuran Zhang
*
* 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 com.component.base.http.converter;
//import com.alibaba.fastjson.serializer.SerializeConfig;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
/**
* A {@linkplain Converter.Factory converter} which uses FastJson for JSON.
* <p>
* Because FastJson is so flexible in the types it supports, this converter assumes that it can
* handle all types. If you are mixing JSON serialization with something else (such as protocol
* buffers), you must {@linkplain Retrofit.Builder#addConverterFactory(Converter.Factory) add
* this instance} last to allow the other converters a chance to see their types.
*/
//public class FastJsonConverterFactory extends Converter.Factory {
// private final SerializeConfig serializeConfig;
//
// private FastJsonConverterFactory(SerializeConfig serializeConfig) {
// if (serializeConfig == null) {
// throw new NullPointerException("com.alibaba.fastjson.serializer.SerializeConfig is null.Forgot to add fastjson in your project?");
// }
// this.serializeConfig = serializeConfig;
// }
//
// /**
// * Create an default instance for conversion. Encoding to JSON and
// * decoding from JSON (when no charset is specified by a header) will use UTF-8.
// * @return The instance of FastJsonConverterFactory
// */
// public static FastJsonConverterFactory create() {
// return create(SerializeConfig.getGlobalInstance());
// }
//
// public static FastJsonConverterFactory create(SerializeConfig serializeConfig) {
// return new FastJsonConverterFactory(serializeConfig);
// }
//
// @Override
// public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
// return new FastJsonResponseBodyConverter<>(type);
// }
//
// @Override
// public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
// return new FastJsonRequestBodyConverter<>(serializeConfig);
// }
//}
```
OnRefreshBeginListener.java
```package com.component.base.widget.reflesh;
/**
* 项目名称:MVP
* 类描述:
* 创建人:admin
* 创建时间:2017/12/20 9:39
* 修改人:admin
* 修改时间:2017/12/20 9:39
* 修改备注:
*/
public interface OnRefreshBeginListener {
void onRefreshBeginListener();
}
```
PtrClassicDefaultHeader.java
```package com.component.base.widget.reflesh;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.TextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.component.base.R;
import com.component.base.widget.reflesh.indicator.PtrIndicator;
public class PtrClassicDefaultHeader extends ConstraintLayout implements PtrUIHandler {
private int mRotateAniTime = 150;
private RotateAnimation mFlipAnimation;
private RotateAnimation mReverseFlipAnimation;
private TextView headerPtrState;
private View mRotateView;
private View mProgressBar;
public PtrClassicDefaultHeader(Context context) {
super(context);
initViews(null);
}
public PtrClassicDefaultHeader(Context context, AttributeSet attrs) {
super(context, attrs);
initViews(attrs);
}
public PtrClassicDefaultHeader(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initViews(attrs);
}
protected void initViews(AttributeSet attrs) {
TypedArray arr = getContext().obtainStyledAttributes(attrs, R.styleable.PtrClassicHeader, 0, 0);
if (arr != null) {
mRotateAniTime = arr.getInt(R.styleable.PtrClassicHeader_ptr_rotate_ani_time, mRotateAniTime);
}
arr.recycle();
buildAnimation();
View header = LayoutInflater.from(getContext()).inflate(R.layout.header_loading, this);
mRotateView = header.findViewById(R.id.header_rotate_view);
headerPtrState = header.findViewById(R.id.header_ptr_state);
mProgressBar = header.findViewById(R.id.header_rotate_view_progressbar);
int height = (int) getResources().getDimension(R.dimen.dp_60);
ViewGroup.LayoutParams prtLayoutParams = new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, height);
header.setLayoutParams(prtLayoutParams);
resetView();
}
private void buildAnimation() {
mFlipAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
mFlipAnimation.setInterpolator(new LinearInterpolator());
mFlipAnimation.setDuration(mRotateAniTime);
mFlipAnimation.setFillAfter(true);
mReverseFlipAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
mReverseFlipAnimation.setInterpolator(new LinearInterpolator());
mReverseFlipAnimation.setDuration(mRotateAniTime);
mReverseFlipAnimation.setFillAfter(true);
}
private void resetView() {
hideRotateView();
mProgressBar.setVisibility(INVISIBLE);
}
private void hideRotateView() {
mRotateView.clearAnimation();
mRotateView.setVisibility(INVISIBLE);
}
@Override
public void onUIReset(PtrFrameLayout frame) {
resetView();
}
@Override
public void onUIRefreshPrepare(PtrFrameLayout frame) {
mProgressBar.setVisibility(INVISIBLE);
mRotateView.setVisibility(VISIBLE);
if (frame.isPullToRefresh()) {
headerPtrState.setText(getResources().getString(R.string.pull_down_to_refresh));
} else {
headerPtrState.setText(getResources().getString(R.string.pull_down));
}
}
@Override
public void onUIRefreshBegin(PtrFrameLayout frame) {
hideRotateView();
mProgressBar.setVisibility(VISIBLE);
headerPtrState.setText(R.string.refreshing);
}
@Override
public void onUIRefreshComplete(PtrFrameLayout frame) {
hideRotateView();
mProgressBar.setVisibility(INVISIBLE);
mRotateView.setVisibility(VISIBLE);
headerPtrState.setText(getResources().getString(R.string.refresh_complete));
}
@Override
public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
final int mOffsetToRefresh = frame.getOffsetToRefresh();
final int currentPos = ptrIndicator.getCurrentPosY();
final int lastPos = ptrIndicator.getLastPosY();
if (currentPos < mOffsetToRefresh && lastPos >= mOffsetToRefresh) {
if (isUnderTouch && status == PtrFrameLayout.PTR_STATUS_PREPARE) {
crossRotateLineFromBottomUnderTouch(frame);
if (mRotateView != null) {
mRotateView.clearAnimation();
mRotateView.startAnimation(mReverseFlipAnimation);
}
}
} else if (currentPos > mOffsetToRefresh && lastPos <= mOffsetToRefresh) {
if (isUnderTouch && status == PtrFrameLayout.PTR_STATUS_PREPARE) {
crossRotateLineFromTopUnderTouch(frame);
if (mRotateView != null) {
mRotateView.clearAnimation();
mRotateView.startAnimation(mFlipAnimation);
}
}
}
}
private void crossRotateLineFromTopUnderTouch(PtrFrameLayout frame) {
if (!frame.isPullToRefresh()) {
headerPtrState.setText(R.string.release_to_refresh);
}
}
private void crossRotateLineFromBottomUnderTouch(PtrFrameLayout frame) {
if (frame.isPullToRefresh()) {
headerPtrState.setText(getResources().getString(R.string.pull_down_to_refresh));
} else {
headerPtrState.setText(getResources().getString(R.string.pull_down));
}
}
}
```
|
70n1/MartinA_U2
|
70n1/MartinA_U2
Tab2.java
```package com.el70n1.martina_u2;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
/**
* Created by motoni on 23/09/2016.
*/
public class Tab2 extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab2, container, false);
}
/*
public void sePulsa(View view){
Toast.makeText(getActivity(), "Pulsado", Toast.LENGTH_SHORT).show();
}
*/
}
```
MainActivity.java
```package com.el70n1.martina_u2;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
private FragmentTabHost tabHost;
private double operando_1 = 0;
private double operando_2 = 0;
private double ratio_euro = 166.39;
private boolean realizando_operacion = false;
private boolean en_euros = true;
private boolean reseteando = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(),android.R.id.tabcontent);
tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Asteroides"),
Tab1.class, null);
tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("Botón"),
Tab2.class, null);
tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("Calculadora"),
Tab3.class, null);
}
public void sePulsa(View view){
Toast.makeText(this, "Pulsado", Toast.LENGTH_SHORT).show();
}
public void pulsado_boton_calculadora(View view) {
String resourceEntryName = getResources().getResourceEntryName(view.getId());
if ((reseteando) && (!(resourceEntryName.equals("button_pasar_moneda")))) {
operando_1 = 0;
operando_2 = 0;
realizando_operacion = false;
reseteando= false;
}
if (resourceEntryName.equals("button_calc_0")) {
anyadir_numero_calculadora(0);
}
if (resourceEntryName.equals("button_calc_1")) {
anyadir_numero_calculadora(1);
}
if (resourceEntryName.equals("button_calc_2")) {
anyadir_numero_calculadora(2);
}
if (resourceEntryName.equals("button_calc_3")) {
anyadir_numero_calculadora(3);
}
if (resourceEntryName.equals("button_calc_4")) {
anyadir_numero_calculadora(4);
}
if (resourceEntryName.equals("button_calc_5")) {
anyadir_numero_calculadora(5);
}
if (resourceEntryName.equals("button_calc_6")) {
anyadir_numero_calculadora(6);
}
if (resourceEntryName.equals("button_calc_7")) {
anyadir_numero_calculadora(7);
}
if (resourceEntryName.equals("button_calc_8")) {
anyadir_numero_calculadora(8);
}
if (resourceEntryName.equals("button_calc_9")) {
anyadir_numero_calculadora(9);
}
if (resourceEntryName.equals("button_calc_mas")) {
operando_1 = operando_1 + operando_2;
operando_2 = 0;
realizando_operacion = true;
}
if (resourceEntryName.equals("button_calc_igual")) {
operando_1 = operando_1 + operando_2;
operando_2 = 0;
realizando_operacion = false;
}
if (resourceEntryName.equals("button_calc_c")) {
operando_1 = 0;
operando_2 = 0;
realizando_operacion = false;
}
if (resourceEntryName.equals("button_pasar_moneda")){
if (en_euros) {
operando_1 = operando_1 * ratio_euro;
operando_2 = operando_2 * ratio_euro;
((Button) findViewById(R.id.button_pasar_moneda)).setText("pasar a Euros");
} else {
if (operando_1>0) {
operando_1 = operando_1 / ratio_euro;
} else {
operando_1 = 0;
}
if (operando_2>0) {
operando_2 = operando_2 / ratio_euro;
} else {
operando_2 = 0;
}
((Button) findViewById(R.id.button_pasar_moneda)).setText("pasar a pesetas");
}
en_euros = !(en_euros);
reseteando = true;
}
mostrar_display();
}
private void mostrar_display() {
String numero_a_mostrar="";
if (realizando_operacion) {
numero_a_mostrar = prettyPrint(operando_2);
} else{
numero_a_mostrar = prettyPrint(operando_1);
}
if (en_euros) {
((TextView) findViewById(R.id.display_calculadora)).setText(numero_a_mostrar +" €");
} else {
((TextView) findViewById(R.id.display_calculadora)).setText(numero_a_mostrar +" ptas");
}
}
public static String prettyPrint(double d) {
int i = (int) d;
return d == i ? String.valueOf(i) : String.format("%.2f", d);
}
private void anyadir_numero_calculadora(int numero){
if (realizando_operacion) {
operando_2 = (operando_2 *10) + numero;
} else {
operando_1 = (operando_1 *10) + numero;
}
}
}
```
|
71D3R/datos
|
71D3R/datos
README.md
```##REQUISITOS
- Java 1.7 o superior
- 7zip
##INSTALACIÓN
1. Del lado derecho seleccione **Download ZIP**.
2. Extraerlo en la carpeta de su preferencia.
3. Abrir la carpeta extraida **solr* **.
4. Buscar el archivo **txt.7z** y extraerlo ahi mismo, usar el password
> **_Marie cuelga. Antes de salir, descarga la Glock y la deja en el_**
se creara una carpeta llamada txt.
##CONFIGURACIÓN
###LINUX & MAC OS X
1. Abrir una terminal en la carpeta solr extraida anteriormente y ejecutar el comando _**ls**_, debe mostrar la siguiente estructura
```sh
[71d3r@pc solr-4.10.3]$ ls
bin contrib docs licenses LUCENE_CHANGES.txt README.txt txt
CHANGES.txt dist example LICENSE.txt NOTICE.txt SYSTEM_REQUIREMENTS.txt txt.7z
```
2. Ejecutar el comando
```sh
bin/solr start -e cloud -noprompt
```
Mostrara una salida en pantalla similar a la siguiente
```sh
[71d3r@pc solr-4.10.3]$ bin/solr start -e cloud -noprompt
which: no lsof in (/usr/local/sbin:/usr/local/bin:/usr/bin:/opt/android-sdk/tools:/usr/lib/jvm/default/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl)
Welcome to the SolrCloud example!
Starting up 2 Solr nodes for your example SolrCloud cluster.
Cloning /home/71d3r/git/datos/solr-4.10.3/example into /home/71d3r/git/datos/solr-4.10.3/node1
Cloning /home/71d3r/git/datos/solr-4.10.3/example into /home/71d3r/git/datos/solr-4.10.3/node2
Starting up SolrCloud node1 on port 8983 using command:
solr start -cloud -d node1 -p 8983
Started Solr server on port 8983 (pid=7332). Happy searching!
```
Si todo salio bien, en este [link](http://localhost:8983/solr/ "solr") se podra ver el panel de administración similar a este

3. Despues de que el panel de administración se muestre correctamente, se agregaran todos los registros al buscador con el siguiente comando
```sh
java -classpath dist/solr-core-4.10.3.jar -Dauto -Drecursive org.apache.solr.util.SimplePostTool txt/
```
El tiempo que tarde en completarse este comando dependera del equipo en donde sea ejecutado.
Cuando termine mostrara un mensaje similar a este
```sh
#### files indexed.
COMMITting Solr index changes to http://localhost:8983/solr/update..
Time spent: #:##:##.###
```
###WINDOWS
1. Abrir una consola **CMD** y cambiar al directorio de **Solr**, si esta en windows 7 o superior, ejecutar la consola como administrador y asegurarse de que en el PATH de Windows se encuentre java, para eso ejecute el comando.
```sh
java -version
javac -version
```

Si el mensaje no es similar al mostrado en la imagen utilice [esta guia](https://www.java.com/es/download/help/path.xml) para agregar Java al PATH de Windows
2. Ejecutar el comando
```sh
java -jar example\start.jar
```
Si todo salio bien, en este [link](http://localhost:8983/solr/ "solr") se podra ver el panel de administración similar a este

3. Despues de que el panel de administración se muestre correctamente, se agregaran todos los registros al buscador ejecutando el siguiente comando en otra ventana de terminal
```sh
java -classpath dist\solr-core-4.10.3.jar -Dauto -Drecursive org.apache.solr.util.SimplePostTool txt\
```
El tiempo que tarde en completarse este comando dependera del equipo en donde sea ejecutado.
Cuando termine mostrara un mensaje similar a este
```sh
#### files indexed.
COMMITting Solr index changes to http://localhost:8983/solr/update..
Time spent: #:##:##.###
```
##USO
Para empezar a usar el buscador basta con ir a este [link](http://localhost:8983/solr/collection1/browse) e ingresar en el cuadro de texto el dato a buscar.
(Para abrir los archivos en una nueva pestaña presionar **Control+Click**.
Cuando haya terminado utilice el siguiente comando para detener el servidor.
###Linux & MAC OS X
```sh
bin/solr stop -all
```
###Windows
Presione Control+c donde ejecuto **java -jar example\start.jar** o en una ventana nueva ejecute
```sh
bin\solr.cmd stop -all
```
```
|
71emj/Reintroduction-to-Javascript
|
71emj/Reintroduction-to-Javascript
excercise-5.js
```const urlSample = new Array;
urlSample[0] = "https://en.wikipedia.org/w/api.php?&origin=*&action=opensearch&search=Ludwig_Mies_van_der_Rohe&limit=10";
urlSample[1] = "/w/api.php?action=query&format=json&maxage=0&origin=*&prop=info%7Cextracts%7Cimages&list=search&meta=&indexpageids=1&titles=Main%20Page&pageids=&callback=&inprop=url%7Cdisplaytitle&intestactions=&imlimit=2&srsearch=Ludwig%20Mies%20van%20derRohe&srnamespace=&srlimit=5";
for (let i = 0; i < urlSample.length; i++) {
fetch(urlSample[i])
.then(function(resp) {
console.log(resp);
return resp.json();
}).then(function(data) {
console.log(data)
});
}
```
excercise-1.js
```/*
navigator.geolocation.getCurrentPosition(success[ , error[ , options]])
*/
/*
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
};
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
};
navigator.geolocation.getCurrentPosition(success, error, options);
*/
(function mapInit() {
"use strict";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(pos) {
const contentBody = document.querySelector('.content-body'),
mapViewPort = contentBody.appendChild(document.createElement('div')),
para = contentBody.insertBefore(document.createElement('p'), mapViewPort);
mapViewPort.setAttribute('id', 'map_canvas');
para.appendChild(document.createTextNode(
'This is where we are right now :)'));
const latlng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
myLoc = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN,
disableDefaultUI: true
},
//create new google map instances
map = new google.maps.Map(mapViewPort, myLoc),
iconBaseUrl = 'https://mt.google.com/vt/icon/name=icons/onion/SHARED-mymaps-container_4x.png,icons/onion/',
marker = new google.maps.Marker({
position: latlng,
icon: (`https://mt.google.com/vt/icon/name=icons/onion/SHARED-mymaps-pin-container_4x.png,icons/onion/1899-blank-shape_pin_4x.png&highlight=000000,ff000000&scale=1.0`),
map: map,
});
}, function() {
console.log('error');
const para = document
.querySelector('.content-body')
.appendChild(document.createElement('p')),
msg = {
denied: 'Why do you reject me? :-(',
other: 'Argh, no geolocation!'
};
//check if the error is caused by user rejection
para.appendChild(document.createTextNode(!(navigator.permissions.state === 'granted') ? msg.denied : msg.other));
});
} else { //else statement not processing
const msg = 'It seems to me your browser don\'t have geolocation~',
para = document
.querySelector('.content-body')
.appendChild(document.createElement('p'));
para.textContent = msg;
}
}());
```
excercise-3.js
```(function() {
"use strict";
const verseChoose = document.querySelector('article.content-body select'),
poemDisplay = document.querySelector('pre#text-display');
const s = new XMLSerializer(),
d = document.querySelector('body');
poemDisplay.textContent = s.serializeToString(d);
verseChoose.addEventListener('change', function(e) {
const verse = e.target.value;
updateDisplay(verse);
});
/*
function updateDisplay(verse) {
verse = verse.replace(/[^a-z]/, "");
verse = verse.toLowerCase();
const url = (`text/${verse}.txt`),
request = new XMLHttpRequest();
request.open('GET', url);
request.reponseType = 'text';
request.onload = function() {
poemDisplay.textContent = request.response;
};
request.send();
}
*/
function updateDisplay(verse) {
verse = verse.replace(/[^a-z]/, "");
verse = verse.toLowerCase();
const url = (`text/${verse}.txt`);
console.log(fetch(url));
console.log(typeof(fetch(url)));
console.log();
fetch(url).then(function (response) {
response.text().then(function (text) {
poemDisplay.textContent = text;
});
});
}
}());```
excercise-2.js
```(function() {
"use strict";
const btnSubmit = document.querySelector('form input[type="submit"]'),
defaultMsg = 'Type list items you wish to print out on the list',
inputArea = document.querySelector('#data-entry'),
listArea = document.querySelector('article>ul.generated-list');
inputArea.placeholder = defaultMsg;
btnSubmit.addEventListener('click', function (e) {
if (e.target && e.target.matches('input[type="submit"]')) {
console.log(e);
e.preventDefault();
/* create a new <li> object every time the button is clicked */
const list_obj = new listObj(listArea);
list_obj.styleInit();
list_obj.setContent(
inputArea.value,
listArea.querySelectorAll('li').length,
listArea
);
/* for reason unknown the height assignment within the object method is bugged
I need to apply it here to align all childrenNode within a <li> */
list_obj.listItem.style.height = list_obj.listIndex.style.height =
(`${list_obj.delBtn.getBoundingClientRect().height}px`);
inputArea.value = "";
console.log('success');
};
});
}());
/*
this is an independent snippet of an object definition
can be split to another document with no reference problem...I think...
*/
function listObj(listArea) {
/* listArea is the ul/ol object you wish to populate */
const genList = listArea.appendChild(document.createElement('li'));
this.listIndex = genList.appendChild(document.createElement('span'));
this.listItem = genList.appendChild(document.createElement('span'));
this.delBtn = genList.appendChild(document.createElement('button'));
};
listObj.prototype.styleInit = function () {
this.listIndex.className += 'three columns';
this.listItem.className += 'six columns';
this.delBtn.className += 'three columns';
//this.listItem.style.height = (`${this.delBtn.getBoundingClientRect().height}px !important`);
/* for some reason this assignment is not working */
this.delBtn.innerHTML = 'delete';
};
listObj.prototype.setContent = function (value, listLen, listArea) {
this.listIndex.innerText = (`Item 00${listLen}`);
this.listItem.innerText = value === "" || value === " " ? 'n/a' : value;
this.delBtn.addEventListener('click', function (e) {
/* find out the index of the node, record it and modify the rest of the index */
const delItem = e.target.parentNode,
listArray = Array.from(document.querySelectorAll('li')),
delIndex = listArray.indexOf(delItem);
/* changes only needs to apply to items that comes after the deleted object */
for (let i = delIndex, max = listArray.length; i < max; i++) {
listArray[i].firstChild.innerText = (`Item 00${i}`);
}
/* remove the child <li> the button resides in from the list */
listArea.removeChild(delItem);
})
};```
index.js
```const pageHead = document.getElementById('header'),
body = document.querySelector('body');
document.addEventListener('scroll', function(e) {
//both e and this refers to the #document, which is not what we want here
window.pageYOffset > 0 ?
pageHead.style.boxShadow = '0px 0px 12px 1px rgba(0,0,0,0.15)':
pageHead.style.boxShadow = 'none';
})
```
|
723854867/Iris
|
723854867/Iris
BeanCreator.java
```package org.Iris.app.jilu.common;
import org.Iris.app.jilu.common.bean.model.AccountModel;
import org.Iris.app.jilu.storage.domain.MemAccount;
import org.Iris.app.jilu.storage.domain.MemMerchant;
import org.Iris.util.lang.DateUtils;
public class BeanCreator {
public static MemMerchant newMemMerchant(String name, String avatar, String address) {
MemMerchant memMerchant = new MemMerchant();
memMerchant.setAddress(address);
memMerchant.setAvatar(avatar);
memMerchant.setName(name);
int time = DateUtils.currentTime();
memMerchant.setCreated(time);
memMerchant.setUpdated(time);
memMerchant.setLastLoginTime(time);
return memMerchant;
}
public static MemAccount newMemAccount(AccountModel am, int time, long merchantId) {
MemAccount memAccount = new MemAccount();
memAccount.setMerchantId(merchantId);
memAccount.setAccount(am.getAccount());
memAccount.setType(am.getType());
memAccount.setUpdated(time);
memAccount.setCreated(time);
return memAccount;
}
}
```
MemMerchantMapper.java
```package org.Iris.app.jilu.storage.mybatis.mapper;
import org.Iris.app.jilu.storage.domain.MemMerchant;
import org.Iris.app.jilu.storage.mybatis.SQLBuilder.MemMerchantSQLBuilder;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.SelectProvider;
public interface MemMerchantMapper {
@SelectProvider(type = MemMerchantSQLBuilder.class, method = "getByMerchantId")
MemMerchant getByMerchantId(long merchantId);
@InsertProvider(type = MemMerchantSQLBuilder.class, method = "insert")
@Options(useGeneratedKeys = true, keyColumn = "merchant_id", keyProperty = "merchantId")
void insert(MemMerchant memMerchant);
void update(MemMerchant memMerchant);
}
```
IrisBoolConst.java
```package org.Iris.core.consts;
public class IrisBoolConst extends IrisConstImpl<Boolean> {
public IrisBoolConst(String key, boolean value) {
super(key, value);
}
public IrisBoolConst(String key, boolean value, int constId) {
super(key, value, constId);
}
@Override
protected Boolean parseValue(String value) {
return Boolean.valueOf(value);
}
}
```
LuaOperateTest.java
```package org.Iris.redis.operate.lua;
import org.Iris.redis.BaseTest;
import org.Iris.redis.bean.User;
public class LuaOperateTest extends BaseTest {
private LuaOperate luaOperate;
private LuaCache luaCache;
@Override
protected void setUp() throws Exception {
super.setUp();
luaCache = new LuaCache();
luaOperate = new LuaOperate();
luaOperate.setLuaCache(luaCache);
luaOperate.setRedisOperate(redisOperate);
}
public void testRecordMobileCode() {
long value = luaOperate.recordCaptcha("code", "codeCount", "1235", 20000, 3, 30000);
System.out.println(value);
}
public void testHdelAndGet() {
User user = luaOperate.hdelAndGet("user", new User());
System.err.println(user.getAge() + " " + user.getName());
}
}
```
Table.java
```package org.Iris.app.jilu.storage.mybatis;
public enum Table {
MEM_MERCHANT("mem_merchant"),
MEM_ACCOUNT("mem_account");
private String mark;
private Table(String mark) {
this.mark = mark;
}
public String mark() {
return mark;
}
}
```
StringUtil.java
```package org.Iris.util.lang;
public class StringUtil {
public static final String EMPTY = "";
/**
* 去掉字符串的头尾空格,任何空格都算,比如制表符,换行符,回车,全角空格等
*
* @param str
* @return
*/
public static String trimWhitespace(String str) {
if (!hasLength(str))
return str;
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0)))
sb.deleteCharAt(0);
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1)))
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
/**
* @see #hasLength(CharSequence)
* @param str
* @return
*/
public static boolean hasLength(String str) {
return hasLength((CharSequence) str);
}
/**
* 任何空格都算在内
*
* @param str
* @return
*/
public static boolean hasLength(CharSequence str) {
return (str != null && str.length() > 0);
}
/**
* 替换字符串
*
* @param string
* @param oldPattern
* @param newPattern
* @return
*/
public static String replace(String string, String oldPattern, String newPattern) {
if (!hasLength(string) || !hasLength(oldPattern) || newPattern == null)
return string;
StringBuilder sb = new StringBuilder();
int pos = 0;
int index = string.indexOf(oldPattern);
int patLen = oldPattern.length();
while (index >= 0) {
sb.append(string.substring(pos, index));
sb.append(newPattern);
pos = index + patLen;
index = string.indexOf(oldPattern, pos);
}
sb.append(string.substring(pos));
return sb.toString();
}
public static boolean hasText(String str) {
return hasText((CharSequence) str);
}
public static boolean hasText(CharSequence str) {
if (!hasLength(str))
return false;
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i)))
return true;
}
return false;
}
}
```
RedisCache.java
```package org.Iris.app.jilu.storage.redis.cache;
import javax.annotation.Resource;
import org.Iris.redis.RedisHashBean;
import org.Iris.redis.operate.RedisOperate;
import org.Iris.util.reflect.BeanUtils;
public abstract class RedisCache {
@Resource
protected RedisOperate redisOperate;
protected <T extends RedisHashBean> T getHashBean(T bean) {
return redisOperate.hgetAll(bean.redisKey(), bean);
}
public void flushHashBean(RedisHashBean bean) {
redisOperate.hmset(bean.redisKey(), BeanUtils.beanToMap(bean));
}
}
```
MerchantServlet.java
```package org.Iris.app.jilu.web.servlet;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.Iris.app.jilu.service.action.UnitAction;
import org.Iris.app.jilu.service.realm.unit.merchant.Merchant;
import org.Iris.app.jilu.web.IrisServlet;
import org.Iris.app.jilu.web.JiLuParams;
import org.Iris.app.jilu.web.auth.MerchantAuthenticator;
import org.Iris.app.jilu.web.session.MerchantSession;
import org.Iris.core.exception.IllegalConstException;
import org.Iris.core.service.bean.Result;
import org.Iris.core.service.locale.ICode;
import org.Iris.core.util.SpringContextUtil;
/**
* 和商户相关的 Servlet
*
* @author Ahab
*/
public class MerchantServlet extends IrisServlet<MerchantSession> {
private static final long serialVersionUID = -3144141122029756489L;
protected Map<String, UnitAction<?>> serialActions = new HashMap<String, UnitAction<?>>();
protected Map<String, UnitAction<?>> parallelActions = new HashMap<String, UnitAction<?>>();
@Override
protected MerchantSession buildSession(HttpServletRequest request, HttpServletResponse response) {
return new MerchantSession(request, response);
}
@Override
public void init() throws ServletException {
super.init();
this.authenticator = SpringContextUtil.getBean("merchantAuthenticator", MerchantAuthenticator.class);
}
@Override
protected void receive(MerchantSession session) {
boolean serial = session.getKVParamOptional(JiLuParams.SERIAL);
String action = session.getKVParam(JiLuParams.ACTION);
UnitAction<?> unitAction = serial ? serialActions.get(action) : parallelActions.get(action);
if (null == unitAction)
throw IllegalConstException.errorException(JiLuParams.ACTION);
if (serial) {
Merchant merchant = session.getUnit();
String lockId = merchant.tryLock();
if (null == lockId) {
session.write(Result.jsonError(ICode.Code.REQUEST_FREQUENTLY));
return;
}
try {
unitAction.execute(session);
} finally {
merchant.unLock(lockId);
}
} else
unitAction.execute(session);
}
}
```
CAPTCHA_GET.java
```package org.Iris.app.jilu.service.action.common;
import org.Iris.app.jilu.common.AppConfig;
import org.Iris.app.jilu.common.model.AccountType;
import org.Iris.app.jilu.common.model.Env;
import org.Iris.app.jilu.service.action.CommonAction;
import org.Iris.app.jilu.storage.redis.RedisKeyGenerator;
import org.Iris.app.jilu.web.JiLuCode;
import org.Iris.app.jilu.web.JiLuParams;
import org.Iris.app.jilu.web.session.IrisSession;
import org.Iris.core.service.bean.Result;
import org.Iris.core.service.locale.ICode;
import org.Iris.util.common.KeyUtil;
/**
* 获取验证码(手机和邮箱获取验证码的规则是一样的)
*
* @author ahab
*/
public class CAPTCHA_GET extends CommonAction {
public static final CAPTCHA_GET INSTANCE = new CAPTCHA_GET();
private CAPTCHA_GET() {}
@Override
protected String execute0(IrisSession session) {
AccountType type = AccountType.match(session.getKVParamOptional(JiLuParams.TYPE));
String account = type == AccountType.MOBILE ? session.getKVParam(JiLuParams.MOBILE) : session.getKVParam(JiLuParams.EMAIL);
String captchaKey = RedisKeyGenerator.getAccountCaptchaKey(type, account);
String captchaCountKey = RedisKeyGenerator.getAccountCaptchaCountKey(type, account);
// 生成验证码并且缓存验证码
String captcha = KeyUtil.randomCaptcha(AppConfig.getCaptchaDigit());
long flag = luaOperate.recordCaptcha(captchaKey, captchaCountKey, captcha,
AppConfig.getCaptchaLifeTime(), AppConfig.getCaptchaCountMaximum(), AppConfig.getCaptchaCountLifeTime());
if (-1 == flag)
return Result.jsonError(JiLuCode.CAPTCHA_GET_CD);
if (-2 == flag)
return Result.jsonError(JiLuCode.CAPTCHA_COUNT_LIMIT);
Env env = AppConfig.getEnv();
switch (env) {
case LOCAL: // 测试环境下直接返回验证码
case TEST:
return Result.jsonSuccess(captcha);
case ONLINE: // 线上环境需要发送短信
jmsService.sendCaptchaMessage(type, account, captcha);
return Result.jsonSuccess();
default:
return Result.jsonError(ICode.Code.SYSTEM_ERROR);
}
}
}
```
AppConfig.java
```package org.Iris.app.jilu.common;
import org.Iris.app.jilu.common.model.Config;
public class AppConfig extends Config {
public static final int CREATE_WAIT_TIMEOUT = 180;
private static int captchaDigit; // 验证码位数
private static int captchaLifeTime; // 验证码有效时间
private static int captchaCountMaximum; // 验证码获取次数限制,一般和 codeCountLifeTime 一起限制验证码的获取频率
private static int captchaCountLifeTime; // 验证码次数累加超时时间,超过该时间没有获取验证码则次数清零
public static int getCaptchaDigit() {
return captchaDigit;
}
public static void setCaptchaDigit(int captchaDigit) {
AppConfig.captchaDigit = captchaDigit;
}
public static int getCaptchaLifeTime() {
return captchaLifeTime;
}
public static void setCaptchaLifeTime(int captchaLifeTime) {
AppConfig.captchaLifeTime = captchaLifeTime;
}
public static int getCaptchaCountMaximum() {
return captchaCountMaximum;
}
public static void setCaptchaCountMaximum(int captchaCountMaximum) {
AppConfig.captchaCountMaximum = captchaCountMaximum;
}
public static int getCaptchaCountLifeTime() {
return captchaCountLifeTime;
}
public static void setCaptchaCountLifeTime(int captchaCountLifeTime) {
AppConfig.captchaCountLifeTime = captchaCountLifeTime;
}
}
```
Unit.java
```package org.Iris.app.jilu.service.realm.unit;
import org.Iris.app.jilu.common.Beans;
public interface Unit extends Beans {
long uid();
UnitType unitType();
}
```
Callback.java
```package org.Iris.util.common;
public interface Callback<T> {
T execute();
}
```
BeanException.java
```package org.Iris.core.exception;
public class BeanException extends IrisRuntimeException {
private static final long serialVersionUID = 7075752118345682318L;
public BeanException(String message) {
super(message);
}
public BeanException(String message, Throwable cause) {
super(message, cause);
}
}
```
UserSqlProvider.java
```package org.Iris.app.web.template.service.persistence.provider;
import org.apache.ibatis.jdbc.SQL;
public class UserSqlProvider {
public String selectAll() {
return new SQL(){
{
SELECT("*");
FROM("user");
}
}.toString();
}
}
```
IrisSession.java
```package org.Iris.app.jilu.web.session;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.Iris.core.consts.IrisConst;
import org.Iris.core.exception.IllegalConstException;
import org.Iris.core.exception.IrisRuntimeException;
import org.Iris.util.common.ConstsPool;
import org.Iris.util.common.MiMeType;
import org.springframework.http.HttpHeaders;
/**
* 默认使用 json
*
* @author Ahab
*/
public class IrisSession {
private HttpServletRequest request;
private HttpServletResponse response;
public IrisSession(HttpServletRequest request, HttpServletResponse response) {
this.request = request;
this.response = response;
response.setHeader(HttpHeaders.CONTENT_TYPE, MiMeType.TEXT_JSON_UTF_8);
response.setCharacterEncoding(ConstsPool.UTF_8.name());
}
/**
* 获取 key - value 形式的键值对,URL 之后的参数,以及 x-www-form-urlencoded 编码的参数可以使用此种方式来获取
*
* @param constant
* @return
* @throws IllegalConstException
*/
public <T> T getKVParam(IrisConst<T> constant) throws IllegalConstException {
String val = request.getParameter(constant.key());
if (null == val)
throw IllegalConstException.nullException("param [" + constant.key() + "] missing!", constant);
try {
return constant.parse(val);
} catch (Exception e) {
throw IllegalConstException.exception("param [" + constant.key() + "] error!", constant);
}
}
/**
* 和 {@link #getKVParam(IrisConst)} 的不同之处在于如果参数不存在或者错误,不会抛出异常,而是返回 {@link IrisConst} 的默认值
*
* @param constant
* @return
*/
public <T> T getKVParamOptional(IrisConst<T> constant) {
try {
return getKVParam(constant);
} catch (IllegalConstException e) {
return constant.defaultValue();
}
}
/**
* 将参数转换成普通的 java 对象来调用,一般适用在 xml 或者 json 格式的调用,当然 key-value 形式的调用也可以转换成普通 java 对象
*
* @param clazz
* @return
*/
public <T> T getObjParam(Class<T> clazz) {
return null;
}
public IrisSession addHeader(String name, String value) {
response.addHeader(name, value);
return this;
}
public IrisSession setHeader(String name, String value) {
response.setHeader(name, value);
return this;
}
public IrisSession write(String reply) {
try {
response.getWriter().write(reply);
} catch (IOException e) {
throw new IrisRuntimeException("Servlet Response writer failure!", e);
}
return this;
}
public IrisSession write(byte[] reply) {
try {
response.getOutputStream().write(reply);
} catch (IOException e) {
throw new IrisRuntimeException("Servlet Response writer failure!", e);
}
return this;
}
}
```
CaptchaMessageListener.java
```package org.Iris.app.jilu.consumer.listener;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.jms.Message;
import org.Iris.app.jilu.common.model.AccountType;
import org.Iris.app.jilu.common.model.jms.CaptchaMessage;
import org.Iris.app.jilu.common.model.jms.QueueName;
import org.Iris.util.network.email.SmtpEmailSender;
import org.Iris.util.network.http.HttpProxy;
import org.Iris.util.network.http.handler.AsyncRespHandler;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class CaptchaMessageListener extends JiLuMessageListener<CaptchaMessage> {
private static final Logger logger = LoggerFactory.getLogger(CaptchaMessageListener.class);
private String PARAM_TPL_VALUE = "tpl_value";
private String PARAM_MOBILE = "mobile";
@Value("${yunPian.apiKey}")
private String yunPianKey;
@Value("${yunpian.captcha.tplId}")
private int captchaTplId;
@Value("${yunpian.captcha.tplSendUrl}")
private static String tplSendUrl;
@Resource
private HttpProxy httpProxy;
@Resource
private SmtpEmailSender emailSender;
private NameValuePair API_KEY;
private NameValuePair TPL_ID;
private CaptchaSendHandler handler;
public CaptchaMessageListener() {
super(QueueName.CAPTCHA);
}
@Override
public void handleMessage(Message message) throws Throwable {
CaptchaMessage cm = getObject(message);
AccountType type = cm.getType();
try {
switch (type) {
case MOBILE:
_sendCaptcha(cm.getAccount(), cm.getCaptcha());
break;
case EMAIL:
emailSender.sendTo("吉鹿验证码", cm.getAccount(), cm.getCaptcha());
break;
default:
throw new RuntimeException("Unsupported captcha receiver device type - " + type.name());
}
} catch (Exception e) {
logger.error("Captcha sender failure : {}!", cm, e);
}
}
private void _sendCaptcha(String mobile, String captcha) {
String tplValue = null;
try {
tplValue = URLEncoder.encode("#code#", "UTF-8") + "=" + URLEncoder.encode(captcha, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error("captcha url encode failure!", e);
return;
}
List<NameValuePair> params = new ArrayList<NameValuePair>(3);
params.add(API_KEY);
params.add(TPL_ID);
params.add(new BasicNameValuePair(PARAM_TPL_VALUE, tplValue));
params.add(new BasicNameValuePair(PARAM_MOBILE, mobile));
HttpPost method = new HttpPost(tplSendUrl);
httpProxy.asyncRequest(method, handler);
}
private class CaptchaSendHandler implements AsyncRespHandler {
@Override
public void completed(HttpResponse response) {
StatusLine statusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
try {
if (null == entity)
return;
if (statusLine.getStatusCode() >= 300)
logger.error("captcha send failure!{}, {} --- {}", statusLine.getStatusCode(), statusLine.getReasonPhrase(), EntityUtils.toString(entity));
else
logger.info("captcha send success --- {}", EntityUtils.toString(entity));
} catch (ParseException | IOException e) {
e.printStackTrace();
} finally {
try {
EntityUtils.consume(entity);
} catch (IOException e) {
logger.warn("Http entity release failure!", e);
}
}
}
@Override
public void failed(Exception ex) {
logger.error("captcha send exception!", ex);
}
@Override
public void cancelled() {
logger.warn("captcha send cancelled!");
}
}
}
```
JiLu.java
```package org.Iris.app.jilu.service;
import org.Iris.app.jilu.common.AppConfig;
import org.Iris.app.jilu.service.jms.JmsService;
import org.Iris.core.App;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JiLu extends App {
private static final Logger logger = LoggerFactory.getLogger(JiLu.class);
private JmsService jmsService;
public JiLu(String name) {
super(name);
}
@Override
public void bootstrap() {
logger.info("App - {} startup!", name);
// init jms service
this.jmsService.init(AppConfig.getEnv());
}
@Override
public void stop() {
logger.info("App - {} shutdown!", name);
}
public void setJmsService(JmsService jmsService) {
this.jmsService = jmsService;
}
}
```
SerialEventDispatcher.java
```package org.Iris.dispatcher;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.Iris.dispatcher.event.Event;
import org.Iris.dispatcher.event.EventType;
import org.Iris.dispatcher.event.IEvent;
import org.Iris.dispatcher.event.SerialEventListener;
import org.Iris.dispatcher.lane.Lane;
import org.Iris.dispatcher.lane.LaneGroup;
import org.jetlang.channels.BatchSubscriber;
import org.jetlang.channels.MemoryChannel;
import org.jetlang.core.Callback;
import org.jetlang.core.Disposable;
import org.jetlang.core.Filter;
/**
* 所有该 Dispatcher 中处理的事件都是串行的被执行(包括注册和注销 EventListener),因此不存在并发问题
*
* @author ahab
*
*/
public abstract class SerialEventDispatcher implements IEventDispatcher<SerialEventListener> {
protected Lane lane;
protected LaneGroup laneGroup;
protected MemoryChannel<IEvent> eventQueue;
private boolean closed;
protected Disposable registerDisposable;
protected Disposable deregisterDisposable;
protected Disposable disposeDisposable;
public SerialEventDispatcher(LaneGroup laneGroup) {
this.laneGroup = laneGroup;
this.lane = laneGroup.getLane();
this.eventQueue = new MemoryChannel<IEvent>();
}
protected void init() {
registerDisposable = doRegister(new RegisterListener());
deregisterDisposable = doRegister(new DeregisterListener());
disposeDisposable = doRegister(new DisposeListener());
}
@Override
public void register(SerialEventListener listener) {
publish(new Event(EventType.LISTENER_REGISTER, listener));
}
@Override
public void deregister(SerialEventListener listener) {
publish(new Event(EventType.LISTENER_DEREGISTER, listener));
}
@Override
public void publish(IEvent event) {
if (lane.isInLane())
publishEventDirect(event);
else
eventQueue.publish(event);
}
@Override
public void dispose() {
publish(new Event(EventType.DISPATCHER_DISPOSE));
}
protected abstract void onRegister(SerialEventListener listener);
protected abstract void onDeregister(SerialEventListener listener);
protected abstract void publishEventDirect(IEvent event);
protected abstract void onDispose();
protected Disposable doRegister(SerialEventListener eventListener) {
Callback<List<IEvent>> callback = createEventCallbackForListener(eventListener);
EventType eventType = eventListener.eventType();
if (eventType == EventType.ANY)
return subscribe(callback);
Filter<IEvent> filter = new Filter<IEvent>() {
@Override
public boolean passes(IEvent event) {
return (eventListener.eventType() == event.eventType());
}
};
return subscribe(callback, filter);
}
protected Callback<List<IEvent>> createEventCallbackForListener(SerialEventListener eventListener) {
Callback<List<IEvent>> eventCallback = new Callback<List<IEvent>>() {
@Override
public void onMessage(List<IEvent> messages) {
for (IEvent event : messages)
eventListener.onEvent(event);
}
};
return eventCallback;
}
protected Disposable subscribe(Callback<List<IEvent>> callback) {
BatchSubscriber<IEvent> subscriber = new BatchSubscriber<IEvent>(lane.getFiber(), callback, 0, TimeUnit.MILLISECONDS);
return eventQueue.subscribe(subscriber);
}
protected Disposable subscribe(Callback<List<IEvent>> callback, Filter<IEvent> filter) {
BatchSubscriber<IEvent> subscriber = new BatchSubscriber<IEvent>(lane.getFiber(), callback, filter, 0, TimeUnit.MILLISECONDS);
return eventQueue.subscribe(subscriber);
}
private class RegisterListener extends SerialEventListener {
@Override
public EventType eventType() {
return EventType.LISTENER_REGISTER;
}
@Override
public void onEvent(IEvent event) {
if (closed)
return;
bind(SerialEventDispatcher.this);
onRegister((SerialEventListener) event.attach());
}
}
private class DeregisterListener extends SerialEventListener {
@Override
public EventType eventType() {
return EventType.LISTENER_DEREGISTER;
}
@Override
public void onEvent(IEvent event) {
if (closed)
return;
unbind(SerialEventDispatcher.this);
onDeregister((SerialEventListener) event.attach());
}
}
private class DisposeListener extends SerialEventListener {
@Override
public EventType eventType() {
return EventType.DISPATCHER_DISPOSE;
}
@Override
public void onEvent(IEvent event) {
if (closed)
return;
deregisterDisposable.dispose();
registerDisposable.dispose();
disposeDisposable.dispose();
deregisterDisposable = null;
registerDisposable = null;
disposeDisposable = null;
onDispose();
eventQueue.clearSubscribers();
laneGroup.returnLane(lane);
laneGroup = null;
lane = null;
closed = true;
}
}
}
```
Main.java
```package org.Iris.app.jilu.consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static ClassPathXmlApplicationContext context;
private static volatile boolean running = true;
public static void main(String[] args) {
System.setProperty("logback.configurationFile", "classpath:logback.xml");
context = new ClassPathXmlApplicationContext("classpath:spring/spring-*.xml");
context.start();
logger.info("JiLu mqconsumer start!");
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
context.stop();
logger.info("JiLu mqconsumer stopped!");
} catch (Throwable t) {
logger.error(t.getMessage(), t);
}
synchronized (Main.class) {
running = false;
Main.class.notify();
}
}
});
synchronized (Main.class) {
while (running) {
try {
Main.class.wait();
} catch (Throwable e) {}
}
}
}
}
```
JiLuMessageListener.java
```package org.Iris.app.jilu.consumer.listener;
import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;
import org.Iris.app.jilu.consumer.QueueNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class JiLuMessageListener<T> implements MessageListener {
private static final Logger logger = LoggerFactory.getLogger(JiLuMessageListener.class);
protected int concurrentConsumers = 1; // 默认为1
private String queueName;
@Resource
private QueueNames queueNames;
public JiLuMessageListener(String queueName) {
this.queueName = queueName;
}
@Override
public void onMessage(Message message) {
try {
logger.info("ActiveMQ message received, id = {}", message.getJMSMessageID());
handleMessage(message);
} catch (Throwable e) {
logger.error("ActiveMQ message process error!", e);
}
}
public abstract void handleMessage(Message message) throws Throwable;
@SuppressWarnings("unchecked")
protected T getObject(Message message) throws JMSException {
ObjectMessage om = (ObjectMessage) message;
return (T) om.getObject();
}
protected String getText(Message message) throws JMSException {
TextMessage tm = (TextMessage) message;
return tm.getText();
}
public String getDestination() {
return queueNames.getDestination(queueName);
}
public void setConcurrentConsumers(int concurrentConsumers) {
this.concurrentConsumers = concurrentConsumers;
}
public int getConcurrentConsumers() {
return concurrentConsumers;
}
}
```
UserCache.java
```package org.Iris.app.jilu.storage.redis.cache;
import org.Iris.app.jilu.common.model.AccountType;
import org.Iris.app.jilu.storage.domain.MemMerchant;
import org.Iris.app.jilu.storage.mybatis.mapper.MemMerchantMapper;
import org.Iris.app.jilu.storage.redis.RedisKeyGenerator;
import org.Iris.redis.operate.RedisOperate;
import org.Iris.util.reflect.BeanUtils;
/**
* 负责所有用户相关的数据存取:比如 mem_merchant,mem_customer等
*
* @author Ahab
*/
public class UserCache {
private MemMerchantMapper memUserMapper;
private RedisOperate redisOperate;
public MemMerchant getById(long uid) {
MemMerchant memUser = redisOperate.hgetAll(RedisKeyGenerator.getMemMerchantDataKey(uid), new MemMerchant());
if (null != memUser)
return memUser;
memUser = memUserMapper.getByMerchantId(uid);
if (null == memUser)
return null;
_flushCache(memUser);
return memUser;
}
public MemMerchant getMerchantByAccount(AccountType type, String account) {
return null;
}
public void insert(MemMerchant memUser) {
}
private void _flushCache(MemMerchant memUser) {
redisOperate.hmset(RedisKeyGenerator.getMemMerchantDataKey(memUser.getMerchantId()), BeanUtils.beanToMap(memUser));
}
}
```
Main.java
```package org.Iris.redis;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
public class Main {
public static void main(String[] args) {
HostAndPort hostAndPort = new HostAndPort("121.42.155.96", 6000);
Jedis jedis = new Jedis(hostAndPort.getHost(), hostAndPort.getPort(), 2000,
2000, false, null, null, null);
jedis.connect();
System.out.println(jedis.auth("zxl870613"));
}
}
```
ParallelEventDispatcher.java
```package org.Iris.dispatcher;
import org.Iris.dispatcher.event.IEvent;
import org.Iris.dispatcher.event.IEventListener;
import org.Iris.dispatcher.lane.Lane;
import org.Iris.dispatcher.lane.LaneGroup;
/**
* <pre>
* 并行 EventDispatcher,该类型的 Dispatcher 一般是多个线程共享,因此需要处理好并发问题,一般仅作模块解耦用。
*
* 注意:
* 注册到该 Dispatcher 的 IEventListener 能被多个 Dispatcher 使用,因此其 onEvent 方法要保证线程安全。
* </pre>
*
* @author Ahab
*/
public class ParallelEventDispatcher implements IEventDispatcher<IEventListener> {
private LaneGroup LaneGroup;
public ParallelEventDispatcher(LaneGroup laneGroup) {
this.LaneGroup = laneGroup;
}
@Override
public void register(IEventListener eventListener) {
}
@Override
public void deregister(IEventListener eventListener) {
// TODO Auto-generated method stub
}
@Override
public void publish(IEvent event) {
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
private class LaneDispatcher implements IEventDispatcher<IEventListener> {
private Lane lane;
public LaneDispatcher(LaneGroup laneGroup) {
this.lane = laneGroup.getLane();
}
@Override
public void register(IEventListener listener) {
}
@Override
public void deregister(IEventListener listener) {
}
@Override
public void publish(IEvent event) {
}
@Override
public void dispose() {
}
}
}
```
ErrorHandler.java
```package org.Iris.app.jilu.web.handler;
import org.Iris.app.jilu.web.session.IrisSession;
import org.Iris.core.exception.IllegalConstException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 专门用来处理错误的 handler
*
* @author ahab
*/
public interface ErrorHandler {
/**
* 当参数不存在时的处理回调
*
* @param session
*/
void onParamNull(IrisSession session, IllegalConstException exception);
/**
* 当参数错误(包括字符串长度不对,类型转换错误等)时的处理回调
*
* @param session
*/
void onParamError(IrisSession session, IllegalConstException exception);
/**
* 当服务器出现异常错误时被调用
*
* @param session
*/
void onServerError(IrisSession session, Exception exception);
class DefaultErrorHandler implements ErrorHandler {
private static final Logger logger = LoggerFactory.getLogger(DefaultErrorHandler.class);
@Override
public void onParamNull(IrisSession session, IllegalConstException e) {
session.write(e.getMessage());
}
@Override
public void onParamError(IrisSession session, IllegalConstException e) {
session.write(e.getMessage());
}
@Override
public void onServerError(IrisSession session, Exception e) {
logger.error("Server exception!", e);
session.write(e.getMessage());
}
}
}
```
Merchant.java
```package org.Iris.app.jilu.service.realm.unit.merchant;
import org.Iris.app.jilu.service.realm.unit.UnitAdapter;
import org.Iris.app.jilu.storage.domain.MemMerchant;
import org.Iris.app.jilu.storage.redis.RedisKeyGenerator;
import org.Iris.util.common.IrisSecurity;
/**
* 商户
*
* @author Ahab
*/
public class Merchant extends UnitAdapter<MemMerchant> {
public Merchant(MemMerchant merchant) {
super(merchant);
}
/**
* 商户登陆动作
*
*/
public boolean login(String account) {
String lockId = tryLock();
if (null == lockId)
return false;
try {
// 删除老的 token
if (null != unit.getToken())
redisOperate.del(RedisKeyGenerator.getTokenUidKey(unit.getToken()));
// 生成新的 token 并且写入
String token = IrisSecurity.encodeToken(account);
unit.setToken(token);
unitCache.flushHashBean(unit);
redisOperate.set(RedisKeyGenerator.getTokenUidKey(unit.getToken()), String.valueOf(unit.getMerchantId()));
return true;
} finally {
unLock(lockId);
}
}
}
```
SerializeUtil.java
```package org.Iris.util.common;
import com.google.gson.Gson;
public interface SerializeUtil {
interface JsonUtil {
final Gson GSON = new Gson();
}
final String OK = "ok";
}
```
AccountModel.java
```package org.Iris.app.jilu.common.bean.model;
import org.Iris.app.jilu.common.model.AccountType;
public class AccountModel {
private int type;
private String account;
public AccountModel() {}
public AccountModel(AccountType type, String account) {
this.type = type.mark();
this.account = account;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
}
```
MerchantAuthenticator.java
```package org.Iris.app.jilu.web.auth;
import org.Iris.app.jilu.web.session.IrisSession;
import org.springframework.stereotype.Component;
@Component
public class MerchantAuthenticator implements Authenticator {
@Override
public boolean auth(IrisSession session) {
return false;
}
}
```
Event.java
```package org.Iris.dispatcher.event;
public class Event implements IEvent {
protected EventType eventType;
protected Object attach;
public Event(EventType eventType) {
this(eventType, null);
}
public Event(EventType eventType, Object attach) {
this.eventType = eventType;
this.attach = attach;
}
@Override
public EventType eventType() {
return this.eventType;
}
@Override
public Object attach() {
return attach;
}
}
```
SmtpEmailSender.java
```package org.Iris.util.network.email;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import org.Iris.util.network.Protocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SmtpEmailSender {
private static final Logger logger = LoggerFactory.getLogger(SmtpEmailSender.class);
private int port = 25;
private String host;
private boolean auth;
private String username;
private String password;
private String senderName;
private String senderEmail;
private String from;
private Properties mailProps;
private Authenticator authenticator;
public void init() throws UnsupportedEncodingException {
mailProps = new Properties();
mailProps.put("mail.transport.protocol", Protocol.SMTP.mark());
mailProps.put("mail.smtp.host", this.host);
mailProps.put("mail.smtp.port", this.port);
mailProps.put("mail.smtp.auth", String.valueOf(auth));
if (auth) {
authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
};
};
}
this.from = String.format("%1$s <%2$s>", MimeUtility.encodeText(this.senderName, "UTF-8", "B"), this.senderEmail);
logger.info("SMTP email sender init success!");
}
/**
* 发送简单文本邮件
*
* @param subject 邮件标题
* @param receivers 收件人邮箱,多个邮箱用逗号隔开
* @param text 文本数据
* @throws AddressException
* @throws MessagingException
*/
public void sendTo(String subject, String receivers, String text) throws AddressException, MessagingException {
Session session = auth ? Session.getDefaultInstance(mailProps, authenticator) : Session.getDefaultInstance(mailProps);
session.setDebug(false);
_sendTo(_createTextMessage(session, subject, receivers, text), session);
}
private Message _createTextMessage(Session session, String subject, String receivers, String text) throws AddressException, MessagingException {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(this.from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receivers));
message.setSubject(subject);
message.setText(text);
return message;
}
private void _sendTo(Message message, Session session) throws MessagingException {
Transport ts = null;
try {
ts = session.getTransport();
ts.connect();
ts.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
} finally {
if (null != ts)
ts.close();
}
}
public void setPort(int port) {
this.port = port;
}
public void setHost(String host) {
this.host = host;
}
public void setAuth(boolean auth) {
this.auth = auth;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
public void setSenderEmail(String senderEmail) {
this.senderEmail = senderEmail;
}
}
```
MerchantSession.java
```package org.Iris.app.jilu.web.session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.Iris.app.jilu.service.realm.unit.merchant.Merchant;
public class MerchantSession extends UnitSession<Merchant> {
public MerchantSession(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
}
```
MemAccountSQLBuilder.java
```package org.Iris.app.jilu.storage.mybatis.SQLBuilder;
import org.Iris.app.jilu.storage.mybatis.Table;
import org.apache.ibatis.jdbc.SQL;
public class MemAccountSQLBuilder {
public String getByAccount() {
return new SQL() {
{
SELECT("*");
FROM(Table.MEM_ACCOUNT.mark());
WHERE("account=#{account}");
}
}.toString();
}
public String insert() {
return new SQL() {
{
INSERT_INTO(Table.MEM_ACCOUNT.mark());
VALUES("account", "#{account}");
VALUES("type", "#{type}");
VALUES("merchant_id", "#{merchantId}");
VALUES("created", "#{created}");
VALUES("updated", "#{updated}");
}
}.toString();
}
}
```
Locale.java
```package org.Iris.core.service.locale;
import org.Iris.core.service.locale.ICode.Code;
import org.Iris.core.util.IrisProperties;
import org.Iris.core.util.IrisPropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 国际化类,主要管理所有需要国际化的字符串
*
* @author ahab
*/
public class Locale {
private static final Logger logger = LoggerFactory.getLogger(Locale.class);
public static final Locale DEFAULT_LANG = new Locale();
private IrisProperties langs;
private Locale() {
langs = IrisPropertiesUtil.load(Locale.class, "/locale/locale_default.properties");
}
public Locale(String langConfigurationLocation) {
this();
IrisPropertiesUtil.load(langs, langConfigurationLocation);
}
/**
* 主要负责将需要国际化的字符串解析到应用
*
*/
public final void init() {
// 解析 Code 语言文件
for (Code code : Code.values())
code.parse(langs.getOptional(code));
init(langs);
logger.info("Local init success");
}
protected void init(IrisProperties langs) {
// do nothing
}
}
```
UnitSession.java
```package org.Iris.app.jilu.web.session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.Iris.app.jilu.service.realm.unit.UnitAdapter;
import org.Iris.core.exception.IrisRuntimeException;
public class UnitSession<T extends UnitAdapter<?>> extends IrisSession {
protected T unit;
public UnitSession(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
public T getUnit() {
return unit;
}
public void setUnit(T unit) {
if (null != this.unit)
throw new IrisRuntimeException("Unit Session already bind to another unit!");
this.unit = unit;
}
}
```
Assert.java
```package org.Iris.core.util;
import org.Iris.core.exception.AssertFailedException;
public class Assert {
public static final void isTrue(boolean expression) {
if (expression)
throw new AssertFailedException(Boolean.TRUE, expression);
}
}
```
IrisProperties.java
```package org.Iris.core.util;
import java.util.Properties;
import org.Iris.core.consts.IrisConst;
import org.Iris.core.exception.IllegalConstException;
public class IrisProperties extends Properties {
private static final long serialVersionUID = -1635951861537927001L;
/**
* 获取 {@link IrisConst#key()} 所对应的属性,如果不存在或者转换错误则抛出异常
*
* @param constant
* @return
* @throws IllegalConstException
*/
public <T> T get(IrisConst<T> constant) throws IllegalConstException {
String val = getProperty(constant.key());
if (null == val)
throw IllegalConstException.nullException(constant);
return constant.parse(val);
}
/**
* 获取 {@link IrisConst#key()} 所对应的属性,如果不存在或者转换错误返回 {@link IrisConst#defaultValue()}
*
* @param constant
* @return
*/
public <T> T getOptional(IrisConst<T> constant) {
try {
return get(constant);
} catch (IllegalConstException e) {
return constant.defaultValue();
}
}
}
```
LuaOperate.java
```package org.Iris.redis.operate.lua;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.Iris.redis.RedisConsts;
import org.Iris.redis.RedisHashLuaSerializableBean;
import org.Iris.redis.operate.RedisOperate;
import org.Iris.redis.operate.RedisOperate.RedisInvocation;
import org.Iris.util.reflect.BeanUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisNoScriptException;
public class LuaOperate {
private LuaCache luaCache;
private RedisOperate redisOperate;
public <T> T evalLua(LuaCommand command, int keyNum, String ...params) {
return evalLua(command.name(), keyNum, params);
}
/**
* 如果 key 值存在并且值等于 value 则删除 value 然后返回 true,否则什么也不做返回 false
*
* @param key
* @param value
* @return
*/
public boolean delIfEquals(String key, String value) {
long flag = evalLua(LuaCommand.DEL_IF_EQUALS, 1, key, value);
return flag == 1;
}
public boolean hmsetIfExist(RedisHashLuaSerializableBean bean) {
String result = evalLua(LuaCommand.HMSET_IF_EXIST.name(), 1, bean.serializeToLuaParams());
return null != result && result.equals(RedisConsts.OK);
}
public boolean hsetIfExist(String key, String field, String value) {
Long result = evalLua(LuaCommand.HSET_IF_EXIST.name(), 1, key, field, value);
return null != result;
}
/**
* 记录验证码
*
* @param codeKey 验证码 key
* @param countKey 验证码获取次数 key
* @param code 验证码
* @param codeLifeTime 验证码有效时长
* @param countMaxinum 验证码获取最大次数
* @param countLiftTime 验证码次数生命周期(超过该时间没有获取验证码,则验证码次数 key 会被删除,也就是说验证码次数会被清零)
* @return 0 - 表示成功;-1 - 表示获取验证码获取太频繁,-2 - 表示验证码获取次数上限
*/
public long recordCaptcha(String codeKey, String countKey, String code, long codeLifeTime, long countMaxinum, long countLiftTime) {
return evalLua(LuaCommand.RECORD_CAPTCHA, 2, codeKey, countKey, code, String.valueOf(codeLifeTime), String.valueOf(countMaxinum), String.valueOf(countLiftTime));
}
public <T> T hdelAndGet(String key, T bean) {
List<String> list = evalLua(LuaCommand.HDEL_AND_GET, 1, key);
if (list.isEmpty())
return null;
Map<String, String> hash = new HashMap<String, String>(list.size()/2, 1);
Iterator<String> iterator = list.iterator();
while (iterator.hasNext())
hash.put(iterator.next(), iterator.next());
return BeanUtils.mapToBean(hash, bean);
}
@SuppressWarnings("unchecked")
public <T> T evalLua(String cacheName, int keyNum, String ...params) {
LuaScript script = this.luaCache.get(cacheName);
if (null == script)
throw new JedisNoScriptException("Script " + cacheName + " not exist!");
return redisOperate.invoke(new RedisInvocation<T>() {
@Override
public T invok(Jedis jedis) {
if (script.isStored())
try {
return (T)jedis.evalsha(script.getSha1Key(), keyNum, params);
} catch (JedisNoScriptException e) {}
T object = (T) jedis.eval(script.getContent(), keyNum, params);
script.setStored(true);
return object;
}
});
}
public void setLuaCache(LuaCache luaCache) {
this.luaCache = luaCache;
}
public void setRedisOperate(RedisOperate redisOperate) {
this.redisOperate = redisOperate;
}
}
```
SmtpEmailSenderTest.java
```package org.Iris.util.network.email;
import java.io.UnsupportedEncodingException;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
public class SmtpEmailSenderTest {
public static void main(String[] args) throws AddressException, MessagingException, UnsupportedEncodingException {
SmtpEmailSender sender = new SmtpEmailSender();
sender.setAuth(true);
sender.setHost("smtp.163.com");
sender.setUsername("zxn0887472@163.com");
sender.setPassword("zxl870613");
sender.setSenderName("吉鹿");
sender.setSenderEmail("zxn0887472@163.com");
sender.init();
sender.sendTo("发大财了", "723854867@qq.com", "我们要发大财啦");
}
}
```
FileReader.java
```package org.Iris.util.io;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileReader {
/**
* 适用于读取小型文件
*
* @param filePath
* @return
* @throws IOException
*/
public static byte[] bufferRead(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists())
throw new FileNotFoundException(filePath);
if (file.isDirectory())
throw new IOException("File " + filePath + "is a directory, no data to read!");
return bufferRead(file);
}
/**
* 适用于读取小型文件
*
* @param file
* @return
* @throws IOException
*/
public static byte[] bufferRead(File file) throws IOException {
BufferedInputStream in = null;
byte[] buffer = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
buffer = new byte[in.available()];
in.read(buffer);
} finally {
if (null != in)
in.close();
}
return buffer;
}
/**
* 适用于读取小型文件,从 jar 文件读取文件
*
* @param clazz
* @param name
* @return
* @throws IOException
*/
public static byte[] bufferReadFromClassOrJar(Class<?> clazz, String name) throws IOException {
BufferedInputStream in = null;
byte[] buffer = null;
try {
in = new BufferedInputStream(clazz.getResourceAsStream(name));
buffer = new byte[in.available()];
in.read(buffer);
} finally {
if (null != in)
in.close();
}
return buffer;
}
}
```
IrisContextLoaderListener.java
```package org.Iris.app.jilu.web.listener;
import javax.servlet.ServletContextEvent;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
public class IrisContextLoaderListener extends ContextLoaderListener {
private static final String LOGBACK_CONFIGURATION_KEY = "logback.configurationFile";
private static final String LOGBACK_CONFIGURATION_LOCATION = "logbackConfigLocation";
public IrisContextLoaderListener() {}
public IrisContextLoaderListener(WebApplicationContext context) {
super(context);
}
@Override
public void contextInitialized(ServletContextEvent event) {
String logbackConfiguration = event.getServletContext().getInitParameter(LOGBACK_CONFIGURATION_LOCATION);
if (null != logbackConfiguration)
System.setProperty(LOGBACK_CONFIGURATION_KEY, logbackConfiguration);
super.contextInitialized(event);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
super.contextDestroyed(event);
}
}
```
MerchantService.java
```package org.Iris.app.jilu.service.realm.unit.merchant;
import javax.annotation.Resource;
import org.Iris.app.jilu.common.model.AccountType;
import org.Iris.app.jilu.storage.domain.MemMerchant;
import org.Iris.app.jilu.storage.redis.cache.UnitCache;
import org.springframework.stereotype.Service;
@Service
public class MerchantService {
@Resource
private UnitCache unitCache;
public Merchant getMerhantByAccount(String account) {
MemMerchant merchant = unitCache.getMerchantByAccount(account);
return null == merchant ? null : new Merchant(merchant);
}
/**
* 创建商户,其实就是晚上商户信息
*
* @param type
* @param account
* @param avatar
* @param address
*/
public void create(AccountType type, String account, String avatar, String address) {
}
public void setUnitCache(UnitCache unitCache) {
this.unitCache = unitCache;
}
}
```
IrisIntConst.java
```package org.Iris.core.consts;
public class IrisIntConst extends IrisConstImpl<Integer> {
public IrisIntConst(String key, int value) {
super(key, value);
}
public IrisIntConst(String key, int value, int constId) {
super(key, value, constId);
}
@Override
protected Integer parseValue(String value) {
return Integer.parseInt(value);
}
}
```
ConfigLoadFailedException.java
```package org.Iris.core.exception;
public class ConfigLoadFailedException extends IrisRuntimeException {
private static final long serialVersionUID = -1450420193275161087L;
public ConfigLoadFailedException(String message) {
super(message);
}
public ConfigLoadFailedException(String message, Throwable cause) {
super(message, cause);
}
}
```
HttpAdapter.java
```package org.Iris.util.network.http;
import org.apache.http.HttpResponse;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
public abstract class HttpAdapter {
protected int keepAliveTime = 5000;
protected int maxConn = 200;
protected int maxConnPerRoute = 200;
protected boolean sslEnabled;
/**
* 设置keepAlive策略;默认为保持5秒
*
* @return
*/
protected ConnectionKeepAliveStrategy keepAliveStrategy() {
ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy() {
public long getKeepAliveDuration(HttpResponse response, org.apache.http.protocol.HttpContext context) {
long keepAlive = super.getKeepAliveDuration(response, context);
if (-1 == keepAlive)
keepAlive = keepAliveTime; // keep connections alive 5
// seconds if a keep-alive value
// has not be explicitly set by
// the server
return keepAlive;
}
};
return keepAliveStrategy;
}
/**
* 清理超时和无效链接
*
*/
abstract void idleExpireClear();
abstract void close();
public void setSslEnabled(boolean sslEnabled) {
this.sslEnabled = sslEnabled;
}
abstract void init() throws Exception;
public void setMaxConn(int maxConn) {
this.maxConn = maxConn;
}
public void setMaxConnPerRoute(int maxConnPerRoute) {
this.maxConnPerRoute = maxConnPerRoute;
}
public void setKeepAliveTime(int keepAliveTime) {
this.keepAliveTime = keepAliveTime;
}
}
```
UnitCache.java
```package org.Iris.app.jilu.storage.redis.cache;
import javax.annotation.Resource;
import org.Iris.app.jilu.storage.domain.MemAccount;
import org.Iris.app.jilu.storage.domain.MemMerchant;
import org.Iris.app.jilu.storage.mybatis.mapper.MemAccountMapper;
import org.Iris.app.jilu.storage.mybatis.mapper.MemMerchantMapper;
import org.springframework.stereotype.Service;
/**
* 负责所有用户相关的数据存取:比如 mem_merchant,mem_customer等
*
* @author Ahab
*/
@Service
public class UnitCache extends RedisCache {
@Resource
private MemAccountMapper memAccountMapper;
@Resource
private MemMerchantMapper memMerchantMapper;
/**
* 通过商户ID获取商户
*
* @param id
* @return
*/
public MemMerchant getMerchantByMerchantId(long merchantId) {
MemMerchant merchant = getHashBean(new MemMerchant(merchantId));
if (null != merchant)
return merchant;
merchant = memMerchantMapper.getByMerchantId(merchantId);
if (null == merchant)
return null;
flushHashBean(merchant);
return merchant;
}
/**
* 通过商户账号获取商户
*
* @param type
* @param account
* @return
*/
public MemMerchant getMerchantByAccount(String account) {
MemAccount memAccount = getHashBean(new MemAccount(account));
if (null == memAccount) {
memAccount = memAccountMapper.getByAccount(account);
if (null == memAccount)
return null;
flushHashBean(memAccount);
}
return getMerchantByMerchantId(memAccount.getMerchantId());
}
}
```
IEvent.java
```package org.Iris.dispatcher.event;
public interface IEvent {
EventType eventType();
Object attach();
}
```
RedisMsgUtil.java
```package org.Iris.redis;
public class RedisMsgUtil {
public static boolean isOK(String value) {
return null == value ? null : value.equals("OK");
}
}
```
JiLuCode.java
```package org.Iris.app.jilu.web;
import org.Iris.core.service.locale.ICode;
import org.Iris.util.lang.StringUtil;
/**
* 注意 101 ~ 200 已经被 {@link JiLuParams} 中的各种网络参数定义了
*
* @author Ahab
*/
public enum JiLuCode implements ICode {
CAPTCHA_GET_CD(201, "captcha get frequently"),
CAPTCHA_COUNT_LIMIT(202, "captcha count limit"),
CAPTCHA_ERROR(203, "captcha error");
private int code;
private String defaultVaule;
private JiLuCode(int code, String defaultValue) {
this.code = code;
this.defaultVaule = defaultValue;
}
@Override
public int constId() {
return this.code;
}
@Override
public String key() {
return CODE_PREFIX + name();
}
@Override
public String parse(String value) {
this.defaultVaule = StringUtil.trimWhitespace(value);
return defaultVaule;
}
@Override
public String defaultValue() {
return this.defaultVaule;
}
}
```
MiMeType.java
```package org.Iris.util.common;
public class MiMeType {
public final static String APPLICATION_FORM_URLENCODED_VALUE = "application/x-www-form-urlencoded";
public final static String TEXT_HTML_UTF_8 = "text/html;charset=UTF-8";
public final static String TEXT_JSON_UTF_8 = "text/json;charset=UTF-8";
public final static String TEXT_PLAIN_UTF_8 = "text/plain;charset=UTF-8";
}
```
MemMerchantSQLBuilder.java
```package org.Iris.app.jilu.storage.mybatis.SQLBuilder;
import org.Iris.app.jilu.storage.mybatis.Table;
import org.apache.ibatis.jdbc.SQL;
public class MemMerchantSQLBuilder {
public String getByMerchantId() {
return new SQL() {
{
SELECT("*");
FROM(Table.MEM_MERCHANT.mark());
WHERE("merchant_id=#{merchantId}");
}
}.toString();
}
public String insert() {
return new SQL() {
{
INSERT_INTO(Table.MEM_MERCHANT.mark());
VALUES("name", "#{name}");
VALUES("address", "#{address}");
VALUES("avatar", "#{avatar}");
VALUES("last_login_time", "#{lastLoginTime}");
VALUES("created", "#{created}");
VALUES("updated", "#{updated}");
}
}.toString();
}
public String update(){
return new SQL(){
{
UPDATE(Table.MEM_MERCHANT.mark());
SET("merchant_id=${merchantId}");
SET("statusMod=${statusMod}");
SET("name=${name}");
SET("mobile=${mobile}");
SET("address=${address}");
SET("avatar=${avatar}");
SET("QRCode=${QRCode}");
SET("lastLoginTime=${lastLoginTime}");
SET("lastPurchaseTime=${lastPurchaseTime}");
SET("updated=${updated}");
WHERE("merchant_id=${merchantId}");
}
}.toString();
}
}
```
CommonServlet.java
```package org.Iris.app.jilu.web.servlet;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.Iris.app.jilu.service.action.CommonAction;
import org.Iris.app.jilu.service.action.common.CAPTCHA_GET;
import org.Iris.app.jilu.service.action.common.CREATE;
import org.Iris.app.jilu.service.action.common.LOGIN;
import org.Iris.app.jilu.web.IrisServlet;
import org.Iris.app.jilu.web.JiLuParams;
import org.Iris.app.jilu.web.session.IrisSession;
import org.Iris.core.exception.IllegalConstException;
public class CommonServlet extends IrisServlet<IrisSession> {
private static final long serialVersionUID = -419034761363132842L;
protected Map<String, CommonAction> actions = new HashMap<String, CommonAction>();
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
// 初始化普通模块的 action
actions.put("captchaGet", CAPTCHA_GET.INSTANCE);
actions.put("login", LOGIN.INSTANCE);
actions.put("create", CREATE.INSTANCE);
}
@Override
protected IrisSession buildSession(HttpServletRequest req, HttpServletResponse resp) {
return new IrisSession(req, resp);
}
@Override
protected void receive(IrisSession session) {
CommonAction action = actions.get(session.getKVParam(JiLuParams.ACTION));
if (null == action)
throw IllegalConstException.errorException(JiLuParams.ACTION);
action.execute(session);
}
}
```
ZkUtil.java
```package org.Iris.app.jilu.common.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.I0Itec.zkclient.ZkClient;
import org.Iris.app.jilu.common.model.Env;
import org.Iris.app.jilu.common.model.Config;
import org.Iris.util.common.IpUtil;
import org.Iris.util.common.SerializeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ZkUtil {
private static final Logger logger = LoggerFactory.getLogger(ZkUtil.class);
@SuppressWarnings("unchecked")
public static Map<String, String> loadConfiguration(ZkClient zkClient, Env env) {
byte[] buffer = zkClient.readData(Config.ZK_CONFIGURATION_PATH, true);
if (null == buffer) {
logger.warn("Zookeeper /configuration/jilu has no data to read!");
return new HashMap<String, String>();
}
Map<String, String> map = SerializeUtil.JsonUtil.GSON.fromJson(new String(buffer), Map.class);
for (Entry<String, String> entry : map.entrySet()) {
StringBuilder builder = new StringBuilder();
builder.append(entry.getValue()).append("-").append(env.name().toLowerCase());
if (env == Env.LOCAL) {
String macAddr = IpUtil.getMacAddress();
if (null != macAddr)
builder.append("-").append(macAddr);
}
map.put(entry.getKey(), builder.toString());
}
logger.info("JiLu zookeeper configuration load success, load {} queue names -- {}", map.size(), map);
return map;
}
}
```
HelloWorld.java
```package org.Iris.app.web.template.web.servlet;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.Iris.app.web.template.service.persistence.domain.User;
import org.Iris.app.web.template.service.persistence.mapper.UserMapper;
import org.Iris.app.web.template.web.IrisServlet;
import org.springframework.beans.factory.annotation.Autowired;
public class HelloWorld extends IrisServlet {
private static final long serialVersionUID = -1633606111581327433L;
@Autowired
private UserMapper userMapper;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<User> list = userMapper.selectAll();
System.out.println(list);
System.out.println("here");
try {
TimeUnit.HOURS.sleep(6);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
LaneGroup.java
```package org.Iris.dispatcher.lane;
public abstract class LaneGroup {
protected Lane[] lanes;
protected LaneGroup(int laneNum) {
lanes = new Lane[laneNum];
for (int i = 0; i < laneNum; i++)
lanes[i] = new Lane(i);
}
public Lane[] lanes() {
return lanes;
}
public abstract Lane getLane();
public abstract void returnLane(Lane lane);
}
```
Test.java
```package org.Iris.app.jilu;
import java.util.List;
import java.util.Map;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.BytesPushThroughSerializer;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.google.gson.Gson;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
public class Test {
public static void main(String[] args) throws Exception {
ZkClient zkClient = new ZkClient("121.42.155.96:2181", 5000, 5000, new BytesPushThroughSerializer());
byte[] buffer = zkClient.readData("/configuration/jilu", true);
System.out.println(new String(buffer));
Map<String, String> map = new Gson().fromJson(new String(buffer), Map.class);
System.out.println(map);
}
public static void testPhone(String mobile) throws NumberParseException {
PhoneNumber pn = PhoneNumberUtil.getInstance().parse(mobile, null);
System.out.println(pn.getCountryCode());
System.out.println(pn.getNationalNumber());
System.out.println(pn);
System.out.println(PhoneNumberUtil.getInstance().isValidNumber(pn));
}
public static void testOss() throws ServerException, ClientException {
// String policy = "{\n" +
// " \"Version\": \"1\", \n" +
// " \"Statement\": [\n" +
// " {\n" +
// " \"Action\": [\n" +
// " \"oss:GetBucket\", \n" +
// " \"oss:GetObject\" \n" +
// " ], \n" +
// " \"Resource\": [\n" +
// " \"acs:oss:*:*:*\"\n" +
// " ], \n" +
// " \"Effect\": \"Allow\"\n" +
// " }\n" +
// " ]\n" +
// "}";
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LWddt7duyV1fBG6W",
"zRJymjB8WNWOLhbBZQSUFQHJ2JdTEw");
DefaultAcsClient client = new DefaultAcsClient(profile);
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setVersion("2015-04-01");
request.setMethod(MethodType.POST);
request.setProtocol(ProtocolType.HTTPS);
request.setRoleArn("acs:ram::1328034689228937:role/jilu");
request.setRoleSessionName("alice-001");
// request.setPolicy(policy);
AssumeRoleResponse response = client.getAcsResponse(request);
System.out.println(response.getRequestId());
System.out.println(response.getCredentials().getAccessKeyId());
System.out.println(response.getCredentials().getAccessKeySecret());
System.out.println(response.getCredentials().getExpiration());
System.out.println(response.getCredentials().getSecurityToken());
System.out.println(response.getAssumedRoleUser().getArn());
System.out.println(response.getAssumedRoleUser().getAssumedRoleId());
}
}
```
LuaCommand.java
```package org.Iris.redis.operate.lua;
public enum LuaCommand {
DEL_IF_EQUALS,
HMSET_IF_EXIST,
HSET_IF_EXIST,
RECORD_CAPTCHA,
HDEL_AND_GET;
}
```
TypeSerialEventDispatcher.java
```package org.Iris.dispatcher;
import java.util.HashMap;
import java.util.Map;
import org.Iris.dispatcher.event.EventType;
import org.Iris.dispatcher.event.IEvent;
import org.Iris.dispatcher.event.SerialEventListener;
import org.Iris.dispatcher.lane.LaneGroup;
import org.jetlang.core.Disposable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <pre>
* EventType 相同的 IEventListener 视为同一个实例
*
* 注意:
* 该类型的 Dispatcher 只能注册 SerialEventListener,并且一个 listener 只能绑定一个 dispatcher,因此
* SerialEventListener.onEvent() 内部是线程安全的不需要考虑并发问题
* </pre>
*
* @author ahab
*/
public class TypeSerialEventDispatcher extends SerialEventDispatcher {
private static final Logger logger = LoggerFactory.getLogger(TypeSerialEventDispatcher.class);
private SerialEventListener any;
private Map<EventType, SerialEventListener> typeBasedListeners;
private Map<SerialEventListener, Disposable> listenersDisposables;
public TypeSerialEventDispatcher(LaneGroup laneGroup) {
super(laneGroup);
this.listenersDisposables = new HashMap<SerialEventListener, Disposable>();
}
@Override
protected void onRegister(SerialEventListener listener) {
if (listener.eventType() == EventType.ANY) {
if (null != any) {
_disposeListener(any);
logger.info("SerialEventListener replace: {} ---> {}", listener, any);
}
any = listener;
} else {
if (null == typeBasedListeners)
typeBasedListeners = new HashMap<EventType, SerialEventListener>();
SerialEventListener old = typeBasedListeners.put(listener.eventType(), listener);
if (null != old) {
_disposeListener(old);
logger.info("SerialEventListener replace: {} ---> {}", listener, old);
}
}
listenersDisposables.put(listener, doRegister(listener));
}
@Override
protected void onDeregister(SerialEventListener listener) {
if (listener.eventType() == listener.eventType()) {
if (null != any) {
_disposeListener(any);
logger.info("SerialEventListener removed: {}", any);
any = null;
}
} else {
listener = null == typeBasedListeners ? null : typeBasedListeners.remove(listener.eventType());
if (null != listener) {
_disposeListener(listener);
logger.info("SerialEventListener removed: {}", any);
}
}
}
@Override
protected void publishEventDirect(IEvent event) {
if (null != any)
any.onEvent(event);
SerialEventListener listener = null != typeBasedListeners ? typeBasedListeners.get(event.eventType()) : null;
if (null != listener)
listener.onEvent(event);
}
private void _disposeListener(SerialEventListener listener) {
Disposable disposable = listenersDisposables.remove(listener);
disposable.dispose();
}
@Override
protected void onDispose() {
any = null;
typeBasedListeners.clear();
for (Disposable disposable : listenersDisposables.values())
disposable.dispose();
listenersDisposables.clear();
}
}
```
RedisConsts.java
```package org.Iris.redis;
import org.Iris.core.consts.IrisBoolConst;
import org.Iris.core.consts.IrisIntConst;
import org.Iris.core.consts.IrisLongConst;
import org.Iris.core.consts.IrisStrConst;
public interface RedisConsts {
final IrisIntConst REDIS_PORT = new IrisIntConst("redis.port", 6379);
final IrisStrConst REDIS_HOST = new IrisStrConst("redis.host", null);
final IrisStrConst REDIS_PASSWORDD = new IrisStrConst("redis.password", null);
final IrisIntConst REDIS_MIN_IDLE = new IrisIntConst("redis.min.idle", 4);
final IrisIntConst REDIS_MAX_IDLE = new IrisIntConst("redis.max.idle", 12);
final IrisBoolConst REDIS_LIFO = new IrisBoolConst("redis.lifo", false);
final IrisIntConst REDIS_MAX_TOTAL = new IrisIntConst("redis.max.total", 12);
final IrisBoolConst REDIS_TEST_ON_BORROW = new IrisBoolConst("redis.test.on.borrow", true);
final IrisLongConst REDIS_MAX_WAIT_MILLIS = new IrisLongConst("redis.max.wait.millis", 3000);
final IrisBoolConst REDIS_TEST_WHILE_IDLE = new IrisBoolConst("redis.test.while.idle", false);
final IrisIntConst REDIS_CONN_TIMEOUT_MILLIS = new IrisIntConst("redis.conn.timeout.millis", 2000);
final IrisBoolConst REIDS_BLOCK_WHEN_EXHAUSTED = new IrisBoolConst("redis.block.when.exhausted", true);
final IrisIntConst REDIS_NUM_TEST_PER_EVICTION_RUN = new IrisIntConst("redis.num.test.per.eviction.run", -1);
final IrisLongConst REDIS_MIN_EVICTABLE_IDLE_MILLIS = new IrisLongConst("redis.min.evitable.idle.millis", -1);
final IrisLongConst REDIS_TIME_BETWEEN_EVICTION_RUNS_MILLIS = new IrisLongConst("redis.time.between.eviction.runs.millis", 30000);
final IrisLongConst REDIS_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS = new IrisLongConst("redis.soft.min.evictable.idle.time.millis", 60000);
final String OK = "OK";
}
```
SerialEventListener.java
```package org.Iris.dispatcher.event;
import java.util.concurrent.atomic.AtomicReference;
import org.Iris.core.exception.IrisRuntimeException;
import org.Iris.dispatcher.SerialEventDispatcher;
public abstract class SerialEventListener implements IEventListener {
private AtomicReference<SerialEventDispatcher> holder = new AtomicReference<SerialEventDispatcher>();
public void bind(SerialEventDispatcher dispatcher) {
if (!holder.compareAndSet(null, dispatcher))
throw new IrisRuntimeException("SerialEventListener has bind to another SerialEventDispatcher!");
}
public void unbind(SerialEventDispatcher dispatcher) {
if (!holder.compareAndSet(dispatcher, null))
throw new IrisRuntimeException("SerialEventListener bind state changed!");
}
}
```
LuaCache.java
```package org.Iris.redis.operate.lua;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.Iris.util.io.FileReader;
import org.Iris.util.io.ResourceUtil;
import org.Iris.util.lang.StringUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LuaCache {
private static final Logger logger = LoggerFactory.getLogger(LuaCache.class);
private static final String DEFAULT_LUA_FILE = "/lua/";
private static final String LUA_SCRIPT_SUFFIX = ".lua";
private Map<String, LuaScript> scripts = new ConcurrentHashMap<String, LuaScript>();
public LuaCache() {
_loadPredefinedScript();
}
public LuaCache(String luaScriptLocation) throws IOException {
_loadPredefinedScript();
scan(luaScriptLocation);
}
private void _loadPredefinedScript() {
for (LuaCommand command : LuaCommand.values()) {
try {
byte[] buffer = FileReader.bufferReadFromClassOrJar(LuaOperate.class, DEFAULT_LUA_FILE + command.name().toLowerCase() + LUA_SCRIPT_SUFFIX);
String content = new String(buffer);
String sha1Key = DigestUtils.sha1Hex(content);
scripts.put(command.name(), new LuaScript(sha1Key, content));
logger.info("Lua script {} is loaded!", command.name());
} catch (IOException e) {
logger.info("Lua script {} load failure!", command.name());
}
}
}
public void scan(String luaScriptLocation) throws IOException {
File file = ResourceUtil.getFile(luaScriptLocation);
if (!file.exists()) {
logger.error("File {} not exist, lua cache load failure!", luaScriptLocation);
return;
}
if (!file.isDirectory()) {
logger.error("File {} is not a directory, lua cache load failure!", luaScriptLocation);
return;
}
_scanning(file);
}
private void _scanning(File file) throws IOException {
File[] files = file.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(LUA_SCRIPT_SUFFIX);
}
});
if (null != files) {
for (File f : files)
addLuaScript(f.getName().replaceAll(LUA_SCRIPT_SUFFIX, StringUtil.EMPTY), f);
logger.info("Load {} lua script from {}!", files.length, file.getAbsoluteFile());
}
files = file.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return file.isDirectory();
}
});
if (null == files)
return;
for (File f : files) {
if (!f.exists() || f.isFile())
continue;
_scanning(f);
}
}
public boolean addLuaScript(String cacheName, File file) throws IOException {
String content = new String(FileReader.bufferRead(file));
String shalKey = DigestUtils.sha1Hex(content);
if (null != scripts.putIfAbsent(cacheName.toUpperCase(), new LuaScript(shalKey, content))) {
logger.warn("Lua script cache - {}:{} already exist!", cacheName, file.getCanonicalPath());
return false;
}
return true;
}
public boolean addLuaScript(String cacheName, String scriptFile) throws IOException {
String content = new String(FileReader.bufferRead(scriptFile));
String shalKey = DigestUtils.sha1Hex(content);
if (null != scripts.putIfAbsent(cacheName.toUpperCase(), new LuaScript(shalKey, content))) {
logger.warn("Lua script cache - {}:{} already exist!", cacheName, scriptFile);
return false;
}
return true;
}
public LuaScript get(String key) {
return this.scripts.get(key);
}
}
```
BaseTest.java
```package org.Iris.redis;
import org.Iris.redis.operate.RedisOperate;
import junit.framework.TestCase;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class BaseTest extends TestCase {
protected RedisOperate redisOperate;
@Override
protected void setUp() throws Exception {
super.setUp();
JedisPool pool = new JedisPool(new JedisPoolConfig(), "121.42.155.96", 6379, 3000, null, 8);
redisOperate = new RedisOperate();
redisOperate.setPool(pool);
}
}
```
RoundRobinLaneGroup.java
```package org.Iris.dispatcher.lane;
import java.util.concurrent.atomic.AtomicInteger;
public class RoundRobinLaneGroup extends LaneGroup {
private AtomicInteger idx = new AtomicInteger(0);
public RoundRobinLaneGroup(int laneNum) {
super(laneNum);
}
@Override
public Lane getLane() {
return lanes[Math.abs(idx.getAndIncrement() % lanes.length)];
}
@Override
public void returnLane(Lane lane) {
// do nothing
}
}
```
UnitType.java
```package org.Iris.app.jilu.service.realm.unit;
import org.Iris.app.jilu.storage.redis.RedisKeyGenerator;
/**
* 单位类型
*
* @author Ahab
*/
public enum UnitType {
/**
* 商户
*
*/
MERCHANT(0),
/**
* 客户
*
*/
CUSTOMER(1);
private int mark;
private UnitType(int mark) {
this.mark = mark;
}
public int mark() {
return mark;
}
public String getUnitLock(long uid) {
return RedisKeyGenerator.getUnitLockKey(this, uid);
}
}
```
Result.java
```package org.Iris.core.service.bean;
import java.io.Serializable;
import org.Iris.core.consts.IrisConst;
import org.Iris.core.service.locale.ICode;
import org.Iris.util.common.SerializeUtil;
/**
* 可以表示任何调用过程的返回结果(rpc调用、web调用、甚至是方法调用都可以)
*
* @author Ahab
*
* @param <T>
*/
public class Result<T> implements Serializable {
private static final long serialVersionUID = 4231387477200661362L;
private int code;
private String desc;
private T data;
public Result(int code, String desc) {
this(code, desc, null);
}
public Result(int code, String desc, T data) {
this.code = code;
this.desc = desc;
this.data = data;
}
public Result(ICode iCode) {
this(iCode, null);
}
public Result(ICode iCode, T data) {
this.code = iCode.constId();
this.desc = iCode.defaultValue();
this.data = data;
}
public Result(IrisConst<String> constant) {
this.code = constant.constId();
this.desc = constant.defaultValue();
}
public int getCode() {
return code;
}
public Result<T> setCode(int code) {
this.code = code;
return this;
}
public String getDesc() {
return desc;
}
public Result<T> setDesc(String desc) {
this.desc = desc;
return this;
}
public T getData() {
return data;
}
public Result<T> setData(T data) {
this.data = data;
return this;
}
public static String jsonError(int code, String desc) {
Result<Void> result = new Result<Void>(code, desc);
return SerializeUtil.JsonUtil.GSON.toJson(result);
}
public static String jsonError(IrisConst<String> constant) {
return SerializeUtil.JsonUtil.GSON.toJson(new Result<Void>(constant));
}
public static String jsonSuccess() {
return SerializeUtil.JsonUtil.GSON.toJson(new Result<Void>(ICode.Code.OK));
}
public static <T> String jsonSuccess(T data) {
return SerializeUtil.JsonUtil.GSON.toJson(new Result<T>(ICode.Code.OK, data));
}
}
```
IEventListener.java
```package org.Iris.dispatcher.event;
public interface IEventListener {
/**
* 表示只处理该类型的 {@link Event}
*
* @return
*/
EventType eventType();
/**
* 处理接收到的事件
*
* @param event
*/
void onEvent(IEvent event);
}
```
Protocol.java
```package org.Iris.util.network;
public enum Protocol {
SMTP("smtp");
private String mark;
private Protocol(String mark) {
this.mark = mark;
}
public String mark() {
return mark;
}
}
```
ListenerPostProcessor.java
```package org.Iris.app.jilu.consumer;
import org.Iris.app.jilu.consumer.listener.JiLuMessageListener;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.stereotype.Component;
@Component
public class ListenerPostProcessor implements BeanPostProcessor, ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof JiLuMessageListener) {
JiLuMessageListener<?> listener = (JiLuMessageListener<?>)bean;
DefaultMessageListenerContainer container = applicationContext.getBean(DefaultMessageListenerContainer.class);
container.setMessageListener(listener);
container.setDestination(new ActiveMQQueue(listener.getDestination()));
if (listener.getConcurrentConsumers() > 0)
container.setConcurrentConsumers(listener.getConcurrentConsumers());
container.start();
}
return bean;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
```
DateUtils.java
```package org.Iris.util.lang;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class DateUtils {
public static final String yyyyMMdd = "yyyyMMdd";
public static final String ISO8601_UTC = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static int currentTime() {
return (int) (System.currentTimeMillis() / 1000);
}
/**
* {@link #getUTCDate(long)}
* @return
*/
public static String getUTCDate() {
return getDate(ISO8601_UTC, System.currentTimeMillis(), TimeZone.getTimeZone("UTC"));
}
/**
* 获取指定 unix 时间的 UTC 时间格式
*
* @param timestamp
* @return
*/
public static String getUTCDate(long timestamp) {
return getDate(ISO8601_UTC, timestamp, TimeZone.getTimeZone("UTC"));
}
/**
* {@link #getDate(String, long, TimeZone)}
* @param format
* @return
*/
public static String getDate(String format) {
return getDate(format, System.currentTimeMillis(), TimeZone.getDefault());
}
/**
* 将 unix 时间戳转换为指定格式的时间字符串
*
* @param format
* @param timestamp
* @param timeZone
* @return
*/
public static String getDate(String format, long timestamp, TimeZone timeZone) {
DateFormat df = new SimpleDateFormat(format);
df.setTimeZone(timeZone);
return df.format(new Date(timestamp));
}
}
```
QueueName.java
```package org.Iris.app.jilu.common.model.jms;
public class QueueName {
public static final String CAPTCHA = "captcha";
}
```
JiLuLang.java
```package org.Iris.app.jilu.service;
import org.Iris.app.jilu.web.JiLuCode;
import org.Iris.core.service.locale.Locale;
import org.Iris.core.util.IrisProperties;
public class JiLuLang extends Locale {
public JiLuLang(String langConfigurationLocation) {
super(langConfigurationLocation);
}
@Override
protected void init(IrisProperties langs) {
for (JiLuCode code : JiLuCode.values())
code.parse(langs.getOptional(code));
}
}
```
UnitAdapter.java
```package org.Iris.app.jilu.service.realm.unit;
import org.Iris.app.jilu.common.Beans;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UnitAdapter<T extends Unit> implements Unit {
private static final Logger logger = LoggerFactory.getLogger(UnitAdapter.class);
protected T unit;
private String lock;
public UnitAdapter(T unit) {
this.unit = unit;
this.lock = unit.unitType().getUnitLock(unit.uid());
}
public String tryLock() {
return Beans.distributeLock.tryLock(lock);
}
public boolean unLock(String lockId) {
boolean flag = Beans.distributeLock.unLock(lock, lockId);
if (!flag)
logger.warn("Unit lock {} release failure for lockId {}!", lock, lockId);
return flag;
}
@Override
public long uid() {
return unit.uid();
}
public T getUnit() {
return unit;
}
@Override
public UnitType unitType() {
return unit.unitType();
}
}
```
IllegalConstException.java
```package org.Iris.core.exception;
import org.Iris.core.consts.IrisConst;
public class IllegalConstException extends IrisRuntimeException {
private static final long serialVersionUID = -3701621791996004997L;
private IrisConst<?> constant;
private boolean nil;
private IllegalConstException(String message, IrisConst<?> constant) {
super(message);
this.constant = constant;
}
private IllegalConstException(String message, Throwable cause, IrisConst<?> constant) {
super(message, cause);
this.constant = constant;
}
public IrisConst<?> constant() {
return constant;
}
public boolean isNil() {
return nil;
}
public void setNil(boolean nil) {
this.nil = nil;
}
public static final IllegalConstException nullException(IrisConst<?> constant) {
IllegalConstException e = exception(constant.key() + " not exist!", constant);
e.setNil(true);
return e;
}
public static final IllegalConstException nullException(String message, IrisConst<?> constant) {
IllegalConstException e = exception(message, constant);
e.setNil(true);
return e;
}
public static final IllegalConstException errorException(IrisConst<?> constant) {
return exception(constant.key() + " error!", constant);
}
public static final IllegalConstException errorException(IrisConst<?> constant, Throwable cause) {
return exception(constant.key() + " error!", cause, constant);
}
public static final IllegalConstException exception(String message, IrisConst<?> constant) {
return new IllegalConstException(message, constant);
}
public static final IllegalConstException exception(String message, Throwable cause, IrisConst<?> constant) {
return new IllegalConstException(message, cause, constant);
}
}
```
IrisConst.java
```package org.Iris.core.consts;
public interface IrisConst<T> {
int constId();
String key();
T parse(String value);
T defaultValue();
}
```
Config.java
```package org.Iris.app.jilu.common.model;
public class Config {
public static final String ZK_CONFIGURATION_PATH = "/configuration/jilu";
private static Env env;
public static Env getEnv() {
return env;
}
public static void setEnv(String env) {
Config.env = Env.match(env);
}
}
```
CaptchaMessage.java
```package org.Iris.app.jilu.common.model.jms;
import java.io.Serializable;
import org.Iris.app.jilu.common.model.AccountType;
/**
* 验证码消息
*
* @author Ahab
*/
public class CaptchaMessage implements Serializable {
private static final long serialVersionUID = 3128414792298024362L;
private AccountType type; // 账号类型
private String account; // 账号
private String captcha; // 验证码值
public CaptchaMessage() {}
public CaptchaMessage(AccountType type, String account, String captcha) {
this.type = type;
this.account = account;
this.captcha = captcha;
}
public AccountType getType() {
return type;
}
public void setType(AccountType type) {
this.type = type;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getCaptcha() {
return captcha;
}
public void setCaptcha(String captcha) {
this.captcha = captcha;
}
@Override
public String toString() {
return type.name() + "-" + account + "-" + captcha;
}
}
```
Beans.java
```package org.Iris.app.jilu.common;
import org.Iris.app.jilu.service.jms.JmsService;
import org.Iris.app.jilu.service.realm.unit.Tx;
import org.Iris.app.jilu.service.realm.unit.merchant.MerchantService;
import org.Iris.app.jilu.storage.redis.cache.UnitCache;
import org.Iris.core.util.SpringContextUtil;
import org.Iris.redis.operate.RedisOperate;
import org.Iris.redis.operate.lock.DistributeLock;
import org.Iris.redis.operate.lua.LuaOperate;
public interface Beans {
final Tx tx = SpringContextUtil.getBean("tx", Tx.class);
final UnitCache unitCache = SpringContextUtil.getBean("unitCache", UnitCache.class);
final JmsService jmsService = SpringContextUtil.getBean("jmsService", JmsService.class);
final LuaOperate luaOperate = SpringContextUtil.getBean("luaOperate", LuaOperate.class);
final RedisOperate redisOperate = SpringContextUtil.getBean("redisOperate", RedisOperate.class);
final DistributeLock distributeLock = SpringContextUtil.getBean("distributeLock", DistributeLock.class);
final MerchantService merchantService = SpringContextUtil.getBean("merchantService", MerchantService.class);
}
```
MerchantForm.java
```package org.Iris.app.jilu.common.bean.form;
import org.Iris.app.jilu.service.realm.unit.merchant.Merchant;
import org.Iris.app.jilu.storage.domain.MemMerchant;
public class MerchantForm {
private long merchantId;
private String token;
public MerchantForm(Merchant merchant) {
MemMerchant memMerchant = merchant.getUnit();
this.merchantId = memMerchant.getMerchantId();
this.token = memMerchant.getToken();
}
public long getMerchantId() {
return merchantId;
}
public void setMerchantId(long merchantId) {
this.merchantId = merchantId;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
```
Lane.java
```package org.Iris.dispatcher.lane;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.jetlang.core.BatchExecutor;
import org.jetlang.core.BatchExecutorImpl;
import org.jetlang.fibers.Fiber;
import org.jetlang.fibers.PoolFiberFactory;
public class Lane {
private static final BatchExecutor BATCH_EXECUTOR = new BatchExecutorImpl();
private int idx;
private String name;
private Fiber fiber;
private Executor exec;
public Lane(int idx) {
this.init();
}
private void init() {
this.exec = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), Executors.defaultThreadFactory());
this.exec.execute(new Runnable() {
@Override
public void run() {
name = Thread.currentThread().getName();
}
});
PoolFiberFactory factory = new PoolFiberFactory(exec, null);
this.fiber = factory.create(BATCH_EXECUTOR);
this.fiber.start();
}
public int getIdx() {
return idx;
}
public Fiber getFiber() {
return fiber;
}
public boolean isInLane() {
return Thread.currentThread().getName().equals(name);
}
}
```
UnitAction.java
```package org.Iris.app.jilu.service.action;
import org.Iris.app.jilu.web.session.MerchantSession;
import org.Iris.app.jilu.web.session.UnitSession;
/**
* 单位操作
*
* @author Ahab
*/
public abstract class UnitAction<SESSION extends UnitSession<?>> implements IAction<MerchantSession> {
public void execute(SESSION session) {
session.write(execute0(session));
}
protected abstract String execute0(SESSION session);
}
```
IAction.java
```package org.Iris.app.jilu.service.action;
import org.Iris.app.jilu.common.Beans;
import org.Iris.app.jilu.web.session.IrisSession;
public interface IAction<SESSION extends IrisSession> extends Beans {
void execute(SESSION session);
}
```
IrisPropertiesUtil.java
```package org.Iris.core.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.Iris.core.exception.IrisIOException;
import org.Iris.util.io.CharsetUtil;
import org.Iris.util.io.ResourceUtil;
public class IrisPropertiesUtil {
public static IrisProperties load(Class<?> clazz, String file) {
IrisProperties properties = new IrisProperties();
InputStreamReader reader = null;
try {
InputStream in = clazz.getResourceAsStream(file);
reader = new InputStreamReader(in, CharsetUtil.UTF_8);
properties.load(reader);
} catch (IOException e) {
throw new IrisIOException(file + " load failure by " + clazz.getName() , e);
} finally {
if (null != reader)
try {
reader.close();
} catch (IOException e) {
throw new IrisIOException(file + " io stream close failure!" , e);
}
}
return properties;
}
public static IrisProperties load(String file) {
IrisProperties properties = new IrisProperties();
InputStreamReader reader = null;
try {
File f = ResourceUtil.getFile(file);
reader = new InputStreamReader(new FileInputStream(f), CharsetUtil.UTF_8);
properties.load(reader);
} catch (FileNotFoundException e) {
throw new IrisIOException(file + " not found!", e);
} catch (IOException e) {
throw new IrisIOException(file + " load failure from classpath!" , e);
} finally {
if (null != reader)
try {
reader.close();
} catch (IOException e) {
throw new IrisIOException(file + " io stream close failure!" , e);
}
}
return properties;
}
public static void load(IrisProperties properties, String file) {
InputStream in = null;
try {
File f = ResourceUtil.getFile(file);
in = new FileInputStream(f);
properties.load(in);
} catch (FileNotFoundException e) {
throw new IrisIOException(file + " not found!", e);
} catch (IOException e) {
throw new IrisIOException(file + " load failure from classpath!" , e);
} finally {
if (null != in)
try {
in.close();
} catch (IOException e) {
throw new IrisIOException(file + " io stream close failure!" , e);
}
}
}
}
```
Tx.java
```package org.Iris.app.jilu.service.realm.unit;
import javax.annotation.Resource;
import org.Iris.app.jilu.common.BeanCreator;
import org.Iris.app.jilu.common.bean.model.AccountModel;
import org.Iris.app.jilu.service.realm.unit.merchant.Merchant;
import org.Iris.app.jilu.storage.domain.MemAccount;
import org.Iris.app.jilu.storage.domain.MemMerchant;
import org.Iris.app.jilu.storage.mybatis.mapper.MemAccountMapper;
import org.Iris.app.jilu.storage.mybatis.mapper.MemMerchantMapper;
import org.Iris.app.jilu.storage.redis.cache.UnitCache;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component(value = "tx")
public class Tx {
@Resource
private MemAccountMapper memAccountMapper;
@Resource
private MemMerchantMapper memMerchantMapper;
@Resource
private UnitCache unitCache;
/**
* 创建商户
*
* @param merchant
* @param am
*/
@Transactional
public Merchant createMerchant(MemMerchant merchant, AccountModel am) {
// 先插db
memMerchantMapper.insert(merchant);
MemAccount account = BeanCreator.newMemAccount(am, merchant.getCreated(), merchant.getMerchantId());
memAccountMapper.insert(account);
// 再更新缓存
unitCache.flushHashBean(merchant);
unitCache.flushHashBean(account);
return new Merchant(merchant);
}
}
```
ICode.java
```package org.Iris.core.service.locale;
import org.Iris.core.consts.IrisConst;
import org.Iris.util.lang.StringUtil;
/**
* 0 ~ 100 是 Iris 预留错误码,不要使用这些类型去定义业务错误码
*
* @author Ahab
*/
public interface ICode extends IrisConst<String> {
public static final String CODE_PREFIX = "CODE_";
enum Code implements ICode {
OK(0, "success"),
PARAM_LACK(1, "param - {0} lack"),
PARAM_ERROR(2, "param - {0} error"),
SYSTEM_ERROR(3, "system exception"),
AUTH_FAIL(4, "auth fail"),
REQUEST_FREQUENTLY(5, "request frequently"),
UNIT_NOT_EXIST(50, "unit not exist");
private int code;
private String defaultVaule;
private Code(int code, String defaultValue) {
this.code = code;
this.defaultVaule = defaultValue;
}
@Override
public int constId() {
return this.code;
}
@Override
public String key() {
return CODE_PREFIX + name();
}
@Override
public String parse(String value) {
this.defaultVaule = StringUtil.trimWhitespace(value);
return defaultVaule;
}
@Override
public String defaultValue() {
return this.defaultVaule;
}
}
}
```
RedisOperate.java
```package org.Iris.redis.operate;
import java.util.Map;
import org.Iris.redis.model.EXPX;
import org.Iris.redis.model.NXXX;
import org.Iris.util.reflect.BeanUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class RedisOperate {
protected JedisPool pool;
public long del(String... keys) {
return invoke(new RedisInvocation<Long>() {
@Override
public Long invok(Jedis jedis) {
return jedis.del(keys);
}
});
}
public long expire(String key, int seconds) {
return invoke(new RedisInvocation<Long>() {
@Override
public Long invok(Jedis jedis) {
return jedis.expire(key, seconds);
}
});
}
public String get(String key) {
return invoke(new RedisInvocation<String>() {
@Override
public String invok(Jedis jedis) {
return jedis.get(key);
}
});
}
public String set(String key, String value) {
return invoke(new RedisInvocation<String>() {
@Override
public String invok(Jedis jedis) {
return jedis.set(key, value);
}
});
}
/**
* 有条件的设置
*
* @param key
* @param value
* @param nxxx
* @param expx
* @param time
* @return
*/
public String setnxpx(String key, String value, NXXX nxxx, EXPX expx, long time) {
return invoke(new RedisInvocation<String>() {
@Override
public String invok(Jedis jedis) {
return jedis.set(key, value, nxxx.name(), expx.name(), time);
}
});
}
public Map<String, String> hgetAll(String key) {
return invoke(new RedisInvocation<Map<String, String>>() {
@Override
public Map<String, String> invok(Jedis jedis) {
return jedis.hgetAll(key);
}
});
}
public <T> T hgetAll(String key, T bean) {
Map<String, String> map = invoke(new RedisInvocation<Map<String, String>>() {
@Override
public Map<String, String> invok(Jedis jedis) {
return jedis.hgetAll(key);
}
});
if (map.isEmpty())
return null;
return BeanUtils.mapToBean(map, bean);
}
public String hmset(String key, Map<String, String> map) {
return invoke(new RedisInvocation<String>() {
@Override
public String invok(Jedis jedis) {
return jedis.hmset(key, map);
}
});
}
public String hmset(String key, Object bean) {
return invoke(new RedisInvocation<String>() {
@Override
public String invok(Jedis jedis) {
return jedis.hmset(key, BeanUtils.beanToMap(bean));
}
});
}
public <T> T invoke(RedisInvocation<T> invoke) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return invoke.invok(jedis);
} finally {
jedis.close();
}
}
public void setPool(JedisPool pool) {
this.pool = pool;
}
public interface RedisInvocation<T> {
T invok(Jedis jedis);
}
}
```
IrisIOException.java
```package org.Iris.core.exception;
import java.io.IOException;
public class IrisIOException extends RuntimeException {
private static final long serialVersionUID = -8040299306013579320L;
public IrisIOException(String message, IOException cause) {
super(message, cause);
}
}
```
SpringActiveMQOperator.java
```package org.Iris.core.util;
import java.io.Serializable;
import java.util.Map;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
public class SpringActiveMQOperator {
protected Map<String, String> queueNames;
private JmsTemplate jmsTemplate;
protected MessageCreator generateObjectCreator(final Serializable obj) {
return new MessageCreator() {
@Override
public Message createMessage(Session session)
throws JMSException {
ObjectMessage objMsg = session.createObjectMessage();
objMsg.setObject(obj);
return objMsg;
}
};
}
protected MessageCreator generateTextCreator(final String str) {
return new MessageCreator() {
@Override
public Message createMessage(Session session)
throws JMSException {
return session.createTextMessage(str);
}
};
}
protected void sendMessage(String queueName, MessageCreator messageCreator) {
Queue queue = new ActiveMQQueue(queueName);
jmsTemplate.setDefaultDestination(queue);
jmsTemplate.send(messageCreator);
}
protected String getQueueName(String key) {
return this.queueNames.get(key);
}
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public void setQueueNames(Map<String, String> queueNames) {
this.queueNames = queueNames;
}
}
```
LOGIN.java
```package org.Iris.app.jilu.service.action.common;
import org.Iris.app.jilu.common.AppConfig;
import org.Iris.app.jilu.common.bean.form.MerchantForm;
import org.Iris.app.jilu.common.bean.model.AccountModel;
import org.Iris.app.jilu.common.model.AccountType;
import org.Iris.app.jilu.service.action.CommonAction;
import org.Iris.app.jilu.service.realm.unit.merchant.Merchant;
import org.Iris.app.jilu.storage.redis.RedisKeyGenerator;
import org.Iris.app.jilu.web.JiLuCode;
import org.Iris.app.jilu.web.JiLuParams;
import org.Iris.app.jilu.web.session.IrisSession;
import org.Iris.core.exception.IllegalConstException;
import org.Iris.core.service.bean.Result;
import org.Iris.core.service.locale.ICode;
import org.Iris.util.common.IrisSecurity;
import org.Iris.util.common.SerializeUtil;
/**
* 登陆
*
* @author Ahab
*/
public class LOGIN extends CommonAction {
public static final LOGIN INSTANCE = new LOGIN();
private LOGIN() {}
@Override
protected String execute0(IrisSession session) {
AccountType type = AccountType.match(session.getKVParamOptional(JiLuParams.TYPE));
String account = type == AccountType.MOBILE ? session.getKVParam(JiLuParams.MOBILE) : session.getKVParam(JiLuParams.EMAIL);
switch (type) {
case MOBILE:
case EMAIL:
if (!luaOperate.delIfEquals(RedisKeyGenerator.getAccountCaptchaKey(type, account), session.getKVParam(JiLuParams.CAPTCHA)))
return Result.jsonError(JiLuCode.CAPTCHA_ERROR);
Merchant merchant = merchantService.getMerhantByAccount(account);
if (null == merchant) {
String token = IrisSecurity.encodeToken(account);
String key = RedisKeyGenerator.getTokenAccountKey(token);
redisOperate.hmset(key, new AccountModel(type, account));
redisOperate.expire(key, AppConfig.CREATE_WAIT_TIMEOUT);
Result<String> result = new Result<String>(ICode.Code.UNIT_NOT_EXIST);
result.setData(token);
return SerializeUtil.JsonUtil.GSON.toJson(result);
}
if (!merchant.login(account))
return Result.jsonError(ICode.Code.REQUEST_FREQUENTLY);
return Result.jsonSuccess(new MerchantForm(merchant));
case WECHAT:
return Result.jsonSuccess();
default:
throw IllegalConstException.errorException(JiLuParams.TYPE);
}
}
}
```
CharsetUtil.java
```package org.Iris.util.io;
import java.nio.charset.Charset;
public class CharsetUtil {
public static final String CHARSET_UTF_8 = "UTF-8";
public static final Charset UTF_8 = Charset.forName(CHARSET_UTF_8);
}
```
NXXX.java
```package org.Iris.redis.model;
public enum NXXX {
/**
* 当且仅当 key 不存在时设置
*/
NX,
/**
* 当且仅当 key 存在时设置
*/
XX;
}
```
QueueNames.java
```package org.Iris.app.jilu.consumer;
import java.util.Map;
import org.I0Itec.zkclient.ZkClient;
import org.Iris.app.jilu.common.model.Env;
import org.Iris.app.jilu.common.util.ZkUtil;
public class QueueNames {
private Env env;
private ZkClient zkClient;
private Map<String, String> queueNames;
public void init() {
this.queueNames = ZkUtil.loadConfiguration(zkClient, env);
}
public String getDestination(String queueName) {
return queueNames.get(queueName);
}
public void setEnv(String env) {
this.env = Env.match(env);
}
public void setZkClient(ZkClient zkClient) {
this.zkClient = zkClient;
}
}
```
AssertFailedException.java
```package org.Iris.core.exception;
public class AssertFailedException extends IrisRuntimeException {
private static final long serialVersionUID = 11728188967378339L;
protected Object expected;
protected Object actual;
public AssertFailedException(Object expected, Object actual) {
super("Assert failure, expected = " + expected + ", actual = " + actual);
}
}
```
UserMapper.java
```package org.Iris.app.web.template.service.persistence.mapper;
import java.util.List;
import org.Iris.app.web.template.service.persistence.domain.User;
import org.Iris.app.web.template.service.persistence.provider.UserSqlProvider;
import org.apache.ibatis.annotations.SelectProvider;
public interface UserMapper {
@SelectProvider(type = UserSqlProvider.class, method = "selectAll")
List<User> selectAll();
}
```
PatternsTest.java
```package org.Iris.util.common;
import org.Iris.util.Patterns;
public class PatternsTest {
public static void main(String[] args) {
System.out.println(Patterns.isEmail("7238548ss67q@s.c"));
}
}
```
IrisStrConst.java
```package org.Iris.core.consts;
import org.Iris.util.lang.StringUtil;
public class IrisStrConst extends IrisConstImpl<String> {
public IrisStrConst(String key, String value) {
super(key, value);
}
public IrisStrConst(String key, String value, int constId) {
super(key, value, constId);
}
public IrisStrConst(String key, int constId) {
super(key, null, constId);
}
@Override
protected String parseValue(String value) {
return StringUtil.trimWhitespace(value);
}
}
```
EventType.java
```package org.Iris.dispatcher.event;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.Iris.core.exception.IrisRuntimeException;
public class EventType {
// only for EventListener that can process all Event
public static final EventType ANY = EventType.create(0x00);
// EventListener register to a dispatcher
public static final EventType LISTENER_REGISTER = EventType.create(0x01);
// EventListener deregister from a dispatcher
public static final EventType LISTENER_DEREGISTER = EventType.create(0x02);
// Dispatcher dispose event
public static final EventType DISPATCHER_DISPOSE = EventType.create(0x03);
private static Map<Integer, EventType> map = new ConcurrentHashMap<Integer, EventType>();
private int mark;
private EventType(int mark) {
this.mark = mark;
}
public static EventType create(int type) {
EventType eventType = map.get(type);
if (null != eventType)
throw new IrisRuntimeException("EventType - " + type + " conflict, it has already defined!");
eventType = new EventType(type);
EventType temp = map.putIfAbsent(type, eventType);
if (null != temp)
throw new IrisRuntimeException("EventType - " + type + " conflict, it has already defined!");
return eventType;
}
public int mark() {
return mark;
}
}
```
User.java
```package org.Iris.util.domain;
public class User {
private int age;
private Integer sex;
private String name;
private double money;
private Double high;
private boolean male;
private Boolean teenage;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public Double getHigh() {
return high;
}
public void setHigh(Double high) {
this.high = high;
}
public boolean isMale() {
return male;
}
public void setMale(boolean male) {
this.male = male;
}
public Boolean getTeenage() {
return teenage;
}
public void setTeenage(Boolean teenage) {
this.teenage = teenage;
}
}
```
Authenticator.java
```package org.Iris.app.jilu.web.auth;
import org.Iris.app.jilu.web.session.IrisSession;
/**
* 请求验证器
*
* @author Ahab
*/
public interface Authenticator {
/**
* 请求验证
*
* @param session
* @return
*/
boolean auth(IrisSession session);
}
```
ConstsPool.java
```package org.Iris.util.common;
import java.nio.charset.Charset;
public class ConstsPool {
public static final Charset UTF_8 = Charset.forName("UTF-8");
}
```
IrisRuntimeException.java
```package org.Iris.core.exception;
public class IrisRuntimeException extends RuntimeException {
private static final long serialVersionUID = -7947964000525855099L;
public IrisRuntimeException(String message) {
super(message);
}
public IrisRuntimeException(String message, Throwable cause) {
super(message, cause);
}
}
```
RedisHashBean.java
```package org.Iris.redis;
public interface RedisHashBean {
String redisKey();
}
```
RedisException.java
```package org.Iris.redis.exception;
import org.Iris.core.exception.IrisException;
public class RedisException extends IrisException {
private static final long serialVersionUID = 7176979538899181652L;
public RedisException(String message, Throwable cause) {
super(message, cause);
}
}
```
IrisLongConst.java
```package org.Iris.core.consts;
public class IrisLongConst extends IrisConstImpl<Long> {
public IrisLongConst(String key, long value) {
super(key, value);
}
public IrisLongConst(String key, long value, int constId) {
super(key, value, constId);
}
@Override
protected Long parseValue(String value) {
return Long.parseLong(value);
}
}
```
GsonResultErrorhandler.java
```package org.Iris.app.jilu.web.handler;
import java.text.MessageFormat;
import org.Iris.app.jilu.web.session.IrisSession;
import org.Iris.core.consts.IrisConst;
import org.Iris.core.exception.IllegalConstException;
import org.Iris.core.service.bean.Result;
import org.Iris.core.service.locale.ICode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component(value = "errorHandler")
public class GsonResultErrorhandler implements ErrorHandler {
private static final Logger logger = LoggerFactory.getLogger(GsonResultErrorhandler.class);
@Override
public void onParamNull(IrisSession session, IllegalConstException exception) {
IrisConst<?> constant = exception.constant();
session.write(Result.jsonError(constant.constId(), MessageFormat.format(ICode.Code.PARAM_LACK.defaultValue(), constant.key())));
}
@Override
public void onParamError(IrisSession session, IllegalConstException exception) {
IrisConst<?> constant = exception.constant();
session.write(Result.jsonError(constant.constId(), MessageFormat.format(ICode.Code.PARAM_ERROR.defaultValue(), constant.key())));
}
@Override
public void onServerError(IrisSession session, Exception exception) {
session.write(Result.jsonError(ICode.Code.SYSTEM_ERROR.constId(), ICode.Code.SYSTEM_ERROR.defaultValue()));
logger.error("Server Error!", exception);
}
}
```
JmsService.java
```package org.Iris.app.jilu.service.jms;
import org.I0Itec.zkclient.ZkClient;
import org.Iris.app.jilu.common.model.AccountType;
import org.Iris.app.jilu.common.model.Env;
import org.Iris.app.jilu.common.model.jms.CaptchaMessage;
import org.Iris.app.jilu.common.model.jms.QueueName;
import org.Iris.app.jilu.common.util.ZkUtil;
import org.Iris.core.util.SpringActiveMQOperator;
public class JmsService extends SpringActiveMQOperator {
private ZkClient zkClient;
public void init(Env env) {
this.queueNames = ZkUtil.loadConfiguration(zkClient, env);
}
/**
* 发送验证码
*
* @param type
* @param account
* @param code
*/
public void sendCaptchaMessage(AccountType type, String account, String captcha) {
sendMessage(getQueueName(QueueName.CAPTCHA), generateObjectCreator(new CaptchaMessage(type, account, captcha)));
}
public void setZkClient(ZkClient zkClient) {
this.zkClient = zkClient;
}
}
```
EXPX.java
```package org.Iris.redis.model;
public enum EXPX {
/**
* 秒为单位设置生命周期
*/
EX,
/**
* 毫秒为单位设置生命周期
*/
PX;
}
```
CommonAction.java
```package org.Iris.app.jilu.service.action;
import org.Iris.app.jilu.web.session.IrisSession;
public abstract class CommonAction implements IAction<IrisSession> {
public final void execute(IrisSession session) {
session.write(execute0(session));
}
protected abstract String execute0(IrisSession session);
}
```
AccountType.java
```package org.Iris.app.jilu.common.model;
public enum AccountType {
MOBILE(0),
EMAIL(1),
WECHAT(2);
private int mark;
private AccountType(int mark) {
this.mark = mark;
}
public int mark() {
return mark;
}
public static final AccountType match(int type) {
for (AccountType at : AccountType.values()) {
if (at.mark != type)
continue;
return at;
}
return null;
}
}
```
CREATE.java
```package org.Iris.app.jilu.service.action.common;
import org.Iris.app.jilu.common.BeanCreator;
import org.Iris.app.jilu.common.bean.form.MerchantForm;
import org.Iris.app.jilu.common.bean.model.AccountModel;
import org.Iris.app.jilu.service.action.CommonAction;
import org.Iris.app.jilu.service.realm.unit.merchant.Merchant;
import org.Iris.app.jilu.storage.redis.RedisKeyGenerator;
import org.Iris.app.jilu.web.JiLuParams;
import org.Iris.app.jilu.web.session.IrisSession;
import org.Iris.core.exception.IllegalConstException;
import org.Iris.core.service.bean.Result;
import org.Iris.core.service.locale.ICode;
public class CREATE extends CommonAction {
public static final CREATE INSTANCE = new CREATE();
private CREATE() {}
@Override
protected String execute0(IrisSession session) {
String name = session.getKVParam(JiLuParams.NAME);
String avatar = session.getKVParam(JiLuParams.AVATAR);
String address = session.getKVParam(JiLuParams.ADDRESS);
String token = session.getKVParam(JiLuParams.TOKEN);
AccountModel am = luaOperate.hdelAndGet(RedisKeyGenerator.getTokenAccountKey(token), new AccountModel());
if (null == am)
throw IllegalConstException.errorException(JiLuParams.TOKEN);
Merchant merchant = tx.createMerchant(BeanCreator.newMemMerchant(name, avatar, address), am);
if (!merchant.login(am.getAccount()))
return Result.jsonError(ICode.Code.REQUEST_FREQUENTLY);
return Result.jsonSuccess(new MerchantForm(merchant));
}
}
```
StringUtilTest.java
```package org.Iris.util.lang;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Assert;
import org.junit.Test;
public class StringUtilTest {
@Test
public void testHasLength() {
CharSequence sequence = " 你 好 ";
Assert.assertTrue(StringUtil.hasLength(sequence));
sequence = " ";
Assert.assertTrue(StringUtil.hasLength(sequence));
}
@Test
public void testTrimWhitespace() {
String string = " 你好 "; // 全角空格
Assert.assertEquals(StringUtil.trimWhitespace(string), "你好");
}
@Test
public void testSha1() {
System.out.println(DigestUtils.sha1Hex("if redis.call(\"get\",KEYS[1]) == ARGV[1] then return redis.call(\"del\",KEYS[1]) else return 0 end"));
}
}
```
IrisConstImpl.java
```package org.Iris.core.consts;
import org.Iris.core.exception.IllegalConstException;
abstract class IrisConstImpl<T> implements IrisConst<T> {
private int constId;
private String key;
private T defaultValue;
public IrisConstImpl(String key, T defaultValue) {
this(key, defaultValue, 0);
}
public IrisConstImpl(String key, T defaultValue, int constId) {
this.key = key;
this.constId = constId;
this.defaultValue = defaultValue;
}
@Override
public T parse(String value) {
try {
return parseValue(value);
} catch (Exception e) {
throw IllegalConstException.errorException(this, e);
}
}
protected abstract T parseValue(String value);
@Override
public int constId() {
return constId;
}
@Override
public String key() {
return this.key;
}
@Override
public T defaultValue() {
return defaultValue;
}
}
```
RedisHashLuaSerializableBean.java
```package org.Iris.redis;
public interface RedisHashLuaSerializableBean extends RedisHashBean {
String[] serializeToLuaParams();
}
```
IEventDispatcher.java
```package org.Iris.dispatcher;
import org.Iris.dispatcher.event.IEvent;
import org.Iris.dispatcher.event.IEventListener;
public interface IEventDispatcher<LISTENER extends IEventListener> {
void register(LISTENER listener);
void deregister(LISTENER listener);
void publish(IEvent event);
void dispose();
}```
MemMerchant.java
```package org.Iris.app.jilu.storage.domain;
import org.Iris.app.jilu.service.realm.unit.Unit;
import org.Iris.app.jilu.service.realm.unit.UnitType;
import org.Iris.app.jilu.storage.redis.RedisKeyGenerator;
import org.Iris.redis.RedisHashBean;
public class MemMerchant implements RedisHashBean, Unit {
private long merchantId;
private int statusMod;
private String name;
private String address;
private String avatar;
private String QRCode;
private int lastLoginTime;
private int lastPurchaseTime;
private int created;
private int updated;
// 只存在 redis 的字段
private String token;
public MemMerchant() {}
public MemMerchant(long merchantId) {
this.merchantId = merchantId;
}
public MemMerchant(String name, String address, String avatar) {
this.name = name;
this.address = address;
this.avatar = avatar;
}
public long getMerchantId() {
return merchantId;
}
public void setMerchantId(long merchantId) {
this.merchantId = merchantId;
}
public int getStatusMod() {
return statusMod;
}
public void setStatusMod(int statusMod) {
this.statusMod = statusMod;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getQRCode() {
return QRCode;
}
public void setQRCode(String qRCode) {
QRCode = qRCode;
}
public int getLastLoginTime() {
return lastLoginTime;
}
public void setLastLoginTime(int lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public int getLastPurchaseTime() {
return lastPurchaseTime;
}
public void setLastPurchaseTime(int lastPurchaseTime) {
this.lastPurchaseTime = lastPurchaseTime;
}
public int getCreated() {
return created;
}
public void setCreated(int created) {
this.created = created;
}
public int getUpdated() {
return updated;
}
public void setUpdated(int updated) {
this.updated = updated;
}
// ***************************************************************
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
@Override
public String redisKey() {
return RedisKeyGenerator.getMemMerchantDataKey(merchantId);
}
@Override
public long uid() {
return merchantId;
}
@Override
public UnitType unitType() {
return UnitType.MERCHANT;
}
}
```
MemAccountMapper.java
```package org.Iris.app.jilu.storage.mybatis.mapper;
import org.Iris.app.jilu.storage.domain.MemAccount;
import org.Iris.app.jilu.storage.mybatis.SQLBuilder.MemAccountSQLBuilder;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.SelectProvider;
public interface MemAccountMapper {
@SelectProvider(type = MemAccountSQLBuilder.class, method = "getByAccount")
MemAccount getByAccount(String account);
@InsertProvider(type = MemAccountSQLBuilder.class, method = "insert")
void insert(MemAccount account);
}
```
JiLuParams.java
```package org.Iris.app.jilu.web;
import org.Iris.core.consts.IrisBoolConst;
import org.Iris.core.consts.IrisIntConst;
import org.Iris.core.consts.IrisStrConst;
import org.Iris.core.exception.IllegalConstException;
import org.Iris.util.Patterns;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
public interface JiLuParams {
final IrisStrConst ACTION = new IrisStrConst("action", 101);
final IrisBoolConst SERIAL = new IrisBoolConst("serial", false, 102);
final IrisIntConst TYPE = new IrisIntConst("type", 0, 103);
final IrisStrConst ACCOUNT = new IrisStrConst("account", 104);
// 手机号码需要验证
final IrisStrConst MOBILE = new IrisStrConst("mobile", 105) {
protected String parseValue(String value) {
PhoneNumberUtil util = PhoneNumberUtil.getInstance();
try {
PhoneNumber number = util.parse(value, null);
if (!util.isValidNumber(number))
throw IllegalConstException.errorException(this);
return "+" + number.getCountryCode() + number.getNationalNumber();
} catch (NumberParseException e) {
throw IllegalConstException.errorException(this);
}
};
};
// 邮箱号码需要验证
final IrisStrConst EMAIL = new IrisStrConst("email", 106) {
protected String parseValue(String value) {
if (!Patterns.isEmail(value))
throw IllegalConstException.errorException(this);
return super.parseValue(value);
};
};
final IrisStrConst CAPTCHA = new IrisStrConst("captcha", 107);
final IrisStrConst AVATAR = new IrisStrConst("avatar", 108);
final IrisStrConst ADDRESS = new IrisStrConst("address", 109);
final IrisStrConst TOKEN = new IrisStrConst("token", 110);
final IrisStrConst NAME = new IrisStrConst("name", 111);
}
```
DistributeLock.java
```package org.Iris.redis.operate.lock;
import java.util.concurrent.TimeUnit;
import org.Iris.redis.RedisConsts;
import org.Iris.redis.model.EXPX;
import org.Iris.redis.model.NXXX;
import org.Iris.redis.operate.RedisOperate;
import org.Iris.redis.operate.lua.LuaOperate;
import org.Iris.util.common.uuid.AlternativeJdkIdGenerator;
import org.Iris.util.common.uuid.IdGenerator;
public class DistributeLock {
private int lockTimeout = 3000; // 锁的有效时间默认为 3 秒中
private LuaOperate luaOperate;
private RedisOperate redisOperate;
private IdGenerator lockIdGenerator = new AlternativeJdkIdGenerator(); // 用来生成分布式锁Id
public String tryLock(String lock) {
String lockId = lockIdGenerator.generateId().toString();
String result = redisOperate.setnxpx(lock, lockId, NXXX.NX, EXPX.PX, lockTimeout);
if (null != result && result.equalsIgnoreCase(RedisConsts.OK))
return lockId;
return null;
}
public String lock(String lock, long timeout) {
long begin = System.nanoTime();
while (true) {
String lockId = tryLock(lock);
if (null != lockId)
return lockId;
long time = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - begin);
if (time >= timeout)
return null;
// TODO:
Thread.yield();
}
}
public boolean unLock(String lock, String lockId) {
return luaOperate.delIfEquals(lock, lockId);
}
public void setLockTimeout(int lockTimeout) {
this.lockTimeout = lockTimeout;
}
public void setLuaOperate(LuaOperate luaOperate) {
this.luaOperate = luaOperate;
}
public void setRedisOperate(RedisOperate redisOperate) {
this.redisOperate = redisOperate;
}
public void setLockIdGenerator(IdGenerator lockIdGenerator) {
this.lockIdGenerator = lockIdGenerator;
}
}
```
Patterns.java
```package org.Iris.util;
import java.util.regex.Pattern;
public class Patterns {
private static Pattern emailPattern = Pattern.compile("\\w+\\x40\\w+\\x2e\\w+");
public static boolean isEmail(String content) {
return emailPattern.matcher(content).matches();
}
}
```
App.java
```package org.Iris.core;
import org.Iris.core.service.locale.Locale;
public abstract class App {
protected String name;
private Locale locale = Locale.DEFAULT_LANG;
protected App(String name) {
this.name = name;
}
public final void start() {
locale.init();
this.bootstrap();
}
protected abstract void bootstrap();
public abstract void stop();
public void setLocale(Locale locale) {
this.locale = locale;
}
}
```
IrisException.java
```package org.Iris.core.exception;
public class IrisException extends Exception {
private static final long serialVersionUID = 5634450529393839633L;
public IrisException(String message) {
super(message);
}
public IrisException(String message, Throwable cause) {
super(message, cause);
}
}
```
IrisServlet.java
```package org.Iris.app.jilu.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.Iris.app.jilu.service.JiLu;
import org.Iris.app.jilu.web.auth.Authenticator;
import org.Iris.app.jilu.web.handler.ErrorHandler;
import org.Iris.app.jilu.web.handler.ErrorHandler.DefaultErrorHandler;
import org.Iris.app.jilu.web.session.IrisSession;
import org.Iris.core.exception.IllegalConstException;
import org.Iris.core.service.bean.Result;
import org.Iris.core.service.locale.ICode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.support.WebApplicationContextUtils;
public abstract class IrisServlet<SESSION extends IrisSession> extends HttpServlet {
private static final long serialVersionUID = -7815032356377001691L;
/**
* 如果要允许其他方法那么需要修改该字段,并且重写该方法;
* 如果要屏蔽某个方法也需要修改该字段(去掉该方法),并且删除该方法;
*/
private static final String METHOD_ALLOWS = "TRACE, OPTIONS, GET, POST";
private static final String ERROR_HANDLER_NAME = "errorHandler";
@Autowired
protected JiLu jilu;
@Autowired
private ErrorHandler errorHandler;
protected Authenticator authenticator;
@Override
public void init() throws ServletException {
super.init();
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
// if user not inject the "errorHandler" then inject the DefaultErrorHandler
if (!context.containsBean(ERROR_HANDLER_NAME)) {
ConfigurableApplicationContext cat = (ConfigurableApplicationContext) context;
DefaultListableBeanFactory dbf = (DefaultListableBeanFactory) cat.getBeanFactory();
BeanDefinitionBuilder dataSourceBuider = BeanDefinitionBuilder.genericBeanDefinition(DefaultErrorHandler.class);
dbf.registerBeanDefinition(ERROR_HANDLER_NAME, dataSourceBuider.getBeanDefinition());
}
AutowireCapableBeanFactory factory = context.getAutowireCapableBeanFactory();
factory.autowireBean(this);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this._receive(req, resp);
}
private void _receive(HttpServletRequest request, HttpServletResponse response) {
SESSION session = buildSession(request, response);
try {
if (null != authenticator && !authenticator.auth(session)) {
session.write(Result.jsonError(ICode.Code.AUTH_FAIL));
return;
}
receive(session);
} catch (IllegalConstException e) {
if (e.isNil())
errorHandler.onParamNull(session, e);
else
errorHandler.onParamError(session, e);
} catch (Exception e) {
errorHandler.onServerError(session, e);
}
}
protected abstract SESSION buildSession(HttpServletRequest req, HttpServletResponse resp);
protected abstract void receive(SESSION session);
@Override
protected final void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader(HttpHeaders.ALLOW, METHOD_ALLOWS);
}
}
```
LuaScript.java
```package org.Iris.redis.operate.lua;
public class LuaScript {
private String sha1Key;
private String content;
private boolean stored;
public LuaScript(String sha1Key, String content) {
this.sha1Key = sha1Key;
this.content = content;
}
public String getSha1Key() {
return sha1Key;
}
public String getContent() {
return content;
}
public boolean isStored() {
return stored;
}
public void setStored(boolean stored) {
this.stored = stored;
}
}
```
MemAccount.java
```package org.Iris.app.jilu.storage.domain;
import org.Iris.app.jilu.storage.redis.RedisKeyGenerator;
import org.Iris.redis.RedisHashBean;
public class MemAccount implements RedisHashBean {
private String account;
private int type;
private long merchantId;
private long created;
private int updated;
public MemAccount() {}
public MemAccount(String account) {
this.account = account;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public long getMerchantId() {
return merchantId;
}
public void setMerchantId(long merchantId) {
this.merchantId = merchantId;
}
public long getCreated() {
return created;
}
public void setCreated(long created) {
this.created = created;
}
public int getUpdated() {
return updated;
}
public void setUpdated(int updated) {
this.updated = updated;
}
@Override
public String redisKey() {
return RedisKeyGenerator.getMemAccountDataKey(account);
}
}
```
KeyUtil.java
```package org.Iris.util.common;
import java.util.Random;
public class KeyUtil {
/**
* 生成 bitNum 数字验证码
*
* @param bitNum
* @return
*/
public static String randomCaptcha(int bitNum) {
StringBuilder sb = new StringBuilder();
Random random = new Random();
while (sb.length() < bitNum)
sb.append(random.nextInt(10));
return sb.toString();
}
}
```
Env.java
```package org.Iris.app.jilu.common.model;
public enum Env {
TEST,
LOCAL,
ONLINE;
public static final Env match(String env) {
for (Env temp : Env.values()) {
if (temp.name().equalsIgnoreCase(env))
return temp;
}
return null;
}
}
```
RedisKeyGenerator.java
```package org.Iris.app.jilu.storage.redis;
import java.text.MessageFormat;
import org.Iris.app.jilu.common.model.AccountType;
import org.Iris.app.jilu.service.realm.unit.UnitType;
public class RedisKeyGenerator {
private static final String LOCK_UNIT = "string:lock:unit:{0}:{1}"; // 用户分布式锁;0-表示用户类型,1-表示用户Id
private static final String ACCOUNT_CAPTCHA = "string:captcha:account:{0}:{1}"; // 账号 - 验证码 对应关系;0-表示账号类型,1-表示账号值
private static final String ACCOUNT_CAPTCHA_COUNT = "string:captcha:account:count:{0}:{1}"; // 账号 - 验证码获取次数 对应关系;0-表示账号类型,1-表示账号值
private static final String TOKEN_UID = "string:token:uid:{0}"; // token uid 对应关系
private static final String TOKEN_ACCOUNT = "hash:token:account:{0}"; //
private static final String MEM_MERCHANT_DATA = "hash:db:mem:merchant:{0}";
private static final String MEM_ACCOUNT_DATA = "hash:db:mem:account:{0}";
public static String getUnitLockKey(UnitType type, long uid) {
return MessageFormat.format(LOCK_UNIT, type.name(), String.valueOf(uid));
}
public static String getAccountCaptchaKey(AccountType type, String account) {
return MessageFormat.format(ACCOUNT_CAPTCHA, type.name().toLowerCase(), account);
}
public static String getAccountCaptchaCountKey(AccountType type, String account) {
return MessageFormat.format(ACCOUNT_CAPTCHA_COUNT, type.name().toLowerCase(), account);
}
public static String getTokenUidKey(String token) {
return MessageFormat.format(TOKEN_UID, token);
}
public static String getTokenAccountKey(String token) {
return MessageFormat.format(TOKEN_ACCOUNT, token);
}
public static String getMemMerchantDataKey(long merchantId) {
return MessageFormat.format(MEM_MERCHANT_DATA, String.valueOf(merchantId));
}
public static String getMemAccountDataKey(String account) {
return MessageFormat.format(MEM_ACCOUNT_DATA, account);
}
}
```
|
72Roman/webprogbase-lab1
|
72Roman/webprogbase-lab1
README.md
```# webprogbase-lab1
lab 1
[Documentation](https://docs.google.com/document/d/1GXvIde18_2hWc1vcGkQBtE6E7G2NhbPQcnMWVwEn69Q/edit?usp=sharing)
```
|
734336454/zhouyong
|
734336454/zhouyong
C.java
```package c;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class C {
public static void main(String[] args) throws IOException {
// File a = new File("E:\\测试\\dd");
// a.listFiles();
// a.createNewFile();//创建文件
// System.out.println(a.getName());//文件名
// a.delete(); //删除文件
// System.out.println(a.getAbsolutePath());//寻找文件
// File[] num = a.listFiles();// 返回一个a数组
// SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd,kk:mm:ss");
// for (int i = 0; i < num.length; i++) {
//
// if (num[i].isDirectory()) {
// // 判断是否是目录
//
// File[] num2 = num[i].listFiles();// 返回一额个数组
// for (int j = 0; j < num2.length; j++) {
// System.out.println(num[2].getName());// 获取名字
// System.out.println(time.format(num[j].lastModified()));
// //获取最后修改时间
// }
// } else {
// System.out.println(num[i].getName());
// System.out.println(time.format(num[i].lastModified()));
// }
//
// }
// File[] num = a.listFiles();
// for(int i=0;i<num.length;i++){
// if(num[i].getName().endsWith(".txt")){
// System.out.println(num[i].getName()+"2");
// }else{
// System.out.println(num[i].getName()+"1");
// }
// }
// }
// FileInputStream no = new FileInputStream("E:\\测试\\2.txt");
// FileOutputStream no1= new FileOutputStream("E:\\测试\\520.txt");
}
}
```
a1.java
```package c;
/**
* 内部类
* @author Administrator
*
*/
public class a1 {
static private String name = "周勇";
// 创建一个静态内部类
static class In {
private int age;
void testDemo() {
System.out.println("我叫" + name);
}
}
public static void main(String[] args) {
a1 ot = new a1();
System.out.println(ot.name);
// 调用静态内部类
a1.In a11 = new a1.In();
a11.testDemo();
}
}
```
|
73796d/SplineCurve
|
73796d/SplineCurve
README.md
```# SplineCurve
样条曲线
cocos creator版本:2.1.3
语言:ts
编辑器:vscode
```
showposition.ts
```const {ccclass, property} = cc._decorator;
@ccclass
export default class ShowPosition extends cc.Component {
@property(cc.Label)
label: cc.Label = null;
update (dt) {
this.label.string = "(" + this.node.position.x.toFixed(1) + "," + this.node.position.y.toFixed(1) + ")";
}
}
```
item.ts
```/**
* Item 信息
*/
import { Rect } from "./rect";
export default class Item {
public id: number = 0;
public img: cc.Texture2D = null;
public imgPath: string = "";
public imgSize: Rect = new Rect(0, 0, 0, 0);
public char: string = "";
public size: number = 0;
public node: cc.Node = null;
}
```
fontutil.ts
```import { FontBinPacker } from "./fontbinpacker";
import { Rect } from "./rect";
import BinPackBuilder from "./binpackbuilder";
import Item from "./item";
export class FontUtil {
public static run(rects: Array<cc.Rect>) {
let font = {
width: 0,
height: 0
};
this.getImageRects(rects, font);
let binBuilder = new BinPackBuilder();
binBuilder.init(font.width, font.height, rects)
if (!binBuilder.build()) {
binBuilder = null;
}
return binBuilder;
}
/**
* 生成字体描述文件
* @param fontName 文件名
* @param items 打包项数组
* @param lH 行高
* @param w 图片宽
* @param h 图片高
* @param count 数量
* @param sW 空格宽度
*/
public static genFontFnt(fontName, items, lH, w, h, count, sW): boolean {
let info = FontUtil.genInfo(fontName, "0", "0", "0", "ANSI", "0", "0", "1", "1", "0,0,0,0", "0,0");
info += FontUtil.genCommon(lH.toString(), "0", w.toString(), h.toString(), "1", "0");
info += FontUtil.genPage("0", fontName + ".png");
info += FontUtil.genChars(count + 1);
info += FontUtil.genChar(this.getCharId(" ").toString(), "0", "0", "0", "0", "0", "0", sW.toString(), "0", "0");
for (let i = 0; i < items.length; i++) {
let item = items[i] as Item;
info += FontUtil.genChar(this.getCharId(item.char).toString(),
item.imgSize.x.toString(),
item.imgSize.y.toString(),
item.imgSize.width.toString(),
item.imgSize.height.toString(),
"0", "0", item.imgSize.width.toString(), "0", "0");
}
FontUtil.saveToFile(info, fontName);
return true;
}
public static getImageRects(rects: Array<cc.Rect>, font) {
let sourceRects: Array<cc.Rect> = new Array<cc.Rect>();
let totalArea: number = 0;
for (let i = 0; i < rects.length; i++) {
let rect = rects[i];
sourceRects.push(rect);
totalArea += rect.width * rect.height;
}
let powerWidth = 1;
let powerHeight = 1;
while (true) {
let area = Math.pow(2, powerWidth) * Math.pow(2, powerHeight);
if (totalArea > area) {
if (powerWidth <= powerHeight) {
powerWidth++;
} else {
powerHeight++;
}
} else {
break;
}
}
let width = Math.pow(2, powerWidth);
let height = Math.pow(2, powerHeight);
font.width = width;
font.height = height;
return sourceRects;
}
public static getCharId(text: string) {
let char: string = text.charAt(0);
let id: number = char.charCodeAt(0);
return id;
}
/**
* 获取info字符串
* @param face 字体名称
* @param size 大小
* @param bold 加粗
* @param italic 斜体
* @param charset 编码字符集
* @param unicode Unicode
* @param stretchH 纵向缩放百分比
* @param smooth 开启平滑
* @param aa 开启抗锯齿
* @param padding 内边距
* @param spacing 外边距
*/
public static genInfo(face: string, size: string, bold: string,
italic: string, charset: string, unicode: string, stretchH: string,
smooth: string, aa: string, padding: string, spacing: string) {
let str: string = `info face="{0}" size={1} bold={2} italic={3} charset="{4}" unicode={5} stretchH={6} smooth={7} aa={8} padding={9} spacing={10}\n`
str = this.stringFormat(str, face, size, bold,italic, charset, unicode, stretchH, smooth, aa, padding, spacing);
return str;
}
/**
* common
* @param lineHeight 行高
* @param base 字的基本大小
* @param scaleW 图片大小
* @param scaleH 图片大小
* @param pages 此种字体用到了几张图
* @param packed 图片不压缩
*/
public static genCommon(lineHeight: string, base: string, scaleW: string, scaleH: string, pages: string, packed: string) {
let str: string = `common lineHeight={0} base={1} scaleW={2} scaleH={3} pages={4} packed={5}\n`
str = this.stringFormat(str, lineHeight, base, scaleW, scaleW, pages, packed);
return str;
}
/**
* page
* @param id 第一页
* @param file 贴图名称
*/
public static genPage(id: string, file: string) {
let str: string = `page id={0} file="{1}"\n`;
str = this.stringFormat(str, id, file);
return str;
}
/**
* chars
* @param count 当前贴图中所容纳的字体数量
*/
public static genChars(count: string) {
let str: string = `chars count={0}\n\n`;
str = this.stringFormat(str, count);
return str;
}
/**
* 数据描述
* @param id 第一个字符编码
* @param x x位置
* @param y y位置
* @param width 宽度
* @param height 高度
* @param xoffset x像素偏移
* @param yoffset y像素偏移
* @param xadvance x往后移
* @param page 字的图块在第一页上
* @param chnl
*/
public static genChar(id: string, x: string, y: string, width: string, height: string,
xoffset: string, yoffset: string, xadvance: string, page: string, chnl: string) {
let str: string = `char id={0} x={1} y={2} width={3} height={4} xoffset={5} yoffset={6} xadvance={7} page={8} chnl={9}\n`;
str = this.stringFormat(str, id, x, y, width, height, xoffset, yoffset, xadvance, page, chnl);
return str;
}
/**
* 字符串格式化
* @param args
*/
public static stringFormat(...args: string[]) {
let s = args[0];
for (let i = 0; i < args.length - 1; i++) {
if (args[i + 1] != undefined) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, args[i + 1]);
}
}
return s;
}
/**
* 保存文件
* @param text
* @param fileName
*/
public static saveToFile(text: string, fileName: string = "default.fnt") {
if (cc.sys.isBrowser) {
let textFileAsBlob = new Blob([text], {type: "text/plain"});
let fileNameToSaveAs = fileName + ".fnt";
let downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.URL != null) {
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
} else {
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
document.body.removeChild(downloadLink);
}
}
}```
drag.ts
```import Global from "./global";
const { ccclass, property } = cc._decorator;
@ccclass
export default class Drag extends cc.Component {
getWorldPos(): cc.Vec2 {
let nodePos = this.node.convertToWorldSpaceAR(cc.Vec2.ZERO);
let v2 = cc.v2(nodePos.x, nodePos.y);
return v2;
}
setWorldPos(pos: cc.Vec2) {
let nodePos = this.node.parent.convertToNodeSpaceAR(pos);
let v2 = cc.v2(nodePos.x, nodePos.y);
this.node.position = v2;
}
onLoad() {}
start() {}
update() {}
lateUpdate() {}
onDestroy() {}
onEnable() {
this.node.on(cc.Node.EventType.TOUCH_START, (touchEvent: cc.Event.EventTouch) => {
Global.eventListener.fire("DRAG_START", this.node.name);
}, this);
this.node.on(cc.Node.EventType.TOUCH_MOVE, (touchEvent: cc.Event.EventTouch) => {
// let location = touchEvent.getDelta();
// this.node.position = cc.v2(this.node.x + location.x, this.node.y + location.y);
this.setWorldPos(touchEvent.getLocation());
Global.eventListener.fire("DRAG_MOVE", this.node.name);
}, this);
this.node.on(cc.Node.EventType.TOUCH_END, (touchEvent: cc.Event.EventTouch) => {
Global.eventListener.fire("DRAG_END", this.node.name);
}, this);
this.node.on(cc.Node.EventType.TOUCH_CANCEL, (touchEvent: cc.Event.EventTouch) => {
}, this);
}
onDisable() {
this.node.off(cc.Node.EventType.TOUCH_START);
this.node.off(cc.Node.EventType.TOUCH_MOVE);
this.node.off(cc.Node.EventType.TOUCH_END);
this.node.off(cc.Node.EventType.TOUCH_CANCEL);
}
}
```
rect.ts
```/**
* Rect 信息
*/
export class Rect extends cc.Rect {
id: number = 0;
constructor(id: number = 0, x: number = 0, y: number = 0, width: number = 0, height: number = 0) {
super(x, y, width, height);
this.id = id;
}
}```
beziernode.ts
```import CubicBezier from "./cubicbezier";
export default class BezierNode {
private index_: number = 0;
public get index(): number {
return this.index_;
}
public set index(value: number) {
this.index_ = value;
}
p0: cc.Node = null;
p1: cc.Node = null;
p2: cc.Node = null;
p3: cc.Node = null;
p0p:cc.Vec2 = cc.Vec2.ZERO;
p1p:cc.Vec2 = cc.Vec2.ZERO;
p2p:cc.Vec2 = cc.Vec2.ZERO;
p3p:cc.Vec2 = cc.Vec2.ZERO;
cubicBezier: CubicBezier = null;
public constructor(p0: cc.Node, p1: cc.Node, p2: cc.Node, p3: cc.Node) {
this.p0 = p0;
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.cubicBezier = new CubicBezier();
}
updatePosition (dt: any) {
this.p0p = this.p0.position;
this.p1p = this.p1.position;
this.p2p = this.p2.position;
this.p3p = this.p3.position;
this.cubicBezier.p0 = this.p0p;
this.cubicBezier.p1 = this.p1p;
this.cubicBezier.p2 = this.p2p;
this.cubicBezier.p3 = this.p3p;
}
getLength(t: number){
return this.cubicBezier.length(t);
}
}
```
eventlistener.ts
```export interface Listener {
cb: Function;
once: boolean;
}
export interface EventsType {
[eventName: string]: Listener[];
}
export default class EventListener {
es: EventsType = {};
on(eventName: string, cb: Function, once: boolean = false) {
if (!this.es[eventName]) {
this.es[eventName] = [];
}
this.es[eventName].push({
cb,
once,
});
}
once(eventName: string, cb: Function) {
this.on(eventName, cb, true);
}
fire(eventName: string, ...params: any[]) {
const listeners = this.es[eventName] || [];
let l = listeners.length;
for (let i = 0; i < l; i++) {
const { cb, once } = listeners[i];
cb.apply(this, params);
if (once) {
listeners.splice(i, 1);
i--;
l--;
}
}
}
off(eventName?: string, cb?: Function) {
// clean all
if (eventName === undefined) {
this.es = {};
} else {
if (cb === undefined) {
// clean the eventName's listeners
delete this.es[eventName];
} else {
const listeners = this.es[eventName] || [];
// clean the event and listener
let l = listeners.length;
for (let i = 0; i < l; i++) {
if (listeners[i].cb === cb) {
listeners.splice(i, 1);
i--;
l--;
}
}
}
}
}
// cname of fire
emit(eventName: string, ...params: any[]) {
this.fire(eventName, ...params);
}
}```
saveimage.ts
```/**
* 通过Renderer功能保存图片
*/
import Global from "../global";
const {ccclass, property} = cc._decorator;
@ccclass
export default class SaveImage extends cc.Component {
@property(cc.Camera)
camera: cc.Camera = null;
_texture: cc.RenderTexture;
_canvas: HTMLCanvasElement;
onLoad() {
// 注册事件
Global.eventListener.on("GENERATE_IMAGE", (fileName) => {
this.init();
this.downloadImg(fileName);
});
}
onDestroy() {
Global.eventListener.off("GENERATE_IMAGE");
}
/**
* 初始化
*/
init() {
let texture = new cc.RenderTexture();
let gl = cc.game._renderContext;
texture.initWithSize(this.node.width, this.node.height, gl.STENCIL_INDEX8);
this.camera.targetTexture = texture;
this.camera.node.position = cc.v2(this.node.width * 0.5, -this.node.height * 0.5);
this._texture = texture;
}
initImage() {
let dataURL = this._canvas.toDataURL("image/png");
let img = document.createElement("img");
img.src = dataURL;
return img;
}
/**
* 读取渲染的数据
*/
createSprite() {
let width = this._texture.width;
let height = this._texture.height;
if (!this._canvas) {
this._canvas = document.createElement("canvas");
this._canvas.width = width;
this._canvas.height = height;
} else {
this.clearCanvas();
}
let ctx = this._canvas.getContext("2d");
this.camera.render(this.node);
let data = this._texture.readPixels();
let rowBytes = width * 4;
for (let row = 0; row < height; row++) {
let srow = height - 1 - row;
let imageData = ctx.createImageData(width, 1);
let start = srow * width * 4;
for (let i = 0; i < rowBytes; i++) {
imageData.data[i] = data[start + i];
}
ctx.putImageData(imageData, 0, row);
}
return this._canvas;
}
/**
* 下载打包好的图片
*/
downloadImg(fileName) {
this.createSprite();
var dataURL = this._canvas.toDataURL("image/png")
var a = document.createElement("a")
a.href = dataURL;
a.download = fileName + ".png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
/**
* 清除Canvas
*/
clearCanvas() {
let ctx = this._canvas.getContext('2d');
ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
}
}
```
itemui.ts
```import Global from "../global";
const {ccclass, property} = cc._decorator;
@ccclass
export default class ItemUI extends cc.Component {
didEnded(editbox) {
let id = this.getId();
let charText = this.node.getChildByName("char").getComponent(cc.EditBox);
if (charText.string === "") { // 为空设置默认值
let pathNode = this.node.getChildByName("imgpath");
let label = pathNode.getComponent(cc.Label);
charText.string = label.string.charAt(0);
}
Global.eventListener.fire("CHANGE_CHAR", id, charText.string);
}
onOperator() {
let id = this.getId();
Global.eventListener.fire("REMOVE_ITEM", id);
}
getId() {
let idNode = this.node.getChildByName("id");
let label = idNode.getComponent(cc.Label);
let id = parseInt(label.string);
return id;
}
}
```
menu.ts
```const {ccclass, property} = cc._decorator;
@ccclass
export default class Menu extends cc.Component {
toBMFontScene() {
cc.director.loadScene("BMFont");
}
toBSplineCurveScene() {
cc.director.loadScene("Curve");
}
}
```
NewScript.ts
```import BaseDraw from "./basedraw";
const { ccclass, property } = cc._decorator;
@ccclass
export default class NewClass extends BaseDraw {
start() {
this.clearDraw()
this.drawRectPoint(cc.Vec2.ZERO, cc.Color.GREEN, 10, 10, true);
// this.drawRectPoint(this.node.position, cc.Color.GREEN, 10, false);
this.node.width = 20;
this.node.height = 20;
}
update() {
this.clearDraw()
this.drawRectPoint(cc.Vec2.ZERO, cc.Color.GREEN, 10, 10, true);
// this.drawRectPoint(this.node.position, cc.Color.GREEN, 10, false);
}
}
```
fontbinpacker.ts
```const BestShortSideFit = 0; // /< -BSSF: 放置在最合适的短边上
const BestLongSideFit = 1; // /< -BLSF: 放置在最合适的长边上
const BestAreaFit = 2; // /< -BAF: 放置合适的最小容器中
const BottomLeftRule = 3; // /< -BL: 俄罗斯方块放置
const ContactPointRule = 4; // /< -CP: 尽可能选择矩形接触其他矩形的位置。
/**
* FontBinPacker
*/
class FontBinPacker {
binWidth: number = 0; // 打包宽度
binHeight: number = 0; // 打包高度
allowRotate: boolean = false; // 是否允许旋转
usedRectangles: Array<cc.Rect> = new Array<cc.Rect>(); // 使用过的矩形
freeRectangles: Array<cc.Rect> = new Array<cc.Rect>(); // 未使用的矩形
freeRectanglesLength: number = 0;
isSuccessBinPack: boolean = false;
/**
* @constructor
* @param {Number} width 容器宽度
* @param {Number} height 容器高度
* @param {Boolean} [allowRotate=false] 是否允许旋转矩形
*/
constructor(width: number, height: number, allowRotate: boolean = false) {
this._init(width, height, allowRotate);
}
/**
* 初始化
* @param {Number} width 容器宽度
* @param {Number} height 容器高度
* @param {Boolean} allowRotate 是否允许旋转矩形
*/
private _init(width: number, height: number, allowRotate: boolean): void {
this.binWidth = width;
this.binHeight = height;
this.allowRotate = allowRotate || false;
this.usedRectangles.length = 0;
this.freeRectangles.length = 0;
this.freeRectangles.push(new cc.Rect(0, 0, width, height));
}
/**
* 插入新矩形
* @param {Number} width 矩形宽度
* @param {Number} height 矩形高度
* @param {Number} method pack规则
* @return {Rect}
*/
insert(width: number, height: number, method: number): cc.Rect {
let newNode = new cc.Rect();
const score1 = {
value: 0
};
const score2 = {
value: 0
};
method = method || 0;
switch (method) {
case BestShortSideFit:
newNode = this._findPositionForNewNodeBestShortSideFit(width, height, score1, score2);
break;
case BottomLeftRule:
newNode = this._findPositionForNewNodeBottomLeft(width, height, score1, score2);
break;
case ContactPointRule:
newNode = this._findPositionForNewNodeContactPoint(width, height, score1);
break;
case BestLongSideFit:
newNode = this._findPositionForNewNodeBestLongSideFit(width, height, score2, score1);
break;
case BestAreaFit:
newNode = this._findPositionForNewNodeBestAreaFit(width, height, score1, score2);
break;
default:
break;
}
if (newNode.height === 0) {
return newNode;
}
this._placeRectangle(newNode);
return newNode;
}
/**
* 插入一组矩形
* @param {Rect[]} rectangles 一组矩形, 可以自定义属性
* @param {Number} method 打包规则
* @return {Rect[]} 打包结果
*/
insert2(rectangles: cc.Rect[], method: number): cc.Rect[] {
this.freeRectanglesLength = rectangles.length;
const res: Array<cc.Rect> = new Array<cc.Rect>();
while (rectangles.length > 0) {
let bestScore1: number = Infinity;
let bestScore2: number = Infinity;
let bestRectangleIndex: number = -1;
let bestNode = new cc.Rect();
// 遍历寻找最佳的可放置矩形
for (let i = 0; i < rectangles.length; i++) {
const score1 = {
value: 0
};
const score2 = {
value: 0
};
const newNode = this._scoreRectangle(rectangles[i].width, rectangles[i].height, method, score1, score2);
if (score1.value < bestScore1 || (score1.value === bestScore1 && score2.value < bestScore2)) {
bestScore1 = score1.value;
bestScore2 = score2.value;
bestNode = newNode;
bestRectangleIndex = i;
}
}
// 没有找到最佳位置
if (bestRectangleIndex === -1) {
return res;
}
// 将剩余空间进行切割
this._placeRectangle(bestNode);
const rect = rectangles.splice(bestRectangleIndex, 1)[0];
rect.x = bestNode.x;
rect.y = bestNode.y;
res.push(rect);
}
if (res.length === this.freeRectanglesLength) {
this.isSuccessBinPack = true;
}
return res;
}
isBinPackSuccess() {
return this.isSuccessBinPack;
}
// 将空间分割
_placeRectangle(node: cc.Rect) {
let numRectanglesToProcess = this.freeRectangles.length;
for (let i = 0; i < numRectanglesToProcess; i++) {
if (this._splitFreeNode(this.freeRectangles[i], node)) {
this.freeRectangles.splice(i, 1);
i--;
numRectanglesToProcess--;
}
}
// 重新梳理
this._pruneFreeList();
// 将已经装箱的矩形加入数组
this.usedRectangles.push(node);
}
// 寻找最佳矩形
_scoreRectangle(width, height, method, score1, score2) {
let newNode = new cc.Rect();
score1.value = Infinity;
score2.value = Infinity;
switch (method) {
case BestShortSideFit:
newNode = this._findPositionForNewNodeBestShortSideFit(width, height, score1, score2);
break;
case BottomLeftRule:
newNode = this._findPositionForNewNodeBottomLeft(width, height, score1, score2);
break;
case ContactPointRule:
newNode = this._findPositionForNewNodeContactPoint(width, height, score1);
//score1 = -score1;
break;
case BestLongSideFit:
newNode = this._findPositionForNewNodeBestLongSideFit(width, height, score2, score1);
break;
case BestAreaFit:
newNode = this._findPositionForNewNodeBestAreaFit(width, height, score1, score2);
break;
default:
break;
}
if (newNode.height === 0) {
score1.value = Infinity;
score2.value = Infinity;
}
return newNode;
}
// 空间利用率
_occupancy() {
const usedRectangles = this.usedRectangles;
let usedSurfaceArea = 0;
for (let i = 0; i < usedRectangles.length; i++) {
usedSurfaceArea += usedRectangles[i].width * usedRectangles[i].height;
}
return usedSurfaceArea / (this.binWidth * this.binHeight);
}
public wastedBinArea() {
const usedRectangles = this.usedRectangles;
let usedSurfaceArea = 0;
for (let i = 0; i < usedRectangles.length; i++) {
usedSurfaceArea += usedRectangles[i].width * usedRectangles[i].height;
}
return (this.binWidth * this.binHeight) - usedSurfaceArea;
}
_findPositionForNewNodeBottomLeft(width, height, bestY, bestX) {
const freeRectangles = this.freeRectangles;
const bestNode = new cc.Rect();
bestY.value = Infinity;
let rect: cc.Rect;
let topSideY: number;
for (let i = 0; i < freeRectangles.length; i++) {
rect = freeRectangles[i];
if (rect.width >= width && rect.height >= height) {
topSideY = rect.y + height;
if (topSideY < bestY.value || (topSideY === bestY.value && rect.x < bestX.value)) {
bestNode.x = rect.x;
bestNode.y = rect.y;
bestNode.width = width;
bestNode.height = height;
bestY.value = topSideY;
bestX.value = rect.x;
}
}
if (this.allowRotate && rect.width >= height && rect.height >= width) {
topSideY = rect.y + width;
if (topSideY < bestY.value || (topSideY === bestY.value && rect.x < bestX.value)) {
bestNode.x = rect.x;
bestNode.y = rect.y;
bestNode.width = height;
bestNode.height = width;
bestY.value = topSideY;
bestX.value = rect.x;
}
}
}
return bestNode;
}
_findPositionForNewNodeBestShortSideFit(width, height, bestShortSideFit, bestLongSideFit) {
const freeRectangles = this.freeRectangles;
const bestNode = new cc.Rect();
bestShortSideFit.value = Infinity;
let rect;
let leftoverHoriz;
let leftoverVert;
let shortSideFit;
let longSideFit;
for (let i = 0; i < freeRectangles.length; i++) {
rect = freeRectangles[i];
if (rect.width >= width && rect.height >= height) {
leftoverHoriz = Math.abs(rect.width - width);
leftoverVert = Math.abs(rect.height - height);
shortSideFit = Math.min(leftoverHoriz, leftoverVert);
longSideFit = Math.max(leftoverHoriz, leftoverVert);
if (shortSideFit < bestShortSideFit.value || (shortSideFit === bestShortSideFit.value && longSideFit < bestLongSideFit.value)) {
bestNode.x = rect.x;
bestNode.y = rect.y;
bestNode.width = width;
bestNode.height = height;
bestShortSideFit.value = shortSideFit;
bestLongSideFit.value = longSideFit;
}
}
let flippedLeftoverHoriz;
let flippedLeftoverVert;
let flippedShortSideFit;
let flippedLongSideFit;
if (this.allowRotate && rect.width >= height && rect.height >= width) {
flippedLeftoverHoriz = Math.abs(rect.width - height);
flippedLeftoverVert = Math.abs(rect.height - width);
flippedShortSideFit = Math.min(flippedLeftoverHoriz, flippedLeftoverVert);
flippedLongSideFit = Math.max(flippedLeftoverHoriz, flippedLeftoverVert);
if (flippedShortSideFit < bestShortSideFit.value || (flippedShortSideFit === bestShortSideFit.value && flippedLongSideFit < bestLongSideFit.value)) {
bestNode.x = rect.x;
bestNode.y = rect.y;
bestNode.width = height;
bestNode.height = width;
bestShortSideFit.value = flippedShortSideFit;
bestLongSideFit.value = flippedLongSideFit;
}
}
}
return bestNode;
}
_findPositionForNewNodeBestLongSideFit(width, height, bestShortSideFit, bestLongSideFit) {
const freeRectangles = this.freeRectangles;
const bestNode = new cc.Rect();
bestLongSideFit.value = Infinity;
let rect;
let leftoverHoriz;
let leftoverVert;
let shortSideFit;
let longSideFit;
for (let i = 0; i < freeRectangles.length; i++) {
rect = freeRectangles[i];
if (rect.width >= width && rect.height >= height) {
leftoverHoriz = Math.abs(rect.width - width);
leftoverVert = Math.abs(rect.height - height);
shortSideFit = Math.min(leftoverHoriz, leftoverVert);
longSideFit = Math.max(leftoverHoriz, leftoverVert);
if (longSideFit < bestLongSideFit.value || (longSideFit === bestLongSideFit.value && shortSideFit < bestShortSideFit.value)) {
bestNode.x = rect.x;
bestNode.y = rect.y;
bestNode.width = width;
bestNode.height = height;
bestShortSideFit.value = shortSideFit;
bestLongSideFit.value = longSideFit;
}
}
if (this.allowRotate && rect.width >= height && rect.height >= width) {
leftoverHoriz = Math.abs(rect.width - height);
leftoverVert = Math.abs(rect.height - width);
shortSideFit = Math.min(leftoverHoriz, leftoverVert);
longSideFit = Math.max(leftoverHoriz, leftoverVert);
if (longSideFit < bestLongSideFit.value || (longSideFit === bestLongSideFit.value && shortSideFit < bestShortSideFit.value)) {
bestNode.x = rect.x;
bestNode.y = rect.y;
bestNode.width = height;
bestNode.height = width;
bestShortSideFit.value = shortSideFit;
bestLongSideFit.value = longSideFit;
}
}
}
return bestNode;
}
_findPositionForNewNodeBestAreaFit(width, height, bestAreaFit, bestShortSideFit) {
const freeRectangles = this.freeRectangles;
const bestNode = new cc.Rect();
bestAreaFit.value = Infinity;
let rect;
let leftoverHoriz;
let leftoverVert;
let shortSideFit;
let areaFit;
for (let i = 0; i < freeRectangles.length; i++) {
rect = freeRectangles[i];
areaFit = rect.width * rect.height - width * height;
if (rect.width >= width && rect.height >= height) {
leftoverHoriz = Math.abs(rect.width - width);
leftoverVert = Math.abs(rect.height - height);
shortSideFit = Math.min(leftoverHoriz, leftoverVert);
if (areaFit < bestAreaFit.value || (areaFit === bestAreaFit.value && shortSideFit < bestShortSideFit.value)) {
bestNode.x = rect.x;
bestNode.y = rect.y;
bestNode.width = width;
bestNode.height = height;
bestShortSideFit.value = shortSideFit;
bestAreaFit = areaFit;
}
}
if (this.allowRotate && rect.width >= height && rect.height >= width) {
leftoverHoriz = Math.abs(rect.width - height);
leftoverVert = Math.abs(rect.height - width);
shortSideFit = Math.min(leftoverHoriz, leftoverVert);
if (areaFit < bestAreaFit.value || (areaFit === bestAreaFit.value && shortSideFit < bestShortSideFit.value)) {
bestNode.x = rect.x;
bestNode.y = rect.y;
bestNode.width = height;
bestNode.height = width;
bestShortSideFit.value = shortSideFit;
bestAreaFit.value = areaFit;
}
}
}
return bestNode;
}
_commonIntervalLength(i1start, i1end, i2start, i2end) {
if (i1end < i2start || i2end < i1start) {
return 0;
}
return Math.min(i1end, i2end) - Math.max(i1start, i2start);
}
_contactPointScoreNode(x, y, width, height) {
const usedRectangles = this.usedRectangles;
let score = 0;
if (x === 0 || x + width === this.binWidth) score += height;
if (y === 0 || y + height === this.binHeight) score += width;
let rect;
for (let i = 0; i < usedRectangles.length; i++) {
rect = usedRectangles[i];
if (rect.x === x + width || rect.x + rect.width === x) score += this._commonIntervalLength(rect.y, rect.y + rect.height, y, y + height);
if (rect.y === y + height || rect.y + rect.height === y) score += this._commonIntervalLength(rect.x, rect.x + rect.width, x, x + width);
}
return score;
}
_findPositionForNewNodeContactPoint(width, height, bestContactScore) {
const freeRectangles = this.freeRectangles;
const bestNode = new cc.Rect();
bestContactScore.value = -1;
let rect;
let score;
for (let i = 0; i < freeRectangles.length; i++) {
rect = freeRectangles[i];
if (rect.width >= width && rect.height >= height) {
score = this._contactPointScoreNode(rect.x, rect.y, width, height);
if (score > bestContactScore.value) {
bestNode.x = rect.x;
bestNode.y = rect.y;
bestNode.width = width;
bestNode.height = height;
bestContactScore = score;
}
}
if (this.allowRotate && rect.width >= height && rect.height >= width) {
score = this._contactPointScoreNode(rect.x, rect.y, height, width);
if (score > bestContactScore.value) {
bestNode.x = rect.x;
bestNode.y = rect.y;
bestNode.width = height;
bestNode.height = width;
bestContactScore.value = score;
}
}
}
return bestNode;
}
_splitFreeNode(freeNode, usedNode) {
const freeRectangles = this.freeRectangles;
// 用SAT测试矩形是否相交
if (usedNode.x >= freeNode.x + freeNode.width || usedNode.x + usedNode.width <= freeNode.x
|| usedNode.y >= freeNode.y + freeNode.height || usedNode.y + usedNode.height <= freeNode.y) return false;
let newNode;
if (usedNode.x < freeNode.x + freeNode.width && usedNode.x + usedNode.width > freeNode.x) {
// 在使用的节点顶部添加新节点
if (usedNode.y > freeNode.y && usedNode.y < freeNode.y + freeNode.height) {
newNode = freeNode.clone();
newNode.height = usedNode.y - newNode.y;
freeRectangles.push(newNode);
}
// 在使用的节点底部添加新节点
if (usedNode.y + usedNode.height < freeNode.y + freeNode.height) {
newNode = freeNode.clone();
newNode.y = usedNode.y + usedNode.height;
newNode.height = freeNode.y + freeNode.height - (usedNode.y + usedNode.height);
freeRectangles.push(newNode);
}
}
if (usedNode.y < freeNode.y + freeNode.height && usedNode.y + usedNode.height > freeNode.y) {
// 在使用的节点左侧添加新节点
if (usedNode.x > freeNode.x && usedNode.x < freeNode.x + freeNode.width) {
newNode = freeNode.clone();
newNode.width = usedNode.x - newNode.x;
freeRectangles.push(newNode);
}
// 在使用的节点右侧添加新节点
if (usedNode.x + usedNode.width < freeNode.x + freeNode.width) {
newNode = freeNode.clone();
newNode.x = usedNode.x + usedNode.width;
newNode.width = freeNode.x + freeNode.width - (usedNode.x + usedNode.width);
freeRectangles.push(newNode);
}
}
return true;
}
// 梳理未使用的数组, 过滤有重叠的数据
_pruneFreeList() {
const freeRectangles = this.freeRectangles;
for (let i = 0; i < freeRectangles.length; i++) {
for (let j = i + 1; j < freeRectangles.length; j++) {
if (freeRectangles[i].containsRect(freeRectangles[j])) {
freeRectangles.splice(j, 1);
j--;
}
if (freeRectangles[j].containsRect(freeRectangles[i])) {
freeRectangles.splice(i, 1);
i--;
break;
}
}
}
}
}
export {
FontBinPacker,
BestShortSideFit,
BestLongSideFit,
BestAreaFit,
BottomLeftRule,
ContactPointRule
};```
bmfontui.ts
```import ItemMgr from "./itemmgr";
import Item from "./item";
import { FontUtil } from "./fontutil";
import { Rect } from "./rect";
import BaseDraw from "../basedraw";
import Global from "../global";
const { ccclass, property } = cc._decorator;
const FILE_STYLE = `
position:absolute;
margin-left:0%;
margin-top:0px;
-webkit-user-select:file;
display:none;`;
const DRAG_STYLE = `
position:absolute;
margin-left:0px;
margin-top:0px;
border:1px solid #aaa;
width:100px;
height:100px;
-webkit-user-select:file;`;
@ccclass
export default class BMFontUI extends cc.Component {
input: HTMLInputElement = null; // 文件选择
zone: any = null;
@property(cc.ScrollView)
fontScrollView: cc.ScrollView = null; // 字体滚动
@property(cc.ScrollView)
imageScrollView: cc.ScrollView = null; // 图像滚动
itemMgr: ItemMgr = null; // item 管理器
itemList: Array<Item> = new Array<Item>(); // item 数组
fileName: string = "default";
packItemList: Array<Item> = null;
onLoad() {
this.itemMgr = cc.find("Canvas/ItemMgr").getComponent(ItemMgr);
this.createDragZone(); // 创建拖拽区域
Global.eventListener.on("REMOVE_ITEM", (id) => {
let item = this.deleteItem(id);
this.itemMgr.deleteItem(item.node);
for (let i = 0; i < this.itemList.length; i++) {
let tempItem = this.itemList[i];
let tempId = tempItem.id;
let tempNode = tempItem.node;
let idNode = tempNode.getChildByName("id");
let label = idNode.getComponent(cc.Label);
label.string = tempId.toString();
}
});
Global.eventListener.on("CHANGE_CHAR", (id, char) => {
let item = this.getItemDataById(id);
item.char = char;
});
}
/**
* 是否可用功能
*/
isCanUse(): boolean {
let isCanUse = false;
if (cc.sys.isBrowser) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
isCanUse = true;
}
}
return isCanUse;
}
/**
* 创建文件选择器
*/
createFileLoader() {
if (this.isCanUse()) {
let onInput = (e: any) => {
let file = e.target.files[0];
if (!file.type.match("image.*")) {
return;
}
this.readFile(file);
};
let input = document.createElement("input");
input.setAttribute("type", "file");
input.setAttribute("accept", "image/*");
input.setAttribute("style", FILE_STYLE);
document.getElementsByTagName("body")[0].appendChild(input);
input.addEventListener("change", onInput);
this.input = input;
} else {
alert('不支持');
}
}
/**
* 创建拖拽区域
*/
createDragZone() {
if (this.isCanUse()) {
document.ondragover = (e) => {
e.preventDefault();
};
document.ondrag = (e) => {
e.preventDefault();
};
let fileSelect = (e) => {
e.stopPropagation();
e.preventDefault();
let list = e.dataTransfer.files;
for (let i = 0; i < list.length; i++) {
let file = list[i];
if (!file.type.match("image.*")) {
return;
}
this.readFile(file);
}
};
let dragOver = (e) => {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
};
let zone = document.createElement("div");
zone.setAttribute("type", "file");
zone.setAttribute("accept", "image/*");
zone.setAttribute("style", DRAG_STYLE);
zone.addEventListener('dragover', dragOver, false);
zone.addEventListener('drop', fileSelect, false);
document.getElementsByTagName("body")[0].appendChild(zone);
this.zone = zone;
} else {
alert('不支持');
}
}
/**
* 读取文件
* @param file 文件
*/
readFile(file) {
// 通过文件名查询是否存在item
if (!this.hasItemByName(file.name)) {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (e) => {
let img = document.createElement("img");
img.src = e.target.result;
let texture = new cc.Texture2D();
texture._nativeAsset = img;
if (texture.loaded) { // 纹理已经加载
this.createItem(texture, file.name, file.size);
this.addFontScrollItem(texture);
} else { // 纹理未加载
texture.on("load", () => {
this.createItem(texture, file.name, file.size);
this.addFontScrollItem(texture);
});
}
};
}
}
/**
* 文件选择器回调
*/
onFileLoader() {
if (this.input) {
document.getElementsByTagName("body")[0].removeChild(this.input);
}
this.createFileLoader();
if (this.input) {
this.input.click();
}
}
onFileNameDidEnd(editbox: cc.EditBox) {
let fileName = editbox.string;
if (fileName === "") {
fileName = editbox.placeholder;
}
this.fileName = fileName;
}
// 增
createItem(texture, imgPath, size) {
// id 从1开始
let id = this.itemList.length + 1;
let item = new Item();
item.id = id;
item.img = texture;
item.imgPath = imgPath;
item.char = item.imgPath.charAt(0);
item.imgSize.width = texture.width;
item.imgSize.height = texture.height;
item.imgSize.id = id;
item.size = size;
this.itemList.push(item);
}
// 删
deleteItem(id) {
let item = this.getItemDataById(id);
let index = this.itemList.indexOf(item)
this.itemList.splice(index, 1);
for (let i = 0; i < this.itemList.length; i++) {
let tempItem = this.itemList[i];
tempItem.id = i + 1;
}
return item;
}
// 改
modifyItem() {
}
// 查
searchItem() {
}
/**
* 点击生成图片回调
* 根据打包好的位置信息, 创建图片
*/
onGenerateImage() {
let rects: Array<cc.Rect> = new Array<cc.Rect>();
for (let i = 0; i < this.itemList.length; i++) {
let item = this.itemList[i];
rects.push(new Rect(item.id, 0, 0, item.imgSize.width, item.imgSize.height));
}
let binBuilder = FontUtil.run(rects);
this.imageScrollView.content.removeAllChildren();
let width = binBuilder.atlasWidth; // 打包后宽度
let height = binBuilder.atlasHeight; // 打包后高度
let packs = binBuilder.packedRects;
this.imageScrollView.content.width = width;
this.imageScrollView.content.height = height;
// let sp = new cc.Node();
// let spc = sp.addComponent(BaseDraw);
// sp.parent = this.imageScrollView.content;
// sp.anchorX = 0;
// sp.anchorY = 1;
// sp.position = cc.v2(0, 0);
// spc.drawRectPoint(cc.v2(0, -height), cc.Color.RED, width, height, false);
if(this.packItemList === null) {
this.packItemList = new Array<Item>();
} else {
this.packItemList.length = 0;
}
for (let i = 0; i < packs.length; i++) {
let rect = packs[i] as Rect;
let id = rect.id;
let itemData = this.getItemDataById(id);
itemData.imgSize.x = rect.x;
itemData.imgSize.y = rect.y;
this.packItemList.push(itemData);
let sp = new cc.Node();
let spc = sp.addComponent(cc.Sprite);
sp.parent = this.imageScrollView.content;
sp.anchorX = 0;
sp.anchorY = 1;
sp.position = cc.v2(rect.x, -rect.y);
spc.spriteFrame = new cc.SpriteFrame(itemData.img);
}
}
/**
* 生成bmf回调, 通过Camera制作
*/
onGenerateBMF() {
if (this.packItemList) {
Global.eventListener.fire("GENERATE_IMAGE", this.fileName);
let spaceWidth = 10; // 空格宽度
let lineHeight = 10; // 行高
for (let i = 0; i < this.packItemList.length; i++) {
let packItem = this.packItemList[i];
if (packItem.imgSize.width > spaceWidth) {
spaceWidth = packItem.imgSize.width;
}
if (packItem.imgSize.height > lineHeight) {
lineHeight = packItem.imgSize.height;
}
}
FontUtil.genFontFnt(
this.fileName,
this.packItemList,
lineHeight,
this.imageScrollView.content.width,
this.imageScrollView.content.height,
this.packItemList.length,
spaceWidth);
}
}
onBackMain() {
Global.eventListener.off("REMOVE_ITEM");
Global.eventListener.off("CHANGE_CHAR");
if (this.input) {
document.getElementsByTagName("body")[0].removeChild(this.input);
}
if (this.zone) {
document.getElementsByTagName("body")[0].removeChild(this.zone);
}
cc.director.loadScene("Menu");
}
/**
* 添加一个显示的字体
* @param texture 纹理
*/
addFontScrollItem(texture: cc.Texture2D) {
let itemData = this.itemList[this.itemList.length - 1];
let item = this.itemMgr.createItem();
itemData.node = item;
let scrollView = this.fontScrollView;
scrollView.content.addChild(item);
let id = item.getChildByName("id").getComponent(cc.Label);
id.string = itemData.id.toString();
let img = item.getChildByName("img").getComponent(cc.Sprite);
img.spriteFrame = new cc.SpriteFrame(itemData.img);
let name = item.getChildByName("imgpath").getComponent(cc.Label);
name.string = itemData.imgPath.toString();
let size = item.getChildByName("size").getComponent(cc.Label);
size.string = Math.floor(itemData.size / 1024).toString();
let contentSize = item.getChildByName("imgsize").getComponent(cc.Label);
contentSize.string = "" + itemData.imgSize.width + "*" + itemData.imgSize.height;
let charText = item.getChildByName("char").getComponent(cc.EditBox);
charText.string = "" + itemData.char;
}
getItemDataById(id: number) {
for (let i = 0; i < this.itemList.length; i++) {
let item = this.itemList[i];
if (item.id === id) {
return item;
}
}
}
hasItemByName(name: string) {
let flag: boolean = false;
for (let i = 0; i < this.itemList.length; i++) {
let item = this.itemList[i];
if (item.imgPath === name) {
flag = true;
}
}
return flag;
}
}
```
pointmgr.ts
```const {ccclass, property} = cc._decorator;
@ccclass
export default class PointMgr extends cc.Component {
@property(cc.Prefab)
readonly prefab: cc.Prefab = null;
@property
readonly size: number = 5;
private pool_: cc.NodePool = null;
public get pool(): cc.NodePool {
return this.pool_;
}
public set pool(value: cc.NodePool) {
this.pool_ = value;
}
onLoad() {
if (this.size < 1) {
throw Error("size < 1");
}
if (this.prefab === null) {
throw Error("prefab null");
}
const pool = new cc.NodePool();
for (let i = 0; i < this.size; i++) {
pool.put(cc.instantiate(this.prefab));
}
this.pool = pool;
}
public createPoint(): cc.Node {
let point = null;
if (this.pool.size() > 0) {
point = this.pool.get();
} else {
point = cc.instantiate(this.prefab);
}
return point;
}
public deletePoint(point: cc.Node) {
this.pool.put(point);
}
public clearPool() {
this.pool.clear();
}
}
```
global.ts
```import EventListener from "./eventlistener";
export const enum ControlMode {
FREE,
ALIGNED,
MIRRORED,
CLOSE
};
export default class Global {
private static instance_: Global = new Global();
private static eventListenter_: EventListener = new EventListener();
private constructor() { }
public static getInstance(): Global {
return Global.instance_;
}
public static set eventListener(v: EventListener) {
this.eventListenter_ = v;
}
public static get eventListener(): EventListener {
return this.eventListenter_;
}
public static controlMode = ControlMode.FREE;
}
```
cubicbezier.ts
```export default class CubicBezier {
constructor(p0?: cc.Vec2, p1?: cc.Vec2, p2?: cc.Vec2, p3?: cc.Vec2) {
if (!!p0) {
this.p0 = p0;
}
if (!!p1) {
this.p1 = p1;
}
if (!!p2) {
this.p2 = p2;
}
if (!!p3) {
this.p3 = p3;
}
}
private p0_: cc.Vec2 = cc.Vec2.ZERO;
private p1_: cc.Vec2 = cc.Vec2.ZERO;
private p2_: cc.Vec2 = cc.Vec2.ZERO;
private p3_: cc.Vec2 = cc.Vec2.ZERO;
public get p0(): cc.Vec2 {
return this.p0_;
}
public set p0(value: cc.Vec2) {
this.p0_ = value;
}
public get p1(): cc.Vec2 {
return this.p1_;
}
public set p1(value: cc.Vec2) {
this.p1_ = value;
}
public get p2(): cc.Vec2 {
return this.p2_;
}
public set p2(value: cc.Vec2) {
this.p2_ = value;
}
public get p3(): cc.Vec2 {
return this.p3_;
}
public set p3(value: cc.Vec2) {
this.p3_ = value;
}
/**
* 时间t的x坐标
* @param t 时间
* x坐标
*/
b3X(t: number): number {
let retn: number;
let oneMinusT = 1 - t;
let quadraticT = Math.pow(t, 2);
let cubicT = Math.pow(t, 3);
let quadraticOMT = Math.pow(oneMinusT, 2);
let cubicOMT = Math.pow(oneMinusT, 3);
retn = cubicOMT * this.p0.x + 3 * t * quadraticOMT * this.p1.x + 3 * quadraticT * oneMinusT * this.p2.x + cubicT * this.p3.x;
return retn;
}
/**
* 时间t的y坐标
* @param t 时间
* x坐标
*/
b3Y(t: number): number {
let retn: number;
let oneMinusT = 1 - t;
let quadraticT = Math.pow(t, 2);
let cubicT = Math.pow(t, 3);
let quadraticOMT = Math.pow(oneMinusT, 2);
let cubicOMT = Math.pow(oneMinusT, 3);
retn = cubicOMT * this.p0.y + 3 * t * quadraticOMT * this.p1.y + 3 * quadraticT * oneMinusT * this.p2.y + cubicT * this.p3.y;
return retn;
}
getPoint(t: number): cc.Vec2 {
let x: number, y: number;
let oneMinusT = 1 - t;
let quadraticT = Math.pow(t, 2);
let cubicT = Math.pow(t, 3);
let quadraticOMT = Math.pow(oneMinusT, 2);
let cubicOMT = Math.pow(oneMinusT, 3);
x = cubicOMT * this.p0.x + 3 * t * quadraticOMT * this.p1.x + 3 * quadraticT * oneMinusT * this.p2.x + cubicT * this.p3.x;
y = cubicOMT * this.p0.y + 3 * t * quadraticOMT * this.p1.y + 3 * quadraticT * oneMinusT * this.p2.y + cubicT * this.p3.y;
return cc.v2(x, y);
}
getFirstDerivative(t: number): cc.Vec2 {
let x: number, y: number;
let oneMinusT = 1 - t;
let quadraticT = Math.pow(t, 2);
let quadraticOMT = Math.pow(oneMinusT, 2);
x = 3 * quadraticOMT * (this.p1.x - this.p0.x) + 6 * oneMinusT * t * (this.p2.x - this.p1.x) + 3 * quadraticT * (this.p3.x - this.p2.x);
y = 3 * quadraticOMT * (this.p1.y - this.p0.y) + 6 * oneMinusT * t * (this.p2.y - this.p1.y) + 3 * quadraticT * (this.p3.y - this.p2.y);
return cc.v2(x, y);
}
getVelocity(t: number): cc.Vec2 {
return this.getFirstDerivative(t);
}
getDirection(t: number) {
let vel = this.getVelocity(t);
return vel.normalize();
}
/**
* 求t时刻的真实时间
* @param t 时间
* @returns 真实时间
*/
t2rt(t: number) {
let realTime: number, deltaTime: number;
let bezierX: number;
let x = this.p0.x + (this.p3.x - this.p0.x) * t;
realTime = 1;
deltaTime = 0.0;
do {
if (deltaTime > 0) {
realTime -= realTime / 2;
} else {
realTime += realTime / 2;
}
bezierX = this.b3X(realTime);
deltaTime = bezierX - x;
} while (deltaTime > 0.0000001);
return realTime;
}
t2rt2(t: number) {
let totalLength = this.length(1);
let len = t * totalLength;
let t1 = t, t2: any;
let dt: number;
do {
t2 = t1 - (this.length(t1) - len) / this.bezeSpeed(t1);
dt = Math.abs(t1 - t2);
if (dt < 0.00001) {
break;
}
t1 = t2;
} while (true);
return t2;
}
invert(t: number, l: number) {
let t1 = t, t2: number;
do {
t2 = t1 - (this.length(t1) - l) / this.bezeSpeed(t1);
if (Math.abs(t1 - t2) < 0.00001) break;
t1 = t2;
} while (true);
return t2;
}
/**
* 求t时间的曲线长度
* @param t 时间
* @returns 曲线长度
*/
length(t: number) {
let TOTAL_SIMPSON_STEP: number = 100000;
let stepCounts: number = TOTAL_SIMPSON_STEP * t;
let halfCounts: number;
let i = 0;
let sum1 = 0, sum2 = 0, dStep: number;
if (stepCounts === 0) {
return 0;
}
if (stepCounts % 2 === 0) { // 偶数
stepCounts++;
}
halfCounts = stepCounts / 2;
dStep = t / stepCounts;
while (i < halfCounts) {
sum1 += this.bezeSpeed((2 * i + 1) * dStep);
i++;
}
i = 1;
while (i < halfCounts) {
sum2 += this.bezeSpeed(2 * i * dStep);
i++;
}
return ((this.bezeSpeed(0) + this.bezeSpeed(1) + 2 * sum2 + 4 * sum1) * dStep / 3);
}
/**
* 求x方向速度分量
* @param t 时间
* @returns x方向速度分量
*/
bezeSpeedX(t: number) {
let oneMinusT = 1 - t;
let quadraticT = Math.pow(t, 2);
let quadraticOMT = Math.pow(oneMinusT, 2);
return -3 * this.p0.x * quadraticOMT + 3 * this.p1.x * quadraticOMT - 6 * this.p1.x * oneMinusT * t + 6 * this.p2.x * oneMinusT * t - 3 * this.p2.x * quadraticT + 3 * this.p3.x * quadraticT;
}
/**
* 求y方向速度分量
* @param t 时间
* @returns y方向速度分量
*/
bezeSpeedY(t: number) {
let oneMinusT = 1 - t;
let quadraticT = Math.pow(t, 2);
let quadraticOMT = Math.pow(oneMinusT, 2);
return -3 * this.p0.y * quadraticOMT + 3 * this.p1.y * quadraticOMT - 6 * this.p1.y * oneMinusT * t + 6 * this.p2.y * oneMinusT * t - 3 * this.p2.y * quadraticT + 3 * this.p3.y * quadraticT;
}
/**
* 求速度
* @param t 时间
* @returns 速度
*/
bezeSpeed(t: number) {
let vx = this.bezeSpeedX(t);
let vy = this.bezeSpeedY(t);
return Math.sqrt(Math.pow(vx, 2) + Math.pow(vy, 2));
}
}
```
test.ts
```import BaseDraw from "./basedraw";
import PointMgr from "./pointmgr";
import BezierNode from "./beziernode";
import Global, { ControlMode } from "./global";
import CubicBezier from "./cubicbezier";
const { ccclass, property } = cc._decorator;
@ccclass
export default class Test extends BaseDraw {
@property(cc.Node)
frame: cc.Node = null;
pointMgr:PointMgr = null; // 点管理器
bezierNodeList: Array<BezierNode> = new Array();
time: number = 0;
playTime: number = 20;
isPlay: boolean = false;
totalLength: number = 0;
lineLengthList: Array<number> = new Array();
pointList: Array<cc.Vec2> = new Array();
isAddPoint: boolean = false;
onLoad() {
super.onLoad();
this.pointMgr = cc.find("Canvas/PointMgr").getComponent(PointMgr);
Global.eventListener.on("ADD_SPLINE", () => {
this.isPlay = false;
this.isAddPoint = false;
this.pointList.length = 0;
this.addBezierNode();
});
Global.eventListener.on("DELETE_SPLINE", () => {
this.isPlay = false;
this.isAddPoint = false;
this.pointList.length = 0;
this.removeBezierNode();
});
Global.eventListener.on("DELETE_ALL_SPLINE", () => {
this.isPlay = false;
this.isAddPoint = false;
this.pointList.length = 0;
while (this.bezierNodeList.length > 0) {
this.removeBezierNode();
}
});
Global.eventListener.on("EDITOR_SCALE_SMALL", () => {
let scale = this.node.scale;
this.node.scale = scale * 0.5;
this.frame.scale = scale * 0.5;
});
Global.eventListener.on("EDITOR_SCALE_BIG", () => {
let scale = this.node.scale;
this.node.scale = scale * 2;
this.frame.scale = scale * 2;
});
Global.eventListener.on("EDITOR_SCALE_RESTORE", () => {
this.node.scale = 1;
this.frame.scale = 1;
this.node.position = cc.v2(0, 0);
this.frame.position = cc.v2(0, 0);
});
Global.eventListener.on("ARROW_L", () => {
let pos = this.node.position;
this.node.position = pos.add(cc.v2(-1, 0));
this.frame.position = pos.add(cc.v2(-1, 0));
});
Global.eventListener.on("ARROW_U", () => {
let pos = this.node.position;
this.node.position = pos.add(cc.v2(0, 1));
this.frame.position = pos.add(cc.v2(0, 1));
});
Global.eventListener.on("ARROW_R", () => {
let pos = this.node.position;
this.node.position = pos.add(cc.v2(1, 0));
this.frame.position = pos.add(cc.v2(1, 0));
});
Global.eventListener.on("ARROW_D", () => {
let pos = this.node.position;
this.node.position = pos.add(cc.v2(0, -1));
this.frame.position = pos.add(cc.v2(0, -1));
});
Global.eventListener.on("PLAY", () => {
if (this.bezierNodeList.length === 0) {return}
this.isPlay = true;
this.totalLength = 0;
this.lineLengthList.splice(0, this.lineLengthList.length) ;
for (let index = 0; index < this.bezierNodeList.length; index++) {
let bezierNode = this.bezierNodeList[index];
let len = bezierNode.getLength(1);
this.totalLength += len;
this.lineLengthList[index] = len;
}
this.isAddPoint = true;
this.time = 0;
});
Global.eventListener.on("STOP", () => {
this.isAddPoint = false;
this.pointList.length = 0;
this.isPlay = false;
});
Global.eventListener.on("CLICK_SAVE", (data) => {
if (data === "path") {
let pointList: Array<cc.Vec2> = new Array();
for (let i = 0; i < this.pointList.length; i++) {
let point = this.pointList[i];
let newPoint = new cc.Vec2(parseFloat(point.x.toFixed(2)), parseFloat(point.y.toFixed(2)));
pointList.push(newPoint);
}
Global.eventListener.fire("SAVE", JSON.stringify(pointList));
} else if (data === "ctrl") {
let bezierList = [];
for (let i = 0; i < this.bezierNodeList.length; i++) {
let bezierNode = this.bezierNodeList[i];
let bezier = {
p0: bezierNode.p0p,
p1: bezierNode.p1p,
p2: bezierNode.p2p,
p3: bezierNode.p3p
};
bezierList.push(bezier);
}
Global.eventListener.fire("SAVE", JSON.stringify(bezierList));
}
});
Global.eventListener.on("SET_CHANGE_PLAY_TIME", (time: number) => {
this.playTime = time;
});
Global.eventListener.on("CONTROL_MODE_CHANGE", () => {
this.isAddPoint = false;
this.isPlay = false;
this.pointList.length = 0;
let len = this.bezierNodeList.length;
if (len > 0) {
let firstBezierNode = this.bezierNodeList[0];
let lastBezierNode = this.bezierNodeList[len - 1];
if (Global.controlMode === ControlMode.CLOSE) {
this.pointMgr.deletePoint(lastBezierNode.p3);
lastBezierNode.p3 = firstBezierNode.p0;
} else {
if (lastBezierNode.p3.name === firstBezierNode.p0.name) {
let p3 = this.pointMgr.createPoint();
let index = len * 3;
p3.name = "Node" + index;
p3.position = firstBezierNode.p0.position;
this.node.addChild(p3);
lastBezierNode.p3 = p3;
}
}
}
});
Global.eventListener.on("DRAG_START", (name: string) => {
cc.log("-----------DRAG_START-----------");
// name: NodeXXX
let index = Number(name.substring(4));
let len = this.bezierNodeList.length;
if (index === 0) { // 第一个端点
cc.log(0);
} else if (index > 0 && index % 3 === 0) { // 端点
let bezierIndex1 = index / 3 - 1;
let bezierIndex2 = index / 3;
if (len === bezierIndex2) { // 最后的端点
cc.log(bezierIndex1);
} else {
cc.log(bezierIndex1);
cc.log(bezierIndex2);
}
} else if (index > 0 && index % 3 != 0) { // 控制点
let bezierIndex = Math.floor(index / 3);
cc.log(bezierIndex);
}
});
Global.eventListener.on("DRAG_MOVE", (name: string) => {
this.isAddPoint = false;
this.isPlay = false;
this.pointList.length = 0;
// name: NodeXXX
let index = Number(name.substring(4));
let len = this.bezierNodeList.length;
if (index === 0) { // 第一个点
cc.log(0);
} else if (index > 0 && index % 3 === 0) { // 端点
let bezierIndex1 = index / 3 - 1;
let bezierIndex2 = index / 3;
if (len === bezierIndex2) { // 最后的端点
cc.log(bezierIndex1);
} else {
cc.log(bezierIndex1);
cc.log(bezierIndex2);
}
} else if (index > 0 && index % 3 != 0) { // 控制点
let bezierIndex = Math.floor(index / 3);
let indexOfBezier = index % 3;
cc.log(bezierIndex);
if (len > 1) {
if ( index > 1 && index < (len * 3 - 1)) {
let currBezierNode = this.bezierNodeList[bezierIndex];
let movePoint: cc.Node = null;
let middlePoint: cc.Node = null;
let currPoint: cc.Node = null;
if (indexOfBezier === 1) {
let lastBezierNode = this.bezierNodeList[bezierIndex - 1];
movePoint = lastBezierNode.p2;
middlePoint = currBezierNode.p0;
currPoint = currBezierNode.p1;
} else if (indexOfBezier === 2) {
let nextBezierNode = this.bezierNodeList[bezierIndex + 1];
movePoint = nextBezierNode.p1;
middlePoint = currBezierNode.p3;
currPoint = currBezierNode.p2;
}
if (movePoint && middlePoint) {
let currVec: cc.Vec2 = currPoint.position.sub(middlePoint.position);
if (Global.controlMode === ControlMode.ALIGNED) {
let moveLen = movePoint.position.sub(middlePoint.position).mag();
movePoint.position = middlePoint.position.add(currVec.neg().normalize().mul(moveLen));
} else if (Global.controlMode === ControlMode.MIRRORED) {
movePoint.position = middlePoint.position.add(currVec.neg());
}
}
}
}
}
});
Global.eventListener.on("DRAG_END", (name: string) => {
// name: NodeXXX
let index = Number(name.substring(4));
let len = this.bezierNodeList.length;
if (index === 0) { // 第一个点
cc.log(0);
} else if (index > 0 && index % 3 === 0) { // 端点
let bezierIndex1 = index / 3 - 1;
let bezierIndex2 = index / 3;
if (len === bezierIndex2) { // 最后的端点
cc.log(bezierIndex1);
} else {
cc.log(bezierIndex1);
cc.log(bezierIndex2);
}
} else if (index > 0 && index % 3 != 0) { // 控制点
let bezierIndex = Math.floor(index / 3);
cc.log(bezierIndex);
}
});
}
onDestroy() {
Global.eventListener.off("ADD_SPLINE");
Global.eventListener.off("DELETE_SPLINE");
Global.eventListener.off("DELETE_ALL_SPLINE");
Global.eventListener.off("EDITOR_SCALE_SMALL");
Global.eventListener.off("EDITOR_SCALE_BIG");
Global.eventListener.off("EDITOR_SCALE_RESTORE");
Global.eventListener.off("ARROW_L");
Global.eventListener.off("ARROW_U");
Global.eventListener.off("ARROW_R");
Global.eventListener.off("ARROW_D");
Global.eventListener.off("PLAY");
Global.eventListener.off("STOP");
Global.eventListener.off("CLICK_SAVE");
Global.eventListener.off("SET_CHANGE_PLAY_TIME");
Global.eventListener.off("CONTROL_MODE_CHANGE");
Global.eventListener.off("DRAG_START");
Global.eventListener.off("DRAG_MOVE");
Global.eventListener.off("DRAG_END");
}
addBezierNode() {
let len = this.bezierNodeList.length;
if (len === 0) {
let p0 = this.pointMgr.createPoint();
let p1 = this.pointMgr.createPoint();
let p2 = this.pointMgr.createPoint();
let p3 = p0;
p0.name = "Node0";
p1.name = "Node1";
p2.name = "Node2";
p0.position = cc.v2(-640, 0);
p1.position = cc.v2(-500, 140);
p2.position = cc.v2(-500, -140);
this.node.addChild(p0);
this.node.addChild(p1);
this.node.addChild(p2);
if (Global.controlMode != ControlMode.CLOSE) {
p3 = this.pointMgr.createPoint();
p3.name = "Node3";
p3.position = cc.v2(-360, 0);
this.node.addChild(p3);
}
let bezierNode = new BezierNode(p0, p1, p2, p3);
bezierNode.index = 0;
this.bezierNodeList.push(bezierNode);
} else {
let lastBezierNode = this.bezierNodeList[len - 1];
let lastP = lastBezierNode.p3;
let tempP = this.pointMgr.createPoint();
let p0 = lastP;
let p1 = this.pointMgr.createPoint();
let p2 = this.pointMgr.createPoint();
let p3 = tempP;
let index = len * 3;
p1.name = "Node" + (index + 1);
p2.name = "Node" + (index + 2);
p3.name = "Node" + (index + 3);
let p0x = lastP.position.x;
let p0y = lastP.position.y
p1.position = cc.v2(p0x + 140, p0y + 140);
p2.position = cc.v2(p0x + 140, p0y - 140);
p3.position = cc.v2(p0x + 280, p0y);
if (Global.controlMode === ControlMode.CLOSE) {
p0 = tempP
p3 = lastP;
p0.name = "Node" + index;
p3.name = lastP.name;
p0.position = lastP.position;
p3.position = lastP.position;
this.node.addChild(p0);
this.node.addChild(p1);
this.node.addChild(p2);
lastBezierNode.p3 = p0;
} else {
this.node.addChild(p1);
this.node.addChild(p2);
this.node.addChild(p3);
}
let bezierNode = new BezierNode(p0, p1, p2, p3);
bezierNode.index = len;
this.bezierNodeList.push(bezierNode);
}
}
removeBezierNode() {
let len = this.bezierNodeList.length;
if (len > 1) {
let lastLastBezierNode = this.bezierNodeList[len - 2];
let lastBezierNode = this.bezierNodeList[len - 1];
this.pointMgr.deletePoint(lastBezierNode.p1);
this.pointMgr.deletePoint(lastBezierNode.p2);
if (Global.controlMode == ControlMode.CLOSE) {
this.pointMgr.deletePoint(lastLastBezierNode.p3);
lastLastBezierNode.p3 = lastBezierNode.p3;
} else {
this.pointMgr.deletePoint(lastBezierNode.p3);
}
this.bezierNodeList.pop();
} else if (len === 1) {
let lastBezierNode = this.bezierNodeList[len - 1];
this.pointMgr.deletePoint(lastBezierNode.p0);
this.pointMgr.deletePoint(lastBezierNode.p1);
this.pointMgr.deletePoint(lastBezierNode.p2);
if (Global.controlMode != ControlMode.CLOSE) {
this.pointMgr.deletePoint(lastBezierNode.p3);
}
this.bezierNodeList.pop();
}
}
update(dt) {
this.clearDraw()
for (const i in this.bezierNodeList) {
if (this.bezierNodeList.hasOwnProperty(i)) {
let bezierNode = this.bezierNodeList[i];
bezierNode.updatePosition(dt);
this.setStrokeColor(cc.Color.BLUE);
this.setLineWidth(2);
this.drawBezierCurve(bezierNode.p0p, bezierNode.p1p, bezierNode.p2p, bezierNode.p3p);
this.drawLine(bezierNode.p0p, bezierNode.p1p, new cc.Color(0, 255, 0, 50), 2);
this.drawLine(bezierNode.p2p, bezierNode.p3p, new cc.Color(0, 255, 0, 50), 2);
}
}
if (this.isPlay === true) {
this.time += dt;
this.updatePoint();
}
}
updatePoint() {
for (let i = 0; i < this.pointList.length; i++) {
this.drawCirclePoint(this.pointList[i], cc.Color.RED, 3, true);
}
if (this.time < this.playTime) {
// let len = cubicbezier.length(1);
// let t1 = cubicbezier.t2rt(0.2);
// let t2 = cubicbezier.t2rt2(0.2);
// let fd = cubicbezier.getFirstDerivative(0.5);
// let d = cubicbezier.getVelocity(0.5);
// let v = cubicbezier.getDirection(0.5);
// for (let j = 0; j < 100; j += 1) {
// let t = j / 100;
// const l = t * len;
// t = cubicbezier.invert(t, l);
// let point = cubicbezier.getPoint(t);
// let color = cc.color(Math.floor(Math.random() * 255), Math.floor(Math.random() * 255), Math.floor(Math.random() * 255));
// this.drawCirclePoint(point, color, 8, true);
// }
let totalLength = this.totalLength;
let percent = this.time / this.playTime;
let perLen = totalLength * percent;
let bezierNodeListLen = this.bezierNodeList.length;
let currIndex = 0;
for (let index = 0; index < bezierNodeListLen; index++) {
perLen -= this.lineLengthList[index];
if (perLen < 0) {
currIndex = index;
break;
}
}
perLen += this.lineLengthList[currIndex];
let len = this.lineLengthList[currIndex];
percent = perLen / len;
let rt = this.bezierNodeList[currIndex].cubicBezier.invert(percent, perLen);
let point = this.bezierNodeList[currIndex].cubicBezier.getPoint(rt);
let color = cc.color(Math.floor(Math.random() * 255), Math.floor(Math.random() * 255), Math.floor(Math.random() * 255));
// this.drawCirclePoint(point, color, 3, true);
this.drawCirclePoint(point, cc.Color.GREEN, 3, true);
if (this.isAddPoint) {
this.pointList.push(point);
}
} else {
this.time = 0;
this.isAddPoint = false;
}
}
}
```
basedraw.ts
```const { ccclass, property } = cc._decorator;
@ccclass
export default class BaseDraw extends cc.Component {
private graphics_: cc.Graphics; // undefined
/// getter, setter
public get graphics(): cc.Graphics {
return this.graphics_;
}
public set graphics(value: cc.Graphics) {
this.graphics_ = value;
}
onLoad() {
if (!this.graphics) {
this.graphics = this.addComponent(cc.Graphics);
} else {
this.graphics = this.getComponent(cc.Graphics);
}
}
/**
* 设置线条的结束端样式
* @param lineCap
*/
setLineCap(lineCap: cc.Graphics.LineCap) {
this.graphics.lineCap = lineCap;
}
/**
* 设置两条线相交时的拐角类型
* @param lineJoin
*/
setLineJoin(lineJoin: cc.Graphics.LineJoin) {
this.graphics.lineJoin = lineJoin;
}
/**
* 设置当前线条的宽度
* @param width
*/
setLineWidth(width: number) {
this.graphics.lineWidth = width;
}
// 笔触颜色
setStrokeColor(color: cc.Color) {
this.graphics.strokeColor = color;
}
// 设置填充颜色
setFillColor(color: cc.Color) {
this.graphics.fillColor = color;
}
// 画圆形点
drawCirclePoint(p0: cc.Vec2, color: cc.Color, size: number, isFill: boolean) {
this.setStrokeColor(color);
this.graphics.circle(p0.x, p0.y, size);
this.graphics.stroke();
if (isFill) {
this.setFillColor(color);
this.graphics.fill();
}
}
/**
* 画矩形点
*/
drawRectPoint(p0: cc.Vec2, color: cc.Color, width: number, height: number, isFill: boolean) {
this.setStrokeColor(color);
this.graphics.rect(p0.x, p0.y, width, height);
this.graphics.stroke();
if (isFill) {
this.setFillColor(color);
this.graphics.fill();
}
}
drawLine(p0: cc.Vec2, p1: cc.Vec2, color: cc.Color, width: number) {
this.setLineWidth(width);
this.setStrokeColor(color);
this.setLineCap(cc.Graphics.LineCap.BUTT);
this.graphics.moveTo(p0.x, p0.y);
this.graphics.lineTo(p1.x, p1.y);
this.graphics.stroke();
}
/**
* 绘制三次贝塞尔曲线
* @param p0 起点
* @param p1 控制点1
* @param p2 控制点2
* @param p3 终点
*/
drawBezierCurve(p0: cc.Vec2, p1: cc.Vec2, p2: cc.Vec2, p3: cc.Vec2) {
this.graphics.moveTo(p0.x, p0.y);
this.graphics.bezierCurveTo(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
this.graphics.stroke();
}
/**
* 清除绘画内容
*/
clearDraw() {
this.graphics.clear();
}
}
```
binpackbuilder.ts
```import {
FontBinPacker,
BestShortSideFit,
BestLongSideFit,
BestAreaFit,
BottomLeftRule,
ContactPointRule
} from "./fontbinpacker";
export default class BinPackBuilder {
atlasWidth: number = 0;
atlasHeight: number = 0;
sourceRects: Array<cc.Rect> = null;
packedRects: Array<cc.Rect> = null;
public init(atlasWidth: number, atlasHeight: number, rects: Array<cc.Rect>): void {
this.atlasWidth = atlasWidth;
this.atlasHeight = atlasHeight;
this.sourceRects = rects;
}
public build(): boolean {
let packs = this.findBestBinPacker(this.atlasWidth, this.atlasHeight, this.sourceRects);
if (packs === null) {
return false
} else {
this.packedRects = packs;
return true;
}
}
findBestBinPacker(width: number, height: number, currentRects: cc.Rect[]) {
let binPackers = new Array<FontBinPacker>();
let packedRects = new Array();
let binPackerMethods = [
BestShortSideFit,
BestLongSideFit,
BestAreaFit,
BottomLeftRule,
ContactPointRule
];
for (let i = 0; i < binPackerMethods.length; i++) {
let tempW = width;
let tempH = height;
let rects = JSON.parse(JSON.stringify(currentRects));
let binPack = new FontBinPacker(tempW, tempH);
let packs = binPack.insert2(rects, binPackerMethods[i]);
while (!binPack.isBinPackSuccess()) {
if (tempW > tempH) {
tempH *= 2;
} else {
tempW *= 2;
}
rects = JSON.parse(JSON.stringify(currentRects));
binPack = new FontBinPacker(tempW, tempW);
packs = binPack.insert2(rects, binPackerMethods[i]);
}
packedRects.push(packs);
binPackers.push(binPack);
}
let leastWastedArea = Infinity;
let leastWastedIndex = -1;
for (let i = 0; i < binPackers.length; i++) {
let binPacker = binPackers[i];
let wastedArea = binPacker.wastedBinArea();
if (wastedArea < leastWastedArea) {
leastWastedIndex = i;
}
}
if (leastWastedIndex == -1) {
return null;
} else {
this.atlasWidth = binPackers[leastWastedIndex].binWidth;
this.atlasHeight = binPackers[leastWastedIndex].binHeight;
return packedRects[leastWastedIndex];
}
}
}
```
ui.ts
```import Global, { ControlMode } from "./global";
import Drag from "./drag";
const {ccclass, property} = cc._decorator;
@ccclass
export default class UI extends cc.Component {
@property(cc.Sprite)
sprite: cc.Sprite = null;
input: HTMLInputElement = null;
onLoad() {
this.setReferenceDraggable(false);
this.createFileLoader();
Global.eventListener.on("SAVE", (text: string) => {
this.saveToFile(text);
});
}
onDestroy() {
Global.eventListener.off("SAVE");
}
createFileLoader() {
if (cc.sys.isBrowser) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
let input = document.createElement("input");
input.setAttribute("type", "file");
input.setAttribute("accept", "image/*");
input.setAttribute("style", "position:absolute;margin-left:0%;margin-top:0px;-webkit-user-select:file;display:none");
document.getElementsByTagName("body")[0].appendChild(input);
let onInput = (e: any) => {
let file = e.target.files[0];
if (!file.type.match("image.*")) {
return false;
}
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (e) => {
let img = document.createElement("img");
img.src = e.target.result;
let texture = new cc.Texture2D();
texture._nativeAsset = img;
texture.on("load", () => {
this.sprite.spriteFrame = new cc.SpriteFrame(texture);
});
};
};
input.addEventListener("change", onInput);
this.input = input;
} else {
alert('不支持');
}
}
}
saveToFile(text: string, fileName: string = "filename") {
if (cc.sys.isBrowser) {
let textFileAsBlob = new Blob([text], {type: "application/json"});
let fileNameToSaveAs = "filename.json";
let downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.URL != null) {
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
} else {
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
document.body.removeChild(downloadLink);
}
}
onClickUp() {
this.node.position = cc.v2(0, 40);
}
onClickDown() {
this.node.position = cc.v2(0, -720);
}
onClickAddSpline() {
Global.eventListener.fire("ADD_SPLINE");
}
onClickDeleteSpline() {
Global.eventListener.fire("DELETE_SPLINE");
}
onClickDeleteAllSpline() {
Global.eventListener.fire("DELETE_ALL_SPLINE");
}
onClickScaleSmall() {
Global.eventListener.fire("EDITOR_SCALE_SMALL");
}
onClickScaleBig() {
Global.eventListener.fire("EDITOR_SCALE_BIG");
}
onClickScaleRestore() {
Global.eventListener.fire("EDITOR_SCALE_RESTORE");
}
onClickArrowL() {
Global.eventListener.fire("ARROW_L");
}
onClickArrowU() {
Global.eventListener.fire("ARROW_U");
}
onClickArrowR() {
Global.eventListener.fire("ARROW_R");
}
onClickArrowD() {
Global.eventListener.fire("ARROW_D");
}
onClickPlay() {
Global.eventListener.fire("PLAY");
}
onClickStop() {
Global.eventListener.fire("STOP");
}
onClickSave(button, customEventData) {
Global.eventListener.fire("CLICK_SAVE", customEventData);
}
onCheckEdit(toggle: cc.Toggle, customEventData) {
cc.log(toggle.isChecked)
Global.eventListener.fire("CHECK_EDIT");
}
onFileLoader() {
if (this.input) {
this.input.click();
}
}
onCheckReferenceEdit(toggle: cc.Toggle, customEventData) {
this.setReferenceDraggable(toggle.isChecked);
}
setReferenceDraggable(flag: boolean) {
if (this.sprite) {
let com = this.sprite.getComponent(Drag);
com.enabled = flag;
}
}
setChangePlayTime(target: cc.EditBox) {
Global.eventListener.fire("SET_CHANGE_PLAY_TIME", Number(target.string));
}
onControlMode(toggle: cc.Toggle, customEventData) {
let isChecked = toggle.isChecked;
let name = toggle.name.substring(0, 7)
if (name === "toggle1") {
Global.controlMode = ControlMode.FREE;
} else if (name=== "toggle2") {
Global.controlMode = ControlMode.ALIGNED;
} else if (name === "toggle3") {
Global.controlMode = ControlMode.MIRRORED;
} else if (name === "toggle4") {
Global.controlMode = ControlMode.CLOSE;
}
cc.log(Global.controlMode)
Global.eventListener.fire("CONTROL_MODE_CHANGE");
}
onBackMain() {
cc.director.loadScene("Menu");
}
}
```
fonttest.ts
```import BaseDraw from "../basedraw";
import { Rect } from "./rect";
import { FontBinPacker } from "./fontbinpacker";
const {ccclass, property} = cc._decorator;
@ccclass
export default class FontTest extends BaseDraw {
onLoad () {
super.onLoad();
}
start () {
let rects: Array<cc.Rect> = new Array<cc.Rect>();
rects.push(new Rect(1, 0, 0, 80, 80));
rects.push(new Rect(2, 0, 0, 80, 80));
rects.push(new Rect(3, 0, 0, 80, 80));
rects.push(new Rect(4, 0, 0, 80, 80));
rects.push(new Rect(5, 0, 0, 80, 80));
rects.push(new Rect(6, 0, 0, 80, 80));
rects.push(new Rect(7, 0, 0, 80, 80));
rects.push(new Rect(8, 0, 0, 80, 80));
let binPacker = new FontBinPacker(256, 512, false);
let sss = binPacker.insert2(rects, 0);
for (let i = 0; i < sss.length; i++) {
this.drawRectPoint(cc.v2(sss[i].x, -(sss[i].y + sss[i].height)), cc.Color.RED, sss[i].width, sss[i].height, false);
}
}
// update (dt) {}
}
```
|
742314100/g-hope
|
742314100/g-hope
getters.js
```export function getTabIndex(state) {
return state.tabIndex;
}
export function getHasLogin(state) {
return state.hasLogin;
}```
login.js
```import {post} from '../utils/http';
export function goLogin(params){
return post('/login',params);
}```
actions.js
```export function setTabIndex({ commit } , params) {
commit("CHANGE_TAB_INDEX", params);
}
export function setHasLogin({ commit } , params) {
commit("HAS_LOGIN", params);
}
```
mutations.js
```export function CHANGE_TAB_INDEX(state, val) {
state.tabIndex = val
}
export function HAS_LOGIN(state, val) {
state.hasLogin = val
}
```
index.js
```
import Vue from "vue";
import VueRouter from "vue-router";
import home from "../views/home";
import news from "../views/news"
import giftCenter from '../views/giftCenter';
import server from '../views/server'
import detail from '../views/detail'
import login from '../views/login'
Vue.use(VueRouter);
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
const routes = [
{
path: "/",
name: "home",
component: home,
},
{
path: "/news",
name: "news",
component: news,
},
{
path: "/giftCenter",
name: "giftCenter",
component: giftCenter,
},
{
path: "/server",
name: "server",
component: server,
},
{
path: "/detail",
name: "detail",
component: detail,
},
{
path: "/login",
name: "login",
component: login,
},
];
const router = new VueRouter({
routes,
});
export default router;
```
newsList.js
```import {get} from '../utils/http';
export function getNewsList(params){
return get('/newsList',params);
}
```
state.js
```export default {
tabIndex: "0",
hasLogin:false
};
```
http.js
```import axios from 'axios';
axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
axios.defaults.headers["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.headers["Cache-Control"] = "no-cache";
axios.defaults.headers["pragma"] = "no-cache";
//axios.defaults.baseURL = "http://82.156.109.184:3000";
axios.defaults.baseURL = "http://localhost:3000";
axios.defaults.withCredentials = false;
export function post(url, data, otherConfig) {
return axios.post(url, data, otherConfig);
}
export function get(url, data, otherConfig) {
return axios.get(url, { params: data, ...otherConfig });
}
```
homeSwiperList.js
```import {get} from '../utils/http';
export function getHomeSwiperList(params){
return get('/homeSwiperList',params);
}
```
details.js
```import {get} from '../utils/http';
export function getDetails(params){
return get('/details',params);
}
```
|
747-diego/holberton-smiling-school
|
747-diego/holberton-smiling-school
README.md
```# Web-Development
<img src="https://into-the-program.com/uploads/keyframes-animation-paused.jpg">
<hr>
<h1> Implement a design from scratch </h1>
<p> Hello! Thanks for diving in this far!
<br> In this project, I will implement from scratch, without any library, a web page. You will use all HTML/CSS/Accessibility/Responsive design knowledges that I have learned previously. </p>
<h3> What's Stored in here ? </h3>
<p> In this project, you will implement 3 web pages with Bootstrap. You will use all HTML/CSS/Accessibility/Responsive design/Bootstrap knowledges that you learned previously.
You won’t have a lot of instruction, you are free to implement it the way that you want - the objective is simple: Have fully functional web pages that look the same as the designer file. </p>
```
|
7506574455/Cab-Invoice-Generator
|
7506574455/Cab-Invoice-Generator
README.md
```# Cab-Invoice-Generator
welcome cab invoice generator problem
```
|
759325100/spark-dmi-koa
|
759325100/spark-dmi-koa
users.js
```module.exports = {
get: {
'/:id': getUserById
},
post: {
'/login': login
}
}
async function getUserById (ctx) {
// 参数验证
if (ctx.state.error.check(ctx, ctx.state.error.generate([['p', 'id']]))) {
let users = await ctx.state.redis.get('users')
console.log(users)
const findResult = await ctx.state.models.User.getUserById(ctx.params.id)
// 成功使用该方法响应
ctx.state.response(ctx, findResult)
}
}
async function login (ctx) {
if (ctx.state.error.check(ctx, ctx.state.error.generate([['b', 'username'], ['b', 'password']]))) {
const authResult = await ctx.state.models.User.login(ctx.request.body.username, ctx.request.body.password)
if (authResult) {
ctx.state.response(ctx, authResult)
} else {
ctx.body = ctx.state.error.business.user.authError
}
}
}
```
README.md
```# spark-dmi-koa```
scenes.js
```'use strict'
const {DataTypes} = require('sequelize')
class Scene {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'Scene'
// 定义模型实行
this.model = sequelize.define('scenes', {
name: DataTypes.STRING,
code: DataTypes.INTEGER,
icon: DataTypes.STRING,
cmd: DataTypes.STRING,
remark: DataTypes.INTEGER
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.hasMany(models.DeviceScene.model)
}
}
module.exports = Scene```
usergroups.js
```'use strict'
const {DataTypes} = require('sequelize')
class UserGroup {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'UserGroup'
// 定义模型实行
this.model = sequelize.define('usergroups', {
usergroupname: DataTypes.STRING,
prefix: DataTypes.STRING
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.hasMany(models.User.model)
}
}
module.exports = UserGroup
```
redis.js
```/*
* Redis的创建及管理
*/
const IORedis = require('ioredis')
const conf = require('../conf/conf')
class Redis {
constructor () {
this.conn = new IORedis(conf.redis.port, conf.redis.url, {dropBufferSupport: true})
}
getRedis () {
return this.conn
}
}
module.exports = new Redis()```
devices.js
```'use strict'
const {DataTypes} = require('sequelize')
class Device {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'Device'
// 定义模型实行
this.model = sequelize.define('devices', {
devicename: DataTypes.STRING,
coreid: DataTypes.STRING,
userId: DataTypes.INTEGER,
iphoneidentify: DataTypes.STRING,
androididentify: DataTypes.STRING,
maindevice: DataTypes.INTEGER,
status: DataTypes.INTEGER,
ison: DataTypes.INTEGER
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.belongsTo(models.DeviceGroup.model)
this.model.belongsTo(models.User.model)
this.model.hasMany(models.DeviceNode.model)
this.model.hasMany(models.ZoneDevice.model, {foreignKey: 'deviceId', sourceKey: 'id'})
this.model.hasMany(models.DeviceScene.model)
this.model.hasMany(models.ExtDevice.model)
}
}
module.exports = Device
```
zones.js
```/**
* Created by jinyang on 2017/6/02.
*/
'use strict'
const {DataTypes} = require('sequelize')
class Zone {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'Zone'
// 定义模型实行
this.model = sequelize.define('zones', {
no: DataTypes.STRING,
name: DataTypes.STRING,
position: DataTypes.STRING,
scenarioimg: DataTypes.STRING,
parentid: DataTypes.INTEGER,
depth: DataTypes.STRING,
sortno: DataTypes.INTEGER,
state: DataTypes.INTEGER,
remark: DataTypes.STRING,
ispublish: DataTypes.INTEGER,
token: DataTypes.STRING,
thumb: DataTypes.STRING
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.hasMany(models.ZoneUser.model)
this.model.hasMany(models.Student.model)
this.model.hasMany(models.ZoneDevice.model)
this.model.hasMany(models.SchoolNotice.model)
this.model.hasMany(models.SubjectSchedule.model)
this.model.belongsTo(models.Zone.model, {foreignKey: 'parentid'})
}
}
module.exports = Zone
```
devicegroups.js
```'use strict'
const {DataTypes} = require('sequelize')
class DeviceGroup {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'DeviceGroup'
// 定义模型实行
this.model = sequelize.define('devicegroups', {
devicegroupname: DataTypes.STRING
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.hasMany(models.Device.model)
}
}
module.exports = DeviceGroup
```
error.js
```/*
* 系统所有错误代码及可实现的错误检测和处理
*/
const error = {
token: {
invalid: {
code: 10000,
msg: 'The access token provided is invalid'
},
expired: {
code: 10002,
msg: 'The access token provided has expired'
},
legal: {
code: 10003,
msg: 'The dtit_key is not legal'
}
},
params: {
legal: {
code: 20000,
msg: 'parameter is not legal'
},
lackToken: {
code: 20101,
msg: 'The access token was not found'
},
lackId: {
code: 20102,
msg: 'The id was not found'
}
},
io: {
dbError: {
code: 30100,
msg: 'Database operation failed'
},
redisError: {
code: 30200,
msg: 'Redis operation failed'
},
redisValueNotFound: {
code: 30201,
msg: 'Redis value not found'
}
},
business: {
user: {
authError: {
code: 40200,
msg: 'Username or password error'
}
}
},
internal: {
serverError: {
code: 99999,
msg: 'Busy server'
},
timeout: {
code: 99998,
msg: 'Request timeout'
}
},
check (ctx, params) {
let ok = true
params.forEach(p => {
if (p.type === 'params' && !ctx.params[p.name]) {
ok = false
} else if (p.type === 'body' && !ctx.request.body[p.name]) {
ok = false
} else if (p.type === 'query' && !ctx.request.query[p.name]) {
ok = false
}
})
if (!ok) {
ctx.body = this.params.legal
}
return ok
},
generate (params) {
let result = []
// 根据params转换成check格式
params.forEach(p => {
if (p.length > 1) {
p = {type: p[0] === 'p' ? 'params' : p[0] === 'b' ? 'body' : p[0] === 'q' ? 'query' : p[0], name: p[1]}
} else {
p = {type: 'params', name: p[0]}
}
result.push(p)
})
return result
},
unknown (err, ctx) {
// 对未知异常进行处理,主要包含 1、自定义的异常 2、系统内部异常 3、IO异常(包含Redis、Mysql、文件操作等)
console.log(err.code)
}
}
module.exports = error```
extcmds.js
```'use strict'
const {DataTypes} = require('sequelize')
class ExtCmd {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'ExtCmd'
// 定义模型实行
this.model = sequelize.define('extcmd', {
action: DataTypes.STRING,
cmd: DataTypes.STRING,
split: DataTypes.INTEGER
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.hasMany(models.ExtDevice.model, {foreignKey: 'cmdId', sourceKey: 'id'})
}
}
module.exports = ExtCmd
```
index.js
```'use strict'
const fs = require('fs')
class Models {
init (sequelize) {
this.db = {}
fs
.readdirSync(__dirname)
.filter((file) => {
return (file.indexOf('.') !== 0) && (file !== 'index.js')
})
.forEach((file) => {
const Model = require(('./' + file))
const model = new Model(sequelize)
this.db[model.name || file.substr(0, file.indexOf('.'))] = model
})
Object.keys(this.db).forEach((modelName) => {
this.db[modelName].associate && this.db[modelName].associate(this.db)
})
console.log(this.db)
return this.db
}
}
module.exports = Models
```
devicerings.js
```'use strict'
const {DataTypes} = require('sequelize')
class DeviceRing {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'DeviceRing'
// 定义模型实行
this.model = sequelize.define('devicering', {
devicenodeId: DataTypes.INTEGER,
deviceId: DataTypes.INTEGER,
nodeno: DataTypes.INTEGER,
ringname: DataTypes.STRING,
ringno: DataTypes.INTEGER,
ison: DataTypes.INTEGER,
brightness: DataTypes.INTEGER,
R: DataTypes.INTEGER,
G: DataTypes.INTEGER,
B: DataTypes.INTEGER,
W: DataTypes.INTEGER
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.belongsTo(models.DeviceNode.model)
}
}
module.exports = DeviceRing
```
extdevices.js
```'use strict'
const {DataTypes} = require('sequelize')
class ExtDevice {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'ExtDevice'
// 定义模型实行
this.model = sequelize.define('extdevices', {
name: DataTypes.STRING,
type: DataTypes.INTEGER,
nd: DataTypes.INTEGER,
deviceId: DataTypes.STRING,
sid: DataTypes.INTEGER,
state: DataTypes.INTEGER,
cmdId: DataTypes.INTEGER
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.belongsTo(models.Device.model)
this.model.belongsTo(models.ExtCmd.model, {foreignKey: 'cmdId', targetKey: 'id'})
}
}
module.exports = ExtDevice
```
devicenodes.js
```'use strict'
const {DataTypes} = require('sequelize')
class DeviceNode {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'DeviceNode'
// 定义模型实行
this.model = sequelize.define('devicenodes', {
deviceId: DataTypes.INTEGER,
devicenodename: DataTypes.STRING,
devicetype: DataTypes.INTEGER,
devicenodetype: DataTypes.INTEGER,
nodeno: DataTypes.INTEGER,
ison: DataTypes.INTEGER,
sId: DataTypes.INTEGER,
scenarioId: DataTypes.INTEGER,
brightness: DataTypes.INTEGER,
cct: DataTypes.INTEGER
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.belongsTo(models.Device.model)
this.model.hasMany(models.DeviceRing.model)
}
}
module.exports = DeviceNode
```
index.js
```const fs = require('fs')
const Router = require('koa-router')
class API {
constructor () {
this.dir = './api/'
}
init (app) {
this.app = app
this.findRouter()
}
findRouter (dir) {
const curDir = dir || this.dir
const fileList = fs.readdirSync(curDir, 'utf-8')
fileList && fileList.forEach(file => {
if (file === 'index.js') {
return
}
const stat = fs.lstatSync(curDir + file)
if (stat.isDirectory()) {
this.findRouter(curDir + file + '/')
} else {
this.loadRoute(curDir + file)
}
})
}
loadRoute (routerFile) {
const route = require(('.' + routerFile.substring(this.dir.length - 1, routerFile.lastIndexOf('.'))))
const routePath = routerFile.substring(routerFile.lastIndexOf('/'), routerFile.lastIndexOf('.'))
// 解析并获得路由对象
const router = this.createRouter(route, route.basePath || routePath)
this.app.use(router.routes())
}
createRouter (router, after) {
const newRouter = new Router({
prefix: after
})
for (let method in router) {
for (let r in router[method]) {
console.log(`method:${method} router: ${after + r}`)
newRouter[method](r, router[method][r])
}
}
return newRouter
}
}
module.exports = new API()```
wechatstudents.js
```/**
* Created by jinyang on 2017/7/21.
*/
'use strict'
const {DataTypes} = require('sequelize')
class WechatStudent {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'WechatStudent'
// 定义模型实行
this.model = sequelize.define('wechatstudents', {
wechatuserId: DataTypes.INTEGER,
studentId: DataTypes.INTEGER,
active: DataTypes.INTEGER
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.belongsTo(models.WechatUser.model, {foreignKey: 'wechatuserId', targetKey: 'id'})
this.model.hasMany(models.WechatUser.model, {foreignKey: 'id', sourceKey: 'wechatuserId'})
this.model.belongsTo(models.Student.model, {foreignKey: 'studentId', targetKey: 'id'})
this.model.hasMany(models.Student.model, {foreignKey: 'id', sourceKey: 'studentId'})
}
}
module.exports = WechatStudent
```
zonedevice.js
```/**
* Created by me on 2017/7/17.
*/
/**
* Created by jinyang on 2017/6/02.
*/
'use strict'
const {DataTypes} = require('sequelize')
class ZoneDevice {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'ZoneDevice'
// 定义模型实行
this.model = sequelize.define('zonedevices', {
zoneId: DataTypes.INTEGER,
deviceId: DataTypes.STRING,
position: DataTypes.STRING
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.belongsTo(models.Device.model, {foreignKey: 'deviceId', targetKey: 'id'})
this.model.belongsTo(models.Zone.model)
}
}
module.exports = ZoneDevice```
db.js
```/*
* orm 初始化
*/
const Sequelize = require('sequelize')
const conf = require('../conf/conf')
const DB = {
create: function () {
if (process.env.NODE_ENV === 'production') {
this.sequelize = new Sequelize(conf.mysql.production.database, conf.mysql.production.username, conf.mysql.production.password, conf.mysql.production)
} else {
this.sequelize = new Sequelize(conf.mysql.dev.database, conf.mysql.dev.username, conf.mysql.dev.password, conf.mysql.dev)
}
return this.sequelize
}
}
module.exports = DB
```
oauth2server.js
```/**
* Copyright 2013-present NightWorld.
*
* 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.
*/
const Authorise = require('./authorise')
const Grant = require('./grant')
/**
* Constructor
*
* @param {Object} config Configuration object
*/
class OAuth2Server {
constructor (config) {
if (!(this instanceof OAuth2Server)) return new OAuth2Server(config)
config = config || {}
if (!config.model) throw new Error('No model supplied to OAuth2Server')
this.model = config.model
this.grants = config.grants || []
this.debug = config.debug || function () {
}
if (typeof this.debug !== 'function') {
this.debug = console.log
}
this.passthroughErrors = config.passthroughErrors
this.continueAfterResponse = config.continueAfterResponse
this.accessTokenLifetime = config.accessTokenLifetime !== undefined ?
config.accessTokenLifetime : 3600
this.refreshTokenLifetime = config.refreshTokenLifetime !== undefined ?
config.refreshTokenLifetime : 1209600
this.authCodeLifetime = config.authCodeLifetime || 30
this.regex = {
clientId: config.clientIdRegex || /^[a-z0-9-_]{3,40}$/i,
grantType: new RegExp('^(' + this.grants.join('|') + ')$', 'i')
}
this.allow = config.allow || {}
}
async authorise (ctx, next) {
if (!this.allowFn(ctx)) {
await Authorise(this, ctx, next)
}
}
async grant (ctx, next) {
Grant(this, ctx.req, ctx.res, next)
}
allowFn (ctx) {
let allowedIsArray = Array.isArray(this.allow)
let allowCache = allowedIsArray ? false : {}
let method = ctx.method.toLowerCase()
let allow = allowedIsArray ? allowCache : allowCache[method]
// Build allow object this method if haven't yet already
if (!allow) {
let paths = Array.isArray(this.allow) ? this.allow : Array.prototype.concat(this.allow.all || [], this.allow[method] || [])
allow = {
len: paths.length,
regex: new RegExp('^(' + paths.join('|') + ')$')
}
if (allowedIsArray) {
allowCache = allow
} else {
allowCache[method] = allow
}
}
if (allow.len && ctx.path.match(allow.regex)) {
return true
}
return false
}
}
module.exports = OAuth2Server```
oauth.js
```/**
* OAuth2认证需要的model,参考 http://oauth2-server.readthedocs.io/en/latest/model/spec.html
*/
const fmt = require('util').format
class OAuth {
constructor (redis) {
this.redis = redis
this.formats = {
client: 'clients:%s',
token: 'tokens:%s',
user: 'users:%s'
}
}
/**
* Get access token.
*/
async getAccessToken (bearerToken) {
let token = await this.redis.get(fmt(this.formats.token, bearerToken))
if (!token) {
return
}
token = JSON.parse(token)
return {
accessToken: token.token,
clientId: token.client_id,
expires: token.expires,
userId: token.user_id
}
}
/**
* Get refresh token.
*/
async getRefreshToken (bearerToken) {
var token = await this.redis.get(fmt(this.formats.token, bearerToken))
if (!token) {
return
}
return {
clientId: token.client_id,
expires: token.expires,
refreshToken: token.token,
userId: token.user_id
}
}
/**
* Get user.
*/
async getUser (username, password) {
let user = await this.redis.get(fmt(this.formats.user, username))
if (!user || password !== user.password) {
return
}
return {
id: username
}
}
async saveToken (token, client, user) {
let data = {
user_id: user.id,
client_id: client.id,
token: token.accessToken,
expires: token.accessTokenExpiresAt,
_id: token.accessToken
}
await this.redis.set(fmt(this.formats.token, token.accessToken), data)
return data
};
}
module.exports = OAuth```
app.js
```const Koa = require('koa')
const bodyParse = require('koa-body')
const timeout = require('koa-timeout-v2')
const serve = require('koa-static')
const cors = require('@koa/cors')
const OAuth2Server = require('./middleware/oauth')
const logger = require('./lib/logger')
const conf = require('./conf/conf')
const api = require('./api')
const db = require('./lib/db')
const Models = require('./models')
const OAuth = require('./lib/oauth')
const error = require('./lib/error')
const res = require('./lib/response')
const app = new Koa()
// 创建数据库连接 && 初始化数据库模型
const models = new Models().init(db.create())
// 创建Redis连接
const redis = require('./lib/redis').getRedis()
app.use(async (ctx, next) => {
// 请求记录
logger.info(`Request ${ctx.method} ${ctx.url}`)
await next()
})
// 添加跨域
app.use(cors())
// 静态资源设置
app.use(serve('public/'))
// 添加body解析中间件
app.use(bodyParse())
// 超时处理
app.use(timeout(conf.http.timeout, {status: 200, message: JSON.stringify(error.internal.timeout)}))
// token验证
app.oauth = new OAuth2Server({
model: new OAuth(redis),
allow: conf.http.allow,
...conf.oauth2
})
// 验证
app.use(app.oauth.authorise())
// 挂载对象到当前请求
app.use(async (ctx, next) => {
ctx.state.conf = conf
ctx.state.logger = logger
ctx.state.models = models
ctx.state.redis = redis
ctx.state.error = error
ctx.state.response = res.response
// 对后续的所有处理进行异常捕获(后续所以异步IO需要使用async/await)
try {
await next()
} catch (ex) {
error.unknown(ex, ctx)
}
})
// 记录请求日志
app.use(async (ctx, next) => {
const start = Date.now()
await next()
const ms = Date.now() - start
logger.info(`Response ${ctx.method} ${ctx.url} - ${ms}ms`)
})
// 初始化api下的路由
api.init(app)
// 未知异常捕获
app.on('error', (err, ctx) => {
// 未处理的系统异常
console.log(err)
ctx.status = 200
ctx.body = error.internal.serverError
})
app.listen(conf.http.port, () => {
console.log(`http server started`)
})
```
wechatusers.js
```/**
* Created by jinyang on 2017/7/21.
*/
'use strict'
const {DataTypes} = require('sequelize')
class WechatUser {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'WechatUser'
// 定义模型实行
this.model = sequelize.define('wechatusers', {
openId: DataTypes.STRING,
nickname: DataTypes.STRING,
sex: DataTypes.INTEGER,
language: DataTypes.STRING,
city: DataTypes.STRING,
province: DataTypes.STRING,
country: DataTypes.STRING,
headimgurl: DataTypes.STRING,
subscribetime: DataTypes.STRING,
mobile: DataTypes.STRING,
channel: DataTypes.INTEGER,
type: DataTypes.INTEGER,
groupId: DataTypes.INTEGER,
pushSensor: DataTypes.INTEGER
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.hasMany(models.WechatStudent.model, {foreignKey: 'wechatuserId', sourceKey: 'id'})
this.model.belongsTo(models.WechatStudent.model, {foreignKey: 'id', targetKey: 'wechatuserId'})
}
}
module.exports = WechatUser```
devicescenes.js
```'use strict'
const {DataTypes} = require('sequelize')
class DeviceScene {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'DeviceScene'
// 定义模型实行
this.model = sequelize.define('devicescenes', {
deviceId: DataTypes.STRING,
sceneId: DataTypes.INTEGER
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.belongsTo(models.Device.model)
this.model.belongsTo(models.Scene.model)
}
}
module.exports = DeviceScene```
cors.js
```/**
* CORS middleware
*
* @param {Object} [options]
* @return {GeneratorFunction}
* @api public
*/
class Cors {
constructor (options) {
this.options = options || {}
this.defaults = {
origin: true,
methods: 'GET,HEAD,PUT,POST,DELETE'
}
// Set defaults
for (let key in this.defaults) {
if (!this.options.hasOwnProperty(key)) {
this.options[key] = this.defaults[key]
}
}
// Set expose
if (Array.isArray(this.options.expose)) {
this.options.expose = this.options.expose.join(',')
}
// Set maxAge
if (typeof this.options.maxAge === 'number') {
this.options.maxAge = this.options.maxAge.toString()
} else {
this.options.maxAge = null
}
// Set methods
if (Array.isArray(this.options.methods)) {
this.options.methods = this.options.methods.join(',')
}
// Set headers
if (Array.isArray(this.options.headers)) {
this.options.headers = this.options.headers.join(',')
}
}
init () {
const that = this
return async function (ctx, next) {
let origin
if (typeof that.options.origin === 'string') {
origin = that.options.origin
} else if (that.options.origin === true) {
origin = ctx.get('origin') || '*'
} else if (that.options.origin === false) {
origin = that.options.origin
} else if (typeof that.options.origin === 'function') {
origin = that.options.origin(ctx.request)
}
if (origin === false) return
ctx.set('Access-Control-Allow-Origin', origin)
/**
* Access Control Expose Headers
*/
if (that.options.expose) {
ctx.set('Access-Control-Expose-Headers', that.options.expose)
}
/**
* Access Control Max Age
*/
if (that.options.maxAge) {
ctx.set('Access-Control-Max-Age', that.options.maxAge)
}
/**
* Access Control Allow Credentials
*/
if (that.options.credentials === true) {
ctx.set('Access-Control-Allow-Credentials', 'true')
}
/**
* Access Control Allow Methods
*/
ctx.set('Access-Control-Allow-Methods', that.options.methods)
/**
* Access Control Allow Headers
*/
let headers
if (that.options.headers) {
headers = that.options.headers
} else {
headers = ctx.get('access-control-request-headers')
}
if (headers) {
ctx.set('Access-Control-Allow-Headers', headers)
}
/**
* Returns
*/
if (ctx.method === 'OPTIONS') {
ctx.status = 204
} else {
await next()
}
}
}
}
module.exports = Cors
```
subjectschedules.js
```/**
* Created by jinyang on 2017/7/20.
*/
/**
* Created by jinyang on 2017/6/02.
*/
'use strict'
const {DataTypes} = require('sequelize')
class SubjectSchedule {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'SubjectSchedule'
// 定义模型实行
this.model = sequelize.define('subjectschedules', {
name: DataTypes.STRING,
start: DataTypes.DATE,
end: DataTypes.DATE,
teacher: DataTypes.STRING,
zoneId: DataTypes.INTEGER,
weekday: DataTypes.INTEGER
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.belongsTo(models.Zone.model)
}
}
module.exports = SubjectSchedule
```
students.js
```/**
* Created by jinyang on 2017/7/21.
*/
'use strict'
const {DataTypes} = require('sequelize')
class Student {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'Student'
// 定义模型实行
this.model = sequelize.define('students', {
id: {type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4},
name: DataTypes.STRING,
username: DataTypes.STRING,
password: DataTypes.STRING,
studentno: DataTypes.STRING,
zoneId: DataTypes.INTEGER,
photo: DataTypes.STRING
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.hasMany(models.WechatStudent.model)
this.model.belongsTo(models.Zone.model)
}
}
module.exports = Student
```
oauth.js
```/**
* Copyright 2013-present Thom Seddon.
*
* 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.
*/
var NodeOAuthServer = require('./oauth2server')
/**
* Constructor
*
* @param {Object} config Configuration object
*/
class OAuthServer {
constructor (config) {
if (!(this instanceof OAuthServer)) return new OAuthServer(config)
config.continueAfterResponse = true
this.server = new NodeOAuthServer(config)
}
authorise () {
const self = this
return async function (cxt, next) {
try {
await self.server.authorise(cxt, next)
await next()
} catch (err) {
if (self.server.passthroughErrors) {
throw err
}
return self.handleError(err, self.server, cxt)
}
}
}
async grant (cxt, next) {
// Mock the jsonp method
cxt.response.jsonp = function (body) {
cxt.body = body
}
try {
await this.server.grant(cxt.request, cxt.response)
} catch (err) {
if (this.server.passthroughErrors) {
throw err
}
return this.handleError(err, this.server, cxt)
}
await next()
}
handleError (err, server, ctx) {
ctx.type = 'json'
ctx.status = 200
if (err.headers) {
ctx.set(err.headers)
}
ctx.body = {
code: err.code,
msg: err.message
}
err.type = 'oauth'
}
}
module.exports = OAuthServer```
response.js
```/*
* 用于定义系统响应格式,以及响应前的基本处理
*/
module.exports = {
response: function (ctx, data) {
ctx.body = {code: 1, msg: 'success', data: data}
}
}```
authorise.js
```/**
* Copyright 2013-present NightWorld.
*
* 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.
*/
const error = require('./error')
module.exports = Authorise
/**
* Authorise
*
* @param {Object} config Instance of OAuth object
* @param {Object} req
* @param {Object} res
* @param {Function} next
*/
async function Authorise (config, ctx, next) {
this.config = config
this.model = config.model
this.req = ctx.request
let err = getBearerToken(this.req)
if (err) {
// 直接响应
throw (err)
} else {
let err = await checkToken()
if (err) {
throw (err)
}
}
}
/**
* Get bearer token
*
* Extract token from request according to RFC6750
*
* @param {Function} done
* @this OAuth
*/
function getBearerToken (req) {
let headerToken = req.get('Authorization') ? req.get('Authorization') : undefined
let getToken = req.query.access_token
let postToken = req.body ? this.req.body.access_token : undefined
// Check exactly one method was used
let methodsUsed = (headerToken !== undefined) + (getToken !== undefined) + (postToken !== undefined)
if (methodsUsed > 1) {
return error('invalid_request',
'Only one method may be used to authenticate at a time (Auth header, ' +
'GET or POST).')
} else if (methodsUsed === 0) {
return error('invalid_request', 'The access token was not found')
}
// Header: http://tools.ietf.org/html/rfc6750#section-2.1
if (headerToken) {
let matches = headerToken.match(/Bearer\s(\S+)/)
if (!matches) {
return error('invalid_request', 'Malformed auth header')
}
headerToken = matches[1]
}
// POST: http://tools.ietf.org/html/rfc6750#section-2.2
if (postToken) {
if (req.method === 'GET') {
return error('invalid_request',
'Method cannot be GET When putting the token in the body.')
}
if (req.is('application/x-www-form-urlencoded')) {
return error('invalid_request', 'When putting the token in the ' +
'body, content type must be application/x-www-form-urlencoded.')
}
}
this.bearerToken = headerToken || postToken || getToken
return null
}
/**
* Check token
*
* Check it against model, ensure it's not expired
* @param {Function} done
* @this OAuth
*/
async function checkToken () {
const self = this
try {
let token = await this.model.getAccessToken(this.bearerToken)
if (!token) {
return error('invalid_token',
'The access token provided is invalid.')
}
if (token.expires !== null &&
(!token.expires || token.expires < new Date())) {
return error('expired_grant',
'The access token provided has expired.')
}
// Expose params
self.req.oauth = {bearerToken: token}
self.req.user = token.user ? token.user : {id: token.userId}
} catch (err) {
return error('server_error', false, err)
}
}
```
users.js
```'use strict'
const {DataTypes} = require('sequelize')
class User {
constructor (sequelize) {
// 定义模型名称,用于调用
this.name = 'User'
// 定义模型实行
this.model = sequelize.define('users', {
username: DataTypes.STRING,
password: DataTypes.STRING,
salt: DataTypes.STRING,
firstname: DataTypes.STRING,
lastname: DataTypes.STRING,
sex: DataTypes.INTEGER,
nickname: DataTypes.STRING,
email: DataTypes.STRING,
image: DataTypes.STRING,
channelcode: DataTypes.INTEGER,
verificationcode: DataTypes.STRING,
expirationtime: DataTypes.DATE
})
}
// 定义模型关联关系
associate (models) {
this.models = models
this.model.belongsTo(models.UserGroup.model)
this.model.hasMany(models.ZoneUser.model)
}
// 定义该模型具有的业务方法
async login (username, password) {
let result = await this.model.findOne({where: {username: username, password: password}})
return result
}
async getUserById (id) {
let result = await this.model.findById(id)
return result
}
}
module.exports = User
```
logger.js
```/*
* 系统日志模块,用于配置格式及记录位置灯
*/
const winston = require('winston')
const DailyRotateFile = require('winston-daily-rotate-file')
const stackTrace = require('stack-trace')
const moment = require('moment')
const dateFormat = function () {
return moment().format('YYYY-MM-DD HH:mm:ss:SSS')
}
const infoLoggerTransport = new DailyRotateFile({
name: 'info',
filename: './logs/info/info.log',
timestamp: dateFormat,
level: 'info',
colorize: true,
maxsize: 1024 * 1024 * 10,
datePattern: '.yyyy-MM-dd'
})
const errorTransport = new (winston.transports.File)({
name: 'error',
filename: './logs/error/error.log',
timestamp: dateFormat,
level: 'error',
colorize: true
})
const logger = new (winston.Logger)({
transports: [
new winston.transports.Console({
timestamp: dateFormat,
colorize: true
}),
infoLoggerTransport,
errorTransport
]
})
let originalMethod = logger.error
logger.error = function () {
let cellSite = stackTrace.get()[1]
originalMethod.apply(logger, [arguments[0] + '\n', {
filePath: cellSite.getFileName(),
lineNumber: cellSite.getLineNumber()
}])
}
module.exports = logger```
conf.js
```module.exports = {
http: {
port: 9001,
allow: {
options: ['/v1/users', '/users', '/wechatusers', '/users/login', '/public/(.{0,})'],
post: ['/v1/users', '/users', '/wechatusers', '/users/login', '/users/checkemail', '/users/checkcode', '/user405s', '/anonymous/login'],
get: ['/server/health', '/v1/access_tokens', '/public/(.{0,})', '/users/help', '/users/regagreement', '/user405s/createuserkey', '/schoolnotices/new/(.*?)'],
delete: ['/v1/access_tokens/([0-9a-f]{40})'],
put: ['/users/sendverificationcode', '/users/updatepassword']
},
// 根据系统性能理性设置(应小于2分钟)
timeout: 30000
},
mysql: {
production: {
username: 'root',
password: 'root123',
database: 'sparkserver_dev02',
host: '127.0.0.1',
dialect: 'mysql',
timezone: '+08:00',
pool: {
max: 10,
min: 0,
idle: 10000
}
},
dev: {
username: 'root',
password: 'root123',
database: 'sparkserver_dev02',
host: '127.0.0.1',
dialect: 'mysql',
timezone: '+08:00',
pool: {
max: 10,
min: 0,
idle: 10000
}
}
},
redis: {
port: 6379,
url: '127.0.0.1'
},
oauth2: {
grants: ['password'],
debug: true,
allowBearerTokensInQueryString: true,
accessTokenLifetime: 90 * 24 * 60 * 60
}
}
```
|
7788wangzi/csharp-interview-questions
|
7788wangzi/csharp-interview-questions
Program.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Find2ndMaximumNumberInGivenArray
{
class Program
{
static void Main(string[] args)
{
int[] input = { 3, 23, 12, 34, 25 };
int max1, max2;
max1 = max2 = input[0];
for(int i=1; i<input.Length; i++)
{
if(input[i]>max1)
{
max2 = max1;
max1 = input[i];
continue;
}
else if (input[i] > max2)
{
max2 = input[i];
}
}
Console.WriteLine($"Max: {max1}; 2nd Max: {max2}");
Console.ReadKey();
}
}
}
```
Program.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CountWords
{
/// <summary>
/// Hello my dear dog
/// -> 4 words
/// </summary>
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a sentence without punctuation: ");
string input = Console.ReadLine();
char[] characters = input.Trim().ToCharArray();
int wordCount = 1;
char lastChar=characters[0];
for(int i = 0; i< characters.Length; i++)
{
if(characters[i]==' '|| characters[i] == '\t'|| characters[i]=='\r'|| characters[i]=='\n')
{
if (characters[i] == lastChar)
continue;
wordCount++;
}
lastChar = characters[i];
}
Console.WriteLine($"Words: {wordCount}");
Console.ReadKey();
}
}
}
```
readme.md
```## Some interview questions implemented in C# lanugage
```
Program.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NumberOf1sInANum
{
/// <summary>
/// 0101 & 0001 = 0001
/// 0101 & 0010 = 0000
/// 0101 & 0100 = 0100
/// 0101 & 1000 = 0000
///
/// 0001 <<1 = 0010
/// 0010 <<1 = 0100
/// 0100 <<1 = 1000
/// </summary>
class Program
{
static void Main(string[] args)
{
int num = 7;
int iter = 1;
int count = 0;
for (int i = 0; i < 32; i++)
{
if ((num & iter) == iter)
{
count++;
}
iter = iter << 1;
}
Console.WriteLine($"number of 1s in {num} is {count}");
Console.ReadLine();
}
}
}
```
Program.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PalindromeNumber
{
/// <summary>
/// e.g.
/// <=>
/// 1
/// <==>
/// 11
/// 22
/// <===>
/// 121
/// 232
/// <====>
/// 1221
/// 2332
/// </summary>
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number: ");
int num = Convert.ToInt32(Console.ReadLine());
// num is going to be desctructed, save it to a temp variable first.
int temp = num;
int reNum=0, rem = 0;
while(num>0)
{
// get the individual digit number from right to left
rem = num % 10;
// construct a new number with each digit multiple 10 and then add the next right one.
reNum = reNum * 10 + rem;
num = num / 10;
}
if(temp==reNum)
{
Console.WriteLine($"{temp} is a Palindrome number.");
}
else
{
Console.WriteLine($"{temp} is NOT a Palindrome number.");
}
Console.Read();
}
}
}
```
Program.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlphabeticalOrderString
{
/// <summary>
/// Hello -> ehllo
/// </summary>
class Program
{
static void Main(string[] args)
{
string inputStr = "Hello";
Console.WriteLine("Enter a word: ");
inputStr = Console.ReadLine();
char[] strArray = inputStr.ToLower().ToArray();
int length = strArray.Length;
Console.Write("Before sort:" );
for(int i=0; i<length; i++)
{
Console.Write($"{strArray[i]} ");
}
// bubble sort 冒泡排序
for(int i=0; i<length-1;i++)
{
for(int j=i+1; j<length-i; j++)
{
if(strArray[i]>strArray[j])
{
char temp = strArray[j];
strArray[j] = strArray[i];
strArray[i] = temp;
}
}
}
Console.WriteLine();
Console.Write("After sort:");
for (int i = 0; i < length; i++)
{
Console.Write($"{strArray[i]} ");
}
Console.ReadKey();
}
}
}
```
Program.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PascalTriangleProgram
{
/// <summary>
/// row
/// 1
/// 1 1
/// 1 2 1
/// 1 3 3 1
/// 1 4 6 4 1
/// </summary>
class Program
{
static void Main(string[] args)
{
int row = 5;
int current = 1;
//while(current<=5)
//{
// for(int i=0; i<row-current; i++)
// {
// Console.Write(" ");
// }
// for(int i=1; i<=current;i++)
// {
// Console.Write("A ");
// }
// Console.WriteLine();
// current++;
//}
for(int i=0; i<row;i++)
{
for(int j=0; j<(row-i); j++)
{
Console.Write(" ");
}
int value = 1;
for(int j=0; j<=i; j++)
{
Console.Write($"{value} ");
value = value * (i - j) / (j + 1);
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
```
Program.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FibonacciSeries
{
/// <summary>
/// 0, 1, 1, 2, 3, 5, 8, 13, 21
/// </summary>
class Program
{
static void Main(string[] args)
{
int num1 = 0, num2 = 1;
int num;
int number = 0;
Console.WriteLine("Enter how many digits to output: ");
number = Convert.ToInt32(Console.ReadLine());
Console.Write($"{num1} {num2} ");
while(number>2)
{
num = num1 + num2;
Console.Write($"{num} ");
num1 = num2;
num2 = num;
number--;
}
Console.ReadKey();
}
}
}
```
Program.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Count1InAGivenNumber
{
/// <summary>
/// Count number of 1 in a given number
/// </summary>
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Enter a number:");
int number = Int32.Parse(Console.ReadLine());
int rem = 0; int count = 0;
int original = number;
while (number > 0)
{
rem = number % 2;
count += rem;
number = number / 2;
}
Console.WriteLine($"Number {original} has {count} of 1.");
}
}
}
}
```
Program.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SwapTwoNumberWithoutAThirdVar
{
/// <summary>
/// a = 10, b = 25
/// =>
/// a = 25, b = 10
/// </summary>
class Program
{
static void Main(string[] args)
{
int a = 10, b = 25;
Console.WriteLine($"Before Swap, the values are: a = {a} ; b = {b}");
a = a + b; // a1 = a0 + b0; b0 = b0;
b = a - b; // a1 - b0 = a0, then assign to b1
a = a - b; // a1 = a0 + b0; b1 = a0; a1-b1 = b0, then assign to a1
Console.WriteLine($"After Swap, the values are: a = {a} ; b = {b}");
Console.ReadKey();
}
}
}
```
Program.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InterviewQuestionLib
{
class Program
{
static void Main(string[] args)
{
int num = 7;
int iter = 1;
int count = 0;
for(int i=0; i<32; i++)
{
if((num&iter)==iter)
{
count++;
}
iter = iter << 1;
}
Console.WriteLine($"number of 1s in {num} is {count}");
Console.ReadLine();
}
}
}
```
|
784679322/myrabbitmq
|
784679322/myrabbitmq
send.java
```package com.mmr.rabbitmq.workfair;
import com.mmr.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class send {
private static final String QUEUE_NAME="test_work_queue";
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
//获取链接
Connection connection=ConnectionUtils.getConnection();
//获取通道
Channel channel=connection.createChannel();
//创建队列申明
// channel.queueDeclare(QUEUE_NAME,true,false,false,null);持久化
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
/**
* 每个消费者发送确认消息之前,消息队列不发送下一个消息到消费者,一次只处理一个消息
*
* 限制发送给同一个消费者不得超过一条消息
*/
int prefetCount=1;
channel.basicQos(prefetCount);
for(int i=0;i<50;i++){
String msg="hello work"+i;
channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());
System.out.println("-- send msg :" +msg);
Thread.sleep(i*20);
}
channel.close();
connection.close();
}
}
```
Recv1.java
```package com.mmr.rabbitmq.translation.tx;
import com.mmr.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*
*/
public class Recv1 {
private static final String QUEUE_NAME="test_queue_tx";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection= ConnectionUtils.getConnection();
final Channel channel=connection.createChannel();
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
//定义消费者
DefaultConsumer consumer= new DefaultConsumer(channel){
//获取到达的消息
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
String msgString =new String(body,"utf-8");
System.out.println("Recv1 work msg ="+msgString);
}
};
channel.basicConsume(QUEUE_NAME,true,consumer);
}
}
```
send3.java
```package com.mmr.rabbitmq.translation.confirm;
import com.mmr.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.TimeoutException;
/**
*
* confirm模式 批量模式
*
*/
public class send3 {
private static final String QUEUE_NAME="test_queue_confirm3";
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
Connection connection=ConnectionUtils.getConnection();
Channel channel=connection.createChannel();
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
//生产者调用confiremselect 将chanel设置成confrim模式
channel.confirmSelect();
//未确认的信息标识
final SortedSet<Long> confirmSet= Collections.synchronizedSortedSet(new TreeSet<Long>());
//通道添加监听
channel.addConfirmListener(new ConfirmListener() {
//回执成功
public void handleAck(long deliveryTag, boolean multiple) throws IOException {
if(multiple){//多条
System.out.println("--handleAck-----multiple"+deliveryTag);
confirmSet.headSet(deliveryTag+1).clear();//批量移除当前之前的tag
}else{//单条
System.out.println("--handleAck-----multiple false"+deliveryTag);
confirmSet.remove(deliveryTag);
}
}
//失败 处理
public void handleNack(long deliveryTag, boolean multiple) throws IOException {
if(multiple){
System.out.println("--handleNack--fail---multiple"+deliveryTag);
confirmSet.headSet(deliveryTag+1).clear();
}else{
System.out.println("--handleNack---fail-multiple false"+deliveryTag);
confirmSet.remove(deliveryTag);
}
}
});
String ackString="msg...";
while (true){
long setNo=channel.getNextPublishSeqNo();
channel.basicPublish("",QUEUE_NAME,null,ackString.getBytes());
confirmSet.add(setNo);
}
}
}
```
MyConsumer.java
```package com.mmr.rabbitmq.spring;
import javax.swing.*;
public class MyConsumer {
public static void main(String[] args) {
}
}
```
send.java
```package com.mmr.rabbitmq.translation.confirm;
import com.mmr.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*
* confirm模式 普通模式
*
*/
public class send {
private static final String QUEUE_NAME="test_queue_confirm1";
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
Connection connection=ConnectionUtils.getConnection();
Channel channel=connection.createChannel();
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
//生产者调用confiremselect 将chanel设置成confrim模式
channel.confirmSelect();
String msg="confirm1。。。。。。msg";
channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());
if(!channel.waitForConfirms()){
System.out.println("error");
}else{
System.out.println("-- send test_queue_confirm1 msg :" +msg);
}
channel.close();
connection.close();
}
}
```
send.java
```package com.mmr.rabbitmq.simple;
import com.mmr.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class send {
private static final String QUEUE_NAME="test_simple_queue";
private static final String QUEUE_NAME2="test_simple_queue2";
public static void main(String[] args) throws IOException, TimeoutException {
//获取链接
Connection connection=ConnectionUtils.getConnection();
//获取通道
Channel channel=connection.createChannel();
//创建队列申明
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
String msg="hello simple";
channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());
System.out.println("-- send msg :" +msg);
channel.close();
connection.close();
}
}
```
Recv2.java
```package com.mmr.rabbitmq.work;
import com.mmr.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*
*/
public class Recv2 {
private static final String QUEUE_NAME="test_work_queue";
@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
//获取链接
Connection connection= ConnectionUtils.getConnection();
//获取通道
Channel channel=connection.createChannel();
//创建队列申明
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
//定义消费者
DefaultConsumer consumer= new DefaultConsumer(channel){
//获取到达的消息
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
String msgString =new String(body,"utf-8");
System.out.println("Recv1 work msg ="+msgString);
try {
Thread.sleep(1002);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
System.out.println("[2] done ");
}
}
};
//监听队列(消费者添加到监听)
boolean autoAck=true;
channel.basicConsume(QUEUE_NAME,autoAck,consumer);
}
}
```
Recv.java
```package com.mmr.rabbitmq.simple;
import com.mmr.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* 消费者消费消息
* 耦合性高,生产者一一对应消费者
* 如果想要多个消费者消费队列中的信息,就不行了
*
* 队列名变更,这时需要同时改变消费者名字
*/
public class Recv {
private static final String QUEUE_NAME="test_simple_queue";
@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
//获取链接
Connection connection= ConnectionUtils.getConnection();
//获取通道
Channel channel=connection.createChannel();
//创建队列申明
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
//定义消费者
DefaultConsumer consumer= new DefaultConsumer(channel){
//获取到达的消息
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
String msgString =new String(body,"utf-8");
System.out.println("Recv1 msg ="+msgString);
}
};
//监听队列(消费者添加到监听)
channel.basicConsume(QUEUE_NAME,true,consumer);
}
private static void oldapi() throws IOException, TimeoutException, InterruptedException {
//获取链接
Connection connection= ConnectionUtils.getConnection();
//获取通道
Channel channel=connection.createChannel();
//定义队列的消费者
QueueingConsumer consumer= new QueueingConsumer(channel);
//监听队列
channel.basicConsume(QUEUE_NAME,true,consumer);
while(true){
QueueingConsumer.Delivery delivery= consumer.nextDelivery();
String msgString =new String(delivery.getBody());
System.out.println("Recv1 msg ="+msgString);
}
}
}
```
ConnectionUtils.java
```package com.mmr.rabbitmq.util;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* 获取Mq的链接
*/
public class ConnectionUtils {
public static Connection getConnection() throws IOException, TimeoutException {
//定义一个链接工厂
ConnectionFactory factory=new ConnectionFactory();
//设置服务地址
factory.setHost("127.0.0.1");
//设置端口
factory.setPort(5672);
//设置vhost
factory.setVirtualHost("/vhost_mmr");
//用户名
factory.setUsername("user_mmr");
//pwd
factory.setPassword("123");
return factory.newConnection();
}
}
```
send.java
```package com.mmr.rabbitmq.topic;
import com.mmr.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*/
public class send {
private static final String EXCHANGE_NAME="test_exchange_topic";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection=ConnectionUtils.getConnection();
Channel channel=connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME,"topic");
String msg="商品。。。delete。";
String routingKey= "goods.delete";
channel.basicPublish(EXCHANGE_NAME,routingKey,null,msg.getBytes());
System.out.println("-- send topic msg :" +msg);
channel.close();
connection.close();
}
}
```
send.java
```package com.mmr.rabbitmq.translation.tx;
import com.mmr.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*
* 消息确认机制
* 事务模式
* 吞吐量降低
*
*
*/
public class send {
private static final String QUEUE_NAME="test_queue_tx";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection=ConnectionUtils.getConnection();
Channel channel=connection.createChannel();
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
String msg="商品。。。test_queue_tx。。。msg";
try{
channel.txSelect();
channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());
int a=1/0;
channel.txCommit();
System.out.println("-- send tx msg :" +msg);
}catch(Exception e){
channel.txRollback();
System.out.println("异常");
}finally {
channel.close();
connection.close();
}
}
}
```
|
785172550/kt-vertx-demo
|
785172550/kt-vertx-demo
JavaRx.java
```import com.wh.coroutines.Movies;
import io.reactivex.Completable;
import io.reactivex.Single;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.http.HttpServerResponse;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import io.vertx.reactivex.ext.web.RoutingContext;
import java.util.List;
import java.util.stream.Collectors;
public class JavaRx {
private JDBCClient client = null;
public static void main(String[] args) {
//
}
public Single<List<Movies>> getAll() {
return client
.rxQuery("")
.map(
ar ->
ar.getRows().stream().map(Movies.Companion::fromJson).collect(Collectors.toList()));
}
public Single<List<Todo>> getAllTode() {
return client
.rxQuery("")
.map(ar -> ar.getRows().stream().map(Todo::fromJson).collect(Collectors.toList()));
}
protected void sendResponse(RoutingContext context, Completable asyncResult) {
HttpServerResponse response = context.response();
if (asyncResult == null) {
internalError(context, "invalid_status");
} else {
asyncResult.subscribe(response::end, ex -> internalError(context, ex));
}
}
protected void internalError(RoutingContext context, Throwable ex) {
context
.response()
.setStatusCode(500)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("error", ex.getMessage()).encodePrettily());
}
protected void internalError(RoutingContext context, String cause) {
context
.response()
.setStatusCode(500)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("error", cause).encodePrettily());
}
}
```
|
786991884/spring-kafka
|
786991884/spring-kafka
README.md
```# spring与kafka集成测试
1,kafka序列化测试,json,pb等
2,kafka生产消费与spring整合测试
3,并行消费与单线程消费测试
4,其它生产消费模型测试
```
KafkaJsonSerializerConfig.java
```package com.test.serializers;
import org.apache.kafka.common.config.AbstractConfig;
import org.apache.kafka.common.config.ConfigDef;
import java.util.Map;
public class KafkaJsonSerializerConfig extends AbstractConfig {
public static final String JSON_INDENT_OUTPUT = "json.indent.output";
public static final boolean JSON_INDENT_OUTPUT_DEFAULT = false;
public static final String JSON_INDENT_OUTPUT_DOC =
"Whether JSON output should be indented (\"pretty-printed\")";
private static ConfigDef config;
static {
config = new ConfigDef()
.define(JSON_INDENT_OUTPUT, ConfigDef.Type.BOOLEAN, JSON_INDENT_OUTPUT_DEFAULT,
ConfigDef.Importance.LOW, JSON_INDENT_OUTPUT_DOC);
}
public KafkaJsonSerializerConfig(Map<?, ?> props) {
super(config, props);
}
}
```
KafkaProducer.java
```package com.mapbar.test;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.util.Properties;
public class KafkaProducer extends Thread {
public static final Properties props = new Properties();
public KafkaProducer() {
props.put("bootstrap.servers", "192.168.9.3:9092,10.10.31.8:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("security.protocol", "SSL");
// props.put("ssl.truststore.location", "/var/private/ssl/kafka.client.truststore.jks");
props.put("ssl.truststore.location", "D:/workspace01/mapbar/src/main/resources/kafka.client.truststore.jks");
props.put("ssl.truststore.password", "123456");
// props.put("ssl.keystore.location", "/var/private/ssl/kafka.client.keystore.jks");
props.put("ssl.keystore.location", "D:/workspace01/mapbar/src/main/resources/kafka.client.keystore.jks");
props.put("ssl.keystore.password", "123456");
props.put("ssl.key.password", "123456");
}
@Override
public void run() {
while (true) {
Producer<String, String> producer = new org.apache.kafka.clients.producer.KafkaProducer<>(props);
for (int i = 0; i < 10; i++) {
producer.send(new ProducerRecord<String, String>("TBTest", Integer.toString(i), Integer.toString(i)));
System.out.println("向topic:TBTest发送了消息,key为" + Integer.toString(i) + ",value为" + Integer.toString(i));
}
producer.close();
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}```
Application.java
```package com;
import com.test.KafkaListener;
import com.test.Person;
import com.test.serializers.KafkaJsonDeserializer;
import com.test.serializers.KafkaJsonSerializer;
import com.test.serializers.MyKafkaConsumerFactory;
import kafka.message.ExchangeMessage;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.kafka.core.*;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
import org.springframework.kafka.listener.config.ContainerProperties;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
@SpringBootApplication
public class Application implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
@Value("${kafka.topic}")
private String[] topic;
@Value("${kafka.broker.address}")
private String brokerAddress;
@Autowired
private KafkaListener kafkaListener;
@Autowired
private KafkaTemplate<String, Object> kafkaTemplate;
@Override
public void run(String... args) throws Exception {
long start = System.currentTimeMillis();
logger.info(start + " start");
for (int i = 0; i < 20000; i++) {
ExchangeMessage.Order order = ExchangeMessage.Order.newBuilder().setOid("xxx" + String.valueOf(1)).build();
kafkaTemplate.send("topic1", "0", new Person("zs", 11, order.toByteArray()));
// kafkaTemplate.send("topic2", "1", "bar");
// kafkaTemplate.send("topic1", "2", "baz");
// kafkaTemplate.send("topic2", "3", "qux");
// kafkaTemplate.flush();
}
long end = System.currentTimeMillis();
logger.info(end + " end,end-start=" + (end - start) + "ms");
}
public static void main(String[] args) throws Exception {
SpringApplication application = new SpringApplication(Application.class);
application.setWebEnvironment(false);
application.run(args);
}
@Bean
public KafkaTemplate<String, Object> kafkaTemplate() {
return new KafkaTemplate<>(producerFactory());
}
@Bean
public ProducerFactory<String, Object> producerFactory() {
Map<String, Object> props = new HashMap<>();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, this.brokerAddress);
props.put(ProducerConfig.RETRIES_CONFIG, 0);
props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
// props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaJsonSerializer.class);
return new DefaultKafkaProducerFactory<>(props);
}
/*@Bean
public KafkaMessageListenerContainer<String, Object> container() throws Exception {
ContainerProperties containerProps = new ContainerProperties(topic);
containerProps.setMessageListener(kafkaListener);
KafkaMessageListenerContainer<String, Object> container = new KafkaMessageListenerContainer<>(consumerFactory(), containerProps);
container.getContainerProperties().setPollTimeout(3000);
return container;
}*/
@Bean
public ConcurrentMessageListenerContainer<String, Object> concurrentContainer() throws Exception {
ContainerProperties containerProps = new ContainerProperties(topic);
containerProps.setMessageListener(kafkaListener);
/* containerProps.setErrorHandler(new ErrorHandler() {
@Override
public void handle(Exception thrownException, ConsumerRecord<?, ?> record) {
System.out.println(record);
}
});*/
//containerProps.setAckOnError(false);
ConcurrentMessageListenerContainer<String, Object> container = new ConcurrentMessageListenerContainer<>(consumerFactory(), containerProps);
container.setConcurrency(2);
container.getContainerProperties().setPollTimeout(300);
return container;
}
/* @Bean
public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, Object>> listenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
factory.setConcurrency(3);
factory.getContainerProperties().setPollTimeout(3000);
factory.setMessageConverter(new StringJsonMessageConverter());
return factory;
}*/
@Bean
public ConsumerFactory<String, Object> consumerFactory() {
Map<String, Object> props = getConsumerConfig();
return new MyKafkaConsumerFactory<>(props);
}
public Map<String, Object> getConsumerConfig() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, this.brokerAddress);
props.put(ConsumerConfig.GROUP_ID_CONFIG, "siTestGroup");
// props.put(ConsumerConfig.GROUP_ID_CONFIG, "TestGroup");
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 100);
props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 15000);
//props.put(ConsumerConfig.)
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
// props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
// props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, KafkaJsonDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, KafkaJsonDeserializer.class);
props.put(ConsumerConfig.CLIENT_ID_CONFIG,"consumer-id-"+ new Random().nextInt());
return props;
}
}```
ExchangeMessage.java
```// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: ExchangeMessage.proto
package com.kafka.message;
public final class ExchangeMessage {
private ExchangeMessage() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface OrderOrBuilder extends
// @@protoc_insertion_point(interface_extends:Order)
com.google.protobuf.MessageOrBuilder {
/**
* <code>optional string oid = 1;</code>
*/
boolean hasOid();
/**
* <code>optional string oid = 1;</code>
*/
String getOid();
/**
* <code>optional string oid = 1;</code>
*/
com.google.protobuf.ByteString
getOidBytes();
}
/**
* Protobuf type {@code Order}
*/
public static final class Order extends
com.google.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:Order)
OrderOrBuilder {
// Use Order.newBuilder() to construct.
private Order(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private Order(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final Order defaultInstance;
public static Order getDefaultInstance() {
return defaultInstance;
}
public Order getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private Order(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000001;
oid_ = bs;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return ExchangeMessage.internal_static_Order_descriptor;
}
protected FieldAccessorTable
internalGetFieldAccessorTable() {
return ExchangeMessage.internal_static_Order_fieldAccessorTable
.ensureFieldAccessorsInitialized(
ExchangeMessage.Order.class, ExchangeMessage.Order.Builder.class);
}
public static com.google.protobuf.Parser<Order> PARSER =
new com.google.protobuf.AbstractParser<Order>() {
public Order parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Order(input, extensionRegistry);
}
};
@Override
public com.google.protobuf.Parser<Order> getParserForType() {
return PARSER;
}
private int bitField0_;
public static final int OID_FIELD_NUMBER = 1;
private Object oid_;
/**
* <code>optional string oid = 1;</code>
*/
public boolean hasOid() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional string oid = 1;</code>
*/
public String getOid() {
Object ref = oid_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
oid_ = s;
}
return s;
}
}
/**
* <code>optional string oid = 1;</code>
*/
public com.google.protobuf.ByteString
getOidBytes() {
Object ref = oid_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
oid_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private void initFields() {
oid_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, getOidBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(1, getOidBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@Override
protected Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static ExchangeMessage.Order parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static ExchangeMessage.Order parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static ExchangeMessage.Order parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static ExchangeMessage.Order parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static ExchangeMessage.Order parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static ExchangeMessage.Order parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static ExchangeMessage.Order parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static ExchangeMessage.Order parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static ExchangeMessage.Order parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static ExchangeMessage.Order parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(ExchangeMessage.Order prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@Override
protected Builder newBuilderForType(
BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Order}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Order)
ExchangeMessage.OrderOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return ExchangeMessage.internal_static_Order_descriptor;
}
protected FieldAccessorTable
internalGetFieldAccessorTable() {
return ExchangeMessage.internal_static_Order_fieldAccessorTable
.ensureFieldAccessorsInitialized(
ExchangeMessage.Order.class, ExchangeMessage.Order.Builder.class);
}
// Construct using kafka.message.ExchangeMessage.Order.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
oid_ = "";
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return ExchangeMessage.internal_static_Order_descriptor;
}
public ExchangeMessage.Order getDefaultInstanceForType() {
return ExchangeMessage.Order.getDefaultInstance();
}
public ExchangeMessage.Order build() {
ExchangeMessage.Order result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public ExchangeMessage.Order buildPartial() {
ExchangeMessage.Order result = new ExchangeMessage.Order(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.oid_ = oid_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof ExchangeMessage.Order) {
return mergeFrom((ExchangeMessage.Order)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(ExchangeMessage.Order other) {
if (other == ExchangeMessage.Order.getDefaultInstance()) return this;
if (other.hasOid()) {
bitField0_ |= 0x00000001;
oid_ = other.oid_;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
ExchangeMessage.Order parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (ExchangeMessage.Order) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private Object oid_ = "";
/**
* <code>optional string oid = 1;</code>
*/
public boolean hasOid() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional string oid = 1;</code>
*/
public String getOid() {
Object ref = oid_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
oid_ = s;
}
return s;
} else {
return (String) ref;
}
}
/**
* <code>optional string oid = 1;</code>
*/
public com.google.protobuf.ByteString
getOidBytes() {
Object ref = oid_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
oid_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string oid = 1;</code>
*/
public Builder setOid(
String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
oid_ = value;
onChanged();
return this;
}
/**
* <code>optional string oid = 1;</code>
*/
public Builder clearOid() {
bitField0_ = (bitField0_ & ~0x00000001);
oid_ = getDefaultInstance().getOid();
onChanged();
return this;
}
/**
* <code>optional string oid = 1;</code>
*/
public Builder setOidBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
oid_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:Order)
}
static {
defaultInstance = new Order(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:Order)
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Order_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_Order_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
String[] descriptorData = {
"\n\025ExchangeMessage.proto\"\024\n\005Order\022\013\n\003oid\030" +
"\001 \001(\tB\"\n\rkafka.messageB\017ExchangeMessageH" +
"\001"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
internal_static_Order_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_Order_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_Order_descriptor,
new String[] { "Oid", });
}
// @@protoc_insertion_point(outer_class_scope)
}
```
MyKafkaConsumerFactory.java
```package com.test.serializers;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.Deserializer;
import org.springframework.kafka.core.ConsumerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* @author Lenovo
* @date 2016-09-05
* @modify
* @copyright
*/
public class MyKafkaConsumerFactory<K, V> implements ConsumerFactory<K, V> {
private final Map<String, Object> configs;
private Deserializer<K> keyDeserializer;
private Deserializer<V> valueDeserializer;
public MyKafkaConsumerFactory(Map<String, Object> configs) {
this(configs, null, null);
}
public MyKafkaConsumerFactory(Map<String, Object> configs,
Deserializer<K> keyDeserializer,
Deserializer<V> valueDeserializer) {
this.configs = new HashMap<>(configs);
this.keyDeserializer = keyDeserializer;
this.valueDeserializer = valueDeserializer;
}
public void setKeyDeserializer(Deserializer<K> keyDeserializer) {
this.keyDeserializer = keyDeserializer;
}
public void setValueDeserializer(Deserializer<V> valueDeserializer) {
this.valueDeserializer = valueDeserializer;
}
@Override
public Consumer<K, V> createConsumer() {
return createKafkaConsumer();
}
protected KafkaConsumer<K, V> createKafkaConsumer() {
String consumerId = (String) this.configs.get(ConsumerConfig.CLIENT_ID_CONFIG);
configs.put(ConsumerConfig.CLIENT_ID_CONFIG, consumerId+new Random().nextInt());
return new KafkaConsumer<K, V>(this.configs, this.keyDeserializer, this.valueDeserializer);
}
@Override
public boolean isAutoCommit() {
Object auto = this.configs.get(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG);
return auto instanceof Boolean ? (Boolean) auto
: auto instanceof String ? Boolean.valueOf((String) auto) : false;
}
}```
OrderSerializer.java
```package com.test.serializers.pb;
import kafka.message.ExchangeMessage.Order;
import org.apache.kafka.common.serialization.Serializer;
public class OrderSerializer extends Adapter implements Serializer<Order> {
@Override
public byte[] serialize(final String topic, final Order data) {
return data.toByteArray();
}
}```
PersonDesc.java
```package com.test;
import org.springframework.kafka.support.serializer.JsonDeserializer;
/**
* @author Lenovo
* @date 2016-08-25
* @modify
* @copyright
*/
public class PersonDesc extends JsonDeserializer<Person> {
}
```
DummyEntity.java
```package com.sping.kafka.test.serializer;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class DummyEntity {
public int intValue;
public Long longValue;
public String stringValue;
public Map<Short, List<String>> complexStruct;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DummyEntity that = (DummyEntity) o;
return intValue == that.intValue &&
Objects.equals(longValue, that.longValue) &&
Objects.equals(stringValue, that.stringValue) &&
Objects.equals(complexStruct, that.complexStruct);
}
@Override
public int hashCode() {
return Objects.hash(intValue, longValue, stringValue, complexStruct);
}
}```
Person.java
```package com.test;
import java.io.Serializable;
/**
* @author Lenovo
* @date 2016-08-25
* @modify
* @copyright
*/
public class Person implements Serializable {
public Person() {
//type = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
private String name;
private int age;
private byte[] b;
public Person(String name, int age, byte[] b) {
this.name = name;
this.age = age;
this.b = b;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public byte[] getB() {
return b;
}
public void setB(byte[] b) {
this.b = b;
}
}
```
KafkaJsonDeserializer.java
```package com.test.serializers;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.kafka.common.errors.SerializationException;
import org.apache.kafka.common.serialization.Deserializer;
import java.lang.reflect.Method;
import java.util.Map;
public class KafkaJsonDeserializer<T> implements Deserializer<T> {
private ObjectMapper objectMapper;
private Class<T> type;
public KafkaJsonDeserializer() {
//type = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
@Override
public void configure(Map<String, ?> props, boolean isKey) {
configure(new KafkaJsonDeserializerConfig(props), isKey);
}
protected void configure(KafkaJsonDecoderConfig config, Class<T> type) {
this.objectMapper = new ObjectMapper();
this.type = type;
//reference = new TypeReference<Person<Item>>(){};
boolean failUnknownProperties = config.getBoolean(KafkaJsonDeserializerConfig.FAIL_UNKNOWN_PROPERTIES);
this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, failUnknownProperties);
}
@SuppressWarnings("unchecked")
private void configure(KafkaJsonDeserializerConfig config, boolean isKey) {
if (isKey) {
configure(config, (Class<T>) config.getClass(KafkaJsonDeserializerConfig.JSON_KEY_TYPE));
} else {
configure(config, (Class<T>) config.getClass(KafkaJsonDeserializerConfig.JSON_VALUE_TYPE));
}
}
@Override
public T deserialize(String _, byte[] bytes) {
if (bytes == null || bytes.length == 0)
return null;
try {
return objectMapper.readValue(bytes, type);
// T t=objectMapper.readValue(bytes,type);
// Method methodClass = t.getClass().getMethod("getType");
// Method method = t.getClass().getMethod("getMessage");
// Method methodSet = t.getClass().getMethod("setMessage",Object.class);
// Class clazz = (Class) methodClass.invoke(t);
// Object object = method.invoke(t);
// byte[] messageBytes=objectMapper.writeValueAsBytes(object);
// methodSet.invoke(t,objectMapper.readValue(messageBytes, clazz));
// return t;
} catch (Exception e) {
throw new SerializationException(e);
}
}
protected Class<T> getType() {
return type;
}
@Override
public void close() {
}
}
```
OrderDeserializer.java
```package com.test.serializers.pb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.kafka.common.serialization.Deserializer;
import kafka.message.ExchangeMessage.Order;
public class OrderDeserializer extends Adapter implements Deserializer<Order> {
private static final Logger LOG = LoggerFactory.getLogger(OrderDeserializer.class);
@Override
public Order deserialize(final String topic, byte[] data) {
try {
return Order.parseFrom(data);
} catch (final InvalidProtocolBufferException e) {
LOG.error("Received unparseable message", e);
throw new RuntimeException("Received unparseable message " + e.getMessage(), e);
}
}
}```
KafkaJsonDeserializerConfig.java
```package com.test.serializers;
import com.test.Person;
import org.apache.kafka.common.config.ConfigDef;
import java.util.Map;
/**
* Deserializer configuration for {@link KafkaJsonDeserializer}. It's slightly odd
* to have this extend {@link KafkaJsonDecoderConfig} (in most other cases the
* Decoder variants extend from the Deserializer version), but the reason is that
* {@link kafka.serializer.Decoder} doesn't provide the ability to distinguish
* between constructing serializers for keys or for values. So the type configuration
* options do not work with {@link KafkaJsonDecoder}.
*/
public class KafkaJsonDeserializerConfig extends KafkaJsonDecoderConfig {
public static final String JSON_KEY_TYPE = "json.key.type";
public static final String JSON_KEY_TYPE_DEFAULT = Object.class.getName();
public static final String JSON_KEY_TYPE_DOC =
"Classname of the type that the message key should be deserialized to";
public static final String JSON_VALUE_TYPE = "json.value.type";
public static final String JSON_VALUE_TYPE_DEFAULT = Person.class.getName();
public static final String JSON_VALUE_TYPE_DOC =
"Classname of the type that the message value should be deserialized to";
private static ConfigDef config;
static {
config = baseConfig()
.define(JSON_KEY_TYPE, ConfigDef.Type.CLASS, JSON_KEY_TYPE_DEFAULT,
ConfigDef.Importance.MEDIUM, JSON_KEY_TYPE_DOC)
.define(JSON_VALUE_TYPE, ConfigDef.Type.CLASS, JSON_VALUE_TYPE_DEFAULT,
ConfigDef.Importance.MEDIUM, JSON_VALUE_TYPE_DOC);
}
public KafkaJsonDeserializerConfig(Map<?, ?> props) {
super(config, props);
}
}
```
OrderProducer.java
```package com.sping.kafka.test.pb;
import com.test.serializers.pb.OrderSerializer;
import kafka.message.ExchangeMessage.Order;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.IntegerSerializer;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
public class OrderProducer extends Thread {
private final KafkaProducer<Integer, Order> producer;
private final String topic;
public OrderProducer(String topic) {
Properties props = new Properties();
props.put("bootstrap.servers", "10.199.90.108:9092");
props.put("client.id", "OrderProducer");
producer = new KafkaProducer<>(props, new IntegerSerializer(), new OrderSerializer());
this.topic = topic;
}
public void run() {
int messageNo = 1;
while (true) {
Order order = Order.newBuilder().setOid("xxx" + String.valueOf(messageNo)).build();
try {
producer.send(new ProducerRecord<>(topic,
messageNo,
order)).get();
System.out.println("Sent message: (" + messageNo + ", " + order.toString() + ")");
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
++messageNo;
}
}
}```
ProducerTest.java
```package com.mapbar;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.util.Properties;
public class ProducerTest {
public static void main(String[] args) {
Properties props = new Properties();
props.put("bootstrap.servers", "192.168.9.3:9092,10.10.31.8:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("security.protocol", "SSL");
props.put("ssl.truststore.location", "/var/private/ssl/kafka.client.truststore.jks");
props.put("ssl.truststore.password", "123456");
props.put("ssl.keystore.location", "/var/private/ssl/kafka.client.keystore.jks");
props.put("ssl.keystore.password", "123456");
props.put("ssl.key.password", "123456");
Producer<String, String> producer = new KafkaProducer<>(props);
for (int i = 0; i < 100; i++) {
producer.send(new ProducerRecord<String, String>("TBTest", Integer.toString(i), Integer.toString(i)));
System.out.println("向topic:TBTest发送了消息,key为" + Integer.toString(i) + ",value为" + Integer.toString(i));
}
producer.close();
}
}
```
KafkaJsonEncoder.java
```package com.test.serializers;
import kafka.serializer.Encoder;
import kafka.utils.VerifiableProperties;
/**
* Encode an Object to a JSON-encoded byte array.
*/
public class KafkaJsonEncoder<T> extends KafkaJsonSerializer<T> implements Encoder<T> {
/* public KafkaJsonEncoder(){}*/
public KafkaJsonEncoder(VerifiableProperties props) {
configure(new KafkaJsonSerializerConfig(props.props()));
}
@Override
public byte[] toBytes(T val) {
return serialize(null, val);
}
}
```
OrderConsumerProducerTest.java
```package com.sping.kafka.test.pb;
public class OrderConsumerProducerTest {
public static void main(String[] args) {
OrderProducer producerThread = new OrderProducer("zz");
producerThread.start();
OrderConsummer consumerThread = new OrderConsummer("zz");
consumerThread.start();
}
}```
KafkaJsonDecoderConfig.java
```package com.test.serializers;
import org.apache.kafka.common.config.AbstractConfig;
import org.apache.kafka.common.config.ConfigDef;
import java.util.Map;
public class KafkaJsonDecoderConfig extends AbstractConfig {
public static final String FAIL_UNKNOWN_PROPERTIES = "json.fail.unknown.properties";
public static final boolean FAIL_UNKNOWN_PROPERTIES_DEFAULT = true;
public static final String FAIL_UNKNOWN_PROPERTIES_DOC =
"Whether to fail deserialization if unknown JSON properties are encountered";
public KafkaJsonDecoderConfig(Map<?, ?> props) {
super(baseConfig(), props);
}
protected KafkaJsonDecoderConfig(ConfigDef config, Map<?, ?> props) {
super(config, props);
}
protected static ConfigDef baseConfig() {
return new ConfigDef()
.define(FAIL_UNKNOWN_PROPERTIES, ConfigDef.Type.BOOLEAN, FAIL_UNKNOWN_PROPERTIES_DEFAULT,
ConfigDef.Importance.LOW, FAIL_UNKNOWN_PROPERTIES_DOC);
}
}
```
OrderConsummer.java
```package com.sping.kafka.test.pb;
import com.test.serializers.pb.OrderDeserializer;
import kafka.utils.ShutdownableThread;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import kafka.message.ExchangeMessage.Order;
import java.util.Collections;
import java.util.Properties;
import org.apache.kafka.common.serialization.IntegerDeserializer;
public class OrderConsummer extends ShutdownableThread {
private final KafkaConsumer<Integer, Order> consumer;
private final String topic;
public OrderConsummer(String topic) {
super("KafkaConsumerExample", false);
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "10.199.90.108:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "OrderConsumer");
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "30000");
consumer = new KafkaConsumer<>(props, new IntegerDeserializer(), new OrderDeserializer());
this.topic = topic;
}
@Override
public void doWork() {
consumer.subscribe(Collections.singletonList(this.topic));
ConsumerRecords<Integer, Order> records = consumer.poll(1000);
for (ConsumerRecord<Integer, Order> record : records) {
System.out.println("Received message: (" + record.key() + ", " + record.value() + ") at offset " + record.offset());
}
}
@Override
public String name() {
return null;
}
@Override
public boolean isInterruptible() {
return false;
}
}```
KafkaListener.java
```package com.test;
import com.google.protobuf.InvalidProtocolBufferException;
import com.kafka.message.ExchangeMessage;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.metrics.stats.SampledStat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.listener.MessageListener;
import org.springframework.stereotype.Component;
/**
* @author Lenovo
* @date 2016-08-24
* @modify
* @copyright
*/
@Component
public class KafkaListener implements MessageListener<String, Object> {
private static final Logger logger = LoggerFactory.getLogger(KafkaListener.class);
private static int i=0;
@Override
public void onMessage(ConsumerRecord record) {
long start = System.currentTimeMillis();
logger.info(start + " start" + (i++));
//System.out.println(record);
Person value = (Person) record.value();
// System.out.println(value.getB());
try {
ExchangeMessage.Order order = ExchangeMessage.Order.parseFrom(value.getB());
//System.out.println(order.getOid());
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
//long end = System.currentTimeMillis();
//logger.info(end + " end,end-start=" + (end - start) + "ms");
}
}
```
|
790013438/hib1706
|
790013438/hib1706
User.java
```package com.qfedu.hib1706.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.DynamicUpdate;
// POJO - Plain Ordinary Java Object
// POJO + Annotation / XML ==> PO
// PO - Persistent Object
@Entity
@Table(name = "tb_user")
@DynamicUpdate
public class User implements Serializable {
@Id
@Column(length = 20)
private String username;
@Column(name = "userpass", nullable = false, length = 20)
private String password;
@Column(unique = true)
private String email;
public User() {
}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
```
App2.java
```package com.qfedu.hib1706;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.qfedu.hib1706.domain.User;
public class App2 {
public static void main(String[] args) {
SessionFactory factory = new Configuration().configure()
.buildSessionFactory();
Session session = factory.openSession();
try {
session.beginTransaction();
User user = session.get(User.class, "admin");
System.out.println(user.getPassword());
System.out.println(user.getEmail());
user.setEmail("admin@126.com");
session.getTransaction().commit();
} catch (HibernateException e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
factory.close();
}
}
}
```
App.java
```package com.qfedu.hib1706;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.qfedu.hib1706.domain.User;
public class App {
public static void main(String[] args) {
User user = new User("admin", "123123", "admin@qq.com");
SessionFactory factory = new Configuration().configure()
.buildSessionFactory();
Session session = factory.openSession();
try {
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
} finally {
session.close();
factory.close();
}
}
}
```
AppTest.java
```package com.qfedu.hib1706;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.qfedu.hib1706.domain.User;
public class AppTest {
private static SessionFactory factory;
private Session session;
static {
factory = new Configuration().configure().buildSessionFactory();
}
@Before
public void setUp() {
session = factory.getCurrentSession();
session.beginTransaction();
}
@After
public void tearDown() {
session.getTransaction().commit();
session.close();
}
@Test
public void testSaveAndDelete() {
User user = new User("wangdachui", "121212", "dcwang@qq.com");
Assert.assertNotNull(session.save(user));
session.delete(user);
}
@Test
public void testGet() {
User user = session.get(User.class, "admin");
Assert.assertNotNull(user);
Assert.assertEquals(user.getEmail(), "admin@qq.com");
User user2 = session.get(User.class, "wangdachui");
Assert.assertNull(user2);
}
@Test(expected = java.lang.Exception.class)
public void testLoad() {
User user = session.load(User.class, "admin");
Assert.assertNotNull(user);
Assert.assertEquals(user.getEmail(), "admin@qq.com");
User user2 = session.load(User.class, "wangdachui");
Assert.assertNull(user2);
}
@Test
public void testFindAll() {
// SQL - Structured Query Language
// HQL - Hibernate Query Language - OO
List<User> userList = session.createQuery(
"from User as u where u.password=:pwd", User.class)
.setParameter("pwd", "123123")
.getResultList();
// Assert.assertEquals(4, userList.size());
for (User user : userList) {
System.out.println(user.getUsername());
}
}
}```
|
794596/dissertation
|
794596/dissertation
writeResults.c
```#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#include <string.h>
int writeResults(long length, double results, char *file) {
FILE *fp = fopen(file, "a");
fprintf(fp, "%ld, %f\n", length, results);
fclose(fp);
return 0;
}
```
numArray.h
```#ifndef NUMARRAY_H_ /* Include guard */
#define NUMARRAY_H_
char *file_to_array(long long length, char *file);
#endif // NUMARRAY_H_
```
writeResults.h
```int writeResults(long length, double results, char *file);
```
createNumbers.c
```#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#include <string.h>
/**
* Function randoms.
* generates a random number as an int and returns it as a string
*
*/
char randoms()
{
int place = rand()%10;
char got[2];
got[0] = place+'0';
return *got;
}
/**
* Function create_number.
* Opens file an inputs a string of integers and then closes.
*
* @param length number of integers inserted onto the file.
* @param file the file that is being opened and the content added.
*/
void create_number(long long length, char *file)
{
FILE *fptr;
fptr = fopen(file , "w");
if (fptr != NULL) {
printf("File created successfully!\n");
}
else {
printf("Failed to create the file.\n");
}
for (long long i = 0; i < length; ++i){
fputc(randoms(), fptr);
if (i%1000000==0){
printf("%lld\n", i);
}
}
fclose(fptr);
}
void main(int argc, char *argv[])
{
create_number(1000000, "number1.txt");
create_number(1000000, "number2.txt");
}
```
multiplication.c
```#include "multiplication.h"
#include "gmp_ext.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
/**
* Function mpz_school_add.
* Computes the sum c of two multi-precision
* integers a and b.
*
* @param c the multi-precision sum a + b.
* @param a the first multi-precision operand.
* @param b the second multi-precision operand.
*/
void mpz_school_add(mpz_t c, mpz_t a, mpz_t b) {
mpz_t result;
mpz_init(result);
mp_limb_t carry = 0, carry_tmp, ai, bi, res_tmp;
// max of len(a) and len(b)
mp_size_t length = (mpz_size(a) > mpz_size(b)) ? mpz_size(a) : mpz_size(b);
// Add
for (mp_size_t i = 0; i < length; i++) {
//get both limbs
ai = mpz_getlimbn(a, i);
bi = mpz_getlimbn(b, i);
// res_tmp = ai + carry
carry_tmp = mp_add_limb(&res_tmp, ai, carry);
// res_tmp = res_tmp + bi
carry = mp_add_limb(&res_tmp, res_tmp, bi);
// carry = carry + carry_tmp
mp_add_limb(&carry, carry, carry_tmp);
// ci = res_tmp
mpz_setlimbn(result, res_tmp, i);
}
mpz_setlimbn(result, carry, length);
mpz_set(c, result);
mpz_clear(result);
}
void mpz_school_add_neg(mpz_t c, mpz_t a, mpz_t b) {
mpz_t result, a_tmp, b_tmp;
mpz_inits(result, a_tmp, b_tmp, NULL);
mp_limb_t carry = 0, carry_tmp, ai, bi, res_tmp;
int a_sgn, b_sgn;
mp_size_t length;
a_sgn = mpz_sgn(a);
b_sgn = mpz_sgn(b);
// printf("%d\n", a_sgn);
// printf("%d\n", b_sgn);
if (a_sgn > 0 && b_sgn > 0){
mpz_set(a_tmp, a);
mpz_set(b_tmp, b); // max of len(a) and len(b)
length = (mpz_size(a_tmp) > mpz_size(b_tmp)) ? mpz_size(a_tmp) : mpz_size(b_tmp);
// Add
for (mp_size_t i = 0; i < length; i++) {
//get both limbs
ai = mpz_getlimbn(a_tmp, i);
bi = mpz_getlimbn(b_tmp, i);
// res_tmp = ai + carry
carry_tmp = mp_add_limb(&res_tmp, ai, carry);
// res_tmp = res_tmp + bi
carry = mp_add_limb(&res_tmp, res_tmp, bi);
// carry = carry + carry_tmp
mp_add_limb(&carry, carry, carry_tmp);
// ci = res_tmp
mpz_setlimbn(result, res_tmp, i);
}
mpz_setlimbn(result, carry, length);
} else if (a_sgn < 0 && b_sgn < 0){
mpz_set(a_tmp, a);
mpz_set(b_tmp, b); // max of len(a) and len(b)
length = (mpz_size(a_tmp) > mpz_size(b_tmp)) ? mpz_size(a_tmp) : mpz_size(b_tmp);
// Add
for (mp_size_t i = 0; i < length; i++) {
//get both limbs
ai = mpz_getlimbn(a_tmp, i);
bi = mpz_getlimbn(b_tmp, i);
// res_tmp = ai + carry
carry_tmp = mp_add_limb(&res_tmp, ai, carry);
// res_tmp = res_tmp + bi
carry = mp_add_limb(&res_tmp, res_tmp, bi);
// carry = carry + carry_tmp
mp_add_limb(&carry, carry, carry_tmp);
// ci = res_tmp
mpz_setlimbn(result, res_tmp, i);
}
mpz_setlimbn(result, carry, length);
mpz_neg(result, result);
} else if (a_sgn < 0 && b_sgn > 0) {
mpz_abs(a_tmp, a);
mpz_abs(b_tmp, b);
if (mpz_cmp(a_tmp,b_tmp)>0){
mpz_sub(result, a_tmp, b_tmp);
mpz_neg(result, result);
} else {
mpz_sub(result, b_tmp, a_tmp);
}
} else if (a_sgn > 0 && b_sgn < 0){
mpz_abs(a_tmp, a);
mpz_abs(b_tmp, b);
if (mpz_cmp(a_tmp,b_tmp)>0){
mpz_sub(result, a_tmp, b_tmp);
} else {
mpz_sub(result,b_tmp, a_tmp);
mpz_neg(result, result);
}
} else if (a_sgn == 0){
mpz_set(result, b);
} else if (b_sgn == 0){
mpz_set(result, a);
}
mpz_set(c, result);
mpz_clear(result);
}
/**
* Function mpz_school_sub.
* Computes the sum c of two multi-precision
* integers a and b.
*
* @param c the multi-precision sum a - b.
* @param a the first multi-precision operand.
* @param b the second multi-precision operand.
*/
void mpz_school_sub(mpz_t c, mpz_t a, mpz_t b) {
mpz_t result, a_tmp, b_tmp;
mpz_inits(result, a_tmp, b_tmp, NULL);
mp_limb_t carry = 0, carry_tmp, ai, bi, res_tmp;
int a_sgn = mpz_sgn(a);
int b_sgn = mpz_sgn(b);
mpz_abs(a_tmp, a);
mpz_abs(b_tmp, b);
// max of len(a) and len(b)
mp_size_t length = (mpz_size(a_tmp) > mpz_size(b_tmp)) ? mpz_size(a_tmp) : mpz_size(b_tmp);
if (a_sgn > 0 && b_sgn < 0) {
mpz_school_add(result, a_tmp, b_tmp);
} else if (a_sgn < 0 && b_sgn > 0) {
mpz_school_add(result, a_tmp, b_tmp);
mpz_neg(result, result);
} else if (a_sgn ==0) {
mpz_set(result, b);
mpz_neg(result, result);
} else if (b_sgn ==0) {
mpz_set(result, a);
} else if(a_sgn < 0 && b_sgn < 0) {
if (mpz_cmp(a_tmp, b_tmp)>0){
mpz_sub(result, a_tmp, b_tmp);
mpz_neg(result, result);
} else {
mpz_sub(result, b_tmp, a_tmp);
}
} else {
if (mpz_cmp(a_tmp, b_tmp)>0){
// Add
for (mp_size_t i = 0; i < length; i++) {
//get both limbs
ai = mpz_getlimbn(a_tmp, i);
bi = mpz_getlimbn(b_tmp, i);
// res_tmp = ai + carry
carry_tmp = mp_sub_limb(&res_tmp, ai, carry);
// res_tmp = res_tmp + bi
carry = mp_sub_limb(&res_tmp, res_tmp, bi);
// carry = carry + carry_tmp
mp_sub_limb(&carry, carry, carry_tmp);
// ci = res_tmp
mpz_setlimbn(result, res_tmp, i);
}
mpz_setlimbn(result, carry, length);
} else {
mpz_sub(result, b, a);
mpz_neg(result, result);
}
}
mpz_set(c, result);
mpz_clear(result);
}
/**
* Function mpz_mul_limb.
* Computes the product c of a multi-precision integer a
* and a single-precision integer b.
*
* @param c the multi-precision product a * b.
* @param a the multi-precision operand.
* @param b the single-precision operand.
*/
void mpz_mul_limb(mpz_t c, mpz_t a, mp_limb_t b) {
mpz_t result;
mpz_init(result);
mp_limb_t carry = 0, carry_tmp, ai, tmp;
for (mp_size_t i = 0; i < mpz_size(a); i++) {
ai = mpz_getlimbn(a, i);
carry_tmp = carry;
//multiply
carry = mp_mul_limb(&tmp, ai, b);
//add the old carry
carry_tmp = mp_add_limb(&tmp, tmp, carry_tmp);
// (new-)carry = carry + carry_tmp
mp_add_limb(&carry, carry, carry_tmp);
mpz_setlimbn(result, tmp, i);
}
mpz_setlimbn(result, carry, mpz_size(a));
mpz_set(c, result);
mpz_clear(result);
}
/**
* Function mpz_mul_base.
* Computes the product c of a multi-precision integer a
* and the i-th power of the base B.
*
* @param c the multi-precision product a * B^i.
* @param a the multi-precision operand.
* @param i the base exponent.
*/
void mpz_mul_base(mpz_t c, mpz_t a, mp_size_t i) {
mpz_t result, a_tmp;
mpz_inits(result, a_tmp, NULL);
int a_sgn;
a_sgn = mpz_sgn(a);
mpz_abs(a_tmp, a);
for (mp_size_t j = 0; j < i; j++) {
mpz_setlimbn(result, 0, j);
}
// copy into result
for (mp_size_t j = 0; j < mpz_size(a_tmp); j++) {
mpz_setlimbn(result, mpz_getlimbn(a_tmp, j), i + j);
}
if (a_sgn < 0){
mpz_neg(result, result);
}
mpz_set(c, result);
mpz_clear(result);
}
/**
* Function mpz_school_mul.
* Computes the product c of two multi-precision
* integers a and b using the schoolbook method.
*
* @param c the multi-precision product a * b.
* @param a the first multi-precision operand.
* @param b the second multi-precision operand.
*/
void mpz_school_mul(mpz_t c, mpz_t a, mpz_t b) {
mpz_t result, tmp, a_tmp, b_tmp;
mpz_inits(result, tmp, a_tmp, b_tmp, NULL);
int a_sgn, b_sgn;
mpz_abs(a_tmp, a);
mpz_abs(b_tmp, b);
a_sgn = mpz_sgn(a);
b_sgn = mpz_sgn(b);
// look over all limbs of a
for (mp_size_t i = 0; i < mpz_size(a_tmp); i++) {
mpz_mul_base(tmp, b_tmp, i);
mpz_mul_limb(tmp, tmp, mpz_getlimbn(a_tmp, i));
mpz_school_add(result, result, tmp);
}
if ((a_sgn >= 0 && b_sgn < 0) || (a_sgn < 0 && b_sgn >= 0)){
mpz_neg(result, result);
}
mpz_set(c, result);
mpz_clears(result, tmp, NULL);
}
/**
* Function mpz_karatsuba_mul.
* Computes the product c of two multi-precision
* integers a and b using Karatsuba's multiplication method.
*
* @param c the multi-precision product a * b.
* @param a the first multi-precision operand.
* @param b the second multi-precision operand.
*/
void mpz_karatsuba_mul(mpz_t c, mpz_t a, mpz_t b) {
mpz_t result;
mpz_init(result);
// max of len(a) and len(b)
mp_size_t n = (mpz_size(a) > mpz_size(b)) ? mpz_size(a) : mpz_size(b);
if (n > 2) {
//Prepare splitting
// get last bit by bitwise%s and with 1
mp_size_t m = (n & 1) ? n / 2 + 1 : n / 2;
mpz_t a1, a0, b1, b0, a1b1, a0b0, a1a0b1b0;
mpz_inits(a1, a0, b1, b0, a1b1, a0b0, a1a0b1b0, NULL);
// Get upper half
for (int i = m; i < n; ++i) {
mpz_setlimbn(a1, mpz_getlimbn(a, i), i - m);
mpz_setlimbn(b1, mpz_getlimbn(b, i), i - m);
}
// Get lower half
for (int i = 0; i < m; ++i) {
mpz_setlimbn(a0, mpz_getlimbn(a, i), i);
mpz_setlimbn(b0, mpz_getlimbn(b, i), i);
}
// prepare multiply
mpz_t tmp_res_1, tmp_res_2;
mpz_inits(tmp_res_1, tmp_res_2, NULL);
// Now multiply and save in result
// result = a1 * b1 * B^(2m)
mpz_karatsuba_mul(a0b0, a0, b0);
mpz_karatsuba_mul(a1b1, a1, b1);
mpz_mul_base(tmp_res_1, a1b1, 2 * m);
mpz_set(result, tmp_res_1);
mpz_school_add(tmp_res_1, a1, a0);
mpz_school_add(tmp_res_2, b1, b0);
mpz_karatsuba_mul(a1a0b1b0, tmp_res_1, tmp_res_2);
// result = result + ((a1+a0)*(b1+b0)-a1*b1-a0*b0)*B^m
mpz_school_sub(tmp_res_1, a1a0b1b0, a1b1);
mpz_school_sub(tmp_res_1, tmp_res_1, a0b0);
mpz_mul_base(tmp_res_1, tmp_res_1, m);
mpz_school_add(result, result, tmp_res_1);
// result = result + a0*b0
mpz_school_add(result, result,a0b0);
// clear the variables
mpz_clears(a1, a0, b1, b0, tmp_res_1, tmp_res_2, a1b1, a0b0, NULL);
} else if (n > 1){
mpz_school_mul(result,a,b);
} else {
// If n <= 1
mp_limb_t carry, res;
if (mpz_size(a) > 1 || mpz_size(b) > 1) {
printf("Error!! Length mismatch");
} else {
//single precision mult
carry = mp_mul_limb(&res, mpz_getlimbn(a, 0), mpz_getlimbn(b, 0));
//result will consist of (carry, result)
mpz_setlimbn(result, res, 0);
mpz_setlimbn(result, carry, 1);
}
}
// Copy result to c
mpz_set(c, result);
mpz_clear(result);
}
void mpz_karatsuba_mul_par(mpz_t c, mpz_t a, mpz_t b) {
mpz_t result;
mpz_init(result);
// max of len(a) and len(b)
mp_size_t n = (mpz_size(a) > mpz_size(b)) ? mpz_size(a) : mpz_size(b);
if (n > 1) {
//Prepare splitting
// get last bit by bitwise and with 1
mp_size_t m = (n & 1) ? n / 2 + 1 : n / 2;
mpz_t a1, a0, b1, b0, a1b1, a0b0, a1a0b1b0;
mpz_inits(a1, a0, b1, b0, a1b1, a0b0, a1a0b1b0, NULL);
// Get upper half
for (int i = m; i < n; ++i) {
mpz_setlimbn(a1, mpz_getlimbn(a, i), i - m);
mpz_setlimbn(b1, mpz_getlimbn(b, i), i - m);
}
// Get lower half
for (int i = 0; i < m; ++i) {
mpz_setlimbn(a0, mpz_getlimbn(a, i), i);
mpz_setlimbn(b0, mpz_getlimbn(b, i), i);
}
// prepare multiply
mpz_t tmp_res_1, tmp_res_2;
mpz_inits(tmp_res_1, tmp_res_2, NULL);
mpz_school_add(tmp_res_1, a1, a0);
mpz_school_add(tmp_res_2, b1, b0);
// Now multiply and save in result
// result = a1 * b1 * B^(2m)
#pragma omp task shared(a0b0)
{
mpz_karatsuba_mul(a0b0, a0, b0);
}
#pragma omp task shared(a1b1)
{
mpz_karatsuba_mul(a1b1, a1, b1);
}
#pragma omp task shared(a1a0b1b0)
{
mpz_karatsuba_mul(a1a0b1b0, tmp_res_1, tmp_res_2);
}
#pragma omp taskwait
mpz_mul_base(tmp_res_1, a1b1, 2 * m);
mpz_set(result, tmp_res_1);
// result = result + ((a1+a0)*(b1+b0)-a1*b1-a0*b0)*B^m
mpz_school_sub(tmp_res_1, a1a0b1b0, a1b1);
mpz_school_sub(tmp_res_1, tmp_res_1, a0b0);
mpz_mul_base(tmp_res_1, tmp_res_1, m);
mpz_school_add(result, result, tmp_res_1);
// result = result + a0*b0
mpz_school_add(result, result,a0b0);
// clear the variables
mpz_clears(a1, a0, b1, b0, tmp_res_1, tmp_res_2, a1b1, a0b0, NULL);
} else {
// If n <= 1
mp_limb_t carry, res;
if (mpz_size(a) > 1 || mpz_size(b) > 1) {
printf("Error!! Length mismatch");
} else {
//single precision mult
carry = mp_mul_limb(&res, mpz_getlimbn(a, 0), mpz_getlimbn(b, 0));
//result will consist of (carry, result)
mpz_setlimbn(result, res, 0);
mpz_setlimbn(result, carry, 1);
}
}
// Copy result to c
mpz_set(c, result);
mpz_clear(result);
}
void mpz_kara_mul_par(mpz_t c, mpz_t a, mpz_t b) {
#pragma omp parallel num_threads(35)
{
#pragma omp master
{
mpz_karatsuba_mul_par(c,a,b);
}
}
}
void evaluation(mpz_t a2, mpz_t a1, mpz_t a0, mpz_t p,mpz_t p0,mpz_t p1,mpz_t pm1,mpz_t pm2,mpz_t pinf) {
mpz_t tmp_res_1, tmp_res_2;
mpz_inits(tmp_res_1, tmp_res_2, NULL);
mpz_add(p, a0,a2);
mpz_set(p0, a0);
mpz_add(p1, p, a1);
mpz_sub(pm1, p, a1);
mpz_add(tmp_res_1, pm1, a2);
mpz_add(pm2, tmp_res_1, tmp_res_1);
mpz_sub(pm2, pm2, a0);
mpz_set(pinf, a2);
}
/**
* Function mpz_toom3_mul.
* Computes the product c of two multi-precision
* integers a and b using toom-3 multiplication method.
*
* @param c the multi-precision product a * b.
* @param a the first multi-precision operand.
* @param b the second multi-precision operand.
*/
void mpz_toom3_mul(mpz_t c, mpz_t a, mpz_t b) {
mpz_t result, tmp_res_1, tmp_res_2, a_tmp, b_tmp, two;
mpz_inits(result, tmp_res_1, tmp_res_2, a_tmp, b_tmp, two, NULL);
mpz_init_set_str(two, "2", 10);
int a_sgn = mpz_sgn(a);
int b_sgn = mpz_sgn(b);
mpz_abs(a_tmp, a);
mpz_abs(b_tmp, b);
mp_size_t n = (mpz_size(a_tmp) > mpz_size(b_tmp)) ? mpz_size(a_tmp) : mpz_size(b_tmp);
if (n > 2) {
//Prepare splitting
// get last bit by bitwise and with 1
long m;
switch (n%3){
case 0:
m = n/3;
break;
case 1:
m = (n+2)/3;
break;
case 2:
m = (n+1)/3;
break;
}
mpz_t a2, a1, a0, b2, b1, b0;
mpz_inits(a2, a1, a0, b2, b1, b0, NULL);
// Get upper half
for (int i = m+m; i < n; i++) {
mpz_setlimbn(a2, mpz_getlimbn(a_tmp, i), i-(m+m));
mpz_setlimbn(b2, mpz_getlimbn(b_tmp, i), i-(m+m));
}
// Get lower half
for (int i = m; i < m+m; i++) {
mpz_setlimbn(a1, mpz_getlimbn(a_tmp, i), i-((m)));
mpz_setlimbn(b1, mpz_getlimbn(b_tmp, i), i-((m)));
}
// Get lower half
for (int i = 0; i < m; i++) {
mpz_setlimbn(a0, mpz_getlimbn(a_tmp, i), i);
mpz_setlimbn(b0, mpz_getlimbn(b_tmp, i), i);
}
// prepare multiply
mpz_t p, p0, p1, pm1, pm2, pinf, q, q0, q1, qm1, qm2, qinf;
mpz_inits(p, p0, p1, pm1, pm2, pinf, q, q0, q1, qm1, qm2, qinf, NULL);
evaluation(a2, a1, a0, p, p0, p1, pm1, pm2, pinf);
evaluation(b2, b1, b0, q, q0, q1, qm1, qm2, qinf);
mpz_t r0, r1, rm1, rm2, rinf;
mpz_inits(r0, r1, rm1, rm2, rinf, NULL);
mpz_toom3_mul(r0, p0, q0);
mpz_toom3_mul(r1, p1, q1);
mpz_toom3_mul(rm1, pm1, qm1);
mpz_toom3_mul(tmp_res_1, pm1, qm1);
mpz_toom3_mul(rm2, pm2, qm2);
mpz_toom3_mul(rinf, pinf, qinf);
mpz_t res0, res1, res2, res3, res4;
mpz_inits(res0, res1, res2, res3, res4, NULL);
mpz_set(res0, r0);
mpz_set(res4, rinf);
mpz_sub(tmp_res_1, rm2, r1);
mpz_divexact_ui(res3, tmp_res_1, 3);
mpz_sub(tmp_res_1, r1, rm1);
mpz_div_2exp(res1, tmp_res_1, 1);
mpz_sub(res2, rm1, r0);
mpz_sub(tmp_res_1, res2, res3);
mpz_sub(tmp_res_2, res2, res3);
mpz_sub(tmp_res_2, tmp_res_2, tmp_res_1);
mpz_div_2exp(tmp_res_1, tmp_res_1, 1);
mpz_add(tmp_res_2, rinf, rinf);
mpz_add(res3, tmp_res_1, tmp_res_2);
mpz_add(res2, res2, res1);
mpz_sub(res2, res2, res4);
mpz_sub(res1, res1, res3);
mpz_mul_base(res4, res4,m*4);
mpz_mul_base(res3, res3,m*3);
mpz_mul_base(res2, res2,m*2);
mpz_mul_base(res1, res1,m*1);
mpz_add(result, res0, res1);
mpz_add(result, result, res2);
mpz_add(result, result, res3);
mpz_add(result, result, res4);
// clear the variables
mpz_clears(a1, a0, b1, b0, tmp_res_1, tmp_res_2, NULL);
} else {
// If n <= 1
//mp_limb_t carry, res;
if (mpz_size(a_tmp) > 2 || mpz_size(b_tmp) > 2) {
printf("Error!! Length mismatch");
} else {
mpz_mul(result, a_tmp, b_tmp);
// //single precision mult
//carry = mp_mul_limb(&res, mpz_getlimbn(a_tmp, 0), mpz_getlimbn(b, 0));
//
// //result will consist of (carry, result)
// mpz_setlimbn(result, res, 0);
// mpz_setlimbn(result, carry, 1);
}
}
if(((b_sgn > 0) && (a_sgn <= 0))||((a_sgn > 0) && (b_sgn <= 0))){
mpz_neg(result, result);
}
// Copy result to c
mpz_set(c, result);
mpz_clear(result);
}
void mpz_toom_mul_par(mpz_t c, mpz_t a, mpz_t b) {
mpz_t result, tmp_res_1, tmp_res_2, a_tmp, b_tmp, two;
mpz_inits(result, tmp_res_1, tmp_res_2, a_tmp, b_tmp, two, NULL);
mpz_init_set_str(two, "2", 10);
int a_sgn = mpz_sgn(a);
int b_sgn = mpz_sgn(b);
// mpz_out_str(stdout, 10, b);
// printf("%s\n", "");
//
// mpz_out_str(stdout, 10, b_tmp);
// printf("%s\n", "");
mpz_abs(a_tmp, a);
mpz_abs(b_tmp, b);
// mpz_out_str(stdout, 10, b);
// printf("%s\n", "");
//
// mpz_out_str(stdout, 10, b_tmp);
// printf("%s\n", "");
// max of len(a) and len(b)
mp_size_t n = (mpz_size(a_tmp) > mpz_size(b_tmp)) ? mpz_size(a_tmp) : mpz_size(b_tmp);
if (n > 2) {
//Prepare splitting
// get last bit by bitwise and with 1
long m;
switch (n%3){
case 0:
m = n/3;
break;
case 1:
m = (n+2)/3;
break;
case 2:
m = (n+1)/3;
break;
}
mpz_t a2, a1, a0, b2, b1, b0;
mpz_inits(a2, a1, a0, b2, b1, b0, NULL);
// Get upper half
for (int i = m+m; i < n; i++) {
mpz_setlimbn(a2, mpz_getlimbn(a_tmp, i), i-(m+m));
mpz_setlimbn(b2, mpz_getlimbn(b_tmp, i), i-(m+m));
}
// Get lower half
for (int i = m; i < m+m; i++) {
mpz_setlimbn(a1, mpz_getlimbn(a_tmp, i), i-((m)));
mpz_setlimbn(b1, mpz_getlimbn(b_tmp, i), i-((m)));
}
// Get lower half
for (int i = 0; i < m; i++) {
mpz_setlimbn(a0, mpz_getlimbn(a_tmp, i), i);
mpz_setlimbn(b0, mpz_getlimbn(b_tmp, i), i);
}
// prepare multiply
mpz_t p, p0, p1, pm1, pm2, pinf, q, q0, q1, qm1, qm2, qinf;
mpz_inits(p, p0, p1, pm1, pm2, pinf, q, q0, q1, qm1, qm2, qinf, NULL);
evaluation(a2, a1, a0, p, p0, p1, pm1, pm2, pinf);
evaluation(b2, b1, b0, q, q0, q1, qm1, qm2, qinf);
mpz_t r0, r1, rm1, rm2, rinf;
mpz_inits(r0, r1, rm1, rm2, rinf, NULL);
#pragma omp task shared(r0)
{
mpz_toom_mul_par(r0, p0, q0);
}
#pragma omp task shared(r1)
{
mpz_toom_mul_par(r1, p1, q1);
}
#pragma omp task shared(rm1)
{
mpz_toom_mul_par(rm1, pm1, qm1);
}
#pragma omp task shared(rm2)
{
mpz_toom_mul_par(rm2, pm2, qm2);
}
#pragma omp task shared(rinf)
{
mpz_toom_mul_par(rinf, pinf, qinf);
}
#pragma omp taskwait
mpz_t res0, res1, res2, res3, res4;
mpz_inits(res0, res1, res2, res3, res4, NULL);
mpz_set(res0, r0);
mpz_set(res4, rinf);
mpz_sub(tmp_res_1, rm2, r1);
mpz_divexact_ui(res3, tmp_res_1, 3);
mpz_sub(tmp_res_1, r1, rm1);
mpz_div_2exp(res1, tmp_res_1, 1);
mpz_sub(res2, rm1, r0);
mpz_sub(tmp_res_1, res2, res3);
mpz_sub(tmp_res_2, res2, res3);
mpz_sub(tmp_res_2, tmp_res_2, tmp_res_1);
mpz_div_2exp(tmp_res_1, tmp_res_1, 1);
mpz_add(tmp_res_2, rinf, rinf);
mpz_add(res3, tmp_res_1, tmp_res_2);
mpz_add(res2, res2, res1);
mpz_sub(res2, res2, res4);
mpz_sub(res1, res1, res3);
mpz_mul_base(res4, res4,m*4);
mpz_mul_base(res3, res3,m*3);
mpz_mul_base(res2, res2,m*2);
mpz_mul_base(res1, res1,m*1);
mpz_add(result, res0, res1);
mpz_add(result, result, res2);
mpz_add(result, result, res3);
mpz_add(result, result, res4);
// clear the variables
mpz_clears(a1, a0, b1, b0, tmp_res_1, tmp_res_2, NULL);
} else {
// If n <= 1
//mp_limb_t carry, res;
if (mpz_size(a_tmp) > 2 || mpz_size(b_tmp) > 2) {
printf("Error!! Length mismatch");
} else {
mpz_mul(result, a_tmp, b_tmp);
// //single precision mult
//carry = mp_mul_limb(&res, mpz_getlimbn(a_tmp, 0), mpz_getlimbn(b, 0));
//
// //result will consist of (carry, result)
// mpz_setlimbn(result, res, 0);
// mpz_setlimbn(result, carry, 1);
}
}
if(((b_sgn > 0) && (a_sgn <= 0))||((a_sgn > 0) && (b_sgn <= 0))){
mpz_neg(result, result);
}
// Copy result to c
mpz_set(c, result);
mpz_clear(result);
}
void mpz_toom3_mul_par(mpz_t c, mpz_t a, mpz_t b) {
#pragma omp parallel num_threads(35)
{
#pragma omp master
{
mpz_toom_mul_par(c,a,b);
}
}
}
```
gmp_ext.h
```/*! \file gmp_ext.h
*/
#ifndef GMP_EXT_H
#define GMP_EXT_H
#include<gmp.h>
/**
* Function mpz_setlimbn.
* Sets a_n of a = (a_k ... a_0) to l.
* If n is greater than k,
* a is increased to size n+1 and
* the previously unused digits
* (a_n-1 to a_k+1) are zeroed out.
* Leading zeroes are avoided.
*
* @param a the multi-precision integer.
* @param l the single-precision integer (digit).
* @param n the index.
*/
void mpz_setlimbn (mpz_t a, mp_limb_t l, mp_size_t n)
{
mp_size_t i;
if ((l == 0) && (mpz_size(a) == 0))
return;
/* Avoid leading zero.*/
if ((l == 0) && (n >= mpz_size(a)))
return;
/* Verify that enough memory is allocated.*/
if (n >= a->_mp_alloc)
{
/* Avoid to continuously allocate small pieces of memory.*/
_mpz_realloc(a,2 * n + 1);
}
/* Zero out previously unused digits */
if (n > mpz_size(a))
{
for(i = n; i > mpz_size(a); i--)
a->_mp_d[i] = 0;
/* Treat as special case to avoid that i (unsigned long) falls below zero if mpz_size(a) == 0 */
a->_mp_d[mpz_size(a)] = 0;
}
a->_mp_d[n] = l;
/* Adjust size of a.*/
/* Eliminate leading zeroes. */
if ((l == 0) && (mpz_size(a) > 0) && (n == mpz_size(a) - 1))
{
/* Check n to assure that the value of i falls not below zero. */
if (n == 0)
{
a->_mp_size = 0;
return;
}
i = n;
while ((i-- > 0) && (a->_mp_d[i] == 0));
if ((i == 0) && (a->_mp_d[i] == 0))
a->_mp_size = 0;
else
a->_mp_size = (mpz_sgn(a) != -1) ? i+1 : -(i+1);
return;
}
else
if (mpz_size(a) < n+1)
{
a->_mp_size = (mpz_sgn(a) != -1) ? n+1 : -(n+1);
}
}
/**
* Function mp_add_limb.
* Adds two digits and returns a two-digit result.
*
* @param s pointer to the digit where the least significant
* digit of the result should be stored.
* @param a 1st operand.
* @param b 2nd operand.
* @return the carry (i.e., 2nd digit of the result).
*/
extern inline mp_limb_t mp_add_limb(mp_limb_t* s, mp_limb_t a, mp_limb_t b) { return mpn_add_n(s, &a, &b, 1); }
/**
* Function mp_sub_limb.
* subtracts two digits and returns a two-digit result.
*
* @param s pointer to the digit where the least significant
* digit of the result should be stored.
* @param a 1st operand.
* @param b 2nd operand.
* @return the carry (i.e., 2nd digit of the result).
*/
extern inline mp_limb_t mp_sub_limb(mp_limb_t* s, mp_limb_t a, mp_limb_t b) { return mpn_sub_n(s, &a, &b, 1); }
/**
* Function mp_mul_limb.
* Multiplies two digits and returns a two-digit result.
*
* @param p pointer to the digit where the least significant
* digit of the result should be stored.
* @param a 1st operand.
* @param b 2nd operand.
* @return the carry (i.e., 2nd digit of the result).
*/
extern inline mp_limb_t mp_mul_limb(mp_limb_t* p, mp_limb_t a, mp_limb_t b) { return mpn_mul_1(p, &a, 1, b); }
#endif /* GMP_EXT_H */
```
main.c
```#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/resource.h>
#include <gmp.h>
#include <string.h>
#include <math.h>
#include "multiplication.h"
#include "numArray.h"
#include "writeResults.h"
int main(int argc, char *argv[])
{
struct timespec time1, time2;
long long length = (long long) atoi(argv[1]);
double elapsed = 0, elapsed_sec = 0 , elapsed_nano = 0;
//initialising variables
mpz_t number1, number2,result,answer;
mpz_init(result);
mpz_init(answer);
printf("%lld\n", length);
char * num1 = file_to_array(length, "number1.txt");
char * num2 = file_to_array(length, "number2.txt");
// printf("%s\n", num1);
// printf("%s\n", num2);
mpz_init_set_str(number1, num1, 10);
mpz_init_set_str(number2, num2, 10);
mpz_init_set_str(number1, num1, 10);
mpz_init_set_str(number2, num2, 10);
// mpz_out_str(stdout,10,number1);
// printf("%s\n", "");
// mpz_out_str(stdout,10,number2);
// printf("%s\n", "");
// mpz_init(TrueResult);
mpz_mul(answer, number1, number2);
// mpz_out_str(stdout,10,answer);
// printf("%s\n", " Answer");
//get time = time1
clock_gettime(CLOCK_REALTIME, &time1);
//calling multiply to get the result of adding the two numbers
mpz_school_mul(result, number1, number2);
//get time = time2
clock_gettime(CLOCK_REALTIME, &time2);
//elapsed = (time2 - time1) * 1000
elapsed_sec = (double)((time2.tv_sec)-(time1.tv_sec))*1000; //milliseconds
//elapsed_nano = (time2 - time1) / 1000000
elapsed_nano = (double)((time2.tv_nsec)-(time1.tv_nsec))/1000000;//milliseconds
//
if (elapsed_nano < 0) elapsed = elapsed + 1000.0;
// elapsed = elapsed = elapsed_nano
elapsed = elapsed_sec + elapsed_nano;
// prints time elapsed
if (mpz_cmp(result,answer)==0){
// writeResults(length, elapsed, "school.csv");
printf("%s:%f\n", "school", elapsed );
// printf("%s:%f\n", "second", elapsed_sec );
// printf("%s:%f\n", "nano", elapsed_nano );
} else {
printf("%s\n", "not equal");
writeResults(length, 0, "school.csv");
}
// mpz_out_str(stdout,10,result);
// printf("%s\n", "");
// mpz_out_str(stdout,10,answer);
// printf("%s\n", "");
//get time = time1
clock_gettime(CLOCK_REALTIME, &time1);
//calling multiply to get the result of adding the two numbers
mpz_karatsuba_mul(result, number1, number2);
//get time = time2
clock_gettime(CLOCK_REALTIME, &time2);
//elapsed = (time2 - time1) * 1000
elapsed_sec = (double)((time2.tv_sec)-(time1.tv_sec))*1000; //milliseconds
//elapsed_nano = (time2 - time1) / 1000000
elapsed_nano = (double)((time2.tv_nsec)-(time1.tv_nsec))/1000000;//milliseconds
if(elapsed_nano < 0) elapsed = elapsed + 1000.0;
// elapsed = elapsed = elapsed_nano
elapsed = elapsed_sec + elapsed_nano;
// prints time elapsed
if (mpz_cmp(result,answer)==0){
// writeResults(length, elapsed, "karatsuba.csv");
printf("%s:%f\n", "karatsuba", elapsed );
// printf("%s:%f\n", "second", elapsed_sec );
// printf("%s:%f\n", "nano", elapsed_nano );
} else {
printf("%s\n", "not equal");
writeResults(length, 0, "karatsuba.csv");
}
//get time = time1
clock_gettime(CLOCK_REALTIME, &time1);
//calling multiply to get the result of adding the two numbers
mpz_kara_mul_par(result, number1, number2);
//get time = time2
clock_gettime(CLOCK_REALTIME, &time2);
//elapsed = (time2 - time1) * 1000
elapsed_sec = (double)((time2.tv_sec)-(time1.tv_sec))*1000; //milliseconds
//elapsed_nano = (time2 - time1) / 1000000
elapsed_nano = (double)((time2.tv_nsec)-(time1.tv_nsec))/1000000;//milliseconds
if (elapsed_nano < 0) {
elapsed = elapsed + 1000;
}
// elapsed = elapsed = elapsed_nano
elapsed = elapsed_sec + elapsed_nano;
// prints time elapsed
if (mpz_cmp(result,answer)==0){
// writeResults(length, elapsed, "karat_parallel.csv");
printf("%s:%f\n", "parallel karatsuba", elapsed );
} else {
printf("%s\n", "not equal");
writeResults(length, 0, "karat_parallel.csv");
}
//get time = time1
clock_gettime(CLOCK_REALTIME, &time1);
//calling multiply to get the result of adding the two numbers
mpz_toom3_mul(result, number1, number2);
//get time = time2
clock_gettime(CLOCK_REALTIME, &time2);
//elapsed = (time2 - time1) * 1000
elapsed_sec = (double)((time2.tv_sec)-(time1.tv_sec))*1000; //milliseconds
//elapsed_nano = (time2 - time1) / 1000000
elapsed_nano = (double)((time2.tv_nsec)-(time1.tv_nsec))/1000000;//milliseconds
if (elapsed_nano < 0) {
elapsed = elapsed + 1000;
}
// elapsed = elapsed = elapsed_nano
elapsed = elapsed_sec + elapsed_nano;
// prints time elapsed
if (mpz_cmp(result,answer)==0){
// writeResults(length, elapsed, "toom.csv");
printf("%s:%f\n", "toom", elapsed );
} else {
printf("%s\n", "not equal");
// mpz_out_str(stdout,10,answer);
// printf("%s\n", "");
// mpz_out_str(stdout,10,result);
// printf("%s\n", "");
//mpz_sub(result, answer, result);
// mpz_out_str(stdout,10,result);
// printf("%s\n", "");
writeResults(length, 0, "toom.csv");
}
//get time = time1
clock_gettime(CLOCK_REALTIME, &time1);
//calling multiply to get the result of adding the two numbers
mpz_toom3_mul_par(result, number1, number2);
//get time = time2
clock_gettime(CLOCK_REALTIME, &time2);
//elapsed = (time2 - time1) * 1000
elapsed_sec = (double)((time2.tv_sec)-(time1.tv_sec))*1000; //milliseconds
//elapsed_nano = (time2 - time1) / 1000000
elapsed_nano = (double)((time2.tv_nsec)-(time1.tv_nsec))/1000000;//milliseconds
if (elapsed_nano < 0) {
elapsed = elapsed + 1000;
}
// elapsed = elapsed = elapsed_nano
elapsed = elapsed_sec + elapsed_nano;
// prints time elapsed
if (mpz_cmp(result,answer)==0){
// writeResults(length, elapsed, "toom_parallel.csv");
printf("%s:%f\n", "toom parallel", elapsed );
} else {
printf("%s\n", "not equal");
mpz_out_str(stdout,10,answer);
printf("%s\n", "");
mpz_out_str(stdout,10,result);
printf("%s\n", "");
mpz_sub(result, answer, result);
mpz_out_str(stdout,10,result);
printf("%s\n", "");
// writeResults(length, 0, "toom_parallel.csv");
}
return 0;
}
```
toom3.c
```#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <gmp.h>
#include "multiplication.h"
// long long *toom(long long m, long long n)
// {
// long long m2, m1, m0, n2, n1, n0, length, b;
//
// length = (log10(m) > log10(n)) ? log10(m)+1 : log10(n)+1;
//
// switch (length%3) {
// case 0:
// b = (length/3);
// break;
// case 1:
// b = ((length+2)/3);
// break;
// case 2:
// b = ((length+1)/3);
// break;
// }
//
// m0 = m % (long long)pow(10, b);
// m1 = (m % (long long)pow(10, b*2)-m0)/(long long)pow(10, b);
// m2 = (m-(m1*(long long)pow(10, b))-m0)/(long long)pow(10, b*2);
//
// n0 = n % (long long)pow(10, b);
// n1 = ((n % (long long)pow(10, b*2))-n0)/(long long)pow(10, b);
// n2 = (n-(n1*(long long)pow(10, b))-n0)/(long long)pow(10, b*2);
//
// long long p, p0, p1, pn1, pn2, pinf;
//
// p = m0+m2;
// p0 = m0;
// p1 = p+m1;
// pn1 = p-m1;
// pn2 = ((pn1+m2)*2)-m0;
// pinf = m2;
//
// long long q, q0, q1, qn1, qn2, qinf;
//
// q = n0+n2;
// q0 = n0;
// q1 = q+n1;
// qn1 = q-n1;
// qn2 = ((qn1+n2)*2)-n0;
// qinf = n2;
//
// long long r0, r1, rn1, rn2, rinf;
//
// r0 = p0*q0;
// r1 = p1*q1;
// rn1 = pn1*qn1;
// rn2 = pn2*qn2;
// rinf = pinf*qinf;
//
// long long res0, res1, res2, res3, res4, result;
//
// res0 = r0;
// res4 = rinf;
// res3 = (rn2-r1)/3;
// res1 = (r1-rn1)/2;
// res2 = (rn1-r0);
// res3 = ((res2-res3)/2)+(2*rinf);
// res2 = res2+res1-res4;
// res1 = res1-res3;
//
// result = (res0+(res1*(long long)pow(10, b))+(res2*(long long)pow(10, b*2))+(res3*(long long)pow(10, b*3))+(res4*(long long)pow(10, b*4)));
// return (long long *)result;
// }
int main(){
// unsigned long long *c;
// c = (unsigned long long *) malloc(sizeof(unsigned long long)*30);
// unsigned long long m = 12345678912345;
// unsigned long long n = 9876543211245;
// printf("%lld\n", m*n);
// c = toom(m, n);
// printf("%lld\n", (long long)c);
mpz_t result, result_karat, result_toom, a, b, x, y, m, n;
mpz_inits(result, result_karat, result_toom, x, y, m, n, NULL);
mpz_init_set_str(a, "123456789012345678901234567890123456789012345", 10);
mpz_init_set_str(b, "987654321098765432109876543210987654321098765", 10);
mpz_toom3_mul(result_toom, a,b);
printf("%s", "Toom: ");
mpz_out_str(stdout, 16, result_toom);
printf("\n%s", "Karatsuba: ");
mpz_karatsuba_mul(result_karat, a, b);
mpz_out_str(stdout, 16, result_karat);
printf("%s\n ", "");
mpz_sub(result, result_karat, result_toom);
mpz_out_str(stdout, 16, result);
printf("%s\n", "");
mpz_init_set_str(x, "1000000", 10);
mpz_init_set_str(y, "100000", 10);
mpz_school_add(result, y, x);
mpz_out_str(stdout, 10, result);
printf("%s\n", "");
mpz_init_set_str(n, "-100", 10);
mpz_init_set_str(m, "12345", 10);
mpz_school_add(result, n, m);
mpz_out_str(stdout, 10, result);
printf("%s\n", "");
mpz_set_str(n, "-10000000000000000000000000000000000000000", 10);
mpz_set_str(m, "-12345678900000000000000000000000000000000", 10);
mpz_school_add(result, n, m);
mpz_out_str(stdout, 10, result);
printf("%s\n", "");
return 0;
}
```
multiplication.h
```#ifndef MPA_ALGS_H
#define MPA_ALGS_H
#include <gmp.h>
/**
* Function mpz_school_add.
* Computes the sum c of two multi-precision
* integers a and b.
*
* @param c the multi-precision sum a + b.
* @param a the first multi-precision operand.
* @param b the second multi-precision operand.
*/
void mpz_school_add(mpz_t c, mpz_t a, mpz_t b);
void mpz_school_add_neg(mpz_t c, mpz_t a, mpz_t b);
/**
* Function mpz_school_sub.
* Computes the sum c of two multi-precision
* integers a and b.
*
* @param c the multi-precision sum a - b.
* @param a the first multi-precision operand.
* @param b the second multi-precision operand.
*/
void mpz_school_sub(mpz_t c, mpz_t a, mpz_t b);
/**
* Function mpz_mul_limb.
* Computes the product c of a multi-precision integer a
* and a single-precision integer b.
*
* @param c the multi-precision product a * b.
* @param a the multi-precision operand.
* @param b the single-precision operand.
*/
void mpz_mul_limb(mpz_t c, mpz_t a, mp_limb_t b);
/**
* Function mpz_mul_base.
* Computes the product c of a multi-precision integer a
* and the i-th power of the base B.
*
* @param c the multi-precision product a * B^i.
* @param a the multi-precision operand.
* @param i the base exponent.
*/
void mpz_mul_base(mpz_t c, mpz_t a, mp_size_t i);
/**
* Function mpz_school_mul.
* Computes the product c of two multi-precision
* integers a and b using the schoolbook method.
*
* @param c the multi-precision product a * b.
* @param a the first multi-precision operand.
* @param b the second multi-precision operand.
*/
void mpz_school_mul(mpz_t c, mpz_t a, mpz_t b);
/**
* Function mpz_rec_mul.
* Computes the product c of two multi-precision
* integers a and b using a recursive multiplication method.
*
* @param c the multi-precision product a * b.
* @param a the first multi-precision operand.
* @param b the second multi-precision operand.
*/
void mpz_rec_mul(mpz_t c, mpz_t a, mpz_t b);
/**
* Function mpz_karatsuba_mul.
* Computes the product c of two multi-precision
* integers a and b using Karatsuba's multiplication method.
*
* @param c the multi-precision product a * b.
* @param a the first multi-precision operand.
* @param b the second multi-precision operand.
*/
void mpz_karatsuba_mul(mpz_t c, mpz_t a, mpz_t b);
void karat_multiplying(mpz_t result, mpz_t number1, mpz_t number2);
void mpz_karatsuba_mul_par(mpz_t c, mpz_t a, mpz_t b);
void mpz_kara_mul_par(mpz_t c, mpz_t a, mpz_t b);
void multiply_kara(mpz_t c, mpz_t a, mpz_t b);
void mpz_toom3_mul(mpz_t c, mpz_t a, mpz_t b);
void mpz_toom3_mul_par(mpz_t c, mpz_t a, mpz_t b);
void mpz_toom_mul_par(mpz_t c, mpz_t a, mpz_t b);
void prnt();
#endif /* MPA_ALGS_H */
```
numArray.c
```#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#include <string.h>
#include "numArray.h"
/**
* Function file_to_array.
* Opens external file and converts the output into an array
*
* @param length size of the array that is being created.
* @param file the file that is being opened and the content extracted.
*/
char *file_to_array(long long length, char *file)
{
char number[length];
char *str;
str = (char *) malloc(sizeof(number));
//opens file
FILE *fp = fopen(file, "rb");
// prints if the file fails to opens
if (fp == NULL) printf("Failed to open the file.\n");
//gets string from file and adds it to number
fgets(number, length, fp);
//closes file
fclose(fp);
//copies string from number to str
strcpy(str, number);
return str;
// frees memory for str
free(str);
}
```
timer.c
```#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/resource.h>
#include <gmp.h>
#include <string.h>
#include <math.h>
#include "multiplication.h"
#include "numArray.h"
#include "writeResults.h"
float timer(double (*function)(), mpz_t number1, mpz_t number2){
struct timespec time1, time2;
double elapsed = 0, elapsed_sec = 0 , elapsed_nano = 0;
mpz_t answer;
mpz_mul(answer, number1, number2);
clock_gettime(CLOCK_REALTIME, &time1);
double result = function();
//get time = time2
clock_gettime(CLOCK_REALTIME, &time2);
//elapsed = (time2 - time1) * 1000
elapsed = (double)((time2.tv_sec)-(time1.tv_sec))*1000; //milliseconds
//elapsed_nano = (time2 - time1) / 1000000
elapsed_nano = (double)((time2.tv_nsec)-(time1.tv_nsec))/1000000;//milliseconds
//
if (elapsed_nano < 0) elapsed += 1000.0;
// elapsed = elapsed = elapsed_nano
elapsed = elapsed + elapsed_nano;
// prints time elapsed
if (mpz_cmp(result, answer)==0){
return elapsed;
} else {
return 0.0;
}
}
int main(int argc, char *argv[])
{
struct timespec time1, time2;
long long length = 2;
double elapsed, elapsed_nano;
//initialising variables
mpz_t number1, number2,result,answer;
mpz_init(result);
mpz_init(answer);
while (length<21){
char * num1 = file_to_array(length, "number1.txt");
char * num2 = file_to_array(length, "number2.txt");
// printf("%s\n", num1);
// printf("%s\n", num2);
mpz_init_set_str(number1, num1, 10);
mpz_init_set_str(number2, num2, 10);
// mpz_init_set_str(number1, num1, 10);
// mpz_init_set_str(number2, num2, 10);
// mpz_out_str(stdout,10,number1);
// printf("%s\n", "");
// mpz_out_str(stdout,10,number2);
// printf("%s\n", "");
// mpz_init(TrueResult);
mpz_mul(answer, number1, number2);
// mpz_out_str(stdout,10,answer);
// printf("%s\n", " Answer");
//get time = time1
clock_gettime(CLOCK_REALTIME, &time1);
//calling multiply to get the result of adding the two numbers
mpz_school_mul(result, number1, number2);
//get time = time2
clock_gettime(CLOCK_REALTIME, &time2);
//elapsed = (time2 - time1) * 1000
elapsed = (double)((time2.tv_sec)-(time1.tv_sec))*1000; //milliseconds
//elapsed_nano = (time2 - time1) / 1000000
elapsed_nano = (double)((time2.tv_nsec)-(time1.tv_nsec))/1000000;//milliseconds
//
if (elapsed_nano < 0) elapsed += 1000.0;
// elapsed = elapsed = elapsed_nano
elapsed = elapsed + elapsed_nano;
// prints time elapsed
if (mpz_cmp(result,answer)==0){
writeResults(elapsed, "school.csv");
printf("%s:%f\n", "school", elapsed );
} else {
printf("%s\n", "not equal");
writeResults(0, "school.csv");
}
// mpz_out_str(stdout,10,result);
// printf("%s\n", "");
// mpz_out_str(stdout,10,answer);
// printf("%s\n", "");
//get time = time1
clock_gettime(CLOCK_REALTIME, &time1);
//calling multiply to get the result of adding the two numbers
mpz_karatsuba_mul(result, number1, number2);
//get time = time2
clock_gettime(CLOCK_REALTIME, &time2);
//elapsed = (time2 - time1) * 1000
elapsed = (double)((time2.tv_sec)-(time1.tv_sec))*1000; //milliseconds
//elapsed_nano = (time2 - time1) / 1000000
elapsed_nano = (double)((time2.tv_nsec)-(time1.tv_nsec))/1000000;//milliseconds
if (elapsed_nano < 0) elapsed += 1000.0;
// elapsed = elapsed = elapsed_nano
elapsed = elapsed + elapsed_nano;
// prints time elapsed
if (mpz_cmp(result,answer)==0){
writeResults(elapsed, "karatsuba.csv");
printf("%s:%f\n", "karatsuba", elapsed );
} else {
printf("%s\n", "not equal");
writeResults(0, "karatsuba.csv");
}
//get time = time1
clock_gettime(CLOCK_REALTIME, &time1);
//calling multiply to get the result of adding the two numbers
mpz_kara_mul_par(result, number1, number2);
//get time = time2
clock_gettime(CLOCK_REALTIME, &time2);
//elapsed = (time2 - time1) * 1000
elapsed = (double)((time2.tv_sec)-(time1.tv_sec))*1000; //milliseconds
//elapsed_nano = (time2 - time1) / 1000000
elapsed_nano = (double)((time2.tv_nsec)-(time1.tv_nsec))/1000000;//milliseconds
if (elapsed_nano < 0) elapsed += 1000.0;
// elapsed = elapsed = elapsed_nano
elapsed = elapsed + elapsed_nano;
// prints time elapsed
if (mpz_cmp(result,answer)==0){
writeResults(elapsed, "parallel.csv");
printf("%s:%f\n", "parallel karatsuba", elapsed );
} else {
printf("%s\n", "not equal");
writeResults(0, "parallel.csv");
}
//
// mpz_out_str(stdout,10,result);
// printf("%s\n", "");
printf("%d\n", (int)log10((double)length));
length = length*10;
}
return 0;
}
```
|
7Anirudh-Iyer/SnakeGame
|
7Anirudh-Iyer/SnakeGame
sketch.js
```const canvas = document.getElementById('c1');
const c = canvas.getContext('2d');
const unitName = 32;
const g = new Image()
const f = new Image()
let a
let dir
let score
//in order to load image, use new Image() to call constructor, then say object name.src = path
g.src = 'ground.png'
f.src = 'food.png'
// function hour(){
// a = new Date().getHours()
// console.log(a)
// }
let snake = []
snake[0] = {
x: 320-32,
y: 320,
}
let food = {
x: Math.floor(Math.random() * 17) * 32,
y: Math.floor(Math.random() * 15) * 32
}
function draw(){
c.drawImage(g,0,0)
for(var i=0;i<snake.length;i+=1){
a = new rect(snake[i].x,snake[i].y,'red')
}
let spx = snake[0].x
let spy = snake[0].y
c.drawImage(f,food.x,food.y)
if(dir == 'left'){
spx-=32
}
if(dir == 'right'){
spx+=32
}
if(dir == 'top'){
spy-=32
}
if(dir == 'bottom'){
spy+=32
}
let nh = {
x: spx,
y: spy,
}
snake.unshift(nh)
if(food.x==spx&&food.y==spy){
food = {
x: Math.floor(Math.random() * 17) * 32,
y: Math.floor(Math.random() * 15) * 32
}
score+=1
}
else{
snake.pop()
}
document.writeln(score)
}
let callFunction = setInterval(draw,100)
function rect(x,y,color){
this.x=x;
this.y=y;
this.width=32;
this.height=32;
this.color=color;
c.fillStyle = this.color
c.fillRect(this.x,this.y,this.width,this.height)
}
document.addEventListener("keydown", function(data){
dir
if (data.keyCode === 37){
dir = 'left'
}
// snake[0].x+=32
if (data.keyCode === 38){
dir = 'top'
}
// snake[0].y-=32
if (data.keyCode === 39){
dir = 'right'
}
// snake[0].x+=32
if (data.keyCode === 40){
dir = 'bottom'
}
// snake[0].y-=32
});
```
|
7ZXU/skku-quiz
|
7ZXU/skku-quiz
App.js
```import React from "react";
import styled from 'styled-components';
import { Route, Switch } from "react-router-dom";
import StartPage from "./pages/StartPage"
import Question1 from "./pages/Question1"
function App() {
return (
<div>
<Switch>
<Route exact path="/" component={StartPage}/>
<Route exact path="/q1" component={Question1}/>
</Switch>
</div>
);
}
export default App;
```
StartPage.js
```import React, {useState} from "react";
import styled from "styled-components";
import background from "../assets/background.png";
import {Link} from "react-router-dom";
const Background = styled.div`
position: absolute;
background: url(${(props) => props.bg});
top: 0;
left: 0;
height: 100%;
width: 100%;
background-size: cover;
display: flex;
flex-direction: column;
justify-content: center;
`;
const Title = styled.div`
position: absolute;
top: 45%;
left: 52%;
transform: translate(-50%, -50%);
color: #5ca8eb;
font-weight: bold;
font-size: 50px;
`;
const PlayBtn = styled.button`
position: absolute;
top: 60%;
left: 52%;
transform: translate(-50%, -50%);
text-align: center;
width: 12%;
height: 6%;
background-color: white;
color: #5ca8eb;
box-shadow: ${props => props.color};
border: none;
`;
function StartPage() {
const [index, setIndex] = useState(0);
return (
<Background bg={background}>
<Title>Javascript Quiz</Title>
<Link to="q1">
<PlayBtn color={index===0? "none" : "0px 0px 5px 2px #5ca8eb" }
onMouseOver={
()=>{
setIndex(1)
}
}
onMouseOut={
()=>{
setIndex(0)
}
}
>Play</PlayBtn>
</Link>
</Background>
);
}
export default StartPage;
```
Question1.js
```import React, { useState } from "react";
import styled from "styled-components";
import background from "../assets/background.png";
import { Link } from "react-router-dom";
const PageWrap = styled.div`
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: #e3effb;
`;
const Wrap = styled.div`
margin: 200px 600px;
display: flex;
flex-direction: column;
`;
const QuestionWrap = styled.div`
display: flex;
justify-content: space-between;
`;
const QuestionBar = styled.div`
display: flex;
flex-direction: column;
align-items: center;
`;
const ProgressBar = styled.div`
width: 200px;
height: 20px;
border: 3px solid #5ca8eb;
`;
const Progress = styled.div`
width: ${(props) => props.width}px;
height: 20px;
background-color: #5ca8eb;
border: 1px solid #5ca8eb;
`;
const ScoreWrap = styled.div`
display: flex;
flex-direction: column;
align-items: center;
`;
const Score = styled.text`
color: #5ca8eb;
font-size: 30px;
font-weight: bold;
`;
const Question = styled.h1``;
const Example = styled.div`
display: flex;
height: 60px;
box-shadow: ${(props) => props.color};
margin-bottom: 10px;
align-items: center;
background-color: ${(props) => props.bg};
`;
const Num = styled.div`
display: flex;
align-items: center;
justify-content: center;
width: 10%;
height: 100%;
background-color: #5ca8eb;
color: white;
font-size: 20px;
`;
const Text = styled.text`
padding-left: 20px;
`;
const ResultWrap = styled.div`
margin: 200px 600px;
display: flex;
flex-direction: column;
align-items: center;
`;
const Total = styled.text`
font-size: 60px;
font-weight: bold;
color: #5ca8eb;
`;
const AgainBtn = styled.button`
text-align: center;
width: 200px;
height: 50px;
font-size: 20px;
font-weight: bold;
background-color: white;
color: #5ca8eb;
box-shadow: ${(props) => props.color};
border-color: #5ca8eb;
margin-top: 20px;
`;
function Question1() {
const [pageNum, setPageNum] = useState(1);
const [score, setScore] = useState(0);
const [index, setIndex] = useState(0);
const [example, setExample] = useState(0);
const [link, setLink] = useState("/q1");
const questions = [
{
q: "Purpose of designing the Javascript",
a: "To Perform Server Side Scripting Operation",
b: "To add Interactivity to HTML Pages",
c: "To Style HTML Pages",
d: "All of the above",
answer: "b",
},
{
q: "Why so JavaScript and Java have similar name?",
a: "They both originated on the island of Java ",
b: "JavaScript's syntax is loosely based on Java's",
c: "Both A and B",
d: "None of the above",
answer: "b",
},
{
q: "Original Name of Javascript is",
a: "Mocha",
b: "LiveScript",
c: "Escript",
d: "Javascript",
answer: "a",
},
{
q: "Which type of language is Javascript",
a: "Programming",
b: "Scripting",
c: "Markup",
d: "None of the above",
answer: "d",
},
{},
{
q: "Which is not valid data type in Javascript",
a: "Undefined",
b: "Boolean",
c: "float",
d: "Number",
answer: "c",
},
{
q: "Which type of language is Javascript",
a: "Programming",
b: "Scripting",
c: "Markup",
d: "None of the above",
answer: "b",
},
{
q: "Purpose of designing the Javascript",
a: "To Perform Server Side Scripting Operation",
b: "To add Interactivity to HTML Pages",
c: "To Style HTML Pages",
d: "All of the above",
answer: "b",
},
{
q: "Why so JavaScript and Java have similar name?",
a: "They both originated on the island of Java ",
b: "JavaScript's syntax is loosely based on Java's",
c: "Both A and B",
d: "None of the above",
answer: "b",
},
{}
];
if (pageNum % 5 !== 0) {
return (
<PageWrap>
{/* onClick={() => {
setExample(1);
{questions[pageNum - 1].answer === "a"?setScore(score+1):setScore(score)};
setIndex(0);
setTimeout(()=>{
setPageNum(pageNum+1);
setExample(0);
}, 1000);
}
} */}
<Wrap>
<QuestionWrap>
<QuestionBar>
<div>Question {Number(pageNum)%5}/4</div>
<ProgressBar>
<Progress width={Number(pageNum)%5 * 50} />
</ProgressBar>
</QuestionBar>
<ScoreWrap>
<div>Score</div>
<Score>{score}</Score>
</ScoreWrap>
</QuestionWrap>
<Question>{questions[pageNum - 1].q}</Question>
{/* A */}
<Example
color={index === 1 ? "0px 0px 5px 2px #5ca8eb" : "none"}
bg={
example === 1
? questions[pageNum - 1].answer === "a"
? "green"
: "red"
: "white"
}
onClick={() => {
setExample(1);
{
questions[pageNum - 1].answer === "a"
? setScore(score + 1)
: setScore(score);
}
setIndex(0);
setTimeout(() => {
setPageNum(pageNum + 1);
setExample(0);
}, 1000);
}}
onMouseOver={() => {
setIndex(1);
}}
onMouseOut={() => {
setIndex(0);
}}
>
<Num>A</Num>
<Text>{questions[pageNum - 1].a}</Text>
</Example>
{/* B */}
<Example
color={index === 2 ? "0px 0px 5px 2px #5ca8eb" : "none"}
bg={
example === 2
? questions[pageNum - 1].answer === "b"
? "green"
: "red"
: "white"
}
onClick={() => {
setExample(2);
{
questions[pageNum - 1].answer === "b"
? setScore(score + 1)
: setScore(score);
}
setIndex(0);
setTimeout(() => {
setPageNum(pageNum + 1);
setExample(0);
}, 1000);
}}
onMouseOver={() => {
setIndex(2);
}}
onMouseOut={() => {
setIndex(0);
}}
>
<Num>B</Num>
<Text>{questions[pageNum - 1].b}</Text>
</Example>
{/* C */}
<Example
color={index === 3 ? "0px 0px 5px 2px #5ca8eb" : "none"}
bg={
example === 3
? questions[pageNum - 1].answer === "c"
? "green"
: "red"
: "white"
}
onClick={() => {
setExample(3);
{
questions[pageNum - 1].answer === "c"
? setScore(score + 1)
: setScore(score);
}
setIndex(0);
setTimeout(() => {
setPageNum(pageNum + 1);
setExample(0);
}, 1000);
}}
onMouseOver={() => {
setIndex(3);
}}
onMouseOut={() => {
setIndex(0);
}}
>
<Num>C</Num>
<Text>{questions[pageNum - 1].c}</Text>
</Example>
{/* D */}
<Example
color={index === 4 ? "0px 0px 5px 2px #5ca8eb" : "none"}
bg={
example === 4
? questions[pageNum - 1].answer === "d"
? "green"
: "red"
: "white"
}
onClick={() => {
setExample(4);
{
questions[pageNum - 1].answer === "d"
? setScore(score + 1)
: setScore(score);
}
setIndex(0);
setTimeout(() => {
setPageNum(pageNum + 1);
setExample(0);
}, 1000);
}}
onMouseOver={() => {
setIndex(4);
}}
onMouseOut={() => {
setIndex(0);
}}
>
<Num>D</Num>
<Text>{questions[pageNum - 1].d}</Text>
</Example>
</Wrap>
</PageWrap>
);
}
return (
<PageWrap>
<ResultWrap>
<Total>Total score: {score}</Total>
<AgainBtn
color={index === 0 ? "none" : "0px 0px 5px 2px #5ca8eb"}
onClick={
()=>{
setPageNum(pageNum+1);
setScore(0);
}
}
onMouseOver={() => {
setIndex(1);
}}
onMouseOut={() => {
setIndex(0);
}}
>
Play Again
</AgainBtn>
</ResultWrap>ß
</PageWrap>
);
}
export default Question1;
```
|
7cb15/ACT-Scores-and-Crime
|
7cb15/ACT-Scores-and-Crime
README.md
```# ACT-Scores-and-Crime
Measuring adverse impact of crime, socioeconomic / public health indicators, and school quality metrics on ACT test performance in Chicago high schools. Methods used include: Kmeans clustering, Kmodes clustering, and random forest regression.
```
|
7ucky/auto
|
7ucky/auto
Nullable.java
```/*
* Copyright (C) 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.auto.value.annotation;
/**
* NOTE: Testing with org.eclipse.jdt.annotation.Nullable (v2) doesn't work because it has
* RetentionPolicy.CLASS, but RUNTIME is needed for
* com.google.auto.value.AutoValueTest.testNullablePropertyConstructorParameterIsNullable()
*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @interface Nullable {
}
```
|
8-bitTom/JavaScript_Tools
|
8-bitTom/JavaScript_Tools
usefull tools.js
```/*Author: Tom Marra
**Email: Tmarradesign@gmail.com
**~JavaScript Tools Library~
**Taken from awesome singleton Scripts I've written or had shared
**with me that can be helpful in any situation
*/
//=##=================================================================================================##=//
//=##= UTILITY METHODS ===============================================================================##=//
//=##=================================================================================================##=//
util = {
//=##= Array METHODS =============================================================================##=//
array :
{
//=##= randomizes and array ==================//
//=##= parameter: array ==================//
randomize : function randomize(array)
{
array.sort(function(){
return (Math.round(Math.random())-0.5);
});
return array;
},
//=##= removes an item from an array by index =============//
//=##= parameter: array, int ==========================//
removeItem : function removeItem(array, item)
{
var idx = array.indexOf(item);
if(idx != -1)
{
array.splice(idx, 1);
};
},
//=##= converts an Associative Array To a normal Array ==================//
//=##= parameter: array(with key:val pairs) ==================//
convertAssociativeArrayToArray : function convertAssociativeArrayToArray(associativeArray)
{
var array = [];
for(var key in associativeArray)
{
var item = associativeArray[key];
if(typeof item == "string")
{
item = {
value : item
};
}
item.associativeKey = key;
array.push(item);
}
return array;
},
//=##= sorts an associative arry of numerical values =============//
//=##= parameter: array, key =================//
sortArrayNumberical : function sortArrayNumberical(array, propertyToSortBy)
{
return array.sort(function(a, b)
{
if(a[propertyToSortBy] > b[propertyToSortBy])
{
return 1;
}
else
{
return -1;
}
});
},
//=##= returns an array of keys from an associative array =============//
//=##= parameter: array ===========================================//
getKeys : function getKeys(obj) {
var keys = [], i;
for (i in obj){
if (obj.hasOwnProperty(i)) {
keys.push(i);
}
}
return keys;
}
},
//=##= Text METHODS =============================================================================##=//
text :
{
//=##= caps the first letter of every word =============//
//=##= parameter: string ===========================//
toProperCase : function toProperCase(str)
{
return str.toLowerCase().replace(/^(.)|\s(.)/g, function($1) {
return $1.toUpperCase();
});
},
//=##= shortens text to limit int and adds ellipsis =============//
//=##= parameter: string, int =================//
truncate : function truncate(str, n) {
var limit, check, output;
if (str.length >= n){
limit = str.lastIndexOf(" ", n);
if (limit === -1){
output = str.slice(0, n-3) + "...";
}
check = str.slice(0, limit) + "...";
output = ((check.length > n) ? this.truncate(check, n) : check);
} else {
output = str;
}
return output;
},
//=##= adds commas to very long numbers =============//
//=##= parameter: int ===========================//
commify : function commify(num) {
var splitter = num.toString().split("."),
bigNum = splitter[0],
decimals = (splitter.length > 1) ? splitter[1] : "",
commad = "",
lastChar;
while (bigNum.length > 3){
lastChar = bigNum.substr(bigNum.length-3);
bigNum = bigNum.slice(0, bigNum.length-3);
commad = "," + lastChar + commad;
}
return bigNum + commad + ((splitter.length > 1) ? "." + decimals : "");
},
//=##= checks a string to see if there are HTML Entities in it I.E. ====//
//=##= parameter: string ==================================================//
hasHTMLEncoded : function hasHTMLEncoded(s)
{
if(/&[A-Z]{2,6};/gi.test(s)){
return true;
}
},
//=##= removes HTML Entities from a string =============//
//=##= parameter: string ===========================//
deHTML : function deHTML(s)
{
var text = s,
//an associative array of common HTML Entities more can be added to this list if needed from http://www.w3schools.com/tags/ref_entities.asp
entities = {""" : '"', "'" : "'", "&" : "&", "<" : "<", ">" : ">"};
//strip all tags from the string and split the string into a pretty array
var allThatRemains = text.replace(/&[A-Z]{2,6};/gi, function (match){
return entities[match] != undefined ? entities[match] : match;
});
return allThatRemains;
}
},
//=##= HTML METHODS =============================================================================##=//
HTML:
{
//=##= finds current mouse xy cords ==============//
//=##= parameter: event ======================//
mouse : function mouse(e)
{
posx = 0;
posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
return {
x : posx,
y : posy
};
},
//=##= scrolls browser to passed dom element =============//
//=##= parameter: obj ================================//
scrollToDom : function scrollToDom(domNode)
{
console.log(domNode);
var topPos = 0;
//based off of the parent node find the offset
if (domNode.offsetParent) {
do {
topPos += domNode.offsetTop;
} while (domNode = domNode.offsetParent);
}
//console.debug("top Pos = " + topPos);
scrollTo(0, topPos);
}
},
//=##= Date METHODS =============================================================================##=//
date :
{
//=##= converts 24 hour time to 12 hour time =============//
//=##= parameter: int ================================//
twelveHrTime : function twelveHrTime(hr) {
var output = hr;
if (hr === 0) {
output = 12;
} else if (hr > 12) {
output = hr - 12;
}
return output;
},
//=##= converts number to month name =============//
//=##= parameter: int ========================//
getFullMonthName : function getFullMonthName(month)
{
var monthNames = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
return monthNames[month];
}
}
}```
|
80cmdude/EmbeddedPicker
|
80cmdude/EmbeddedPicker
MainPage.xaml.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace EmbeddedPicker
{
public partial class MainPage : ContentPage
{
public MainPage()
{
try
{
InitializeComponent();
}
catch (Exception e)
{
var check = e.Message;
}
this.BindingContext = new MainPageViewModel();
}
}
}
```
README.md
```# EmbeddedPicker
Embedded page picker control for Xamarin.forms for both Android and iOS

## Getting Started
This is a small sample project for xamarin.forms to show an example of an embedded picker inside a page of a xamarin forms application. Pull the project and run for either iOS or Android.
## Example
```
<local:CustomPicker ItemsSource="{Binding PickerItemSource}" SelectedIndex="{Binding PickerIndex}" SelectorLineColor="Black" />
```
## Properties
**ItemSource**
IEnumerable type that holds the list of data to be displayed in the picker
**SelectedIndex**
Int type that holds the currently selected index of the picker
**FontSize**
Double property that sets the font size of each of the individual items in the list
**FontFamily**
String property that sets the font family of the individual items in the list
**SelectorLineColor** (Android Only)
Color property that changes the color of the line on the selector. This is currently only for android as its the only platform I figured out how to do :(
**WrapSelectorWheel** (Android Only)
Bool property that sets if a picker will scroll indefinetely. Default native option on android
**CellHeight** (iOS only)
Float property that sets the height of each individual item in the list. This property will change depending on how big or small you choose to make your picker. This will require some trial and error to show the required amount of options :). Not needed on android as it auto sizes to fit the view.
## Contribution
My code is far from perfect so please feel free to raise pull requests or submit tickets so that I can improve if needed :)
## Acknowledgements
I originally came across this project by amay077 [link](https://github.com/amay077/Xamarin_Forms_PickerViewSample) after searching for hours. From here I have created a simpler but more customisable picker. However if you want a multiple rowed picker then the one on that link is fantastic.
Thanks to https://github.com/djordje200179 for the UWP implementation :)
I hope this helps :)
```
CustomPickerRenderer.cs
```using System;
using System.Collections.Generic;
using System.ComponentModel;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Util;
using Android.Widget;
using Xamarin.Forms.Platform.Android;
using EmbeddedPicker;
using EmbeddedPicker.Droid;
using Java.Lang.Reflect;
using Xamarin.Forms;
[assembly: ExportRenderer(typeof(CustomPicker), typeof(CustomPickerRenderer))]
namespace EmbeddedPicker.Droid
{
public class CustomPickerRenderer : ViewRenderer<CustomPicker, NumberPicker>
{
public CustomPickerRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<CustomPicker> e)
{
base.OnElementChanged(e);
if (Control == null)
{
SetNativeControl(new NumberPicker(Context));
}
else
{
Control.ValueChanged -= Control_ValueChanged;
}
if (e.NewElement == null) return;
Control.ValueChanged += Control_ValueChanged;
// This property controls if the picker wraps around in a circle inifintiely
Control.WrapSelectorWheel = e.NewElement.WrapSelectorWheel;
UpdateItemsSource();
UpdateSelectedIndex();
UpdateFont();
SetDividerColor(Control, Element.SelectorLineColor.ToAndroid());
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == CustomPicker.ItemsSourceProperty.PropertyName)
{
UpdateItemsSource();
}
else if (e.PropertyName == CustomPicker.SelectedIndexProperty.PropertyName)
{
UpdateSelectedIndex();
}
else if (e.PropertyName == CustomPicker.FontFamilyProperty.PropertyName)
{
UpdateFont();
}
else if (e.PropertyName == CustomPicker.FontSizeProperty.PropertyName)
{
UpdateFont();
}
}
private void UpdateItemsSource()
{
var arr = new List<string>();
if (Element.ItemsSource != null)
{
foreach (var item in Element.ItemsSource)
{
arr.Add(item.ToString());
}
}
if (arr.Count <= 0) return;
var newMax = arr.Count - 1;
if (newMax < Control.Value)
{
Element.SelectedIndex = newMax;
}
var extend = Control.MaxValue <= newMax;
if (extend)
{
Control.SetDisplayedValues(arr.ToArray());
}
Control.MaxValue = newMax;
Control.MinValue = 0;
if (!extend)
{
Control.SetDisplayedValues(arr.ToArray());
}
}
private void UpdateSelectedIndex()
{
if (Element.SelectedIndex < Control.MinValue || Element.SelectedIndex > Control.MaxValue)
{
return;
}
Control.Value = Element.SelectedIndex;
}
/// <summary>
/// Updates the font family of each element in the picker
/// </summary>
private void UpdateFont()
{
var font = string.IsNullOrEmpty(Element.FontFamily) ?
Font.SystemFontOfSize(Element.FontSize) :
Font.OfSize(Element.FontFamily, Element.FontSize);
SetTextSize(Control, font.ToTypeface(), (float)(Element.FontSize * Context.Resources.DisplayMetrics.Density));
}
void Control_ValueChanged(object sender, NumberPicker.ValueChangeEventArgs e)
{
Element.SelectedIndex = e.NewVal;
}
/// <summary>
/// Sets the text decoration of the individual elements of the picker
/// </summary>
private static void SetTextSize(NumberPicker numberPicker, Typeface fontFamily, float textSizeInSp)
{
var count = numberPicker.ChildCount;
for (var i = 0; i < count; i++)
{
var child = numberPicker.GetChildAt(i);
if (child is EditText editText)
{
try
{
var selectorWheelPaintField = numberPicker.Class
.GetDeclaredField("mSelectorWheelPaint");
selectorWheelPaintField.Accessible = true;
((Paint)selectorWheelPaintField.Get(numberPicker)).TextSize = textSizeInSp;
editText.Typeface = fontFamily;
editText.SetTextSize(ComplexUnitType.Px, textSizeInSp);
// Need this property set to false or you can edit the elements in the picker
editText.Focusable = false;
numberPicker.Invalidate();
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("SetNumberPickerTextColor failed.", e);
}
}
}
}
/// <summary>
/// Sets the colour of the divider lines in the center of the picker
/// </summary>
private void SetDividerColor(NumberPicker picker, Android.Graphics.Color color)
{
try
{
var numberPickerType = Java.Lang.Class.FromType(typeof(NumberPicker));
var divider = numberPickerType.GetDeclaredField("mSelectionDivider");
divider.Accessible = true;
var dividerDraw = new ColorDrawable(color);
divider.Set(picker, dividerDraw);
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine("SetNumberPickerDividerColor failed.", e);
}
}
}
}```
CustomPickerRenderer.cs
```using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using EmbeddedPicker;
using EmbeddedPicker.iOS;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(CustomPicker), typeof(CustomPickerRenderer))]
namespace EmbeddedPicker.iOS
{
public class CustomPickerRenderer : ViewRenderer<CustomPicker, UIPickerView>
{
protected override void OnElementChanged(ElementChangedEventArgs<CustomPicker> e)
{
base.OnElementChanged(e);
if (Control == null)
{
SetNativeControl(new UIPickerView(RectangleF.Empty));
}
if (e.NewElement == null) return;
UpdateItemsSource();
UpdateSelectedIndex();
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == CustomPicker.ItemsSourceProperty.PropertyName)
{
UpdateItemsSource();
}
else if (e.PropertyName == CustomPicker.SelectedIndexProperty.PropertyName)
{
UpdateSelectedIndex();
}
else if (e.PropertyName == CustomPicker.FontSizeProperty.PropertyName)
{
UpdateItemsSource();
}
else if (e.PropertyName == CustomPicker.FontFamilyProperty.PropertyName)
{
UpdateItemsSource();
}
}
private void UpdateItemsSource()
{
var font = string.IsNullOrEmpty(Element.FontFamily) ?
Font.SystemFontOfSize(Element.FontSize) :
Font.OfSize(Element.FontFamily, Element.FontSize);
var nativeFont = font.ToUIFont();
Control.Model = new DataModel(this.Element.ItemsSource, row =>
{
Element.SelectedIndex = row;
}, nativeFont, Element.CellHeight);
}
private void UpdateSelectedIndex()
{
if (Control.Model == null)
{
return;
}
if (Element.SelectedIndex < 0 || Element.SelectedIndex >= Control.Model.GetRowsInComponent(Control, 0))
{
return;
}
Control.Select(Element.SelectedIndex, 0, true);
}
}
internal class DataModel : UIPickerViewModel
{
private readonly IList<string> _list = new List<string>();
private readonly Action<int> _selectedHandler;
private readonly UIFont _nativeFont;
private readonly nfloat _cellHeight;
public DataModel(IEnumerable items, Action<int> selectedHandler, UIFont nativeFont, nfloat cellHeight)
{
_selectedHandler = selectedHandler;
_nativeFont = nativeFont;
_cellHeight = cellHeight;
if (items != null)
{
foreach (var item in items)
{
_list.Add(item.ToString());
}
}
}
public override System.nint GetComponentCount(UIPickerView pickerView)
{
return 1;
}
public override System.nint GetRowsInComponent(UIPickerView pickerView, System.nint component)
{
return _list.Count;
}
// Update the height of each individual cell
public override nfloat GetRowHeight(UIPickerView pickerView, nint component)
{
return _cellHeight;
}
public override string GetTitle(UIPickerView pickerView, System.nint row, System.nint component)
{
return _list[(int)row];
}
public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view)
{
var label = new UILabel(pickerView.Bounds)
{
Font = _nativeFont,
Text = _list[(int) row],
TextAlignment = UITextAlignment.Center
};
return label;
}
public override void Selected(UIPickerView pickerView, nint row, nint component)
{
_selectedHandler?.Invoke((int)row);
}
}
}```
MainPageViewModel.cs
```using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace EmbeddedPicker
{
public class MainPageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public List<string> PickerItemSource { get; set; }
public int PickerIndex { get; set; }
public string PickerItem => PickerItemSource[PickerIndex];
public MainPageViewModel()
{
PickerItemSource = new List<string>
{
"1",
"2",
"3",
"4",
"5",
};
}
}
}
```
CustomPickerRenderer.cs
```using EmbeddedPicker;
using EmbeddedPicker.UWP;
using System.ComponentModel;
using System.Linq;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Platform.UWP;
using XF = Xamarin.Forms;
[assembly: ExportRenderer(typeof(CustomPicker), typeof(CustomPickerRenderer))]
namespace EmbeddedPicker.UWP {
public class CustomPickerRenderer : ViewRenderer<CustomPicker, ListBox> {
protected override void OnElementChanged(ElementChangedEventArgs<CustomPicker> e) {
base.OnElementChanged(e);
if (Control is null) {
SetNativeControl(new ListBox());
} else {
Control.SelectionChanged -= Control_SelectionChanged;
}
if (e.NewElement is null)
return;
Control.SelectionChanged += Control_SelectionChanged;
UpdateItemsSource();
UpdateSelectedIndex();
UpdateFont();
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) {
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == CustomPicker.ItemsSourceProperty.PropertyName) {
UpdateItemsSource();
} else if (e.PropertyName == CustomPicker.SelectedIndexProperty.PropertyName) {
UpdateSelectedIndex();
} else if (e.PropertyName == CustomPicker.FontFamilyProperty.PropertyName) {
UpdateFont();
} else if (e.PropertyName == CustomPicker.FontSizeProperty.PropertyName) {
UpdateFont();
}
}
private void UpdateItemsSource() => Control.ItemsSource = Element.ItemsSource;
private void UpdateSelectedIndex() => Control.SelectedIndex = Element.SelectedIndex;
/// <summary>
/// Updates the font family of each element in the picker
/// </summary>
private void UpdateFont() {
var font = string.IsNullOrEmpty(Element.FontFamily) ?
XF.Font.SystemFontOfSize(Element.FontSize) :
XF.Font.OfSize(Element.FontFamily, Element.FontSize);
Control.ApplyFont(font);
Control.FontSize = Element.FontSize;
}
void Control_SelectionChanged(object sender, SelectionChangedEventArgs e) {
Element.SelectedIndex = Element.ItemsSource.Cast<object>().IndexOf(
item => item.ToString() == e.AddedItems[0].ToString()
);
}
}
}
```
CustomPicker.cs
```using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace EmbeddedPicker
{
public class CustomPicker : View
{
// Item Source
public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create(nameof(ItemsSource), typeof(IEnumerable), typeof(CustomPicker), null);
public IEnumerable ItemsSource
{
get => (IEnumerable)GetValue(ItemsSourceProperty);
set => SetValue(ItemsSourceProperty, value);
}
// Selected Index
public static readonly BindableProperty SelectedIndexProperty = BindableProperty.Create(nameof(SelectedIndex), typeof(int), typeof(CustomPicker), -1, BindingMode.TwoWay, coerceValue: CoerceSelectedIndex);
public int SelectedIndex
{
get => (int)GetValue(SelectedIndexProperty);
set => SetValue(SelectedIndexProperty, value);
}
private static object CoerceSelectedIndex(BindableObject bindable, object value)
{
return value ?? 0;
}
// Font Size
public static readonly BindableProperty FontSizeProperty = BindableProperty.Create(nameof(FontSize), typeof(double), typeof(CustomPicker), -1.0, defaultValueCreator: bindable => Device.GetNamedSize(NamedSize.Default, (CustomPicker)bindable), coerceValue: CoerceFontSize);
public double FontSize
{
get => (double)GetValue(FontSizeProperty);
set => SetValue(FontSizeProperty, value);
}
private static object CoerceFontSize(BindableObject bindable, object value)
{
return value ?? Device.GetNamedSize(NamedSize.Default, (CustomPicker)bindable);
}
// Font Family
public static readonly BindableProperty FontFamilyProperty = BindableProperty.Create(nameof(FontFamily), typeof(string), typeof(CustomPicker), default(string));
public string FontFamily
{
get => (string)GetValue(FontFamilyProperty);
set => SetValue(FontFamilyProperty, value);
}
// Selector Line Color _Android Only_
public static readonly BindableProperty SelectorLineColorProperty = BindableProperty.Create(nameof(SelectorLineColor), typeof(Color), typeof(CustomPicker), Color.Gray);
public Color SelectorLineColor
{
get => (Color)GetValue(SelectorLineColorProperty);
set => SetValue(SelectorLineColorProperty, value);
}
// Wrap Wheel _Android Only_
public static readonly BindableProperty WrapSelectorWheelProperty = BindableProperty.Create(nameof(WrapSelectorWheel), typeof(bool), typeof(CustomPicker), false);
public bool WrapSelectorWheel
{
get => (bool)GetValue(WrapSelectorWheelProperty);
set => SetValue(WrapSelectorWheelProperty, value);
}
// Cell height _iOS Only_
public static readonly BindableProperty CellHeightProperty = BindableProperty.Create(nameof(CellHeight), typeof(float), typeof(CustomPicker), 40F);
public float CellHeight
{
get => (float)GetValue(CellHeightProperty);
set => SetValue(CellHeightProperty, value);
}
}
}
```
|
841412003/python3
|
841412003/python3
自动朗读.py
```#! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:L
# Date:2018/9/19 13:41
import uuid
import re
import os
import argparse
from pydub import AudioSegment
from aip import AipSpeech
from playsound import playsound
from goose3 import Goose
from goose3.text import StopWordsChinese
""" 你的 百度 APPID AK SK """
APP_ID = '14234285'
API_KEY = '8Vjov2dljwViGIu5dPPRtGvW'
SECRET_KEY = 'vpa7YAcMZHWPIdyW35Sy671UCHvcfBGL'
# 命令行输入参数处理
# parser = argparse.ArgumentParser()
# parser.add_argument('-u', '--url', type=str, help="input the target url")
# 获取参数
# args = parser.parse_args()
# URL = args.url
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
def text_to_voice(text):
file_name = str(uuid.uuid1()) + '.mp3'
result = client.synthesis(text, 'zh', 3, {
'vol': 5,
})
# 识别正确返回语音二进制 错误则返回 dict 参照下面错误码
if not isinstance(result, dict):
with open(file_name, 'wb+') as f:
f.write(result)
return file_name
def get_text():
g = Goose()
url = "https://item.btime.com/36a0f17i0489keqltn35q96p4lr?from=haozcxw"
article = g.extract(url=url)
print(article.title)
print(article.cleaned_text)
return article.cleaned_text
# 合并音频文件
def merge_voice(file_list):
voice_dict = {}
song = None
for i, f in enumerate(file_list):
if i == 0:
song = AudioSegment.from_file(f, "mp3")
else:
# 拼接音频文件
song += AudioSegment.from_file(f, "mp3")
# 删除临时音频
os.unlink(f)
# 导出合并后的音频文件,格式为MP3格式
file_name = str(uuid.uuid1()) + ".mp3"
song.export(file_name, format="mp3")
return file_name
if __name__ == "__main__":
# text = get_text()
# test = "Those days when we were together appear in my mind time after time,because they were so joyful, happy, blest, disappointing, sad and painful. I miss you ,and miss you so mach.Within you I lose myself, without you I find myself wanting to be lost again."
# 将文本按 500 的长度分割成多个文本
# text_list = [text[i:i + 500] for i in range(0, len(text), 500)]
# text_list = "我买几个橘子去你就在此地不要走动"
text_list =["我买几个橘子去", "你就在此地不要走动"]
file_list = []
for t in text_list:
file_list.append(text_to_voice(t))
print(file_list)
final_voice = merge_voice(file_list)
print(final_voice)
# 播放音频
playsound(final_voice)```
8.31.2.py
```#! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:L
# Date:2018/8/30 23:10
from sklearn.datasets import load_digits
import matplotlib.pyplot as plt
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler
import numpy as np
digits = load_digits()
fig = plt.figure(figsize=(8,8))
fig.subplots_adjust(left=0,right=1,bottom=0,top=1,hspace=0.05,wspace=0.05)
for i in range(36):
ax = fig.add_subplot(6,6,i+1,xticks=[],yticks=[])
ax.imshow(digits.images[i],cmap=plt.cm.binary,interpolation='nearest')
ax.text(0,7,str(digits.target[i]),color = 'red',fontsize=20)
scaler = StandardScaler()
scaler.fit(digits.data)
X_scaled = scaler.transform(digits.data)
mlp = MLPClassifier(hidden_layer_sizes=(30,30,30),activation = 'logistic',max_iter=200)
mlp.fit(X_scaled,digits.target)
predicted = mlp.predict(X_scaled)
fig = plt.figure(figsize=(8,8))
fig.subplots_adjust(left=0,right=1,bottom=0,top=1,hspace=0.05,wspace=0.05)
for i in range(36):
ax = fig.add_subplot(6,6,i+1,xticks=[],yticks=[])
ax.imshow(digits.images[i],cmap=plt.cm.binary,interpolation='nearest')
ax.text(0,7,str('{}-{}'.format(digits.target[i],predicted[i])),color = 'red',fontsize=20)
res=[]
for i,j in zip(digits.target,predicted):
res.append(i==j)
print(sum(res)/len(digits.target))
plt.show()
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data[:,[0,1]]
y = iris.target```
8.28.py
```#! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:L
# Date:2018/8/27 23:10
import pandas
df = pandas.read_excel('house_price_regression.xlsx')
df['age'] = df['age'].map(lambda e:2018-int(e.strip().strip('建筑年代:')))
df[['room','living_room']] = df['layout'].str.extract('(\d+)室(\d+)厅')
df['room'] = df['room'].astype(int)
df['living_room'] = df['living_room'].astype(int)
df['total_floor'] = df['floor_info'].str.extract('共(\d+)层')
df['total_floor'] = df['total_floor'].astype(int)
df['floor'] = df['floor_info'].str.extract('^(.)层')
df['direction'] = df['direction'].map(lambda e:e.strip())
del df['layout']
del df['floor_info']
del df['title']
del df['url']
df = pandas.concat([df,pandas.get_dummies(df['direction']),pandas.get_dummies(df['floor'])],axis=1)
del df['南北向']
del df['低']
del df['floor']
del df['direction']
from matplotlib import pyplot as plt
df[['price','area']].plot(kind='scatter',x = 'area',y = 'price',figsize = [10,5])
y = df['price']
x = df[['area']]
from sklearn.linear_model import LinearRegression
regr = LinearRegression()
regr.fit(x,y)
plt.scatter(x, y, color='blue')
plt.plot(x,regr.predict(x),linewidth = 3,color='red')
plt.xlabel('area')
plt.ylabel('price')
plt.show()
import statsmodels.api as sm
X2 = sm.add_constant(x)
est = sm.OLS(y,X2)
est2 = est.fit()
predictorcols = ['age','area','room','living_room','total_floor','东南向','东向','南向','西南向','西向','中','高']
import itertools
AICs = {}
for k in range(1,len(predictorcols)+1):
for variables in itertools.combinations(predictorcols,k):
predictors = x[list(variables)]
predictors2 = sm.add_constant(predictors)
est = sm.OLS(y,predictors2)
res = est.fit()
AICs[variables] = res.aic
from collections import Counter
c = Counter(AICs)
c.most_common()[::-10]
print(c.most_common()[::-10])```
meizitu1.0.py
```#! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:L
# Date:2018/8/24 17:01
import requests
from bs4 import BeautifulSoup
def get_page_number(num):
url = 'http://www.mmjpg.com/home/' + num
# 构造每个分页的网址
response = requests.get(url).content
```
news.py
```#! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:L
# Date:2018/9/26 8:44
import requests
from bs4 import BeautifulSoup
res = requests.get('https://new.qq.com/omn/20180929/20180929A0DX7Q.html')
soup = BeautifulSoup(res.text, 'html.parser')
newsary = []
for news in soup.select('.one-p'):
# newsary.append(news.select('.one-p'[0].text))
newsary.append(news.text)
print(newsary)
```
9.10.py
```#! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:L
# Date:2018/9/10 10:24
import pandas
df = pandas.read_csv('customer_churn.csv',header=0,index_col=0)
df = df.ix[:,3:]
cat_var=['international_plan','voice_mail_plan','churn']
for var in cat_var:
df[var] = df[var].map(lambda e:1 if e=='yes' else 0)
y = df.ix[:,-1]
x = df.ix[:,:-1]
print(df.columns)
```
biaoqianyun.py
```# -*- coding: utf-8 -*-
from pytagcloud import create_tag_image, make_tags
newarr={}
with open('sqlshuju.txt','r',encoding='GBK') as f:
arr=f.read().strip().split()
for k in arr:
if k not in newarr:
newarr[k]=1
else:
newarr[k]+=1
print(newarr)
from operator import itemgetter
swd = sorted(newarr.items(), key=itemgetter(1), reverse=True)
print(swd)
tags = make_tags(swd,maxsize = 120,minsize=50)
create_tag_image(tags, 'loud6.png',size=(540, 360),fontname="simhei")```
test.py
```#! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:L
# Date:2018/9/19 18:13
from goose3 import Goose
from goose3.text import StopWordsChinese
def gooseExample():
g = Goose({'stopwords_class': StopWordsChinese})
url = "https://item.btime.com/36a0f17i0489keqltn35q96p4lr?from=haozcxw"
article = g.extract(url=url)
print(article.title)
print(article.cleaned_text)
def gooseChineseExample():
g = Goose({'stopwords_class': StopWordsChinese})
url = "https://item.btime.com/36a0f17i0489keqltn35q96p4lr?from=haozcxw"
article = g.extract(url=url)
print(article.title)
print(article.meta_description)
print(article.cleaned_text[:150])
if __name__ == '__main__':
# begin_insert_job("knowledge", "person", "../data/Person.json")
gooseExample()
gooseChineseExample()
```
111.py
```speech_text='''Chief Justice Roberts, President Carter, President Clinton, President Bush, President Obama, fellow Americans and people of the world, thank you.
We, the citizens of America, are now joined in a great national effort to rebuild our country and restore its promise for all of our people.
Together, we will determine the course of America and the world for many, many years to come. We will face challenges, we will confront hardships, but we will get the job done.
Every four years, we gather on these steps to carry out the orderly and peaceful transfer of power, and we are grateful to President Obama and First Lady Michelle Obama for their gracious aid throughout this transition. They have been magnificent. Thank you.
Today's ceremony, however, has very special meaning because today, we are not merely transferring power from one administration to another or from one party to another, but we are transferring power from Washington, D.C. and giving it back to you, the people.
For too long, a small group in our nation's capital has reaped the rewards of government while the people have borne the cost. Washington flourished, but the people did not share in its wealth. Politicians prospered, but the jobs left and the factories closed. The establishment protected itself, but not the citizens of our country. Their victories have not been your victories. Their triumphs have not been your triumphs. And while they celebrated in our nation's capital, there was little to celebrate for struggling families all across our land.
That all changes starting right here and right now because this moment is your moment, it belongs to you.
It belongs to everyone gathered here today and everyone watching all across America. This is your day. This is your celebration. And this, the United States of America, is your country.
What truly matters is not which party controls our government, but whether our government is controlled by the people.
January 20th, 2017 will be remembered as the day the people became the rulers of this nation again.
The forgotten men and women of our country will be forgotten no longer.
Everyone is listening to you now. You came by the tens of millions to become part of a historic movement, the likes of which the world has never seen before.
At the center of this movement is a crucial conviction, that a nation exists to serve its citizens. Americans want great schools for their children, safe neighborhoods for their families, and good jobs for themselves. These are just and reasonable demands of righteous people and a righteous public.
But for too many of our citizens, a different reality exists: mothers and children trapped in poverty in our inner cities; rusted out factories scattered like tombstones across the landscape of our nation; an education system flush with cash, but which leaves our young and beautiful students deprived of all knowledge; and the crime and the gangs and the drugs that have stolen too many lives and robbed our country of so much unrealized potential.
This American carnage stops right here and stops right now.
We are one nation and their pain is our pain. Their dreams are our dreams. And their success will be our success. We share one heart, one home, and one glorious destiny. The oath of office I take today is an oath of allegiance to all Americans.
For many decades, we've enriched foreign industry at the expense of American industry; subsidized the armies of other countries, while allowing for the very sad depletion of our military. We've defended other nations' borders while refusing to defend our own.
And spent trillions and trillions of dollars overseas while America's infrastructure has fallen into disrepair and decay. We've made other countries rich, while the wealth, strength and confidence of our country has dissipated over the horizon.
One by one, the factories shuttered and left our shores, with not even a thought about the millions and millions of American workers that were left behind. The wealth of our middle class has been ripped from their homes and then redistributed all across the world.
But that is the past. And now, we are looking only to the future.
We assembled here today are issuing a new decree to be heard in every city, in every foreign capital, and in every hall of power. From this day forward, a new vision will govern our land. From this day forward, it's going to be only America first, America first.
Every decision on trade, on taxes, on immigration, on foreign affairs will be made to benefit American workers and American families. We must protect our borders from the ravages of other countries making our products, stealing our companies and destroying our jobs.
Protection will lead to great prosperity and strength. I will fight for you with every breath in my body and I will never ever let you down.
America will start winning again, winning like never before.
We will bring back our jobs. We will bring back our borders. We will bring back our wealth. And we will bring back our dreams.
We will build new roads and highways and bridges and airports and tunnels and railways all across our wonderful nation. We will get our people off of welfare and back to work, rebuilding our country with American hands and American labor.
We will follow two simple rules; buy American and hire American.
We will seek friendship and goodwill with the nations of the world, but we do so with the understanding that it is the right of all nations to put their own interests first. We do not seek to impose our way of life on anyone, but rather to let it shine as an example. We will shine for everyone to follow.
We will reinforce old alliances and form new ones and unite the civilized world against radical Islamic terrorism, which we will eradicate from the face of the Earth.
At the bedrock of our politics will be a total allegiance to the United States of America,and through our loyalty to our country, we will rediscover our loyalty to each other.When you open your heart to patriotism, there is no room for prejudice.
The Bible tells us how good and pleasant it is when God's people live together in unity. We must speak our minds openly, debate our disagreements honestly, but always pursue solidarity. When America is united, America is totally unstoppable.
There should be no fear. We are protected and we will always be protected. We will be protected by the great men and women of our military and law enforcement. And most importantly, we will be protected by God.
Finally, we must think big and dream even bigger. In America, we understand that a nation is only living as long as it is striving. We will no longer accept politicians who are all talk and no action, constantly complaining, but never doing anything about it.
The time for empty talk is over. Now arrives the hour of action.
Do not allow anyone to tell you that it cannot be done. No challenge can match the heart and fight and spirit of America. We will not fail. Our country will thrive and prosper again.
We stand at the birth of a new millennium, ready to unlock the mysteries of space, to free the earth from the miseries of disease, and to harness the energies, industries and technologies of tomorrow. A new national pride will stir ourselves, lift our sights and heal our divisions.
It's time to remember that old wisdom our soldiers will never forget, that whether we are black or brown or white, we all bleed the same red blood of patriots.
We all enjoy the same glorious freedoms and we all salute the same great American flag.
And whether a child is born in the urban sprawl of Detroit or the wind-swept plains of Nebraska, they look up at the same night sky, they will their heart with the same dreams, and they are infused with the breath of life by the same almighty creator.
So to all Americans in every city near and far, small and large, from mountain to mountain, from ocean to ocean, hear these words: You will never be ignored again.
Your voice, your hopes, and your dreams will define our American destiny. And your courage and goodness and love will forever guide us along the way.
Together, we will make America strong again. We will make America wealthy again. We will make America proud again. We will make America safe again. And yes, together we will make America great again.
Thank you. God bless you. And God bless America.
Thank you.
God bless America.
'''
speech=speech_text.lower().split()
dic={}
for word in speech:
if word not in dic:
dic[word] = 1
else:
dic[word] += 1
import operator
swd=sorted(dic.items(),key=operator.itemgetter(1),reverse=True)
import nltk
from nltk.corpus import stopwords
stop_words = stopwords.words('English')
#stop_words
arr=[]
for k,v in swd:
if k not in stop_words:
k=k.rstrip('.,;')
if v>3:
arr.append((k,v))
from pytagcloud import create_tag_image, make_tags
from pytagcloud.lang.counter import get_tag_counts
tags = make_tags(arr, maxsize=120)
create_tag_image(tags, 'cloud_large1.png', size=(900, 600), fontname='Lobster')```
8.27.py
```#! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:L
# Date:2018/8/27 17:00
import pandas
df = pandas.read_csv("house-prices.csv")
house = pandas.concat([df,pandas.get_dummies(df['Brick']),pandas.get_dummies(df['Neighborhood'])],axis=1)
del house['No']
del house['West']
del house['Brick']
del house['Neighborhood']
del house['Home']
X = house[['SqFt','Bedrooms','Bathrooms','Offers','Yes','East','North']]
Y = house['Price'].values
from sklearn.linear_model import LinearRegression
regr = LinearRegression()
regr.fit(X,Y)
import statsmodels.api as sm
X2 = sm.add_constant(X)
est = sm.OLS(Y,X2)
est2 = est.fit()
predictorcols = ['SqFt','Bedrooms','Bathrooms','Offers','Yes','East','North']
import itertools
AICs = {}
for k in range(1, len(predictorcols)+1):
for variables in itertools.combinations(predictorcols, k):
predictors = X[list(variables)]
predictors2 = sm.add_constant(predictors)
est = sm.OLS(Y, predictors2)
res = est.fit()
AICs[variables] = res.aic
from collections import Counter
c = Counter(AICs)
print(c.most_common()[::-10])
```
8.31.1.py
```#! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:L
# Date:2018/8/30 20:15
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
def plot_estimator(estimator,X,y,title):
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),
np.arange(y_min, y_max, 0.1))
Z = estimator.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.plot()
plt.contour(xx, yy, Z, alpha=0.4, cmap=plt.cm.RdYlBu)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.brg)
plt.title(title)
plt.xlabel('Sepal.Length')
plt.ylabel('Sepal.Width')
plt.show()
iris = load_iris()
X = iris.data[:,[0,1]]
y = iris.target
clf = RandomForestClassifier(n_estimators=100,criterion="entropy",random_state=0)
clf.fit(X,y)
plot_estimator(clf,X,y,'RandomForestClassifier')
clf1 = SVC(kernel='rbf')
clf1.fit(X,y)
clf2 = DecisionTreeClassifier()
clf2.fit(X,y)
clf3 = RandomForestClassifier(n_estimators=10,criterion='entropy')
clf3.fit(X,y)
clf4 = LogisticRegression()
clf4.fit(X,y)
plot_estimator(clf1,X,y,'rbf')
plot_estimator(clf2,X,y,'DecisionTreeClassifier')
plot_estimator(clf3,X,y,'RandomForestClassifier')
plot_estimator(clf3,X,y,'LogisticRegression')
```
8.29.py
```#! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:L
# Date:2018/8/29 15:42
from itertools import product
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
X = iris.data[:,[2,3]]
y = iris.target
clf = tree.DecisionTreeClassifier(max_depth=2)
clf.fit(X,y)
plt.scatter(X[:,0],X[:,1],color='black')
# plt.show()
x_min,x_max = X[:,0].min()-1,X[:,0].max()+1
y_min,y_max = X[:,1].min()-1,X[:,1].max()+1
xx,yy = np.meshgrid(np.arange(x_min,x_max,0.1),
np.arange(y_min,y_max,0.1))
plt.plot()
Z = clf.predict(np.c_[xx.ravel(),yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contour(xx,yy,Z,alpha = 0.4,cmap = plt.cm.rainbow)
plt.scatter(X[:,0],X[:,1],c=y,alpha=1,cmap=plt.cm.rainbow)
plt.title('Decision Tree')
plt.xlabel('Lengeth')
plt.ylabel('width')
plt.show()```
views.py
```from django.shortcuts import render
from .models import Topic
def index(request):
"""学习笔记的主页"""
return render(request, 'learning_logs/index.html')
def topics(request):
"""显示所有的主题"""
topics = Topic.object.order_by('date_added')
context = {'topics':topics}
return render(request, 'learning_logs/topics.html', context)
```
8.28.2.py
```#! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:L
# Date:2018/8/28 15:03
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
# print(iris.data)
clf = tree.DecisionTreeClassifier(max_depth=2)
clf.fit(iris.data,iris.target)
print(clf.predict(iris.data))
tree.export_graphviz(clf,out_file='tree.dot')
from IPython.display import Image
print(Image('tree.png'))
```
|
844348677/Savetick
|
844348677/Savetick
TickInfo.java
```package tdb.util;
import org.bridj.Pointer;
import tdbapi.TDBDefine_ReqTick;
/**
* Created by liuh on 2016/5/9.
*/
public class TickInfo {
/*
* struct TDBDefine_ReqTick
{
char chCode[32]; //证券万得代码(AG1312.SHF)
char chMarketKey[24]; //市场设置,如:SH-1-0;SZ-2-0
int nDate; //开始日期(交易日),为0则从今天,格式:YYMMDD,例如20130101表示2013年1月1日
int nBeginTime; //开始时间:若<=0则从头,格式:(HHMMSSmmm)例如94500000 表示 9点45分00秒000毫秒
int nEndTime; //结束时间:若<=0则至最后
int nAutoComplete; //自动补齐标志:( 0:不自动补齐,1:自动补齐)
};
*/
public static Pointer<TDBDefine_ReqTick> getReqTick(String szCode, String szMarket, String y, String m, String d){ //获取各种信息
Pointer<TDBDefine_ReqTick> resPointer = Pointer.allocate(TDBDefine_ReqTick.class);
TDBDefine_ReqTick reqTick = resPointer.get();
Pointer<Byte > codePointer = reqTick.chCode();
codePointer.setArray(szCode.getBytes());
Pointer<Byte > marketKeyPointer = reqTick.chMarketKey();
marketKeyPointer.setArray(szMarket.getBytes());
int intDate = Integer.parseInt(y)*10000 + Integer.parseInt(m)*100 + Integer.parseInt(d);
reqTick.nDate(intDate);
reqTick.nBeginTime(80000000);
reqTick.nEndTime(160000000);
return resPointer;
}
}
```
LoginInfo.java
```package tdb.util;
import org.bridj.Pointer;
import tdbapi.OPEN_SETTINGS;
import tdbapi.TDBDefine_ResLogin;
/**
* Created by liuh on 2016/5/9.
*/
public class LoginInfo {
public static Pointer<OPEN_SETTINGS> getOpsPointer(String ip, String port, String user, String password){
Pointer<OPEN_SETTINGS> opsPointer = Pointer.allocate(OPEN_SETTINGS.class); //创建OPEN_SETTINGS类型的指针,方法对不对我也不知道,反正能用
OPEN_SETTINGS ops =opsPointer.get(); //拿到OPEN_SETTING对象
Pointer<Byte> ipPointer = ops.szIP(); //拿到szIP的指针对象,再设置ip
byte[] ipBtyes = ip.getBytes();
ipPointer.setArray(ipBtyes);
Pointer<Byte> portPointer = ops.szPort();
byte[] portBytes = port.getBytes();
portPointer.setArray(portBytes);
Pointer<Byte> userPointer = ops.szUser();
byte[] userBytes = user.getBytes();
userPointer.setArray(userBytes);
Pointer<Byte> passwordPointer = ops.szPassword();
byte[] passwordBytes = password.getBytes();
passwordPointer.setArray(passwordBytes);
System.out.println(opsPointer);
System.out.println(opsPointer.get().toString());
System.out.println(opsPointer.get().szIP().toString());
System.out.println(opsPointer.get().szIP().get(1).toString());
return opsPointer;
}
public static String[] getMarkets(Pointer<TDBDefine_ResLogin> loginResPointer){
TDBDefine_ResLogin loginRes = loginResPointer.get();
int nMarkets = loginRes.nMarkets(); //支持市场个数
System.out.println("支持市场个数: "+nMarkets);
String[] result = new String[nMarkets]; //结果 支持市场的String[]数组
byte[] szMarketByts = loginRes.szMarket().getBytes();
for(int i=0;i<result.length;i++){
byte[] tmp = new byte[24];
for(int j=0;j<tmp.length;j++)
tmp[j]=szMarketByts[i*24 + j];
result[i] = new String(tmp).trim();
System.out.println(result[i]);
}
return result;
}
}
```
Util.java
```package tdb.util;
import org.bridj.Pointer;
import tdbapi.TDBDefine_Code;
import tdbapi.TDBDefine_Tick;
/**
* Created by liuh on 2016/5/9.
*/
public class Util {
//byte[]数组转成String
public static String Bytes2HexString(byte[] b) {
String ret = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase();
}
return ret;
}
public static void getCodeInfo(Pointer<Pointer<TDBDefine_Code>> pCodeTable, int pCount){
TDBDefine_Code codeInfo = pCodeTable.get().get(0); //双重指针
String chWindCode = new String(codeInfo.chWindCode().getBytes()).trim(); //万得代码(AG1312.SHF)
String chCode = new String(codeInfo.chCode().getBytes()).trim(); //交易所代码(ag1312)
String chMarket = new String(codeInfo.chMarket().getBytes()).trim(); //市场代码(SHF)
String chCNName = new String(codeInfo.chCNName().getBytes()).trim(); //证券中文名称
String chENName = new String(codeInfo.chENName().getBytes()).trim(); //证券英文名称
int nType = codeInfo.nType(); //证券类型
System.out.println("万得代码(AG1312.SHF),交易所代码(ag1312),市场代码(SHF),证券中文名称,证券英文名称");
System.out.println(chWindCode+","+chCode+","+chMarket
+","+chCNName+","+chENName+","+nType);
}
public static void getTickInfo(Pointer<Pointer<TDBDefine_Tick>> pData, int pTickCount){
TDBDefine_Tick tickData = pData.get().get(0);
String chWindCode = new String(tickData.chWindCode().getBytes()).trim(); //万得代码(AG1312.SHF)
String chCode = new String(tickData.chCode().getBytes()).trim(); //交易所代码(ag1312)
int nDate = tickData.nDate(); //日期(自然日)
int nTime = tickData.nTime(); //时间(HHMMSSmmm)例如94500000 表示 9点45分00秒000毫秒
int nPrice = tickData.nPrice(); //成交价((a double number + 0.00005) *10000)
long iVolume = tickData.iVolume(); //成交量
long iTurover = tickData.iTurover(); //成交额(元)
int nMatchItems = tickData.nMatchItems(); //成交笔数
int nInterest = tickData.nInterest(); //IOPV(基金)、利息(债券)
byte chTradeFlag = tickData.chTradeFlag(); //成交标志
byte chBSFlag = tickData.chBSFlag(); //BS标志
long iAccVolume = tickData.iAccVolume(); //当日累计成交量
long iAccTurover = tickData.iAccTurover(); //当日成交额(元)
int nHigh = tickData.nHigh(); //最高((a double number + 0.00005) *10000)
int nLow = tickData.nLow(); //最低((a double number + 0.00005) *10000)
int nOpen = tickData.nOpen(); //开盘((a double number + 0.00005) *10000)
int nPreClose = tickData.nPreClose(); //前收盘((a double number + 0.00005) *10000)
//期货字段
int nSettle = tickData.nSettle(); //结算价((a double number + 0.00005) *10000)
int nPosition = tickData.nPosition(); //持仓量
int nCurDelta = tickData.nCurDelta(); //虚实度
int nPreSettle = tickData.nPreSettle(); //昨结算((a double number + 0.00005) *10000)
int nPrePosition = tickData.nPrePosition(); //昨持仓
//买卖盘字段
int[] nAskPrice = tickData.nAskPrice().getInts() ; //叫卖价((a double number + 0.00005) *10000)
int[] nAskVolume = tickData.nAskVolume().getInts(); //叫卖量
int[] nBidPrice = tickData.nBidPrice().getInts(); //叫买价((a double number + 0.00005) *10000)
int[] nBidVolume = tickData.nBidVolume().getInts(); //叫买量
int nAskAvPrice = tickData.nAskAvPrice(); //加权平均叫卖价(上海L2)((a double number + 0.00005) *10000)
int nBidAvPrice = tickData.nBidAvPrice(); //加权平均叫买价(上海L2)((a double number + 0.00005) *10000)
long iTotalAskVolume = tickData.iTotalAskVolume(); //叫卖总量(上海L2)
long iTotalBidVolume = tickData.iTotalBidVolume(); //叫买总量(上海L2)
//下面的字段指数使用
int nIndex = tickData.nIndex(); //不加权指数
int nStocks = tickData.nStocks(); //品种总数
int nUps = tickData.nUps(); //上涨品种数
int nDowns = tickData.nDowns(); //下跌品种数
int nHoldLines = tickData.nHoldLines(); //持平品种数
//保留字段
int nResv1 = tickData.nResv1();//保留字段1
int nResv2 = tickData.nResv2();//保留字段2
int nResv3 = tickData.nResv3();//保留字段3
System.out.println("万得代码(AG1312.SHF),交易所代码(ag1312),日期(自然日),时间(HHMMSSmmm)例如94500000 表示 9点45分00秒000毫秒,成交价((a double number + 0.00005) *10000),"
+ "成交量,成交额(元),成交笔数,IOPV(基金)、利息(债券),成交标志,BS标志,当日累计成交量,当日成交额(元),最高((a double number + 0.00005) *10000),最低((a double number + 0.00005) *10000),"
+ "开盘((a double number + 0.00005) *10000),前收盘((a double number + 0.00005) *10000),结算价((a double number + 0.00005) *10000),结算价((a double number + 0.00005) *10000),"
+ "持仓量,虚实度,昨结算((a double number + 0.00005) *10000),昨持仓,叫卖价((a double number + 0.00005) *10000),叫卖量,叫买价((a double number + 0.00005) *10000),"
+ "叫买量,加权平均叫卖价(上海L2)((a double number + 0.00005) *10000),加权平均叫买价(上海L2)((a double number + 0.00005) *10000),不加权指数,品种总数,上涨品种数,下跌品种数,持平品种数,保留字段1,保留字段2,保留字段3");
System.out.println(chWindCode+","+chCode+","+nDate+","+nTime+","+nPrice+","+iVolume+","+iTurover+","+nMatchItems+","+nInterest+","+chTradeFlag+","+chBSFlag+","+iAccVolume+","
+iAccTurover+","+nHigh+","+nLow+","+nOpen+","+nPreClose+","+nSettle+","+nPosition+","+nCurDelta+","+nPreSettle+","+nPrePosition+","+nAskAvPrice+","+nAskVolume+","+nBidPrice+","
+nBidVolume+","+nAskAvPrice+","+nBidAvPrice+","+iTotalAskVolume+","+iTotalBidVolume+","+nIndex+","+nStocks+","+nUps+","+nDowns+","+nHoldLines+","+nResv1+","+nResv2+","+nResv3);
}
}
```
MainTDB.java
```package tdb.main;
import org.bridj.Pointer;
import tdb.util.LoginInfo;
import tdb.util.TickInfo;
import tdb.util.Util;
import tdbapi.*;
/**
* Created by liuh on 2016/5/9.
*/
public class MainTDB {
public static void main(String[] args) {
String kind = "tick";
String ip = "114.80.154.34";
String port = "6260";
String user = "TD1066965004";
String password = "60295306";
String market = "SHF-1-0";
String code = "ni00.SHF";
String output = "ticks";
String y = "2016";
String m = "05";
String d = "05";
Pointer<OPEN_SETTINGS> opsPointer = LoginInfo.getOpsPointer(ip,port,user,password); //设置登录服务器信息
Pointer<TDBDefine_ResLogin> loginResPointer = Pointer.allocate(TDBDefine_ResLogin.class);
Pointer<?> hTdb = null;
hTdb = TDBAPILibrary.TDB_Open(opsPointer, loginResPointer); //登录
//System.out.println(hTdb.toString());
String[] szMarkets = LoginInfo.getMarkets(loginResPointer); //获取账号对应的市场String[]
Pointer<Byte> szMarket = Pointer.pointerToBytes(szMarkets[0].getBytes()); //设置 市场(格式:Market-Level-Source(SZ-2-0)),为空请求所有授权市场
Pointer<Pointer<TDBDefine_Code>> pCodeTable = Pointer.allocatePointer(TDBDefine_Code.class);
Pointer<Integer> pCount = Pointer.pointerToInt(0);
int getCodeRes = TDBAPILibrary.TDB_GetCodeTable(hTdb, szMarket, pCodeTable, pCount); //根据市场获取对应的code
System.out.println(getCodeRes+" : "+pCount.getInt());
Util.getCodeInfo(pCodeTable,pCount.get());//获取code信息
Pointer<TDBDefine_ReqTick> pReq = TickInfo.getReqTick(code, market, y,m,d); //获取reqTick的指针
Pointer<Pointer<TDBDefine_Tick>> pData = Pointer.allocatePointer(TDBDefine_Tick.class);
Pointer<Integer> pTickCount = Pointer.pointerToInt(0);
int getTickRes = TDBAPILibrary.TDB_GetTick(hTdb, pReq, pData, pTickCount);
System.out.println("TickCount: "+pTickCount.get());
Util.getTickInfo(pData, pTickCount.getInt());
/* byte testb= pData.get().get().chTradeFlag();
System.out.println(testb);
byte testb2 = pData.get().get().chBSFlag();
System.out.println(testb2);*/
/* int[] intArray = pData.get().get().nAskPrice().getInts();
int[] intArray2 = pData.get().get().nAskVolume().getInts();
int[] intArray3 = pData.get().get().nBidPrice().getInts();
int[] intArray4 = pData.get().get().nBidVolume().getInts();
for(int i=0;i<intArray.length;i++){
System.out.println(intArray[i]+","+intArray2[i]+","+intArray3[i]+","+intArray4[i]);
}*/
TDBAPILibrary.TDB_Close(hTdb);
}
}
```
|
853695319/scrapy
|
853695319/scrapy
readme.md
```Running Tesseract
Tesseract is a command-line program, so first open a terminal or command prompt. The command is used like this:
```
tesseract imagename outputbase [-l lang] [-psm pagesegmode] [configfile...]
l:\etc\Tesseract-OCR\tesseract.exe tesseracttest.jpg out
out.txt =>
This is some text, written in Arial, that will be read by
Tesseract. Here are some symbols: !@#$%*&*()
```
So basic usage to do OCR on an image called 'myscan.png' and save the result to 'out.txt' would be:
```
tesseract myscan.png out
```
Or to do the same with German:
```
tesseract myscan.png out -l deu
```
It can even be used with multiple languages traineddata at a time eg. English and German:
```
tesseract myscan.png out -l eng+deu
```
Tesseract also includes a hOCR mode, which produces a special HTML file with the coordinates of each word. This can be used to create a searchable pdf, using a tool such as Hocr2PDF. To use it, use the 'hocr' config option, like this:
```
tesseract myscan.png out hocr
```
You can also create a searchable pdf directly from tesseract ( versions >=3.03):
```
tesseract myscan.png out pdf
```
More information about the various options is available in the Tesseract manpage.```
05-贴吧小爬虫.py
```import urllib.parse
import urllib.request
# 特别注意导入模块的方式
url = "https://www.baidu.com/baidu"
keyword = input("请输入要查询的字符串:")
wd = {'wd': keyword}
query = urllib.parse.urlencode(wd)
fullurl = url + "?" + query
ua_header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"
}
request = urllib.request.Request(fullurl, headers=ua_header)
response = urllib.request.urlopen(request)
# 可以用抓包工具查看结果
# print(response.read())
# 200 成功,然后检查网址
print(response.getcode())
print(response.geturl())
```
readme.md
```### headless firefox vs phantonjs
firefox 截图受窗口限制, 而phantonjs 截图不受窗口限制,会截取整个网页出来```
07-urllib_post.py
```import urllib.request
import urllib.parse
"""
目的:学习POST方式
POST https://fanyi.baidu.com/v2transapi HTTP/1.1
Host: fanyi.baidu.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0
Accept: */*
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate, br
Referer: https://fanyi.baidu.com/?aldtype=16047
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 121
Connection: keep-alive
Cookie: BAIDUID=CAD28827099BE88F67EC86DC33EEB368:FG=1; BIDUPSID=CAD28827099BE88F67EC86DC33EEB368; PSTM=1556418486; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; H_PS_PSSID=1464_21096_28721_28832_28584; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1556505103,1556509798,1556509836; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1556509836; from_lang_often=%5B%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%2C%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%5D; to_lang_often=%5B%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%2C%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%5D; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; BDRCVFR[Fc9oatPmwxn]=srT4swvGNE6uzdhUL68mv3; delPer=0; PSINO=7; locale=zh
from=en
to=zh
query=query
transtype=realtime
simple_means_flag=3
sign=83774.369679
token=649d104fe64f36f71148f1c87c183954
"""
url = "https://fanyi.baidu.com/v2transapi"
# query = input("请输入翻译关键字:")
form_data = {
"from": "zh",
"to": "en",
"query": "这里",
"transtype": "realtime",
# "simple_means_flag": "3",
"sign": "162854.433943",
"token": "649d104fe64f36f71148f1c87c183954",
}
# 注意 post的body 数据要全部进行转码
data = urllib.parse.urlencode(form_data).encode()
header = {
"Host": "fanyi.baidu.com",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0",
"Accept": "*/*",
"Referer": "https://fanyi.baidu.com/?aldtype=16047",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"X-Requested-With": "XMLHttpRequest",
# cookie是一定要的
"Cookie": "BAIDUID=CAD28827099BE88F67EC86DC33EEB368:FG=1; BIDUPSID=CAD28827099BE88F67EC86DC33EEB368; PSTM=1556418486; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; H_PS_PSSID=1464_21096_28721_28832_28584; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1556505103,1556509798,1556509836; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1556509836; from_lang_often=%5B%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%2C%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%5D; to_lang_often=%5B%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%2C%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%5D; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; BDRCVFR[Fc9oatPmwxn]=srT4swvGNE6uzdhUL68mv3; delPer=0; PSINO=7; locale=zh"
}
request = urllib.request.Request(url, data=data, headers=header)
reponse = urllib.request.urlopen(request)
print("code:{}\nurl:{}\n".format(reponse.getcode(), reponse.geturl()))
print("-"*20)
print(reponse.read())
```
README.md
```# scrapy
爬虫学习记录
```
sunspider.py
```# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from dgsun.items import DgsunItem
class SunSpider(CrawlSpider):
name = 'sun'
allowed_domains = ['wz.sun0769.com']
offset = 0
start_urls = [f'http://wz.sun0769.com/index.php/question/questionType?type=4&page={offset}']
rules = (
# self.follow = False if callback else True
# 也就是默认有callback就不follow,没callback就follow
# 页码
Rule(
LinkExtractor(allow=r'type=4&page=\d*'),
follow=True # follow=True,那么爬取到符合规则的URL,就会不断抽取URL,可以爬取全部分页
# follow=False # 只抽取当前页面一次,不follow抽取的URL,只是当前页
),
# 处理帖子内容
Rule(
LinkExtractor(allow=r'/html/question/\d+/\d+.shtml'),
callback='parse_item',
follow=False
),
)
def parse_item(self, response):
try:
item = DgsunItem()
# 标题
item['title'] = response.css('div.wzy1 span.niae2_top::text').get()
# 编号
item['number'] = response.css('div.wzy1 span:nth-child(2)::text').get().split(':')[-1]
# 文字内容,默认先取出有图片情况下的文字内容列表
item['content'] = response.css('div.wzy1 .txt16_3 *::text').get().strip()
# 链接
item['url'] = response.url
yield item
except Exception as err:
self.logger.exception('')
```
pytesseract.md
```Python Tesseract
================
.. image:: https://travis-ci.org/madmaze/pytesseract.svg
:target: https://travis-ci.org/madmaze/pytesseract
:alt: Travis build status
.. image:: https://img.shields.io/pypi/v/pytesseract.svg
:target: https://pypi.python.org/pypi/pytesseract
:alt: PyPI release
.. image:: https://img.shields.io/github/release/madmaze/pytesseract.svg
:target: https://github.com/madmaze/pytesseract/releases
:alt: Github release
.. image:: https://img.shields.io/pypi/pyversions/pytesseract.svg
:target: https://pypi.python.org/pypi/pytesseract
:alt: Python versions
Python-tesseract is an optical character recognition (OCR) tool for python.
That is, it will recognize and "read" the text embedded in images.
Python-tesseract is a wrapper for `Google's Tesseract-OCR Engine <https://github.com/tesseract-ocr/tesseract>`_.
It is also useful as a stand-alone invocation script to tesseract, as it can read all image types
supported by the Pillow and Leptonica imaging libraries, including jpeg, png, gif, bmp, tiff,
and others. Additionally, if used as a script, Python-tesseract will print the recognized
text instead of writing it to a file.
USAGE
-----
**Quickstart**
*Note*: Test images are located in the ``tests/data`` folder of the Git repo.
.. code-block:: python
try:
from PIL import Image
except ImportError:
import Image
import pytesseract
# If you don't have tesseract executable in your PATH, include the following:
pytesseract.pytesseract.tesseract_cmd = r'<full_path_to_your_tesseract_executable>'
# Example tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract'
# Simple image to string
print(pytesseract.image_to_string(Image.open('test.png')))
# French text image to string
print(pytesseract.image_to_string(Image.open('test-european.jpg'), lang='fra'))
# In order to bypass the image conversions of pytesseract, just use relative or absolute image path
# NOTE: In this case you should provide tesseract supported images or tesseract will return error
print(pytesseract.image_to_string('test.png'))
# Batch processing with a single file containing the list of multiple image file paths
print(pytesseract.image_to_string('images.txt'))
# Get bounding box estimates
print(pytesseract.image_to_boxes(Image.open('test.png')))
# Get verbose data including boxes, confidences, line and page numbers
print(pytesseract.image_to_data(Image.open('test.png')))
# Get information about orientation and script detection
print(pytesseract.image_to_osd(Image.open('test.png')))
# Get a searchable PDF
pdf = pytesseract.image_to_pdf_or_hocr('test.png', extension='pdf')
# Get HOCR output
hocr = pytesseract.image_to_pdf_or_hocr('test.png', extension='hocr')
Support for OpenCV image/NumPy array objects
.. code-block:: python
import cv2
img = cv2.imread(r'/<path_to_image>/digits.png')
print(pytesseract.image_to_string(img))
# OR explicit beforehand converting
print(pytesseract.image_to_string(Image.fromarray(img))
If you need custom configuration like `oem`/`psm`, use the **config** keyword.
.. code-block:: python
# Example of adding any additional options.
custom_oem_psm_config = r'--oem 3 --psm 6'
pytesseract.image_to_string(image, config=custom_oem_psm_config)
Add the following config, if you have tessdata error like: "Error opening data file..."
.. code-block:: python
# Example config: r'--tessdata-dir "C:\Program Files (x86)\Tesseract-OCR\tessdata"'
# It's important to add double quotes around the dir path.
tessdata_dir_config = r'--tessdata-dir "<replace_with_your_tessdata_dir_path>"'
pytesseract.image_to_string(image, lang='chi_sim', config=tessdata_dir_config)
**Functions**
* **get_tesseract_version** Returns the Tesseract version installed in the system.
* **image_to_string** Returns the result of a Tesseract OCR run on the image to string
* **image_to_boxes** Returns result containing recognized characters and their box boundaries
* **image_to_data** Returns result containing box boundaries, confidences, and other information. Requires Tesseract 3.05+. For more information, please check the `Tesseract TSV documentation <https://github.com/tesseract-ocr/tesseract/wiki/Command-Line-Usage#tsv-output-currently-available-in-305-dev-in-master-branch-on-github>`_
* **image_to_osd** Returns result containing information about orientation and script detection.
**Parameters**
``image_to_data(image, lang=None, config='', nice=0, output_type=Output.STRING, timeout=0)``
* **image** Object, PIL Image/NumPy array of the image to be processed by Tesseract
* **lang** String, Tesseract language code string
* **config** String, Any additional configurations as a string, ex: ``config='--psm 6'``
* **nice** Integer, modifies the processor priority for the Tesseract run. Not supported on Windows. Nice adjusts the niceness of unix-like processes.
* **output_type** Class attribute, specifies the type of the output, defaults to ``string``. For the full list of all supported types, please check the definition of `pytesseract.Output <https://github.com/madmaze/pytesseract/blob/master/src/pytesseract.py>`_ class.
* **timeout** Integer or Float, duration in seconds for the OCR processing, after which, pytesseract will terminate and raise RuntimeError.
INSTALLATION
------------
Prerequisites:
- Python-tesseract requires Python 2.7 or Python 3.5+
- You will need the Python Imaging Library (PIL) (or the `Pillow <https://pypi.org/project/Pillow/>`_ fork).
Under Debian/Ubuntu, this is the package **python-imaging** or **python3-imaging**.
- Install `Google Tesseract OCR <https://github.com/tesseract-ocr/tesseract>`_
(additional info how to install the engine on Linux, Mac OSX and Windows).
You must be able to invoke the tesseract command as *tesseract*. If this
isn't the case, for example because tesseract isn't in your PATH, you will
have to change the "tesseract_cmd" variable ``pytesseract.pytesseract.tesseract_cmd``.
Under Debian/Ubuntu you can use the package **tesseract-ocr**.
For Mac OS users. please install homebrew package **tesseract**.
| Installing via pip:
Check the `pytesseract package page <https://pypi.python.org/pypi/pytesseract>`_ for more information.
.. code-block:: bash
$ (env)> pip install pytesseract
| Or if you have git installed:
.. code-block:: bash
$ (env)> pip install -U git+https://github.com/madmaze/pytesseract.git
| Installing from source:
.. code-block:: bash
$> git clone https://github.com/madmaze/pytesseract.git
$ (env)> cd pytesseract && pip install -U .
TESTING
-------
To run this project's test suite, install and run ``tox``. Ensure that you have ``tesseract``
installed and in your PATH.
.. code-block:: bash
$ (env)> pip install tox
$ (env)> tox
LICENSE
-------
Python-tesseract is released under the GPL v3.
CONTRIBUTORS
------------
- Originally written by `Samuel Hoffstaetter <https://github.com/h>`_
- `Juarez Bochi <https://github.com/jbochi>`_
- `Matthias Lee <https://github.com/madmaze>`_
- `Lars Kistner <https://github.com/Sr4l>`_
- `Ryan Mitchell <https://github.com/REMitchell>`_
- `Emilio Cecchini <https://github.com/ceccoemi>`_
- `John Hagen <https://github.com/johnthagen>`_```
12-代理处理器.py
```import urllib.request
# http请求
request = urllib.request.Request("http://www.baidu.com/")
# 1 构建一个代理处理器,参数是字典,不能为空, 可以为空字典
proxy = "112.91.218.21:9000"
# 注意,如果你明确知道该代理是HTTP协议还是HTTPS协议,那么速度可以更快
# 实际上,代理一般不直接记录在程序里,通常通过倒入模块,或者设置环境变量
http_proxy_handle = urllib.request.ProxyHandler({
"http": "http://" + proxy,
"https": "https://" + proxy,
})
# 构建一个空代理
null_proxy_handle = urllib.request.ProxyHandler({})
# 代理开关
proxy_swith = True
# 注意区分
if proxy_swith:
opener = urllib.request.build_opener(http_proxy_handle)
else:
opener = urllib.request.build_opener(null_proxy_handle)
# 2 tip:构建一个全局opener,之后所有请求都可以用urlopen()方式去发送,也附带handle的功能
urllib.request.install_opener(opener)
# 3 响应请求
response = urllib.request.urlopen(request)
print(response.read())
# 有时候使用代理平台返回的编码格式是gbk,表示是从win发来的,可以进行编码
# print(response.read().decode("gbk"))
print(response.getcode())
```
run.sh
```#!/bin/bash
/usr/sbin/sshd || echo "fail sshd"
pipenv shell```
21-使用jsonpath.py
```import json
import requests
import jsonpath
import chardet
url = "https://www.lagou.com/lbs/getAllCitySearchLabels.json"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"}
response = requests.get(url, headers=headers)
# print(response) # for test
data_json = json.loads(response.text) # 默认Unicode,如果传入其他编码gbk,需要指定encoding='gbk'
# print(type(data_json))
city_list = jsonpath.jsonpath(data_json, '$..name')
# for city in city_list:
# print(city)
json.dump(city_list, open('city_list.json', 'w', encoding='utf-8'), ensure_ascii=False)```
08-urllib_ajax.py
```import urllib.request
import urllib.parse
"""
GET https://movie.douban.com/j/chart/top_list?type=24&interval_id=100%3A90&action=&start=0&limit=1 HTTP/1.1
Host: movie.douban.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Cookie: bid=cvRdirp_XjE
Upgrade-Insecure-Requests: 1
"""
url = "https://movie.douban.com/j/chart/top_list?"
query_string = {
"type": "24",
"interval_id": "100:90",
"action": "",
# ajax get
"start": "0",
"limit": "1"
}
fullurl = url + urllib.parse.urlencode(query_string)
# ajax post
form_data = {
"start": "0",
"limit": "1"
}
data = urllib.parse.urlencode(form_data).encode()
header = {
# "Host": "movie.douban.com",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
# "Cookie": "bid=cvRdirp_XjE",
# "Upgrade-Insecure-Requests": "1",
}
# ajax post
# request = urllib.request.Request(fullurl, data=data, headers=header)
# ajax get
request = urllib.request.Request(fullurl, headers=header)
# 上面两种方法都可行
reponse = urllib.request.urlopen(request)
print("code:{}\nurl:{}\n".format(reponse.getcode(), reponse.geturl()))
print("-"*20)
print(reponse.read()) # 在win平台默认gbk编码,输出的时候很麻烦
# print(reponse.read().decode()) # python3 08-urllib_ajax.py > douban.json linux平台可以做到,win不可以
```
14-环境变量代理.py
```import urllib.request
import os
# http请求
request = urllib.request.Request("http://www.baidu.com/")
# 1 构建一个代理处理器,参数是字典,不能为空, 可以为空字典
# 注意,如果你明确知道该代理是HTTP协议还是HTTPS协议,那么速度可以更快
# 实际上,代理一般不直接记录在程序里,通常通过倒入模块,或者设置环境变量
# 用处是将需要授权的代理账户和密码记录在环境变量里,这样就不怕别人使用你的代理
# 获取环境变量
proxy = "{}:{}".format(
os.environ.get("proxyhost"), os.environ.get("proxyport")
)
http_proxy_handle = urllib.request.ProxyHandler({
"http": "http://" + proxy,
})
# !!关键变化:不指定 proxies ,使用系统变量里设置的代理变量 <protocol>_proxy
# http_proxy=http://112.91.218.21:9000
# export http_proxy
null_proxy_handle = urllib.request.ProxyHandler()
# 代理开关
# 切换到False 使用环境变量,True 程序设置代理
proxy_swith = True
# 注意区分
if proxy_swith:
opener = urllib.request.build_opener(http_proxy_handle)
else:
opener = urllib.request.build_opener(null_proxy_handle)
# 2 tip:构建一个全局opener,之后所有请求都可以用urlopen()方式去发送,也附带handle的功能
urllib.request.install_opener(opener)
# 3 响应请求
response = urllib.request.urlopen(request)
print(response.read())
# 有时候使用代理平台返回的编码格式是gbk,表示是从win发来的,可以进行编码
# print(response.read().decode("gbk"))
print(response.getcode())
```
22-爬糗事.py
```"""
第一步 分析网页
url = 'https://www.qiushibaike.com/text/page/{}/'.format(page)
# 作为根节点
article_box = $x('//div[contains(@id, "qiushi_tag_")]')
# username
./div[1]/a[2]/h2
# content
.//div[@class="content"]/span[1]
# 点赞
.//div[@class="stats"]/span[1]//i
# 评论
.//div[@class="stats"]/span[2]//i
"""
import json
import requests
from lxml import etree
def spider_qiushi(page):
"""
page: 页码
作用:解析网页,并将解析内容写入到qiushi.json
"""
url = 'https://www.qiushibaike.com/text/page/{}/'.format(page)
ua_header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"
}
response = requests.get(url, headers=ua_header)
print("status_code:%d" % response.status_code)
html = response.text
xml = etree.HTML(html)
article_box = xml.xpath('//div[contains(@id, "qiushi_tag_")]')
item = {}
for article in article_box:
username = article.xpath('./div[1]/a[2]/h2')[0].text.strip()
content = article.xpath('.//div[@class="content"]/span[1]')[0].text.strip()
goodpoint = article.xpath('.//div[@class="stats"]/span[1]//i')[0].text.strip()
comment = article.xpath('.//div[@class="stats"]/span[2]//i')[0].text.strip()
item = {
'username': username,
'content': content,
'goodpoint': goodpoint,
"comment": comment
}
with open('qiushi.json', 'a') as fw:
fw.write(
json.dumps(item, ensure_ascii=False) + '\n'
)
print('ok')
def main():
print('start work')
page = int(input('请输入页码:'))
spider_qiushi(page)
print('complete work')
if __name__ == "__main__":
main()```
15-web客户端验证.py
```import urllib.request
"""
目标:是那种以登陆就要求输入账号密码的IP,很少见
"""
# 下面的内容也可以写入到环境变量
username = "test"
password = "123456"
webserver = "192.168.1.104"
proxyserver = "192.168.1.104:8000"
# 1 构建一个密码管理对象, 可以用来保存和HTTP请求相关的授权账户信息
passwrod_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
# 2 添加账户信息,第一个 域 realm 如果没有指定就None, 后三个 站点IP, 账户和密码
passwrod_mgr.add_password(None, webserver, username, password)
# 3.1 基于HTTP基础验证类创建HTTPHandle
http_handle = urllib.request.HTTPBasicAuthHandler(passwrod_mgr)
# 3.2 基于代理基础验证类创建HTTPHandle, 授权代理处理器,不过一般用环境变量的方法,比较简单方便
proxy_handle = urllib.request.ProxyBasicAuthHandler(passwrod_mgr)
# 4 创建opener
opener = urllib.request.build_opener(http_handle)
# opener 可以有多个HTTPHandle
# def build_opener(*handlers) *handlers 不定长参数,可以有多个HTTPHandle
# opener = urllib.request.build_opener(http_handle, proxy_handle)
# 5 请求响应
request = urllib.request.Request("http://{}/".format(webserver))
response = opener.open(request)
print(response.read())```
itcastspider.py
```import scrapy
from mySpider.items import ItcastItem
import locale
class ItcastSpider(scrapy.Spider):
name = 'itcast' # 爬虫名,启动爬虫时使用的,scrapy crawl itcast
# 网站域名,允许爬取的范围
allowed_domains = ["http://www.itcast.cn/"]
# 从那个网址开始爬取
start_urls = ['http://www.itcast.cn/channel/teacher.shtml#ajavaee']
def parse(self, response):
"""
处理响应内容
"""
# for test
# 注意 wb 以二进制方式写入!!
# with open('itcast.html', 'wb') as fw:
# fw.write(response.body)
# teacher_info = []
teacher_list = response.xpath('//div[@class="li_txt"]')
for teacher in teacher_list:
name = teacher.xpath('./h3/text()').extract() # 提取所有list(), extract_first 提取第一个str
title = teacher.xpath('./h4/text()').extract()
info = teacher.xpath('./p/text()').extract()
item = ItcastItem()
# for json Unicode 编码 全平台通用
item['name'] = name[0]
item['title'] = title[0]
item['info'] = info[0]
yield item
# for csv
# cur_code = locale.getpreferredencoding(False) # 获取当前用户可能使用的编码 'UTF-8'
# item['name'] = name[0].encode(cur_code)
# item['title'] = title[0].encode(cur_code)
# item['info'] = info[0].encode(cur_code)
# teacher_info.append(item)
# return teacher_info
# 返回到外面 可以通过 scrapy crawl itcast -o <filename>
# filename 可以为 .json .csv 等
# 输出.json 为Unicode www.json.cn 可以看到转换后的结果
# csv 可以通过 Excel 打开
```
00-headless_mode_firefox.py
```from selenium.webdriver import Firefox
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support import expected_conditions as expected
from selenium.webdriver.support.wait import WebDriverWait
if __name__ == "__main__":
options = Options()
options.headless = True
driver = Firefox(executable_path=r"l:\code\scrapy\Selenium\geckodriver.exe", options=options)
wait = WebDriverWait(driver, timeout=10)
driver.get('https://www.baidu.com')
wait.until(expected.visibility_of_element_located((By.ID, 'kw'))).send_keys('headless firefox' + Keys.ENTER)
driver.save_screenshot("headless_firefox.png")
# wait.until(expected.visibility_of_element_located((By.CSS_SELECTOR, '#3>h3>a'))).click()
print(driver.current_url)
driver.quit()
```
10-自定义HTTP处理器.py
```import urllib.request
# 1 构建HTTPHandle处理http请求
http_handle = urllib.request.HTTPHandler()
# 2 构建自定义opener
opener = urllib.request.build_opener(http_handle)
request = urllib.request.Request("http://www.baidu.com/")
# 3 用自定义opener处理http请求
response = opener.open(request)
# 4 输出结果
print(response.read().decode())
```
03-douyu.py
```#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import unittest
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.common.keys import Keys
class TestDouyu(unittest.TestCase):
def setUp(self):
# 初始化方法
self.driver = webdriver.PhantomJS(executable_path=r'L:\code\scrapy\Selenium\phantomjs.exe')
pass
def testDouyu(self):
self.driver.get('https://www.douyu.com/directory/all')
while True:
# 通过解析源码来获得数据,不同的角度,这样做的目的就是为了遍历网页
# 因为过去用HttpClient获取动态页面是没有加载到动态数据的,所以要用浏览器
markup = self.driver.page_source
soup = BeautifulSoup(markup, "html.parser") # 其实应该用lxml,但是我目前没安装,所以用Python标准库
room_name_list = soup.find_all('h3', attrs={'class': 'DyListCover-intro'})
room_viewer_list = soup.find_all('span', attrs={'class': 'DyListCover-hot'})
for room_name, room_viewer in zip(room_name_list, room_viewer_list):
print('room_name: {}, room_viewer:{}'.format(room_name.get_text().strip(), room_viewer.get_text().strip()))
if self.driver.page_source.find('dy-Pagination-disabled dy-Pagination-next') != -1:
break
self.driver.find_element_by_class_name('dy-Pagination-next').click()
print('Next Page')
pass
def tearDown(self):
self.driver.quit()
pass
if __name__ == '__main__':
unittest.main()
```
09-忽略ssl警告.py
```import urllib.request
import urllib.parse
import ssl
url = "https://www.baidu.com/"
ua_header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"
}
# 忽略未认证SSL警告
# 一般都可以用HTTP发,但有些类是交易,金融网站就比较严格
context = ssl._create_unverified_context()
request = urllib.request.Request(url, headers=ua_header)
response = urllib.request.urlopen(request, context=context)
print(response.read().decode())
```
06-贴吧搜索.py
```import urllib.request
import urllib.parse
import time
def load_page(url, filename):
"""
作用:根据url发送请求,获取服务器响应文件
url: 要爬取的地址
filename: 文件名
return: html: str
"""
UA_HEADER = {
"User-Agent": "Mozilla/5.0 \
(Windows NT 10.0; Win64; x64; rv:66.0) \
Gecko/20100101 Firefox/66.0"
}
request = urllib.request.Request(url, headers=UA_HEADER)
response = urllib.request.urlopen(request)
# print("code: {}\n\n\n url: {}\n\nhtml:{}".format(
# response.getcode(), response.geturl(), response.read()))
ret = response.read().decode("utf-8")
# print(ret[:3000])
return ret
def write_page(html, filename):
"""
作用:将html内容写入到本地
html:服务器相应文件内容
"""
print('正在保存{}'.format(filename))
# UnicodeEncodeError:
# 'gbk' codec can't encode character '\xba' in position 100787:
# illegal multibyte sequence
# 解决办法,在写入的时候指定编码
# encoding使用平台默认编码,可以用locale.getpreferredencoding() -> 'cp936' 查看 win的坑
with open(filename, "w", encoding="utf-8") as f:
f.write(html)
return True
def tieba_spider(url, begin_page, end_page):
"""
作用: 贴吧爬虫调度器,负责组合处理每个页面的url
url: 贴吧url前部分
begin_page: 起始页
end_page: 结束页面
"""
for page in range(begin_page, end_page+1):
filename = "第" + str(page) + "页.html"
pn = (page - 1) * 50
fullurl = url + "&pn=" + str(pn)
# print(fullurl)
print("正在下载{}".format(filename))
start = time.time()
html = load_page(fullurl, filename)
if write_page(html, filename):
end = time.time()
print("{}下载完成,用时{:.2f}秒".format(filename, end-start))
print("-"*10)
if __name__ == "__main__":
keyword = input("请输入要检索的贴吧:")
while True:
begin_page = int(input("请输入开始页码:"))
end_page = int(input("请输入结束页码:"))
if begin_page <= end_page:
break
else:
print("请输入正确的页码范围,如(1,2)")
kw = {'kw': keyword}
query = urllib.parse.urlencode(kw)
url = "https://tieba.baidu.com/f?" + query
tieba_spider(url, begin_page, end_page)
print("谢谢使用")
```
03-urllib_request_useragentlist.py
```import urllib.request
import random
ualist_header = [
"Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101",
"Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11",
"Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"
]
url = "http://www.baidu.com/"
user_agent = random.choice(ualist_header)
# 网址最后的斜杠表示根目录,不要漏掉`
request = urllib.request.Request(url)
request.add_header("User-Agent", user_agent)
# 记住第一个字符大写,之后小写!!
print(request.get_header('User-agent'))
```
23-多线程爬糗事.py
```from queue import Queue
import threading
import json
from lxml import etree
import requests
import time
class SpiderWorker(threading.Thread):
def __init__(self, name, page_queue, parse_queue):
super(SpiderWorker, self).__init__(name=name)
self.page_queue = page_queue
self.parse_queue = parse_queue
def run(self):
while True:
page = self.page_queue.get()
if page is None:
break
print("{}爬取页码-{}-开始".format(self.name, page))
html = self.spider_qiushi(page)
print("{}爬取页码-{}-完成".format(self.name, page))
# 将爬取的HTML源码放入处理队列
self.parse_queue.put((html, page))
# 本次任务完成
self.page_queue.task_done()
@staticmethod
def spider_qiushi(page):
"""
:param page: 指定爬取页码
:return html: 返回爬取的html(string)
"""
url = 'https://www.qiushibaike.com/text/page/{}/'.format(page)
ua_header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"
}
response = requests.get(url, headers=ua_header)
time.sleep(1) # 下载延时,使得每个请求发出去有短暂的间隔
print("status_code:%d" % response.status_code)
html = response.text
return html
class ParseWorker(threading.Thread):
def __init__(self, name, data_queue):
super(ParseWorker, self).__init__(name=name)
self.q = data_queue
def run(self) -> None:
while True:
item = self.q.get()
if item is None:
break
html, page = item
print("{}处理页码-{}-开始".format(self.name, page))
self.parse_html(html, page)
print("{}处理页码-{}-结束".format(self.name, page))
# 本次任务完成
self.q.task_done()
@staticmethod
def parse_html(html, page):
xml = etree.HTML(html)
article_box = xml.xpath('//div[contains(@id, "qiushi_tag_")]')
def if_exist(some_thing):
if some_thing:
return some_thing[0].text.strip()
else:
return None
for article in article_box:
try:
username = if_exist(article.xpath('./div[@class="author clearfix"]//h2'))
content = if_exist(article.xpath('.//div[@class="content"]/span[1]'))
goodpoint = if_exist(article.xpath('.//div[@class="stats"]/span[1]//i'))
comment = if_exist(article.xpath('.//div[@class="stats"]/span[2]//i'))
item = {
'username': username,
'content': content,
'goodpoint': goodpoint,
"comment": comment
}
except Exception as e:
print('Error:{}'.format(e))
item = {}
with open('qiushi_page{}.json'.format(page), 'a') as fw:
fw.write(
json.dumps(item, ensure_ascii=False) + '\n'
)
class MyThreadQueue:
def __init__(self, get_queue, thread_num, worker, my_source, other_q=None):
self.q = get_queue # 线程取任务队列
self.num_worker_threads = thread_num # 开启线程数
self.worker = worker # 线程实例
self.source = my_source # 爬取范围
self.other_q = other_q # 默认单队列
self.threads = []
def start_work(self):
# 开启页面爬虫 单队列
threads_name = ['线程{}号'.format(i) for i in range(self.num_worker_threads)]
if self.other_q is None:
# 2 处理网页
for i in range(self.num_worker_threads):
t = self.worker(threads_name[i], self.q)
t.start()
self.threads.append(t)
else:
# 1 爬取网页 双队列
for i in range(self.num_worker_threads):
t = self.worker(threads_name[i], self.q, self.other_q)
t.start()
self.threads.append(t)
# 初始队列需要手动投入任务
for item in self.source():
self.q.put(item)
def join_work(self):
# block until all tasks are done
# 堵塞直到队列为空,且爬虫全部结束任务
self.q.join()
# stop workers
for i in range(self.num_worker_threads):
self.q.put(None)
for t in self.threads:
t.join()
def source():
"""
:return: 爬取页码范围
"""
return range(1, 3)
def main():
page_queue = Queue(3) # 页码队列
data_queue = Queue(3) # 解析HTML队列
spider_page = MyThreadQueue(page_queue, 3, SpiderWorker, source, data_queue)
parse_html = MyThreadQueue(data_queue, 3, ParseWorker, source)
print('start work')
spider_page.start_work()
parse_html.start_work()
spider_page.join_work()
parse_html.join_work()
print('done')
if __name__ == "__main__":
main()
```
img2text.py
```try:
from PIL import Image
except ImportError:
import Image
import pytesseract
if __name__ == "__main__":
# If you don't have tesseract executable in your PATH, include the following:
pytesseract.pytesseract.tesseract_cmd = r'l:\etc\Tesseract-OCR\tesseract.exe'
# Example tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract'
# Simple image to string
# print(pytesseract.image_to_string(Image.open('test.png')))
# French text image to string
# print(pytesseract.image_to_string(Image.open('test-european.jpg'), lang='fra'))
# In order to bypass the image conversions of pytesseract, just use relative or absolute image path
# NOTE: In this case you should provide tesseract supported images or tesseract will return error
# print(pytesseract.image_to_string('test.png'))
# Batch processing with a single file containing the list of multiple image file paths
# print(pytesseract.image_to_string('images.txt'))
# Get bounding box estimates
# print(pytesseract.image_to_boxes(Image.open('test.png')))
# Get verbose data including boxes, confidences, line and page numbers
# print(pytesseract.image_to_data(Image.open('test.png')))
# Get information about orientation and script detection
# print(pytesseract.image_to_osd(Image.open('test.png')))
# Get a searchable PDF
# pdf = pytesseract.image_to_pdf_or_hocr('test.png', extension='pdf')
# Get HOCR output
# hocr = pytesseract.image_to_pdf_or_hocr('test.png', extension='hocr')
```
13-环境变量.py
```import os
# os是跟系统相关的
# system 是跟python相关的
"""
1 个人用户环境变量 vi ~/.bash_profile 或者 vi ~/.bashrc
设置代理变量
.bashrc
# 代理变量
proxyhost="112.91.218.21"
proxyport="9000"
export proxyhost
export proxyport
立刻应用
source ~/.bashrc
"""
host = os.environ.get("proxyhost")
port = os.environ.get("proxyport")
print("http://{}:{}".format(host, port))
proxies = os.environ.get("http_proxy")
print(proxies)
```
01-urllib_request_request.py
```import urllib.request
# 字典格式!!
ua_header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"
}
# 网址最后的斜杠表示根目录,不要漏掉`
request = urllib.request.Request("http://www.baidu.com/", headers=ua_header)
response = urllib.request.urlopen(url=request)
html = response.read()
# print(html)
print(response.getcode())
print(response.geturl())
print(response.info())
```
20-bs4模拟登录.py
```import requests
from bs4 import BeatifulSoup
def zhihu_login():
# 实例化session对象,可以保存cookie
sess = requests.session()
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
# get方法获取需要的cookie
html = sess.get('https://www.zhihu.com/signin', headers=headers)
# 防止跨站请求伪造,通过GET方法得到它,然后POST才能成功
_xrsf = sess.cookies.get('_xrsf')
print(_xrsf)
# post方法登录
# 输入验证码,现在验证码是点击登录后,再PUT方法生成的,不简单
```
b64转回图片.py
```import base64
import re
raw_img = """data:image/jpg;base64,R0lGODdhkAFYAIcAAPn5+VVVVenp6dfX14eHh5eXl6ioqGNjY3V1dcXFxWtra7q6urS0tHx8fMvL
y+Li4qKioouLi93d3ZGRkZubm9DQ0K6urgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAkAFYAEAI/wABCBxI
sKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjyBDihxJsqTJkyhTqlzJsqXLlzBjQhTgYIAA
AQYC6AxwYACAn0CDCh1KtKjRo0iTKl3KtKnTp1CjKhXQIIDVqwcAaAXgQEGAr18JABhLtqzZs2jT
ql3Ltq3bt3DPOiAQoG4AAQDyAhhQYIEAAIABGwgQgACAw4cFBFh8YACAx5AjS55MubJkAgEaCADA
GUCAz6BBDwBAurTp06gBEAgQIAGA17Bjy54te0CA27gLANjNu7fv38CDCx/ee0GA48gTAFjOvLlz
AAIKBJgegIAAANizawcQoHsABAkkJP8w0CCA+fPoAxwgMACA+/fw48uXjyCA/QAKHADYz7+/f4AA
BA4kWNDgQYQJFRoUIGHAAwAABgSgSJEBAIwZCQTgyFEAAAAECgAgSXJAhAAGBgAgQADAS5gxYyoI
UFMAAJw5cRoI0DOAggQAhA4VKiDA0QAEBAAAEMCpUwBRpU6lCoBAAKwHAGzlmiDA1wMAxI4lEMDs
AwBp1apNoCDAW7hx4R4QAADBgQYEDhAwIADAX8CBBQ8mDKBAAMQBFgBg3NgxAAcBJAeQAMCygAUK
AmxGQKBAggECAIwmXdr0aQAFAqwOsGABgQCxZctWgCDA7QACAOwGYCDAb+ACACRA0GD/AADkAAQM
GOBAQQDoBQgQMABBQYAACAQA4N7d+3fw4cWPJ1++vAQEAdSvB9DefXsBBQIEYADAvv0DAfTvNyAA
AEAAAgcOCGAwwAEACQIwXAAAQIIAEhcAABDgYgMAGjdqDODR4wAAIkcCCGAyAAQAKlUGaNmSAYCY
MmcCYBDgJoCcOgEwCOAzgAAAQoUKKBAgAIIEAgYgCOD0KVSnBAwAABDgagAAWgFECOB1AAAACwKQ
JQDg7FkBAdYGIDAAAFy4AgLQrdvAAYC8EAIEKCBgQIDACAQAKGyYQYDEARwAaOx4wAIBAAAsEADg
MgADATYPAOAZgAAFAUaTHg0BAAAB/wECNCAQ4HWABBEMHAhgOwGA3LoFAACwIADwAgsiBAhw4ECA
5AEOBGjuPEABAxAIJBAA4Dr27Nq3c+/u/Tt48BICkD9QoEAAAwDWHwjgPoAAAPIBEAhgP0ABAPr1
L4AAACAAgQUOFAhw8CAAAAgCNBQAYACCABMFALA4AEEAjRsDDADwESSAAQQClAxAAEDKlAQCtCQA
AGZMmQcC1AwAACfOBwF4BmAAAGhQoQAEGCCAIEBSpUkJIAgAIcEABAcCVK2qYEGCAgG4DgDwtUAA
sQkAlC0bAG2ACADYtgUgIEDcAAsA1LVrQAEEAQAC9FUwAEBgwQIIBDB8YAEAxYsVB/9wbABAZMkB
KAdgAAAzZgUBOHfubAAAgAEBSAcgAAB1atWqBSAI8BqCAAACBiwwwAACggC7ee8eAAB4cOHDiRc3
fhx5cuXCHxQI8Pz5AgDTqVefbiBA9gMDAHT3/h18dwEEAgQ4sMBAAPUKJiAIgGAAAPkGFgCwf9/+
gAD7GwDwDxCAQIECEBQIgDCAAgAMARQIADEigIkACAS4iDFjAAIFAnj0CCCkyJEkAQgoECBlgAMK
DgR4WWAAgJk0ARgIgLMAgJ07BwT4GQCAUAADEBQQgFSCgKUDCARQcCCA1AANDAC4ihXAgABcDwwA
ADZsWAIBygYAgBZAgQBs2yIAADf/LoQAdAMgAIA3r4MAfAsAALAAAYECBSIcCIAYcQIAjBs7HqAg
gOQAAgBYFtAggOYCAgB4FhAgdAAIAEqbPo06terVrFu7fg07tuzSAxIMAIA7t+7duBUECDABgHDh
AgoEOB7AAYDlzJkvCFAggPTpAKpbvw4ggPbt3Lt71z4AgPjx5MubN58gQAAECQQAeA8/PgABDQLY
FwAgv/79/Pv3B8ggwEACAgAcRJhQ4UKGAhwkSABA4kSKFSsmGABA48aNCQIUABBS5EiSIw0cCJDy
wIABCAg8ABBTQYAABgDcxJlT506ePX3+BBpU6FCiRY3iFABA6dKlBwI8hZoAwFSq/1WtXsWaVetW
rl2tDggQoAAAsmXNnkWbVu1atm3dvoUb1+2AAwHsHnAAQO9evn39/gUcWPBgwoUNH0acWPFixo0d
P4YcWfJkypUtX8acWfNmzp09fwYdWrSBAKVNBzAAQPVq1q1dv4YdW/Zs2rVt38adW/du3r19/wYe
XPhw3AIWHAiQPEACAM2bC4AOQPp06tWtX8eeHfuDAN27AwAfXvx48uXNn0cPQEAA9uwLAIAfX/58
+vXt38cPX0CAAwgMABwAYCDBggYHCkAQYGEABAYEAIgocWLEAQEuXhQAYCPHjh4/ggwpciTJkiZP
oiwpoECAlgEKCAAgcybNmgIcEP8IoHNnAAQDADAIIBQA0aJGiwZImlQBggBOnz5t4AAA1apWATgI
oHWrgQBevR4AIFYAgwMNAKBNC+ABgQBu38KFC2Au3boABAQIIAAA3759DRwIIFiBAACGDyNOLOBA
gMaNCQgAIHky5cqUBThIwKBBgM6eOxsAIFq0gACmAxAAoHo1awAJEBAoYCCBAAC2bwMQUIAAAgUB
fgc4gIBAgOIBGgBIrnx5cgEBnhNIIAAAAAECEiwYAGA79+7euw8IID4AAgDmz6NPr349+/bu38Nn
jyAA/QAHAuBvAGD//gIBACJYwOBAAIMHETgAsHChAAgBIEaUWACAgQAXBwAQgCD/QMcDAwYEEElA
AAAAAxAEULmSJcsCAWDGlMkgQM0BAHAG0LlTJ4IAP4EGDTAAQIIARwMAULp0qYEATwMsADCValWr
AbASALCVQQCvAQQAgBCAbNkDAdCmPcAAQFu3AALEjasAQF27AQYA0BuAL18AfwEXCDB4MAIAAggE
UKxYAADHjgcgCDCZsoIICQoE0BxAAADPnwEYCDC6QQDTAQwAUA0gQgDXCBYIADB7NoMAtw0A0A0g
QIADAwAEB+DgQIAABQAkV76ceXPnz6FHlz6d+YIA1w8IALCde3cADhoEED8eAQDzDgKkD3DAAAD3
AwLEb4AgQP0CAAAwCLA/AQAA/wADCAwgAIBBgw4UBFgYwEACBgYSJCAQ4ACBABgDMADAkWOAjwEQ
AAAgYEACAw0CqFzJcmUDAgFiBjgAoKbNmzhtIgjAMwADAECDAiAQIAABAEgBLAjAdAAAAAIOBJgq
AIBVqwGyIngAoCsAAQMSBBg7VgCAswAKBFgbAMIABAHiCgBAt64ABAHy6m1QwAGAv38LBEgAoHDh
BQESJwDAGIAABAEiGwBAuTJlBgEIKAgQoACAz6BDgx5gIAGA0w4SAFjNmjWDAAEICABAuzYAAQYC
6A5gAIDv38CDCx9OvLjx48YLBAhwIAGA59CfEwhA3QAAAAsCHDAAoLv37gYQIP8IQJ78gQgBDggA
YCCAewYAAAg4ECCAAQAADATYvwAAAIACAgwkWBCBgAITAiwMUADAw4cBJEoEUNHixYoGAmwE0FFA
AJABCgAgWdLkyZIEAqxMAMDlS5cODjAAUBPAgAA5CwDgCYBBAKAFAAgIUNRoAAMAlC5VaiDA0wAA
pApwkCDBAwAAFgTgigDAV7BfBSAIUDYBALRpCwRgG6AAALhxCwSgG0AAALx4GwTgGwDAX8B/HygI
UDjAAACJFS9OPABBAMgDAEweEMCyAgcANAMQEMCz5wIARI8mXdr0adSpVa9mTTqBAQQBBgCgXdv2
bQIBdBMA0Nv3b+C+ByAIUJz/wAAAyZUfCNA8AAEA0aVHbxDAOgEHDBoEQFDAwAABEAIUCFC+PAD0
6dWvfxDAfQAA8eXHD1C//gEA+fXv3y9AAcAAAgUaEADgIMKEAg4EaFhAAICIEh8cCGARAMaMGgEs
OBDgYwACAgCQLGmSZIEAKgswMGBggYMBMhNAiEAgAM6cOhVEOBDg5wAAQocCEEAgQAIASpcqhRAg
wAAAUqUKQBDgKtYFALZy7QqAQICwBgCQHdAgAFoIANauVRDg7YEFAObSrWv3Lt68evfy7ev3L+DA
gAUgCGD4wAAAih8cMDAAAAAEASYTMBDgMmYAmjdz7uz5M+jQokePLhDgtAAA/6pXs27tWvUAAgQS
AKht+zbu3Lp38+7t+zduAQ4KBChuvMAAAMqXAxgQ4HmAAgCmU69u/Tr27Nq3c+/u/Tv48OLFRwgQ
wAGA9OrXs2/v/j38+PLnv09QQACA/Pr38+/vHyAAgQMJFjR4EGFChQsZNnQocECAAAQEALB4EWNG
jRs5dvT4EWRIkSNJljR5EmVKlStZtnT5EmZMmTNp1rR5E2dOnTt59vT5E2hQoUOJFjV6FGlSpUuZ
NnX6FGpUqVOpshRgQEEArQEUAPA6gEAAsQEKADB7Fm1atWvZtnX7Fm5cuXPp1rV7F6/bBAcC9CWQ
QAAAwYIXEGiAQEGAAAYANP92/BhyZMmTKVe2fBlzZs2bLS9QEAB0BAEASJc2fRp1atWrWaMuQABA
bNmzade2fRt37tgLAihgIABAcOHDiRc3fhx5cuXLmS8vEAA6dAMAqFcHYCBA9gYAuHf3/h18ePHj
yZc3fx59evXdBxQIgICBAAALAtQ/kAAAAAYB+PNHABCAwIEECxo8iDAhwQQBGjoMACCixIkUK1q8
iDHjgAAcOyIQACCkyJEkS5o8iTIlAAkHArh0WQCAzJk0awIoECCnTgYAevr8CUBAgKEBEAgAgDSp
AAMKAjh9eoABgKlUq1q9elXCgQAHDAgAADas2LFky5o9izat2rICCAR4G6D/gAAAdOvaBSBggIEA
fPkeKJAAgGADAQIoAIA4sWLEBhowkAAgsuTJlCtTNhAgcwADAAQE+Aw6dAABAEqbPo0adYDVAQC4
fg07tmzYEgLYtm0AgO7dvHsPOBAggAIBAIobP448ufLiDwQAeA79+YMDAaoHSAAgu/bt3LkPYGBA
AIDx5MkLGAAhgPr16gkYSPBAAID59Ovbv48///wCAfoHAHhgAQCCBQ0eRJhQ4UKGDRsOaBBA4sQA
CBIAwJhR40YAAgIoABBS5AADBgKchABA5UqWKw0EgFlggIABCRgkSGDgQACePCMAABo06IEARYsq
eBBAqVIBAJw+hQpVQACq/1UTAMAKgEAArg8AfAX7lUCAAAUAnEWblkAAtgEaCAAAYECCAQDs3r3r
AEEAvggaQBggAMBgwoUNAxgQIcBixowPBDhQIIEAAJUtCwiQOcACAAISGABN4EAA0qVNGwCQWrVq
AQMEAIAdG0EA2gcA3L7tgEAA3gEKADAQQHiAAwGMHzeuIAEA5s0BCDAQoAGBAwEKQFAQQLt2BQEC
IFgAQPx48uXNn0efXv169uINBIAfYAAAAAIA3L/vIMD+BgAaABQAAEACAgEUOACgcOHCAQgCQGyg
YIAAAAAGBMhYQICBAAEOMAAgMgDJAAcAoEyZ0gGCAC4PDAAAQECAmjUZMP9wIAAAz54+HwQIGvQB
gKJGBQRIGkAAgKYCAkANAGAq1aoIAmA9YAAA165euxYIIBYAWQYGBgBIK2DBAAEA3sJ9+yCBAAB2
796NEGDv3gIA/gIObCAA4QAADiM2EGBxAAQCBigIIFlyAgCWLwsYIAAAZwACKhQ4EGD0aAUFGAwQ
AABAgQCuAxBoEGB2AQC2bSMIoPuAAQEAfjMIIDwAAQDGAQw4ECDAAADOATAYAGA69erWr2PPrn07
9+7WBxwIID7AgQQAzqMXEGD9egoAAAwIID9AAgAAEhAIQCCBAAAAACZQEIBgAAUCBARQGAAAAAEB
IAYQAKBAAIsJAGTUmHH/QQCPARgIECkAAIAAJwMQELBSAAADAWAGKACApoAAN3HmDACAZ0+eBgIE
DQCAaFGiCAIkTTpAAACnAwY4mNDAwAAAVwE4CLBVAACvAwKELQAAwIMAZw8sALBWAIUAb+EaADB3
bgC7AQgIALB3r4AABxwAABCAcAADABAnZhCAcQACACADWBCAcgABADBnHqAgQOcBAEADkKAgQOkB
AFCnBuAgQOsIBwIEOCAAQO0EAQJEEABggIIAv4EDJ5BgQAICAQIMALAcgAACAaAfKACAenXr17Fn
176de/ftAw4oCBAgwgIFAdAbALCefXv3ABIcCDA/AQABAAQA0L9fv4EA/wADCHSAIIBBAQAAEAgQ
gAAAAAkCSEwAoKJFAQgCaCQgAIDHjx4DiAxgAIBJkwFSpgTAsqVLlgFiEgAggAGDBwAGBNgZIAGA
nwAMKFgwAIDRo0cNBFiKQACAp1ABCAhAdQCAqwACaCUAoGuArwEKABg7tkGAswQAAHhQAAEBAgcC
yJ0b4EACAQYC6D0wgEGAvwYACB4MoECAwwgEAFjMuLGBAgAiR04QoLKBBAcCaN4cAMECAQBCiyYQ
oACCAKgJKDhAgECAAAggCABAuzZtAQFyA9jNm3cCBQECKAhwAMGBAMiTIwfAvLnz59CjS59OvTr1
ANgDIADAnQABBAHCh/8/UGAAgPMIAiAAAGBBAAIMEASYPwCAfQIBCDQIwD+AAIAABCgIEAACAAAD
Aiw0AMChwwIBJE48EAGBgQUMCgQIQCDAxwATAIwceSDASQIABARg2ZLlhAAxAwgAULOmggA5AwDg
2dMnAAFBAQAYMMBAAKRJAxw4QEAAAAEBpBYYMABCAKwBFADgCiHA1wAAxIq1EMAsAQBp1aYN0DZA
AwBx40IIUFcBAAIB9AYAMKBBAMCBBQ9GAMAwgQAEACxmXCDAYwMAJEtGEMAyAQACJAgA0BlAggAB
Ihw4AMD0adSpA6xmHcBAggEDJAgAACBBgQQJBgDg3dv3b+DBhQ8nXtz/+PEGAZQHKADA+XMDAaQT
EAAgwYEA2QMIANDd+/fuBg5ECFCegAAACQKsNwAAQAD4AQgAoK8gwP0CAg4E4C8AAEAAAgcuIBDg
YAAIABYuJBDgIQEAEidOnBDg4sUBADYCCODRI4CQIkeSFCkgAEoCAgCwbAkgAMwABADQZBDgpgIA
OgcgCOCTQIEEAhwQCGA0gAAASpcCGBDgaQABAKZSrcogANYFALZy3VogANgCAMaSBSAgANoAANay
BRDgbYAEABgoCGD3bgAGAwQA6Nv3QYDAgQUAKGz4sOEFARYjEAAAQAEFBgBQrgzAwYEAmgMUAOD5
M+jQokeTLm36NGrR/w8QBGhtAADs2LIfBKgdAAKA3Lp38waw4ECA4MIXCAhgPIACAMqVCwBQAUGA
AAYEAKgOoECA7AIAcO/OvcCEAOIDEABgHoCCAOrVA2jv/n17AQMIBKhv374AAPr38++vH+CAAAMJ
CABwEGHChAsOBHAIACIAAQQCVBQAAICABgE4HnAAAGTIkAFIliwJQQAAlQMOBHApAEBMmTETHAhw
8wEAnQwUBPD5UwAAoUIHKAhwNAAApUsNBHB6AEBUqVEHKAhwNQADAFu5dt0aAGwAAgDIAjAQAC3a
BADYGgjw9oAAAHPp1rV7F29evXv59p3bIEBgwQgEADB8GPHhAgEYB/8gAAByZMmTJSdwoCBA5gAJ
AAAQgCBA6AICAJQ2bVoAggCrCSQooIAAhAQAAAwIUCBA7twAePfmLSABgQEAiAN4EAB5AADLmQMY
EAA6dADTqVevniBAdu3aGxgA8B08eAcIApRnAAB9egMB2A8A8B7++wEB6Ne33yCBAAD7+fNPADCA
QAQDABg8iBBBgIUFADh0yCCARIkJAFi86CCAxgADAHj8KABBgAALAJgEYCCAypUrBQB4CTOmggA0
AywAgBNAgJ07AfgEIIBAgKEIABg9ijSp0qVMmzp9CjWqVKMOCiQAgDWr1q0MEAQIgKCAAABky5YV
gCCAWgUCALh9yyD/gNwGAgDYvWtXQIAABAL49QsgsODBgiEEOIwYgOLFABIEeAwZgOTJlCsnCBDg
wAAAnDt7BrAAQYAACgYAOI0a9YIArBkAeA07NuwBBhwAuI07N+4ECgIEQCAAgHABDQIYP6AggPID
BAoUINBAQYDp0xtECKBgAYDt3Lt77z4gQAMBAMqbB1AggPoACQC4fw//vYABAgDYZxAgf4ADAPr3
B7ggwMAADAAcRJhQ4UKGDR0+hBhR4kSKFR0KEABA48YAHT0CABkypIAGARAEQJkSAQCWLV2ynBBA
5swACwDcxJnzQYIBAHz+BBpU6FCiRBMEQBoBwFKmTZ0+dWogQAAE/wMAXMWaVetWrl29fgUbdquA
BQHMmm0wAMBaAQECHFgAQO5cunXt3sWbV+9evn39/gUc2O4DBQECPACQOLGABgEcPw5wQAAAygAE
JHgAQPNmzp09fwYdWvTo0AICnFYAQPVq1q1dqxYAQPZs2rVt38adW/du3rMfEChgwIACBAYMFBgg
AMBy5s2ZDwgQPfoAANWtX8eeXft27t29fwcfXvx48uEHBEAfQIEDAO3dv4cfX/58+vXt349PIEAA
AP39AwQgcCDBggYPIkyocCHDhg4fIlwQYGKABAAuYsyocSPHjh4/ggwpciTJkiZPokypciXLli5f
wkRpAADNmjZv4v/MqXMnz54+fwINKnQo0aJGjyJNqnQp06ZOn0KNKnUq1apWr2LNqnUr165ev4IN
K3Ys2bJmz6JNq3Yt27Zu38KNK3cu3bp27+LNq3cv375+/wIOLHgw4cKGD5sVsCBAAAILAECOLHky
5cqWL2POrHkz586eP4MOLXo06dKmT6NOzVnAgQCuXwcAIBuAgAIIChRIAGA3796+fwMPLnw48eLG
jyNPrnw58+bOewuIDmA69erWr2PPrn079+7ev4MPv11AAQUBAhQAACBCgPYBFCQAIH8+/fr27+PP
r38///7+AQIQOJBgQYMHESZUuJBhQ4cMIwSQOJHAAAAXByAIsJH/4wAAH0GGFDmSZEmTJ1GmVLmS
ZUuUCRQEkElgAACbN3Hm1LmTZ0+fP4EGFSp0wAEHAJAmVbqUaVOnT6FGlTp1aoIDAbBiPQCAK9cB
CAKEDQuAbFmzZ9GmVbuWbVu3b+HGlat2AIIAdxcA0LuXb1+/fwEHFvx3QADDEAAkVryYcWPHjyFH
BrAgQGUFAwBk1ryZc2fPn0GH3sxggQAAp1GnVq1awAABrwHElj2b9oIAt28PALCbN+8BCQQAED6c
eHHjx5EnV76ceXPnz6ETFwDhQIAABBoECHCggAAAAAgECIAgQIEBANCnV7+efXv379cHkD9/AAD7
9/Hn17+ff3///wAFBBg48EACAAgTKlzIsKHDhxARFghAMQCBAQAyatzIEUCCACBDKhAAoKTJkwAk
BFgZ4IAAADBjxhxQIIDNAgIA6NzJs6fPnwMCBFgAoKjRo0iTKl3KtKnTp1AFMGBggACAq1cXBNh6
wAGArwYCiF0AoCyABQHSBjAAoK3bt3Djyp1L922Au3jvGgDAt6/fv4D5PggwAIDhw4gTK15cIIDj
xxMASJ5MubLly5gza55sIIDnzwkAiB5NurQAAgFSpyYgAIDr17AFBJgdgIAAALgFLCiAIIDv38AX
ABhOvLjx48YFNAjAPMACANCjS59Ovbr169iza7deIID3AAcSAP8YT758eQMBAhgQAKB9+wDwAwCY
T7++/fv4898/ECAAAYAOAAwMUNDgQQEAFC5k2NBhAIgBAEykWNHiRYsEAmzc2ADAR5AhQwooUGAA
AJQpVa5k2dIlSwcHAswMoADATZw5deY0cCBAgAIAhA4lKjTA0aMHAixl2lQBAQoGFgwQAMDqVaxZ
tW5FEMCr1wMAxI4lW9bsWbRp1a5lS3ZAgwBxAxQQAMDuXbwADBw4EMDv378OAABIECBAAQCJFS9O
nCDAYwIDBkgQUNnBAggKAigQAMDzZ9CeBwQgTRrBgACpVa9ODcD1a9ivBQxIMCHAbdwBAOzm3Zt3
ggAAhA8fLqD/QADkAQoIANDc+XPoBQJMD0BAAgDs2bVv565dwIIAARQ0KDAAwHn0AgKsXw/A/Xv4
8eXLFyBggAECCgLs579fAcAFAgQAKGjQ4IICBhIIAODwIcSIEicKIBDgYoAEADZy7OjxI8iQIkeS
LLnxQYEAKgMgSADgJcyYMmEiCLAAwIAFBQIggACgQIAACgAQLWq0KIEASpcybarUAICoUqcaCGD1
KoQAWrUmAOD1K1iwAcaSLYsgQYC0AQCwbevWQIAACQDQrVtXQIC8eQcA6Ov3L+ABCAIQLoxgAIDE
ihczZnAggAIEBwJQrmw5QAEBADYDEBDgcwADAEaTBiBgQIEA/6pXq2YA4DVsAAIQBKhdu8ADAAAU
BOiNAADw4AAoEDAA4DiBAMqXE0AQ4PnzBACmU58uYMADAQIAcAfAIAD4AAUGCABg/jz69OrXs2/v
/r17BgcCIIBgAEGA/PkHAOjvH2ACAwwMBFgAAKGBAAkANGwoIAGCABMDFABwEWNGjAUCdBwAAGRI
AAIIBDBpUoEEACtZrgzw8iUBAAAC1KwJAGdOnTsBCAjwMwAAoUMNBDDKAEBSpQAQBHAKAGpUqQkC
VK2qoECDAAcCdCUAAIAAAGMNBDBLYIAAAGvZtnX7lq2ABAgC1CXwAEBevXsBDAjwN0ACAQYCFDZ8
2HADBgMEAP9w/Bhy5McEAlQOAACAAAcGDgTw/BlBgwCjAyQAIGBAgQCrVytIAAB2bNgFAhxQEAB3
bt26CwDw/Rt4cOHDiRc3fhw5gADLlw8A8By6AAMKAlRPAGBAAQEAAAigECDAhAEAyAMQAAC9BAMD
BABw/15AAPkHHhAwMABA/vwNAvQPADABgIEECRoIgDDAAAAMAzh0CCCixIkUBwS4GIABgI0cHwT4
GACASJEMApgkACClSpUCDgR4GSDBgwEJDCgosCCnAAAACgT4uQCA0KFEixo9SpRCgKVLEwB4CjXq
ggBUAwgAgBVrgQBcGQAAUOBAgAAHGAgAgDat2rVpCwR4Czf/rtwABAgEuEtAAIC9AAgE+PsXgQAA
AhAEQGDgAYDFiwUgCBAgAoDJAAQAACBAAIDNnDt7/gw6tOjRpEsDEHAggOoCCRAoaEAAgGwACxQE
IAAgt4MGAQIgGAAguHDhBAIYP268wQAACQI4XwBAQIDpAQwAEBAg+4EEAAQggMCAQQEEBg4EOH9e
QYAABgK4d38ggPwGAgYQAIAfP4MA/PsLAAhAIAABFQgEQBgAAQCGARwGMABA4sSJEAJcPLAAwEaO
HTsGABkAwMgIAQIgGABAAIEAAQoMEABAgIMFCAIcKDAAwE6eOw8EAApUAACiRAcAQAqAQACmAQA8
hUohwNSp/wgAFAiQVSsArl0NKGhAIEIDBQHMHgiQNm0CAG3dCiAQQC6BAwHsQgCQF8CAAH0POAAQ
WHAAwgEOAEAMgECAAAQAPAYwIEAAAwAsX8acWfNmzp09fwaN2UAA0qUDGACQWjWBAAEOBAhgYICC
ALUDGACQe4CCAL0JFAgQXHiABAAQBEAuAICABgGcFwCwIMB0AwCsWx+woEEA7t0DKCDQIECBAOUD
HAgQAIGCAAwCvA8AQH6BAPXt37ffAAIDAgcQAHwAIADBABAAIEyIsECAhgESAIgocSJFAQEuJgCg
8UGAjgoGAEgQYGSAAwgCoEyZEgGAli4DwAxwIAGAmjYDNP8AoDMAzwAIAAANaiAAUaICAABwcCAA
0wACAECNaiAA1QAGAGAFMEBBgK4CAIANC2BBgLIRAqA9MAAAWwAB3iIQgCBAgAgJHgwgEGBvAgB+
BwQIwAAAYcIJAiAOoAAA48aOH0OOLHky5cqWGScIoDnAgQcAPoMGYCAA6QMJAKAGEGB1AAIGAsAu
IAAAbdoMAuAOQEDAgAC+CwAA8CAA8QYAAARIHuABgObOATxoEGD6AQDWrwMIoD1AAQDevQcIHx4B
gPLlHygIECABgAcB3gOILz9+gPoBCADIr19AgQD+ASJAEKABgQMBDigIsJBhgAQAAFAIMBFARQAO
AmRcAAD/wIAAHwkIADASgIAAJ08eWACAJcsALwMUADCT5oAAAQwAEBCAZwAHAIAGZRCAaAADAJAi
TaAgAAEAT6E+JRCA6gAAVwEIQBCAawEDBQoYEAAAwIAAZwkEUBsAQNsBDQIESACArgMFARAQCLCX
b9+9CgwkEFwgQOEABAQAULyYcWPHjyFHljx5coIGATBnDiAAQGfPnhlEEACANOkFAVAfMCAAQGvX
rw8EkB1AQIEAtwcAAGAgQAAEAgAICDDcAADjxwEMCLA8QAEAz6E/DzA9gAEA168H0K5dAADv38ED
CDA+AADz5wEEUK8eQPv2CRAcILAAQH37AwgE0H8gQoQE/wAHCABAEECAgwYAKAQQoGEAAQAANAhA
kQCAixcXBNgYQACAjyANBBhJMoACAwIGHAgQAMEABwFiEgBAsyYAAwFyHhAAoKfPnwIICABAFMCC
AEgHAFg6oECAp1ADEHAAoKoABAEIEAjAtavXAAoEABhLdqyDAwECCADAFsCABAkWRAhAt65duwQE
ANjLt6/fv4ADCx5MuO8AAQASIwjAOACAx5AjR35gQEGAywEAAHCg4ACBAAYcABgNIEGA0wcgBFgd
AACAAQcCBDAAAECBALgHANjNe0GA3wESABhOHIADBwGSBzAAoHnzANChA5hOvTqABAGya9d+4ECA
7wEAiP8fT778eAQB0gdgAKC9ewAOAgRQAKA+AAEB8jMAwD+Af4ABFgAgSDDAwQAJAABIoCDAQ4gP
FSAYAADAAAQBNCIYUCDAxwQARI4UQCDASQQCAKxkyVJCAAYAZMpMEMBmAgADIhAgEMBnAAMAhA4V
CiEAgQBJAwgA0NSpAABRpU4FgABBAgBZtWqNECAAggEAAAhwAGECggBp0y4A0NbtW7hx5c6lW9fu
XAEB9AZIAMAvAAcNCjAwcCDAYQUGBAggEKAAAMgCAkymLAAAAAENAhyIEMBzgAQAABQIEKCBAAAC
AqxuAMD16wCxZc+mTSDA7QAGAOzeHcB3AAIAGgQgXtz/ePEFAJQrHxDAeYABAKRPp159OoIA2REk
GOBAAADwAAKMNwDAPAAFAdQLAADAwYEA8QHMny8hwH0CAgDs5w8gAMAAAgMAKFhQQYCEAQYsCOAw
AICIAh4kMEAgAMaMGQ8wAOBxQAAFAwCQJMkgAMoFAFauRBDgpQEAMmfKTBCgAYEAAQYA6Onzp08B
BwIEKDBAAICkSpUKQEBgAICoUqdGFeCggAAAWrdy7er1K9iwYseGLRDgLAIBAggoGCCAQYC4ARAI
AGAXQIMAAQwQCHBAAAABBAIEcADgMIIABQ4EaBwAAIAFASYnAADAQIDMDgBwBjAgAOjQAQwAKG0a
wAQC/wFWByAA4PVrBAFmTwBgG0GAAAcSAADwIADwAACGEw9g3DiA5MqXN0CgIAB0BQGmU68eQEEB
BgUCcA9wIICCAOIDGABgvkCA9AQAsGd/IAB8BADm058f4H4ACgD27xcQAGCAAAYABDAYoAAAAAIY
BHD40OEBBQEQJHggAACAAQECFADwESSCACMNADBpEkEAlQcMEDiAwIAAAAAGBAhwoIABADt59uwp
AEEAoQcaBDBqFEGAAAgaKAgQ4IABAFOpVrV6FWtWrVu5du0aAGzYAgDIAhiAIEDaBADYGgjwNkAB
AHPp1p3rAEGBAHsDGAAgIEBgBQAAKAhwOAAAxQIIBP9w3CBA5AACAFS2DGAAgQCbAxQA8PlzgQCj
CQAwffp0ggCrVwNw7bpAANkBBACwfRv3bQG7BTgI8FsBAwEAiBNfEAA5cgQCAAggEAA6AOkCCASw
vgBAdgADAnQP4ABAePEABAQwH2AAAPXrAUgAAGBAAPkFANS3X79AAP0EBADwDxCAQAAQAgQ4MACA
woUBGgZIACAiAAEBKlqsWGAAgI0PAnj0CCCkyJEjEwQ4GWAAgJUsWQoYsOBAgJkBCAgAgDOnzp08
e/r8CTSo0J8OAhhVIACA0qUDAjgNMABAgQBUAwwAgDUrVgEPBAwwECBABAQBAiwAIEBBgAAIBAAQ
ECD/7gEHAABACIC3AAAAAfoGWJAggoECDAAAKDAhgOIAEAA4dqwggGQEACpbvkwggGbNADoDCAAa
NIDRpEubJr0ggGoDAFq7bl0gwIEFAGoDOBAgwIEEAHonCAA8gIAIARAEOH5cAYDlzJcvCAA9gAAA
1KtXF4AggHYBALp7704ggHgDAMqbB3AggPoAANq7HxAgfoABAAw0aEAggH79APr7BwgAwIMDAQwG
eABA4UKGCwsEgGgAwMQEAQIQGABAo0YBCgJ8/CgAwEiSJU2eRJlS5UqWLVEyOBAgQAIANW3aTBBA
JwEBAHwuABBU6NABBQIcRXqggAEACw4EgCoAwFQD/woKCBhQIEAABQMAfE0QQCwFAwoQFDBQYIGA
AhMCvA0wAcBcAAIC3L0LQO9evn0fAABcIMDgAAMAHEacWDHiAI0DDAAQWbJkAQAsW4YQQPMAAJ0B
GAgQ2gEAAAkCnD5NQAAA1q1ZEwgQO0ACAgoQHAjAQAAAAAUC/GYAQPhw4QMUBEA+AMDy5QQCPH8+
AMB06g0CXA8gAMD27QUCfA8AQPx48QMQBEAfIAEA9u3dsycQQH4AAQDsJwiQP/8AAP0HAAwgMAAF
AAYPIkyocCHDhg4fQlToAEGAigcEAMiocSMABAE+NgAgciTJkiIHIAigMoACAQQCwAyAYACAmjUH
BP8IAEEAgJ49BSgIIBQA0aJEBRCYEGBpAAQAngIIIHXqAABWrw6AcCAA165evQIIK3Ys2bACCgRI
S2CAgAEG3hIwAGAuXQAB7gYwAGAvgAcKAgAGIBiAgQABDgwAoHixYgEMAkCOfIAAgMqWA2AOcAAA
586dDQQIHUAAAAACEARIrToAgNauDQSIHRsA7doLAuBuAACAAAEAfgNYEGD48AQAjiNPDmBBgOYB
EgCIDqBAgOoBCADIDkBBgO4EAIAPL348+fLmz6NPrz68AAYKAsCHXwAA/fr26xsIoD8AAQD+AQIQ
OJBgwQEBDiwwEIBhgAEAFgSQaEAAAIsXMQIwEID/owEAH0F+HBCgQACTAQ4AUKlSAIEALwMwADAz
QQCbNxFUALATgIAAP38CEDqUaFECAZAmVXpgAACnT506OBCA6gAAV68mCLDVAACvXgUAAFAAwYEA
Z9GmJZBAAAC3b90iCDC3AAC7d/E2CLAXAQC/ABwcCDB4MAMAhxEbCLA4AAMAjyFLOBAggAEAlxkE
0LyZ8wAAn0GHRhCANGkApwEYCLA6wAAArwEkCDBbwQAAt3Hn1r2bd2/fv4EHxy1gAYIAxwMYALCc
efPmDgJED1AAQHXr17FfF9AgQPcDCQCEB2AgQPkACACkV6/eQQD37+EHKDBgQYACAfDjB7Cff3//
/wABFAhAkAGAgwgBFAjAkCGAhxAjRhwQoKLFAAgWCADAsWNHAQFCBkAAoKRJAQQCqBQAoKVLlwsO
BJhJM8ACADhz6gQgAEGAnwsACB1KFICCAEgLCADwIIGFBQQCSA0wAIDVqwAMBAiAQACAr2ABEAgQ
IAGAs2cLBFjLNgACAQDiyp1LIIDdAwIA6HUQoO+BBQACA2AQoHAAAgASK17MuLHjx5AjS55MubIA
BAEyA9jMubNnAAIMKAhAmgGA06hPMwjAOgABALBjAxAQoHaABABy684toEGAAgGCBwdAvLhx4wMC
KFcOoLnz5gGiRz8AoLr169gJBNiOIAGA7+DDA/8YgCBAgAMGAKhfr35AgPcIAMifT1++AwQBDhgA
wL+/f4AABDIIUBCBAAADFARg2NDhw4cIIgSgOADARYwYBQDg2LHjggABBgAgWXJAAJQoEQgA0NLl
SwACAgRoIADATQQBdAZ4AMAngAEBhAYgIADAUaRJlS5l2tTpU6hRpU6lilSAggMBCAwQAMDrV7Be
GQQgewDAWbQCFARgawDAW7hwBwQ4EMDuXQB59e7NG8DvX78JBhg4EMDwYcQAFC9m3BgAAQICAEym
XFkAggABEBgA0NnzZwAQAoweAMD0adSpVa9OoCBAAAQDAMymPcDBbQEAdO/eLcD3gAQMCgyPQED/
AADkyZUvV37AAADo0aELCFC9AADs2bVv174gwPcACg4sAFAewIAA6QMIANDe/Xv48eXPp1/f/n38
+fXvnz/gAEAEAgAQJEggAEKEAgAwbNiwQAACASZSHADgIsaMAwJw7OiRI4EKAgAAqHAgAMoDAFay
bOnyZUsBCQwsEADgJs6cOQcE6BkAANCgQocSJbogAFIDAgAwber0KdSoUqdSrWoVqgAFAbZudQAA
QIEAARYAAODgwAIAateybev2Ldy4cufSrWv3Lt68AAQE6NuXAoDAggUnCBBgQoDEigMMAOD4MeTH
BQJQXgDgMubMmjdz7uz5c2YGAUY7AGD6NOrU/6pPCyAQQEECALJn065t+zbu3Lp387YtwACCAMID
KCggAABy5AUCMC8A4Dn06NKnU69u/Tr27Nq3c+/uXbqBAOIhAChf3kCA9OrVOwAggECA+AQA0K9v
/z7+/Pr38++/H6AABAEIAjB4EGFChQYFJBgAAGJEiRMpVrR4EWNGjREHOGCgQEEAkQEOEIggAEBK
lSsjBHAZgAEAmTNp1rR5E2dOnTt59vT5E2hQmgsCFABwFCmABAcCNHVKAEBUqVOpVrV6FWtWrVup
PggQQIEDAGPJljV7Fm1atWvZtnX7Fi7bCQHoBlAAAG9evXv59vX7F3BgwYMJFzZ8mDCDAIsXI9sA
8BhyZMmTKVe2fBlz5skLAgRIAAB0aNGjSZc2fRp1atWrWbdeTSBA7AAOANS2fRt3bt27eff2/Rt4
cOHDiQMXcCBA8gQAmDd3/hx6dOnTqVe3Hh1CgAIAuHf3/h18ePHjyZc3fx59+vQHAgQ4kABAfPnz
6de3fx9/fv37+ff3DxCAwIEECxo8iDChQAgFBAB4CDGixIkUK1q8iDGjxQcCAHj8CDKkyJEkS5o8
iTKlypUsARhAMACAzJk0a9q8iTOnzp08e/r8CTSo0KFEixo9ijSp0qVMmzqdGRAAOw==
"""
raw_header, raw_content = raw_img.split(',')
print(raw_header)
raw_header_list = re.split(r':|/|;', raw_header)
for _ in raw_header_list:
print(_)
with open('img.jpg', 'wb') as f:
f.write(base64.b64decode(raw_content))
print('ok')```
11-HTTP处理器支持debug.py
```import urllib.request
request = urllib.request.Request("http://www.baidu.com/")
# 1 构建HTTPHandle处理http请求
# dbbuglever 打开debug log 模式, 程序会执行的时候会打印收发包的信息,注释到 4 print
http_handle = urllib.request.HTTPHandler(debuglevel=1)
# 2 构建自定义opener
opener = urllib.request.build_opener(http_handle)
# 3 用自定义opener返回http响应
response = opener.open(request)
# 4 输出结果
# print(response.read().decode())
```
19-用xPath爬贴吧.py
```import urllib.request
import urllib.parse
import time
import re
from functools import wraps
from lxml import etree
def deco_http2xml(func):
@wraps(func)
def wrapper(url, filename):
# 获得html
origin_html = func(url, filename)
# 由于百度贴吧的页面被注释了,所以通过正则表达式预处理html
main_html = re.sub(
r'<!--|-->',
"", origin_html
)
# 解析成HTML DOM
main_xml = etree.HTML(main_html)
# 通过xpath提取帖子链接
main_links = list(map(
lambda x: 'https://tieba.baidu.com{}'.format(x),
main_xml.xpath('//div[@class="threadlist_title pull_left j_th_tit "]//a[@class="j_th_tit "]/@href')
))
# print("main_links:{}".format(main_links)) # for test
# 根据帖子链接进入详情页爬图片
sum_img_links = []
for mlink in main_links:
UA_HEADER = {
"User-Agent": "Mozilla/5.0 \
(Windows NT 10.0; Win64; x64; rv:66.0) \
Gecko/20100101 Firefox/66.0"
}
request = urllib.request.Request(mlink, headers=UA_HEADER)
detail_html = urllib.request.urlopen(request).read().decode()
detail_xml = etree.HTML(detail_html)
image_links = list(map(
lambda x: '<img src="{}">'.format(x),
detail_xml.xpath('//img[@changedsize="true"]/@src')
))
# print("image_links:{}".format(image_links)) # for test
sum_img_links.extend(image_links)
return '\n'.join(sum_img_links)
return wrapper
@deco_http2xml
def load_page(url, filename):
"""
作用:根据url发送请求,获取服务器响应文件
url: 要爬取的地址
filename: 文件名
return: html: str
"""
UA_HEADER = {
"User-Agent": "Mozilla/5.0 \
(Windows NT 10.0; Win64; x64; rv:66.0) \
Gecko/20100101 Firefox/66.0"
}
request = urllib.request.Request(url, headers=UA_HEADER)
response = urllib.request.urlopen(request)
# print("code: {}\n\n\n url: {}\n\nhtml:{}".format(
# response.getcode(), response.geturl(), response.read()))
ret = response.read().decode("utf-8")
# print(ret[:3000])
return ret
def write_page(html, filename):
"""
作用:将html内容写入到本地
html:服务器相应文件内容
"""
print('正在保存{}'.format(filename))
# UnicodeEncodeError:
# 'gbk' codec can't encode character '\xba' in position 100787:
# illegal multibyte sequence
# 解决办法,在写入的时候指定编码
# encoding使用平台默认编码,可以用locale.getpreferredencoding() -> 'cp936' 查看 win的坑
with open(filename, "w", encoding="utf-8") as f:
f.write(html)
return True
def tieba_spider(url, begin_page, end_page):
"""
作用: 贴吧爬虫调度器,负责组合处理每个页面的url
url: 贴吧url前部分
begin_page: 起始页
end_page: 结束页面
"""
for page in range(begin_page, end_page+1):
filename = "第" + str(page) + "页.html"
pn = (page - 1) * 50
fullurl = url + "&pn=" + str(pn)
# print(fullurl)
print("正在下载{}".format(filename))
start = time.time()
html = load_page(fullurl, filename)
if write_page(html, filename):
end = time.time()
print("{}下载完成,用时{:.2f}秒".format(filename, end-start))
print("-"*10)
if __name__ == "__main__":
# keyword = input("请输入要检索的贴吧:")
# while True:
# begin_page = int(input("请输入开始页码:"))
# end_page = int(input("请输入结束页码:"))
# if begin_page <= end_page:
# break
# else:
# print("请输入正确的页码范围,如(1,2)")
keyword = '美女'
begin_page = 1
end_page = 1
kw = {'kw': keyword}
query = urllib.parse.urlencode(kw)
url = "https://tieba.baidu.com/f?" + query
tieba_spider(url, begin_page, end_page)
print("谢谢使用")
```
04-urllib_parse_urlencode.py
```import urllib.parse
wd = {"wd": "中文"}
# 该方法用于GET方法查询字符串的产生, 转码
result = urllib.parse.urlencode(wd)
print(result)
# 解码 urllib.parse.unquote()
org = urllib.parse.unquote(result)
print(org)
```
02-web_login.py
```#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# 导入webdriver API对象,可以调用浏览器和操作页面
from selenium import webdriver
# 导入Keys, 可以使用操作键盘、标签和鼠标
from selenium.webdriver.common.keys import Keys
# options = webdriver.FirefoxOptions()
# options.headless = True
# firefox = webdriver.Firefox(executable_path=r'L:\code\scrapy\Selenium\geckodriver.exe', options=options)
# url = 'https://bbs.level-plus.net/'
# firefox.get(url)
driver = webdriver.PhantomJS(executable_path=r"L:\code\scrapy\Selenium\phantomjs.exe")
driver.get('https://bbs.level-plus.net/')
driver.save_screenshot('soul_plus.png') # 能截取整个网页,比Firefox好
# login before
driver.find_element_by_name('pwuser').send_keys('xxx')
driver.find_element_by_name('pwpwd').send_keys('xxx')
driver.save_screenshot('login_before.png')
# login after
driver.find_element_by_class_name('btn').click()
driver.save_screenshot('login_after.png')
```
02-urllib_request_urlopend.py
```import urllib.request
request = urllib.request.urlopen(url="http://www.baidu.com/")
html = request.read()
print(html)
```
|
871301458/okhttpdemo
|
871301458/okhttpdemo
SimpleCallback.java
```package com.example.okhttpdemo.second;
import android.content.Context;
import java.io.IOException;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by wuyin on 2016/5/20.
*/
public abstract class SimpleCallback<T> extends BaseCallback<T> {
protected Context mContext;
public SimpleCallback(Context context){
mContext = context;
}
@Override
public void onBeforeRequest(Request request) {
}
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) {
}
}
```
SpotsCallBack.java
```package com.example.okhttpdemo.second;
import android.content.Context;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;
import dmax.dialog.SpotsDialog;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by wuyin on 2016/5/20.
*/
public abstract class SpotsCallBack<T> extends SimpleCallback {
private SpotsDialog mDialog;
public SpotsCallBack(Context context){
super(context);
initSpotsDialog();
}
private void initSpotsDialog(){
mDialog = new SpotsDialog(mContext,"拼命加载中...");
}
public void showDialog(){
mDialog.show();
}
public void dismissDialog(){
mDialog.dismiss();
}
public void setLoadMessage(int resId){
mDialog.setMessage(mContext.getString(resId));
}
@Override
public void onBeforeRequest(Request request) {
showDialog();
}
@Override
public void onResponse(Response response) {
SystemClock.sleep(1000);
dismissDialog();
}
}
```
OkHttpHelper.java
```package com.example.okhttpdemo.second;
import android.os.Handler;
import android.os.Looper;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by wuyin on 2016/5/20.
*/
public class OkHttpHelper {
private Gson mGson; //解析对象 begin array
private Handler mHandler; //请求数据成功后返回到主线程
//okhttp实例
private static OkHttpClient okHttpHelper;
//私有构造方法
private OkHttpHelper() {
mGson = new Gson();
okHttpHelper = new OkHttpClient();
//设置请求超时
okHttpHelper.newBuilder().connectTimeout(10, TimeUnit.SECONDS);
okHttpHelper.newBuilder().readTimeout(10, TimeUnit.SECONDS);
okHttpHelper.newBuilder().writeTimeout(10, TimeUnit.SECONDS);
mHandler = new Handler(Looper.getMainLooper());
}
//获取实例
public static OkHttpHelper getInstance() {
return new OkHttpHelper();
}
public void get(String url, BaseCallback callback) {
Request request = buildRequest(url, null, HttpMethodType.GET);
doRequest(request, callback);
}
public void post(String url, Map<String, String> params, BaseCallback callback) {
Request request = buildRequest(url, params, HttpMethodType.POST);
doRequest(request, callback);
}
/**
* 请求的方法
*
* @param request
*/
public void doRequest(final Request request, final BaseCallback callback) {
okHttpHelper.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.onFailure(request, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String resultStr = response.body().string();
if (callback.mType == String.class) {
callbackSuccess(callback, response, resultStr);
} else {
Object object = mGson.fromJson(resultStr, callback.mType);
try {
callbackSuccess(callback, response, object);
} catch (JsonParseException e) {
callbackError(callback, response, e);
}
}
} else {
callbackError(callback, response, null);
}
}
});
}
private Request buildRequest(String url, Map<String, String> params, HttpMethodType methodType) {
Request.Builder builder = new Request.Builder();
builder.url(url);
if (methodType == HttpMethodType.GET) {
builder.get();
} else if (methodType == HttpMethodType.POST) {
RequestBody body = buildFormData(params);
builder.post(body);
}
return builder.build();
}
/**
* 构建参数body实体
*
* @param params
* @return
*/
private RequestBody buildFormData(Map<String, String> params) {
FormBody.Builder builder = new FormBody.Builder();
if (params != null) {
/**
* 在这对添加的参数进行遍历,map遍历有四种方式,如果想要了解的可以网上查找
*/
for (Map.Entry<String, String> map : params.entrySet()) {
String key = map.getKey().toString();
String value = null;
/**
* 判断值是否是空的
*/
if (map.getValue() == null) {
value = "";
} else {
value = map.getValue();
}
/**
* 把key和value添加到formbody中
*/
builder.add(key, value);
}
}
return builder.build();
}
private void callbackSuccess(final BaseCallback callback, final Response response, final Object object) {
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onSuccess(response, object);
}
});
}
private void callbackError(final BaseCallback callback, final Response response, final Exception e) {
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onError(response, response.code(), e);
}
});
}
/**
* 请求方式,在这里只写get和post
*/
enum HttpMethodType {
GET, POST
}
}
```
README.md
```# okhttpdemo
###okhttp的简单介绍和简单的封装:

###使用方法:
一、如果是使用的first里面封装好的okhttp请求,那么就需要你自己去封装解析数据了。方法如下
```
OkHttpManager.getAsync(Contants.ASYNC_URL, new OkHttpManager.DataCallBack() {
@Override
public void requestFailure(Request request, IOException e) {
}
@Override
public void requestSuccess(String result) throws Exception {
//在这个地方返回的是请求的数据
// tvtext.setText(result);
}
});
```
二、如果是使用的second里面封装好的okhttp请求,那么这个时候就不需要在去自己解析了,
直接传入javabean,返回的结果就是已经封装好的,事例代码如下:
```
mHttpHelper.get(url, new SpotsCallBack<List<T>>(this) {
@Override
public void onSuccess(Response response, Object o) {
List<T> t = (List<t>) o; //这个o就是返回的数据集合,T就是你封装好的javabean
}
@Override
public void onError(Response response, int code, Exception e) {
}
});
```
而且第二种还有一个请求的dialog哈,是不是很简单的。```
ItemBean.java
```package com.example.okhttpdemo.first;
/**
* Created by 若兰 on 2016/1/27.
* 一个懂得了编程乐趣的小白,希望自己
* 能够在这个道路上走的很远,也希望自己学习到的
* 知识可以帮助更多的人,分享就是学习的一种乐趣
* QQ:1069584784
* csdn:http://blog.csdn.net/wuyinlei
*/
public class ItemBean {
private String name;
private String method;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
}
```
SecondActivity.java
```package com.example.okhttpdemo.second;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.okhttpdemo.Contants;
import com.example.okhttpdemo.R;
import java.io.IOException;
import java.util.List;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;
public class SecondActivity extends AppCompatActivity {
@butterknife.Bind(R.id.user_id)
TextView mUserId;
@butterknife.Bind(R.id.user_name)
TextView mUserName;
@butterknife.Bind(R.id.user_blog)
TextView mUserBlog;
@butterknife.Bind(R.id.user_email)
TextView mUserEmail;
@butterknife.Bind(R.id.btnQuery)
Button mBtnQuery;
private OkHttpHelper mHttpHelper = OkHttpHelper.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
butterknife.ButterKnife.bind(this);
}
User mUser = null;
@OnClick(R.id.btnQuery)
public void btnQuery(){
mHttpHelper.get(Contants.JACK_URL, new BaseCallback<List<User>>() {
@Override
public void onRequestBefore(Request request) {
}
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onSuccess(Response response, List<User> users) {
mUser = users.get(0);
updateUi(mUser);
}
@Override
public void onError(Response response, int code, Exception e) {
Toast.makeText(SecondActivity.this, "错误", Toast.LENGTH_SHORT).show();
}
});
}
public void updateUi(User mUser){
mUserId.setText("ID:" + mUser.getId());
mUserName.setText("名字:" + mUser.getName());
mUserBlog.setText("博客地址:"+mUser.getBlog());
mUserEmail.setText("邮箱:" +mUser.getEmail());
}
}
```
Contants.java
```package com.example.okhttpdemo;
/**
* Created by 若兰 on 2016/1/16.
* 一个懂得了编程乐趣的小白,希望自己
* 能够在这个道路上走的很远,也希望自己学习到的
* 知识可以帮助更多的人,分享就是学习的一种乐趣
* QQ:1069584784
* csdn:http://blog.csdn.net/wuyinlei
*/
public class Contants {
/**
* 本机地址
*/
public static final String BASE_URL = "http://192.168.1.108:8080/";
/**
* 同步请求
*/
public static final String SYNC_URL = BASE_URL + "test.json";
/**
* 异步请求
*/
public static final String ASYNC_URL = BASE_URL + "test1.json";
/**
* POST提交
*/
public static final String POST_URL = BASE_URL + "test2.json";
public static final String JACK_URL = BASE_URL+"jack.json";
}
```
|
877927262/shark-h5-master
|
877927262/shark-h5-master
index.js
```'use strict';
import React, { Component } from "react";
import { browserHistory } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import _ from '../../../util';
import { promotionIncomeStatusEnum } from "../../../enum";
const {
Cells,
Cell,
CellHeader,
CellBody,
CellFooter,
Article,
Button
} = WeUI;
@inject("Promotion") @observer
export default class Incomepage extends Component {
constructor(props) {
super(props);
this.promotion = this.props.Promotion;
}
componentDidMount() {
this.promotion.initWechatShare();
}
render() {
const { currentPromotionUser, processWithdrawAction } = this.promotion;
const promotionInfo = _.get(currentPromotionUser, 'promotionInfo', null);
const income = _.get(promotionInfo, 'income', {}),
incomeSum = (_.get(promotionInfo, 'incomeSum', 0) / 100).toFixed(0);
const reservedIncome = (_.get(income, promotionIncomeStatusEnum.RESERVED.key, 0) / 100),
availableIncome = (_.get(income, promotionIncomeStatusEnum.AVAILABLE.key, 0) / 100);
return (
<div className="promotion-page income-page w-full">
<header className="page-header w-full bar bar-nav">
<a className="icon icon-left pull-left p-l-none p-r-none" onClick={() => browserHistory.replace('/promotion/home')} />
<span className="title">我 的 收 益</span>
</header>
<main className="income-page-main">
<div className="income-page-main-profit">
<div className="profit text-center p-t-xl p-b-none p-l-none p-r-none">
<span className="profit-number">{(reservedIncome + availableIncome).toFixed(0)}</span>
<span className="profit-balance">收益余额</span>
</div>
<Button className="income-page-main-recored text-center m-b" type="default" size="small" onClick={() => browserHistory.push('/promotion/incomes')}>查看记录</Button>
</div>
<Cells className="income-page-main-list m-t-none">
<Cell className="income-main-list p-md">
<CellHeader>在路上</CellHeader>
<CellBody/>
<CellFooter className="list-road-number">{reservedIncome.toFixed(0)}</CellFooter>
</Cell>
<Cell className="income-main-list p-md">
<CellHeader>可提现</CellHeader>
<CellBody/>
<CellFooter className="list-withdraw-number" >{availableIncome.toFixed(0)}</CellFooter>
</Cell>
<Cell className="income-main-list p-md">
<CellHeader>已提现</CellHeader>
<CellBody/>
<CellFooter>{(_.get(income, promotionIncomeStatusEnum.COINED.key, 0) / 100).toFixed(0)}</CellFooter>
</Cell>
<Cell className="income-main-list p-md">
<CellHeader>收益总额</CellHeader>
<CellBody/>
<CellFooter>{incomeSum}</CellFooter>
</Cell>
</Cells>
<Article className="income-main-description">
<section className="m-b-sm">收益余额=在路上+可提现</section>
<section className="m-b-sm">
<span>在路上:</span>
<span>指你的友军购买了课程,但是还没有结课,如果友军退课的话,在路上的收益就会飞走哦~(即:收益没了。。。)</span>
</section>
<section className="m-b-sm">
<span>可提现:</span>
<span>指你的友军购买了课程,并且已结课,此时在路上的收益就会变成可提现的收益</span>
</section>
<section className="m-b-sm">如果友军在课程中表现优秀,比如每天打卡,还会有格外的奖励哦~</section>
<section className="m-b-sm">收益总额=收益余额+已提现</section>
</Article>
</main>
<footer className="income-footer m-t-n-md">
<Button disabled={availableIncome <= 0} onClick={processWithdrawAction}>提至优币</Button>
</footer>
</div>
)
}
}
```
rank-list.js
```'use strict';
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import InfiniteScroll from "react-infinite-scroller";
import EmptyTip from '../../../EmptyTip';
const {
Cells,
Cell,
CellHeader,
CellBody,
CellFooter
} = WeUI;
@inject("RankList") @observer
class RankList extends Component {
constructor(props) {
super(props);
this.rankList = this.props.RankList;
}
componentDidMount() {
const { courseBanner, courseName } = this.props;
this.rankList.initWechatShare(courseName, courseBanner)
}
render() {
const { getRankList, favourRankItem, rankListPaginator, isCurrentUserFirst } = this.rankList;
const { values, hasMore } = rankListPaginator;
return (
<div className="rank-infinite-scroll">
<InfiniteScroll
threshold={20}
useWindow={false}
initialLoad={false}
loadMore={getRankList}
hasMore={hasMore}
loader={
<div className="infinite-scroll-preloader">
<div className="preloader"/>
</div>
}>
<Cells className="m-t-none">
{
values.length === 0
? <EmptyTip tip="还没有排行榜信息"/>
: values.map((item, index) => (
<Cell className={`rank-item ${ isCurrentUserFirst === true && index === 0 ? 'current-user-rank-item' : ''}`} key={item.id}>
<CellHeader className="rank-item-header">
{item.rank}
</CellHeader>
<CellBody className="rank-item-body">
<img src={item.userInfo.headImgUrl} className="rank-item-avatar" alt="用户头像"/>
<span className="rank-item-name text-overflow-hidden">{item.userInfo.name}</span>
</CellBody>
<CellFooter className="rank-item-footer">
<div className="rank-item-score">{item.grade >= 1000 ? '999+' : item.grade}</div>
<div className="rank-item-favor">
<span className="rank-item-praise text-center">{item.favourInfo.sum}</span>
<i className={`icon-gb ${item.favourInfo.isFavour ? 'icon-gb-heart-full' : 'icon-gb-heart-empty'}`}
onClick={() => favourRankItem(item, index)}/>
</div>
</CellFooter>
</Cell>
))
}
</Cells>
</InfiniteScroll>
</div>
)
}
}
export default RankList;
```
profile.js
```import React, {Component} from "react";
import {Link} from 'react-router';
import {observer, inject, PropTypes} from "mobx-react";
import WeUI from "react-weui";
const {
CellsTitle,
Cells,
Cell,
CellHeader,
CellBody,
CellFooter,
Input
} = WeUI;
@inject("User") @observer
class Profile extends Component {
constructor(props) {
super(props);
this.user = this.props.User;
}
updateBirthday = (event) => {
this.user.setBirthday(event.target.value);
};
render() {
const {info, cusBirthday} = this.user;
return (
<div className="page page-current me-page">
<header className="bar bar-nav">
<button className="button button-link button-nav pull-left" onClick={() => history.go(-1)}>
<span className="icon icon-left"/>
</button>
<h1 className="title">我的资料</h1>
</header>
<div className="content">
<CellsTitle>基本信息</CellsTitle>
<Cells>
<Cell className="profile-cell">
<CellHeader>
头像
</CellHeader>
<CellBody>
<div className="avatar-wrap">
<img src={info.headImgUrl}/>
</div>
</CellBody>
</Cell>
<Cell className="profile-cell">
<CellHeader>
昵称
</CellHeader>
<CellBody>
{info.name}
</CellBody>
</Cell>
<Cell className="profile-cell">
<CellHeader>
出生日期
</CellHeader>
<CellBody>
<Input type="date"
value={cusBirthday ? cusBirthday : info.birthday}
onChange={ this.updateBirthday }/>
</CellBody>
</Cell>
<Cell className="profile-cell">
<CellHeader>
性别
</CellHeader>
<CellBody>
{info.sex === 1 ? "男" : (info.sex === 2 ? "女" : "未知")}
</CellBody>
</Cell>
<Cell className="profile-cell">
<CellHeader>
学号
</CellHeader>
<CellBody>
{info.studentNumber}
</CellBody>
</Cell>
</Cells>
<Cells>
<Cell component={Link} to="/me/password" access>
<CellBody>
修改密码
</CellBody>
<CellFooter/>
</Cell>
</Cells>
</div>
</div>
)
}
}
export default Profile;
```
setting.js
```"use strict";
import { observable, useStrict, action } from "mobx";
import util from "../util";
import { httpGet, httpPut } from "../../service";
import uniqueToast from "../common/httpToast";
useStrict(true);
const baseUrl = `${util.baseUrl}api/account`;
class Setting {
@observable setting = {};
@observable
showTimeZonePicker = false;
timeZoneGroup = [
{
items: [
{
key: "UTC-12",
label: "马朱罗-西十二区"
},
{
key: "UTC-11",
label: "中途岛-西十一区"
},
{
key: "UTC-10",
label: "檀香山-西十区"
},
{
key: "UTC-9",
label: "朱诺-西九区"
},
{
key: "UTC-8",
label: "洛杉矶-西八区"
},
{
key: "UTC-7",
label: "盐湖城-西七区"
},
{
key: "UTC-6",
label: "墨西哥城-西六区"
},
{
key: "UTC-5",
label: "纽约-西五区"
},
{
key: "UTC-4",
label: "加拉加斯-西四区"
},
{
key: "UTC-3",
label: "巴西利亚-西三区"
},
{
key: "UTC-2",
label: "华盛顿-西二区"
},
{
key: "UTC-1",
label: "达塔德尔加达-西一区"
},
{
key: 'UTC',
label: '格林威治标准时间'
},
{
key: "UTC+1",
label: "柏林-东一区"
},
{
key: "UTC+2",
label: "雅典-东二区"
},
{
key: "UTC+3",
label: "莫斯科-东三区"
},
{
key: "UTC+4",
label: "阿布扎比-东四区"
},
{
key: "UTC+5",
label: "伊斯兰堡-东五区"
},
{
key: "UTC+6",
label: "达卡-东六区"
},
{
key: "UTC+7",
label: "曼谷-东七区"
},
{
key: "UTC+8",
label: "北京-东八区"
},
{
key: "UTC+9",
label: "东京-东九区"
},
{
key: "UTC+10",
label: "堪培拉-东十区"
},
{
key: "UTC+11",
label: "霍尼亚拉-东十一区"
},
{
key: "UTC+12",
label: "惠灵顿-东十二区"
}
]
}
];
constructor() {
}
@action
clickInput = (e) => {
this.showTimeZonePicker = true;
};
@action
changeTimeZone = (selected) => {
let value = "";
selected.forEach((s, i) => {
value = this.timeZoneGroup[i]["items"][s].key
});
this.setting.timezone = value;
this.showTimeZonePicker = false
};
@action
cancelTimeZone = () => {
this.showTimeZonePicker = false;
};
saveTimeZone = (cb) => (selected) => {
this.changeTimeZone(selected);
httpPut(
`${baseUrl}/privacy`,
{
timezone: this.setting.timezone
})
.then(cb);
};
bindToastWithAction = () => this.saveTimeZone = this.saveTimeZone(this.actionToast);
actionToast = (resBody) => {
if (resBody === true) {
uniqueToast.showToast({ text: "操作成功", icon: "success" });
} else {
uniqueToast.showToast({ text: "操作失败", icon: "warn" });
}
};
fetchInfo = (scb) =>
httpGet(`${baseUrl}/privacy`)
.then(scb);
setInfo = () => this.fetchInfo(action((data) => {
this.setting = data;
}));
}
export default Setting;
```
list.js
```"use strict";
import { observable, useStrict, action } from "mobx";
import { browserHistory } from "react-router";
import courseList from "../course/list";
import { httpGet, httpDel } from "../../service";
useStrict(true);
import util from "../util";
import Dialog from "../common/dialog";
import uniqueToast from "../common/httpToast";
const baseUrl = `${util.baseUrl}api/clazz`;
class TaskList {
@observable clazz = {};
@observable content = [];
@observable strategy = "";
@observable state = false;
constructor() {
this.dialog = new Dialog();
}
setCourseId = (courseId) => {
this.courseId = courseId;
};
@action
clearData = () => {
this.courseId = null;
this.clazz = {};
this.content = [];
this.strategy = "";
this.state = false;
};
@action
setDetail = (data) => {
data.tasks.forEach(item => this.content.push(item));
this.clazz = data;
};
fetchInfo = (cb) => {
httpGet(`${baseUrl}/${this.courseId}/tasks`)
.then(cb);
};
getInfo = () => {
this.fetchInfo(this.setDetail);
};
getStrategy = () => {
httpGet(`${baseUrl}/${this.courseId}/strategy`)
.then(action(data => this.strategy = data.strategy))
};
@action
openPopup = () => this.state = true;
@action
closePopup = () => this.state = false;
//这里是dialog点击确认后处理退课请求
processCourseCanceling = () => {
this.dialog.dismissDialog();
this.cancelCourse()
.then(() => {
uniqueToast.showToast({
text: "退出课程成功",
icon: "success",
cb: () => {
courseList.markReloadFlag();
browserHistory.replace("/course/list")
}
});
});
};
cancelCourse = () => {
return httpDel(`${baseUrl}/${this.courseId}`);
};
}
export default new TaskList();
```
chat.js
```import {observable, useStrict, action, computed, autorun} from "mobx";
useStrict(true);
import util from "../util";
import {httpGet, httpPost} from "../../service";
import Toast from "../common/toast"
const baseUrl = `${util.baseUrl}api/clazz`;
class Scroll {
@observable node = null;
@action
getNode = (node) => {
this.node = node;
};
scrollToBottom = () => {
this.node.scrollTop = this.node.scrollHeight;
}
}
export let scroll = new Scroll();
const PLAY = "PLAY",
PAUSE = "PAUSE";
class Chat {
@observable list = [];
@observable seletedAudio = null;
@observable endDate = "";
@observable text = "";
@observable toast = new Toast();
constructor(cid, fid) {
this.cid = cid;
this.fid = fid;
this.pageSize = 6;
this.hasMore = true;
}
tFetchChats = (endDate = "", pageSize = this.pageSize) => {
return httpGet(`${baseUrl}/${this.cid}/feedback/${this.fid}?pageSize=${pageSize}&endDate=${endDate}`);
};
sFetchChats = (endDate = "", pageSize = this.pageSize) => {
return httpGet(`${baseUrl}/${this.cid}/feedback?pageSize=${pageSize}&endDate=${endDate}`);
};
@action
updateData = (data) => {
if (!data[0]) {
this.hasMore = false;
return
}
this.endDate = data[0].date;
const temp = data.map((item) => {
if (item.type === "VOICE")
item["audio"] = new AudioItem(this, item.id);
return item
});
this._shiftArray(temp, this.list);
};
_shiftArray = (raw, result) => {
if (raw.length > 0)
for (let i = raw.length - 1; i >= 0; i--) {
result.unshift(raw[i]);
}
};
getChats = (isTeacher, resolve = () => {}) => {
isTeacher
? this.tFetchChats(this.endDate)
.then((data) => {
this.updateData(data);
resolve();
})
: this.sFetchChats(this.endDate)
.then((data) => {
this.updateData(data);
resolve();
});
};
@action
handleTextChange = (e) => {
this.text = e.target.value;
};
postReply = (replyType, content) => {
let subUrl = this.fid ? `/${this.fid}` : ``;
return httpPost(
`${baseUrl}/${this.cid}/feedback${ subUrl }`,
{
replyType: replyType,
content: content
});
};
postText = () => {
if (this.text == null || this.text === "") {
return void this.toast._showToast({
text: "内容不能为空",
icon: "warn",
back: false
});
}
if (this.text.length > 1000) {
return void this.toast._showToast({
text: "内容过长,请分次发送",
icon: "warn",
back: false
});
}
this.postReply("TEXT", this.text)
.then(action(data => {
this.text = "";
this.list.push(data);
setTimeout(scroll.scrollToBottom, 0);
}))
};
}
export class AudioItem {
@observable nextState = PLAY;
@observable node = null;
constructor(chat, idx) {
this.chat = chat;
this.idx = idx;
autorun(this._onlyOne);
}
@action
playAudio = (audioNode) => {
this.nextState = PAUSE;
this.node = audioNode;
this.chat.seletedAudio = this.idx;
audioNode.play();
};
@action
pauseAudio = (audioNode) => {
this.nextState = PLAY;
audioNode.pause();
audioNode.currentTime = 0;
};
@computed
get isSelected() {
return this.chat.seletedAudio === this.idx;
}
_onlyOne = () => {
if (this.node && !this.isSelected)
this.pauseAudio(this.node)
};
controllAudio = (audioNode) => {
this.nextState === PLAY ?
this.playAudio(audioNode) : this.pauseAudio(audioNode);
};
}
export default Chat;```
list.js
```import {observable, useStrict, action} from "mobx";
import util from "../util";
const baseUrl = `${util.baseUrl}api`;
import {httpGet} from "../../service";
useStrict(true);
class EnrollList {
@observable list = [];
@action
setCourses(list) {
this.list = list;
}
fetchList = (scb) => {
httpGet(`${baseUrl}/clazzes?status=OPEN`)
.then(scb);
}
}
export default EnrollList;```
chat-item.js
```'use strict';
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import _ from '../../util';
/**
* 文字类型消息
*
* @param content
*/
const TextMessage = ({ content }) => (
<div className="chat-text-msg chat-msg-item">
<div dangerouslySetInnerHTML={{ __html: content }}/>
</div>
);
/**
* 图片类型消息
*
* @param url
* @param onImgLoaded
*/
const ImageMessage = ({ url, onImgLoaded }) => (
<div className="chat-img-msg chat-msg-item">
<img className="w-full" src={url} onLoad={onImgLoaded}/>
</div>
);
/**
* 语音类型消息
* 使用 CommonAudioStore 控制音频状态
*/
@inject("CommonAudioStore") @observer
class AudioMessage extends Component {
constructor(props) {
super(props);
const { url, chatList, CommonAudioStore } = this.props;
// 语音地址
this.url = url;
// audio node 节点
this.audioNode = null;
// 语音item
this.audioStore = new CommonAudioStore();
this.chatList = chatList;
// 设置当前选中的audio
if (this.chatList.selectedAudio === null) {
this.chatList.selectedAudio = this;
}
}
toggleAudioPlay = () => {
const { isPlaying } = this.audioStore;
// 如果正在播放则停止,否则开始播放
if (isPlaying === true) {
this.stopAudio();
} else {
// 全局唯一播放
if (this.chatList.selectedAudio != null && this.chatList.selectedAudio !== this) {
this.chatList.selectedAudio.stopAudio();
}
this.playAudio();
}
};
// 播放音频
playAudio = () => {
this.audioNode.play();
this.chatList.selectedAudio = this;
this.audioStore.setIsPlaying(true);
};
// 停止音频
stopAudio = () => {
this.audioNode.pause();
this.audioNode.currentTime = 0;
this.audioStore.setCurrent(0);
this.audioStore.setIsPlaying(false);
};
setAudioItemDuration = () => this.audioStore.setDuration(this.audioNode.duration);
setAudioItemCurrent = () => this.audioStore.setCurrent(this.audioNode.currentTime);
onLoadedMetaData = () => {
this.setAudioItemDuration();
if (this.chatList.selectedAudio === this) {
// 仅在android下自动播放
if (_.isIOS() === false) {
this.playAudio();
}
}
};
componentWillUnmount() {
this.audioNode.removeEventListener("ended", this.stopAudio);
this.audioNode.removeEventListener("loadedmetadata", this.onLoadedMetaData);
this.audioNode.removeEventListener("timeupdate", this.setAudioItemCurrent);
this.audioNode.removeEventListener("canplaythrough", this.setAudioItemDuration);
}
render() {
const { duration, isPlaying } = this.audioStore;
return (
<div className="chat-audio-msg chat-msg-item">
<div className="audio-spiral" onClick={this.toggleAudioPlay}>
<audio ref={node => this.audioNode = node} preload="metadata"
onEnded={this.stopAudio}
onLoadedMetadata={this.onLoadedMetaData}
onTimeUpdate={this.setAudioItemCurrent}
onCanPlayThrough={this.setAudioItemDuration}>
<source src={this.url}/>
</audio>
<i className={`icon-gb ${isPlaying ? 'icon-gb-audio-playing' : 'icon-gb-audio-pause'}`}/>
<span className="audio-time-duration">{duration}</span>
</div>
</div>
);
};
}
/**
* 聊天item
* 根据消息类型,构建消息条目
*
* @param item
* @param onImgLoaded
* @param chatList
* @returns {XML}
* @constructor
*/
const ChatItem = ({ item, onImgLoaded, chatList }) => {
const { type, userInfo, url, content } = item;
return (<div className={`chat-item ${userInfo.isSelf ? 'me' : ''}`}>
<div className="chat-avatar">
<img src={userInfo.headImgUrl}/>
</div>
<div className="chat-content">
{
((type) => {
switch (type) {
case 'AUDIO':
return <AudioMessage url={url} chatList={chatList}/>;
case 'IMAGE':
return <ImageMessage url={url} onImgLoaded={onImgLoaded}/>;
case 'TEXT':
return <TextMessage content={content}/>;
}
})(type)
}
</div>
</div>);
};
export default ChatItem;
```
audio.js
```'use strict';
import { observable, action } from "mobx";
import util from "../util";
export default class AudioItem {
@observable
duration = "00:00";
@observable
current = "00:00";
@observable
isPlaying = false;
constructor() {
}
@action
setDuration = (duration) => {
this.duration = util.formatAudioTimer(duration);
};
@action
setCurrent = (current) => {
this.current = util.formatAudioTimer(current);
};
@action
setIsPlaying = (isPlaying) => {
this.isPlaying = isPlaying === true;
};
}
```
user.js
```"use strict";
import { observable, useStrict, action, computed } from "mobx";
import util from "../util";
import cutil from "../../common-util";
import { httpGet, httpPut } from "../../service";
import topTip from "../common/toptip";
useStrict(true);
const baseUrl = `${util.baseUrl}api`;
class User {
@observable info = {};
@observable birthday = "";
constructor() {
}
@action
setInfo = (data) => {
this.info = data;
};
@action
setBirthday = (date) => {
const now = new Date();
const custDate = new Date(date);
this.birthday = custDate > now ? cutil.format(now, "yyyy-MM-dd") : date;
return this.updateBirthday()
.then(() => {
topTip.showToptip({type: "primary", content: "修改生日成功!"})
});
};
fetchInfo = (scb) =>
httpGet(`${baseUrl}/account`)
.then(scb);
updateBirthday = () => httpPut(
`${baseUrl}/account`,
{
birthday: this.birthday ? this.birthday : cutil.format(new Date(), "yyyy-MM-dd")
}
);
@computed
get cusBirthday() {
return this.birthday;
}
}
export default new User();
```
course-item.js
```'use strict';
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
@inject("CheckinList", "CourseStudy", "TaskList", "RankList") @observer
class CourseItem extends Component {
constructor(props) {
super(props);
const { TaskList, CheckinList, RankList, params } = this.props;
const { courseId } = params;
this.tasks = TaskList;
this.checkins = CheckinList;
this.rankList = RankList;
this.tasks.setCourseId(courseId);
this.checkins.setCourseId(courseId);
this.rankList.setCourseId(courseId);
}
componentDidMount() {
this.tasks.getInfo();
this.checkins.getCheckins();
const { getRankList, getCurrentUserRankInfo } = this.rankList;
getCurrentUserRankInfo();
getRankList();
}
componentWillUnmount() {
this.tasks.clearData();
this.checkins.clearData();
this.rankList.clearData();
}
render() {
return this.props.children
}
}
export default CourseItem;
```
enum.js
```export const taskIntroductionEnum = {
"TEACHER_QA": {
key: "TEACHER_QA",
name: "笃师问答"
},
"TEACHER_NAG": {
key: "TEACHER_NAG",
name: "笃师碎碎念"
},
"TASK_DESCRIPTION": {
key: "TASK_DESCRIPTION",
name: "任务描述"
},
"SPECIAL_NOTIFICATION": {
key: "SPECIAL_NOTIFICATION",
name: "特别通知"
},
"OTHER": {
key: "OTHER",
name: "其他"
}
};
export const fileTypeEnum = {
"voice": {
key: "voice",
name: "语音",
icon: ""
},
"shortvideo": {
key: "shortvideo",
name: "短视频"
},
"image": {
key: "image",
name: "图片"
},
"video": {
key: "video",
name: "视频"
},
"weblink": {
key: "weblink",
name: "外部链接"
},
"attach": {
key: "attach",
name: "附件"
}
};
export const timezoneEnum = {
'UTC': {
key: 'UTC',
name: '格林威治标准时间'
},
"UTC+1": {
key: "UTC+1",
name: "柏林-东一区"
},
"UTC+2": {
key: "UTC+2",
name: "雅典-东二区"
},
"UTC+3": {
key: "UTC+3",
name: "莫斯科-东三区"
},
"UTC+4": {
key: "UTC+4",
name: "阿布扎比-东四区"
},
"UTC+5": {
key: "UTC+5",
name: "伊斯兰堡-东五区"
},
"UTC+6": {
key: "UTC+6",
name: "达卡-东六区"
},
"UTC+7": {
key: "UTC+7",
name: "曼谷-东七区"
},
"UTC+8": {
key: "UTC+8",
name: "北京-东八区"
},
"UTC+9": {
key: "UTC+9",
name: "东京-东九区"
},
"UTC+10": {
key: "UTC+10",
name: "堪培拉-东十区"
},
"UTC+11": {
key: "UTC+11",
name: "霍尼亚拉-东十一区"
},
"UTC+12": {
key: "UTC+12",
name: "惠灵顿-东十二区"
},
"UTC-1": {
key: "UTC-1",
name: "达塔德尔加达-西一区"
},
"UTC-2": {
key: "UTC-2",
name: "华盛顿-西二区"
},
"UTC-3": {
key: "UTC-3",
name: "巴西利亚-西三区"
},
"UTC-4": {
key: "UTC-4",
name: "加拉加斯-西四区"
},
"UTC-5": {
key: "UTC-5",
name: "纽约-西五区"
},
"UTC-6": {
key: "UTC-6",
name: "墨西哥城-西六区"
},
"UTC-7": {
key: "UTC-7",
name: "盐湖城-西七区"
},
"UTC-8": {
key: "UTC-8",
name: "洛杉矶-西八区"
},
"UTC-9": {
key: "UTC-9",
name: "朱诺-西九区"
},
"UTC-10": {
key: "UTC-10",
name: "檀香山-西十区"
},
"UTC-11": {
key: "UTC-11",
name: "中途岛-西十一区"
},
"UTC-12": {
key: "UTC-12",
name: "马朱罗-西十二区"
}
};
export const genderEnum = {
"0": {
name: "未知",
key: "0"
},
"1": {
name: "男",
key: "1"
},
"2": {
name: "女",
key: "2"
}
};
export const settingTypeEnum = {
"wechat": {
name: "微信账号",
key: "wechat"
},
"alipay": {
name: "支付宝账号",
key: "alipay"
},
"phoneNumber": {
name: "手机号",
key: "phoneNumber"
},
"realName": {
name: "真实姓名",
key: "realName"
}
};
export const clazzFeedbackStatusEnum = {
"SUBMITTING": {
key: "SUBMITTING",
name: "待提交"
},
"WAITING": {
key: "WAITING",
name: "未回复"
},
"REPLIED": {
key: "REPLIED",
name: "已回复"
},
"CLOSED": {
key: "CLOSED",
name: "已关闭"
}
};
export const withdrawStatusEnum = {
"WAITING": {
key: "WAITING",
name: "待处理"
},
"AGREED": {
key: "AGREED",
name: "已同意"
},
"REJECTED": {
key: "REJECTED",
name: "已拒绝"
}
};
export const clazzJoinTypeEnum = {
"PAY": {
key: "PAY",
name: "付费班"
},
"FREE": {
key: "FREE",
name: "免费班"
},
"GAMBITION_COIN": {
key: "GAMBITION_COIN",
name: "笃金班"
}
};
export const userPassportGenderEnum = {
"2": {
name: "美丽聪慧的妹子",
key: "2"
},
"1": {
name: "英俊勇敢的汉子",
key: "1"
}
};
export const userEnglishLevelEnum = {
NATIVE_SPEAKER: {
key: 'NATIVE_SPEAKER',
name: '能和华莱士谈笑风生'
},
NOT_CONFIDENT: {
key: 'NOT_CONFIDENT',
name: '能说一些,出口却不自信'
},
PROFESSIONAL: {
key: 'PROFESSIONAL',
name: '我是英专生,持续成长中'
},
CONFUSION: {
key: 'CONFUSION',
name: '我感觉我学了多年假英语'
},
FRESH_MAN: {
key: 'FRESH_MAN',
name: '真的零基础,不信来战'
}
};
export const userSelfIdentityEnum = {
NATIVE_SPEAKER: {
key: 'NATIVE_SPEAKER',
name: '能和华莱士谈笑风生'
},
BOOKWORK: {
key: 'BOOKWORK',
name: '能饱览世界群书、禁书'
},
LISTENING_FLUENT: {
key: 'LISTENING_FLUENT',
name: '看美剧英剧听新闻无压力',
},
EXPERT: {
key: 'EXPERT',
name: '我就是靠这个吃饭的,叉',
},
EXAM_FOCUS: {
key: 'EXAM_FOCUS',
name: '不是为了考试我才不学英语'
}
};
export const learningModeEnum = {
FRIENDS: {
key: 'FRIENDS',
name: '和身边的朋友组队学'
},
ONLINE: {
key: 'ONLINE',
name: '和网路上的朋友一起学'
},
ALONE: {
key: 'ALONE',
name: '我就想一个人学'
}
};
export const clazzStatusEnum = {
'CLOSE': {
name: '已结束',
key: 'CLOSE'
},
'PROCESSING': {
name: '进行中',
key: 'PROCESSING'
},
'OPEN': {
name: '报名中',
key: 'OPEN'
}
};
export const clazzTypeEnum = {
'SEMESTER': {
name: '学期班',
key: 'SEMESTER'
},
'LTS': {
name: '非学期班',
key: 'LTS'
},
'LONG_TERM': {
name: '长期班',
key: 'LONG_TERM'
},
'PROMOTION': {
name: '推广活动班',
key: 'PROMOTION'
}
};
/**
* 推广收益状态枚举
*
* @type {{}}
*/
export const promotionIncomeStatusEnum = {
'RESERVED': {
key: 'RESERVED',
name: '在路上'
},
'AVAILABLE': {
key: 'AVAILABLE',
name: '可提现'
},
'COINED': {
key: 'COINED',
name: '已提现'
},
'CANCELED': {
key: 'CANCELED',
name: '飞走了'
},
};
export const clazzJoinStatusEnum = {
'INVITATION': {
name: '邀请中',
key: 'INVITATION'
},
'PENDING': {
name: '待审核',
key: 'PENDING'
},
'PAYING': {
name: '待支付️',
key: 'PAYING'
},
'WAITENTER': {
name: '待确认',
key: 'WAITENTER'
},
'PROCESSING': {
name: '进行中',
key: 'PROCESSING'
},
'CANCELED': {
name: '已退课',
key: 'CANCELED'
},
'CLOSE': {
name: '已结课',
key: 'CLOSE'
}
};
export function getEnumByKey(key, EnumObj) {
if (EnumObj[key]) {
return EnumObj[key];
} else {
return null;
}
}
```
recommend.js
```'use strict';
import React, { Component } from "react";
import { browserHistory } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import CopyToClipboard from 'react-copy-to-clipboard';
import _ from '../../util';
const {
Cell,
CellHeader,
CellBody,
CellFooter,
Article,
Button,
} = WeUI;
@inject("Promotion") @observer
export default class Recommentpage extends Component {
constructor(props) {
super(props);
this.promotion = this.props.Promotion;
}
componentDidMount() {
this.promotion.initWechatShare();
}
render() {
const { currentPromotionUser, isRecommendMaskDisplay, alertCopySuccess, toggleRecommendMask } = this.promotion;
const promotionInfo = _.get(currentPromotionUser, 'promotionInfo', null),
currentUserName = _.get(currentPromotionUser, 'name', '');
const promotionKey = _.get(promotionInfo, 'key', '');
return (
<div className="promotion-page recommend-page w-full">
<header className="page-header w-full bar bar-nav">
<a className="icon icon-left pull-left p-l-none p-r-none"
onClick={() => browserHistory.replace('/promotion/home')}/>
<span className="title">强 烈 推 荐</span>
</header>
<main className="recommend-page-main">
<Cell className="recommend-page-main-user">
<CellHeader className="user-profit">
<div className="user-profit-info">
<span>邀请码</span>
<span>{promotionKey}</span>
</div>
<div className="user-profit-info">
<span>总收益</span>
<span className="all-profit">¥{(_.get(promotionInfo, 'incomeSum', 0) / 100).toFixed(0)}</span>
</div>
</CellHeader>
<CellBody className="user-info-photo">
<img className="user-photo" src={_.get(currentPromotionUser, 'headImgUrl', '')} alt="用户头像"/>
</CellBody>
<CellFooter className="current-user-info text-right">
<span>{currentUserName}</span>
<span>学号:{_.get(currentPromotionUser, 'studentNumber', '')}</span>
</CellFooter>
</Cell>
<Article className="text-center">
<section className="text-center">
<p>分享首单优惠码</p>
<p>和好友一起<span className="come-study">得优惠,来学习</span></p>
</section>
<section className="first-order text-center">
<p className="first-order-des m-b-none">首单优惠码</p>
<span className="invitecode text-center">{promotionKey}</span>
<CopyToClipboard text={promotionKey} onCopy={alertCopySuccess}>
<Button className="copy-button">一键复制</Button>
</CopyToClipboard>
</section>
<section className="text-center m-t-n-xl">
<p className="m-b-xs">点击下方分享</p>
<p className="m-b-xs">帮助你召唤一大波友军</p>
<p className="m-b-xs">友军越多,优惠越多,惊喜不断哦~</p>
<p className="m-b-xs">赶快行动起来吧!</p>
</section>
<Button className="share-button" onClick={toggleRecommendMask}>分享</Button>
<p className="note text-center m-t-xl m-b-xl m-l-none m-r-none">注:首单优惠码在购课时方可使用,仅限首次购课</p>
</Article>
</main>
<div className="masking-out w-full text-center" style={{ display: isRecommendMaskDisplay ? 'block' : 'none' }}
onClick={toggleRecommendMask}>
<i className="tap icon-gb-promotion-tap icon-gb"/>
<p className="des">点击上方进行分享</p>
</div>
</div>
)
}
}
```
clazz-exit.js
```'use strict';
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
const {
Button,
CellBody,
CellsTitle,
Dialog,
Form,
FormCell,
Select,
TextArea
} = WeUI;
@inject("ClazzExit") @observer
class ClazzExit extends Component {
constructor(props) {
super(props);
this.clazzExit = new this.props.ClazzExit();
}
updateSelectedClazz = (event) => this.clazzExit.setSelectedClazzId(event.target.value);
updateExitReason = (event) => this.clazzExit.setExitReason(event.target.value);
componentDidMount() {
this.clazzExit.fetchProcessingClazzList();
}
render() {
const {
clazzList, selectedClazzId, exitReason, isDialogshow, dialogButtons, isFormValid,
showDialog
} = this.clazzExit;
return (
<div className="page page-current me-page">
<header className="bar bar-nav">
<button className="button button-link button-nav pull-left" onClick={() => history.go(-1)}>
<span className="icon icon-left"/>
</button>
<h1 className="title">退班申请</h1>
</header>
<div className="content">
<CellsTitle>退班班级</CellsTitle>
<Form>
<FormCell select>
<CellBody>
<Select value={selectedClazzId} onChange={this.updateSelectedClazz}>
{
clazzList.map((clazzItem) => <option value={clazzItem.id}
key={clazzItem.id}>{clazzItem.name}</option>)
}
</Select>
</CellBody>
</FormCell>
</Form>
<CellsTitle>原因</CellsTitle>
<Form>
<FormCell>
<CellBody>
<TextArea placeholder="请详细填写,以便我们改进课程哦!" rows="3" maxlength="200"
value={exitReason} onChange={this.updateExitReason}/>
</CellBody>
</FormCell>
</Form>
</div>
<footer className="bar bar-tab">
<Button id="clazz-exit-confirm-button" onClick={showDialog} disabled={!isFormValid}>
提交申请
</Button>
</footer>
<Dialog title="确认退班" buttons={dialogButtons} show={isDialogshow}>退班需要后台审核,一般需1~3个工作日</Dialog>
</div>
)
}
}
export default ClazzExit;
```
index.js
```'use strict';
import React, { Component } from "react";
class Enroll extends Component {
constructor(props) {
super(props);
this.user = this.props.User;
}
componentDidMount() {
}
render() {
return (
<div className="page-group">
{this.props.children}
</div>
)
}
}
export default Enroll;
```
popUp.js
```/**
* Created by violinsolo on 27/03/2017.
*/
import {observable, action} from "mobx";
class PopUp {
@observable show = false;
@action
_showPopUp() {
this.show = true;
}
@action
_hidePopUp() {
this.show = false;
}
}
export default PopUp;```
checkin-list.js
```'use strict';
import { browserHistory } from "react-router";
import React, { Component } from "react";
import { Link } from "react-router";
import { observer, inject } from "mobx-react";
import _ from "../../../util";
import cutil from "../../../../common-util";
import WeUI from "react-weui";
const {
Tab,
TabBody,
Cells,
Cell,
CellHeader,
CellBody,
CellFooter,
Button
} = WeUI;
@inject("CheckinList") @observer
class CheckinList extends Component {
constructor(props) {
super(props);
}
static getInterval(secondString) {
const second = parseInt(secondString, 10);
const h = Math.floor(second / 3600),
m = Math.floor((second - h * 3600) / 60),
s = Math.floor(second - h * 3600 - m * 60);
return `${h ? h + '小时' : ''}${m ? m + '分' : ''}${s}秒`
}
render() {
const { CheckinList: checkinList, backUrl } = this.props;
const { courseId, checkins, info } = checkinList;
const checkinState = info.canCheckin;// 原始代码(&& !info.hasCheckin):现在不判断是否已经打卡了,只要允许打卡,不管当天是否已经打卡,都要能打卡
return (
<div>
<header className="bar bar-nav">
<button className="button button-link button-nav pull-left"
onClick={() => browserHistory.replace(backUrl)}>
<span className="icon-gb icon-gb-close page-header-close-button"/>
</button>
<h1 className="title">作业记录</h1>
</header>
<div className="content">
<Tab>
<TabBody>
<div className="checkin-list-top">
<div className="checkin-user">
<div className="avatar-wrap">
<img src={_.get(checkinList, "info.userInfo.headImgUrl", "")}/>
</div>
<div className="info-wrap">
{_.get(checkinList, "info.userInfo.name", "")}
</div>
<div className="btn-wrap">
<Link to={`/course/${ courseId }/checkin`}><Button size="small"
disabled={!checkinState}>去打卡</Button></Link>
</div>
</div>
<div className="checkin-total">
<div className="checkin-score">
<div className="number">{info.scoreSum}</div>
<div>已获学分</div>
</div>
<div className={(checkinState ? "normal" : "unnormal") + " checkin-day"}>
<div className="number">{info.openDays}</div>
<div>开班天数</div>
</div>
<div className={(checkinState ? "normal" : "unnormal") + " checkin-time"}>
<div className="number">{checkins.length}</div>
<div>打卡次数</div>
</div>
</div>
</div>
<div className="checkin-list-wrap">
<Cells>
{
checkins.map(item => (
<Cell className="checkin-item" key={item.id}
component={Link} to={`/course/${ courseId }/checkin/${ item.id }`} access>
<CellHeader>
<div className="checkin-score">{item.dayNumber}</div>
</CellHeader>
<CellBody>
<div className="checkin-time">{cutil.format(new Date(item.checkinTime), "hh:mm:ss")}</div>
<div className="checkin-tip">提前了{CheckinList.getInterval(item.aheadSeconds)}打卡</div>
</CellBody>
<CellFooter/>
</Cell>
))
}
<Cell className="checkin-footer-item" access>
<CellBody>
没有更多记录
</CellBody>
</Cell>
</Cells>
</div>
</TabBody>
</Tab>
</div>
</div>
)
}
}
export default CheckinList;
```
setting.js
```"use strict";
import React, { Component } from "react";
import { Link } from "react-router";
import { observer, inject, PropTypes } from "mobx-react";
import { timezoneEnum, getEnumByKey } from "../../enum";
import _ from "../../util"
import IMAGE_URL_MAP from "../../BigImageUrl";
import WeUI from "react-weui";
const {
CellsTitle,
Cells,
Cell,
CellHeader,
CellBody,
CellFooter,
CellsTips,
Form,
FormCell,
Picker,
Input
} = WeUI;
@inject("Setting") @observer
class Setting extends Component {
constructor(props) {
super(props);
this.setting = new this.props.Setting();
}
componentDidMount() {
this.setting.setInfo();
this.setting.bindToastWithAction();
}
render() {
const { setting } = this.setting;
return (
<div className="page page-current me-page">
<header className="bar bar-nav">
<button className="button button-link button-nav pull-left" onClick={() => history.go(-1)}>
<span className="icon icon-left"/>
</button>
<h1 className="title">个人设置</h1>
</header>
<div className="content">
<Cells>
<Cell className="setting-cell" component={Link} to={"/me/setting/phoneNumber"} access>
<CellBody className="text-no-wrap setting-cell-primary-text">
手机号
</CellBody>
<CellFooter className="text-overflow-hidden">
{setting.phoneNumber ||
(<span className="setting-label">
去设置
</span>)}
</CellFooter>
</Cell>
<Cell className="setting-cell" component={Link} to={"/me/setting/realName"} access>
<CellBody className="text-no-wrap setting-cell-primary-text">
真实姓名
</CellBody>
<CellFooter className="text-overflow-hidden">
{setting.realName ||
(<span className="setting-label">
去设置
</span>)}
</CellFooter>
</Cell>
</Cells>
<Cells>
<Cell className="setting-cell" component={Link} to={"/me/setting/wechat"} access>
<CellHeader>
<i className="icon-gb icon-gb-wechat"/>
</CellHeader>
<CellBody className="text-no-wrap setting-cell-primary-text">
微信号
</CellBody>
<CellFooter className="text-overflow-hidden">
{setting.wechat ||
(<span className="setting-label">
去设置
</span>)}
</CellFooter>
</Cell>
<Cell className="setting-cell" component={Link} to={"/me/setting/alipay"} access>
<CellHeader>
{/*<i className="icon-gb icon-gb-alipay"/>*/}
<img src={IMAGE_URL_MAP["ALIPAY"]} className="alipay-logo"/>
</CellHeader>
<CellBody className="text-no-wrap setting-cell-primary-text">
支付宝
</CellBody>
<CellFooter className="text-overflow-hidden">
{setting.alipay ||
(<span className="setting-label">
去设置
</span>)}
</CellFooter>
</Cell>
</Cells>
<CellsTips>完善信息以便我们可以多种渠道联系到您</CellsTips>
<CellsTitle>时区设置</CellsTitle>
<Form>
<FormCell className="setting-cell zone-cell">
<CellHeader>
时区
</CellHeader>
<CellBody>
<Input
type="text"
onClick={this.setting.clickInput}
placeholder=""
value={getEnumByKey(_.get(setting, "timezone", "UTC+8"), timezoneEnum).name}
readOnly={true}
/>
</CellBody>
</FormCell>
</Form>
<CellsTips>时区不同打卡时间不同,一个月只能改一次时区</CellsTips>
<Picker
onChange={this.setting.saveTimeZone}
defaultSelect={[20]}
groups={this.setting.timeZoneGroup}
show={this.setting.showTimeZonePicker}
onCancel={this.setting.cancelTimeZone}
lang={{ leftBtn: "取消", rightBtn: "确定" }}
/>
</div>
</div>
)
}
}
export default Setting;
```
success.js
```'use strict';
import React, { Component } from "react";
import { browserHistory } from 'react-router';
import { observer, inject, PropTypes } from "mobx-react";
import Weui from 'react-weui';
import httpToast from '../../../../store/common/httpToast';
import _ from '../../../util';
const {
MediaBox,
MediaBoxBody,
MediaBoxTitle,
MediaBoxDescription,
Button,
Panel,
PanelBody
} = Weui;
@inject("Setting", "SettingConfig", "EnrollDetail") @observer
class EnrollPaySuccessPage extends Component {
constructor(props) {
super(props);
const { Setting, SettingConfig, EnrollDetail, params, } = this.props;
this.setting = new Setting();
this.config = new SettingConfig('phoneNumber');
this.courseId = params.courseId;
this.detail = new EnrollDetail(this.courseId);
}
componentDidMount() {
this.setting.setInfo();
this.detail.fetchDetail(this.detail.setDetail);
}
render() {
const { setting } = this.setting;
const { value, saveConfig, handleChange } = this.config;
const phoneNumber = value == null ? setting.phoneNumber : value;
const isPhoneValid = _.isValidPhoneNumber(phoneNumber);
const redirectUrl = `/redirect?target=/course/detail/${ this.courseId }`;
return (
<div className="page page-current enroll-page pay-success-page">
<header className="bar bar-nav p-xxs pay-success-header">
<i className="icon-gb icon-gb-share-tap pull-right"/>
<span className="pull-right m-r-lg share-tip">点击上方,分享这门好课</span>
</header>
<main className="content pay-success-content">
<MediaBox type="text" className="text-center p-n">
<MediaBoxBody className="success-message">
<MediaBoxTitle className="success-message-title p-m">
课程报名成功!查看
<span className="course-title"
onClick={ () => browserHistory.replace(redirectUrl)}>
我的课程
</span>
</MediaBoxTitle>
<div className="divide-full"/>
<MediaBoxDescription className="success-message-form">
完善下方信息获取更多服务哦~
<div className="phone-number m-t m-b-sm">
<span className="m-r-sm">手机号</span>
<input type="number" className="phone-number-input p-l-xs p-r-xs"
value={phoneNumber}
onChange={handleChange}/>
</div>
<Button size="small" disabled={isPhoneValid === false}
onClick={() => saveConfig()
.then(() => {
httpToast.showToast({ text: '设置成功', icon: 'success' });
setTimeout(() => browserHistory.replace(redirectUrl), 1200);
})
}>
提交
</Button>
</MediaBoxDescription>
</MediaBoxBody>
</MediaBox>
<Panel className="m-t-md">
<PanelBody className="text-center p-m subscribe-guide">
<div className="subscribe-alarm"><i className="icon-gb icon-gb-alarm pull-left"/>关键一步</div>
<img className="subscribe-info m-b-sm" src="http://qiniuprivate.gambition.cn/gGJ0Vv_subscribe_uband.png"/>
<img className="subscribe-qrcode" src="http://qiniuprivate.gambition.cn/5V62W2_uband_qrcode.png"/>
</PanelBody>
</Panel>
</main>
</div>
)
}
}
EnrollPaySuccessPage.propTypes = {
Setting: PropTypes.objectOrObservableObject,
params: React.PropTypes.object
};
export default EnrollPaySuccessPage;
```
detail.js
```'use strict';
/**
* Created by violinsolo on 07/07/2017.
*/
import { observable, useStrict, action } from "mobx";
import util from "../util";
import WechatShare from "../common/wechatShare";
import { httpGet, httpPost } from "../../service";
import Modal from "../common/modal";
useStrict(true);
const baseUrl = `${util.baseUrl}api`;
export default class ActivityDetail {
@observable
modal = new Modal("关注回复'活动'二字参与", "关闭");
@observable
activityInfo = {
name: null,
banner: null,
isSelf: false,
isFavour: false,
progressRate: 0,
neededFavor: 0
};
@observable
userInfo = {
name: null,
headImgUrl: null
};
constructor(activityId, userId) {
this.activityId = activityId;
this.userId = userId;
}
@action
setActivityInfo = (activityInfo) => {
const { name: username, headImgUrl, isSelf, isFavour, progressRate, neededFavor } = activityInfo;
const { name: activityName, description: activityDescription, banner } = activityInfo.activityInfo;
this.activityInfo = {
name: activityName,
banner: banner,
isSelf: isSelf,
isFavour: isFavour,
progressRate: progressRate,
neededFavor: neededFavor
};
this.userInfo = {
name: username,
headImgUrl: headImgUrl
};
const shareUsername = isSelf ? '我' : username;
const shareDescription = `${ shareUsername }正在参加“${ activityName }”,快来支持${ shareUsername }!`;
this.wechatShare = new WechatShare(
activityName,
shareDescription,
`${ location.origin }/redirect?target=/activity/${ this.activityId }/user/${this.userId}`,
banner
);
};
fetchActivityInfo = () => httpGet(`${baseUrl}/activity/${this.activityId}/user/${this.userId}`);
favourUser = () => httpPost(`${baseUrl}/activity/${this.activityId}/user/${this.userId}/favour`);
}
```
me.js
```'use strict';
import React, {Component} from "react";
import {observer, inject} from "mobx-react";
import "../../../../style/me.scss";
@inject("User") @observer
class Me extends Component {
constructor(props) {
super(props);
this.user = this.props.User;
}
componentDidMount() {
this.user.fetchInfo(this.user.setInfo);
}
render() {
return (
<div className="page-group">
{this.props.children}
</div>
)
}
}
export default Me;
```
redirect.js
```import React, { Component } from "react";
import { browserHistory } from "react-router";
class RedirectPage extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { target } = this.props.location.query;
setTimeout(() => {
if (target) {
if (target.startsWith("/enroll/pay/")) {
// 如果到支付页面则替换
window.location.href = target;
} else {
browserHistory.replace(target);
}
} else {
browserHistory.replace('/');
}
}, 0);
}
render() {
return (
<div className="page page-current">
页面跳转中。。。。
</div>
)
}
}
export default RedirectPage;
```
pay.js
```'use strict';
import { observable, useStrict, action, computed } from "mobx";
import { browserHistory } from 'react-router';
import uniqueToast from '../common/httpToast';
useStrict(true);
import util from "../util";
const baseUrl = `${util.baseUrl}api`;
import { httpGet, httpPost } from "../../service";
class Pay {
@observable payment = {
promotionOffer: null
};
@observable dialog = { title: "提示", content: "", show: false };
@observable fee = {
coupon: false,
coin: false,
couponItem: null,
coinItem: null,
amount: 0,
totalFee: 0,
originFee: 0,
priceItemName: '免费'
};
// 首单优惠码
@observable firstOfferCode = null;
// 首单优惠码是否合法
@observable isFirstOfferCodeValid = false;
constructor(cid) {
this.cid = cid;
this.diaButtons = [
{
type: "default",
label: "取消",
onClick: this.hideDialog
},
{
type: "primary",
label: "确认",
onClick: this.prePay
}
];
}
@action
setFee = (priceItem) => {
this.fee.totalFee = priceItem.totalFee;
this.fee.originFee = priceItem.originFee;
this.fee.months = priceItem.months;
this.fee.couponItem = priceItem.coupon;
this.fee.coinItem = priceItem.coin;
this.fee.priceItemName = priceItem.name;
this.calculateActualAmount();
};
@action
setPayment = (data) => {
this.payment = { ...data };
this.firstOfferCode = util.get(data, 'promotionOffer.promotionUserInfo.key', null)
if (this.isFirstOffer && this.firstOfferCode) {
this.isFirstOfferCodeValid = true;
}
this.setFee(data.priceList[0]);
};
fetchPayInfo = (scb) =>
httpGet(`${baseUrl}/clazz/${this.cid}/payment`)
.then(scb);
@action
hideDialog = () => this.dialog.show = false;
@action
showDialog = () => this.dialog.show = true;
formatMoney = (rawMoney) => {
return (rawMoney != null ? Number(rawMoney) / 100 : 0).toFixed(2);
};
@computed
get coinState() {
return this.fee.coupon ? "min" : "max";
}
@computed
get diaContent() {
return `您还要支付${this.formatMoney(this.fee.amount)}元, 是否前往支付?`
}
/**
* 是否为首单
*
* @returns {boolean}
*/
@computed
get isFirstOffer() {
return util.get(this.payment, 'promotionOffer.joinedClazzCount', 0) === 0;
}
@action
calculateActualAmount = () => {
const coupon = (this.fee.couponItem != null && this.fee.coupon)
? this.fee.couponItem.money
: 0;
const coin = this.fee.coin ? this.fee.coinItem[this.coinState] : 0;
const offerPrice = this.isFirstOfferCodeValid
? util.get(this.payment, 'promotionOffer.offerPrice', 0)
: 0;
this.fee.amount = Math.max(this.fee.totalFee - (coupon + coin) * 100 - offerPrice, 0);
};
@action
changeSwitch = (type) => {
this.fee[type] = !this.fee[type];
this.calculateActualAmount();
};
/**
* 优惠码更新事件处理器
*
* @param promotionCode
*/
@action
promotionCodeChangeHandler = (promotionCode) => {
// 优惠码不合法
this.isFirstOfferCodeValid = false;
// 设置新值
this.firstOfferCode = promotionCode;
// 更新优惠价格为0
this.payment.promotionOffer.offerPrice = 0;
this.calculateActualAmount();
if (promotionCode.length >= 6) {
this._fetchPromotionOffer(promotionCode)
.then(action((promotionOffer) => {
const promotionUser = promotionOffer.promotionUser;
if (promotionUser != null) {
// 更新推荐人信息
this.payment.promotionOffer.promotionUserInfo = promotionUser;
// 更新优惠价格
this.payment.promotionOffer.offerPrice = promotionOffer.offerPrice;
// 优惠码合法
this.isFirstOfferCodeValid = true;
// 重新计算价格
this.calculateActualAmount();
}
}));
}
};
alertInvalidPromotionCode = () => {
if (this.isFirstOfferCodeValid !== true) {
uniqueToast.showToast({ text: '无效的优惠码' });
}
};
// 调用远端API,获取优惠码详情
_fetchPromotionOffer = (promotionCode) => httpGet(`${baseUrl}/clazz/${ this.cid }/promotion/offer?promotionCode=${ promotionCode }`);
prePay = () => {
uniqueToast.stickyToast({ text: "订单生成中...", icon: 'loading' });
const { amount, priceItemName, months, coupon, coin, couponItem, coinItem } = this.fee;
const body = {
money: amount,
priceItemName: priceItemName,
months: months,
coupon: {
selected: coupon,
id: coupon ? couponItem.id : undefined
},
coin: {
selected: coin,
coin: coin ? coinItem[this.coinState] : 0
}
};
// 如果优惠码合法,则增加之
if (this.isFirstOfferCodeValid) {
body.promotionCode = this.firstOfferCode;
}
httpPost(`${baseUrl}/clazz/${this.cid}/payment`, body)
.then(data => {
uniqueToast.hideToast();
this.hideDialog();
const { action, clazzInfo, redirectToPassport } = data;
const redirectUrl = `/redirect?target=/enroll/pay/${ this.cid }/success`;
switch (action) {
case "ALREADY_JOIN":
browserHistory.replace(redirectUrl);
break;
case "SUCCESS":
uniqueToast.showToast({ text: "成功加入班级", icon: "success" });
window.setTimeout(() => browserHistory.replace(redirectUrl), 1500);
break;
case "TOPAY":
this.invokeWXPay(data.signData, redirectUrl);
break;
default:
uniqueToast.showToast({ text: "业务处理失败", icon: "warn" });
break;
}
})
.catch((error) => {
uniqueToast.hideToast();
uniqueToast.showToast({ text: "业务处理失败", icon: "warn" });
})
};
invokeWXPay = (signData, redirectUrl) => {
const jsApiCall = () => {
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
{
appId: signData.appid,
timeStamp: `${ signData.timeStamp }`,
nonceStr: signData.nonceStr,
package: signData.package,
signType: signData.signType,
paySign: signData.paySign
},
(res) => {
this.hideDialog();
//判断支付返回的参数是否支付成功并跳转
if (res.err_msg === "get_brand_wcpay_request:ok") {
// 支付成功后的回调函数
uniqueToast.showToast({ text: "支付成功", icon: "success" });
window.setTimeout(() => browserHistory.replace(redirectUrl), 1500);
} else {
uniqueToast.showToast({ text: "支付失败", icon: "warn" });
}
}
);
};
if (typeof WeixinJSBridge === "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', jsApiCall);
document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
}
} else {
jsApiCall();
}
}
}
export default Pay;
```
study.js
```'use strict';
import { observable, useStrict, action, computed } from "mobx";
import util from "../util";
useStrict(true);
const baseUrl = `${util.baseUrl}api`;
class CourseStudy {
@observable
currentPanel = this.PANEL.taskPanel;
constructor(courseId) {
this.courseId = courseId;
this.PANEL = {
taskPanel: 'taskPanel',
rankPanel: 'rankPanel'
};
}
@action
setCurrentPanel = (panel) => {
const currentPanel = util.get(this.PANEL, panel, null);
if (currentPanel != null) {
this.currentPanel = currentPanel;
}
};
@computed
get currentDetailPanel() {
return this.currentPanel;
}
}
export default CourseStudy;
```
config.js
```'use strict';
import { observable, useStrict, action } from "mobx";
import util from "../util";
import { httpGet } from "../../service";
useStrict(true);
const baseUrl = `${util.baseUrl}api`;
class SystemConfig {
@observable
appInfo = null;
constructor() {
}
fetchAppInfo = (platform) => {
if (sessionStorage.APP_INFO == null) {
return this._fetchAppInfo(platform)
.then((appInfo) => {
if (appInfo.url != null) {
sessionStorage.APP_INFO = true;
this._setAppInfo(appInfo);
window.setTimeout(() => this._setAppInfo(null), 5000);
}
});
}
return Promise.resolve({});
};
/*********************************************************************************************************************
* 私有方法
*********************************************************************************************************************/
_fetchAppInfo = (platform) => httpGet(`${ baseUrl }/app?platform=${ platform }`);
@action
_setAppInfo = (appInfo) => this.appInfo = appInfo;
}
export default SystemConfig;
```
teacher-list.js
```'use strict';
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import { Link } from "react-router";
import WeUI from "react-weui";
import UbandHeader from "../ubandHeader";
import BottomTabBar from "../bottomTabBar";
import EmptyTip from "../../EmptyTip";
import _ from '../../util';
import { genderEnum } from "../../enum";
const {
Cells,
Cell,
CellHeader,
CellBody,
CellFooter
} = WeUI;
@inject("TeacherList") @observer
export default class TeacherListPage extends Component {
constructor(props) {
super(props);
this.teacherList = new this.props.TeacherList();
}
componentDidMount() {
const { fetchList, setTeachers } = this.teacherList;
// fetch teacher list
fetchList().then(setTeachers);
}
render() {
const { teacherList } = this.teacherList;
return (
<div className="teacher-page">
<UbandHeader/>
<div className="teacher-classification">全部 | 口译 | 编程</div>
<div className="content">
<Cells className="m-t-none teacher-list">
{
(_.get(teacherList, 'length', 0) > 0)
? teacherList.map((item) => {
const { id, name, headImgUrl, description, followUserCount, clazzStudentCount, gender, tags } = item;
return <Cell className="teacher-cell" component={Link} to={`/redirect?target=/teacher/${ id }`} key={ id }>
<CellHeader>
<div className="avatar-wrap">
<img src={headImgUrl}/>
</div>
</CellHeader>
<CellBody className="teacher-info">
<div className="teacher-header">
<span className="teacher-name long-text-should-ellipsis">{name}</span>
<span className="header-text-hint long-text-should-ellipsis header-text-hint-gap ">关注 {followUserCount}</span>
<span className="header-text-hint long-text-should-ellipsis">学生 {clazzStudentCount}</span>
</div>
<div className="teacher-desc text-overflow-hidden">
{description}
</div>
<div className="teacher-label text-overflow-hidden">
{
tags.map((tagItem) => {
return <span className={`badge label-${(_.get(genderEnum, gender, '0')).key}`} key={ id + tagItem }>{tagItem}</span>
})
}
</div>
</CellBody>
<CellFooter>
</CellFooter>
</Cell>
})
: <EmptyTip tip="空空如也"/>
}
</Cells>
</div>
<BottomTabBar currentTab="teacher-list"/>
</div>
);
}
}
```
student.js
```import {observable, useStrict, action, computed} from "mobx";
useStrict(true);
import util from "../util";
import Paginator from "../common/paginator";
import {httpGet} from "../../service";
const baseUrl = `${util.baseUrl}api/clazz`;
class Students {
@observable showWaiting = util.get(sessionStorage, "SHARK_ONE_SHOW_WAITING", "true") === "true";
@observable keyWord = util.get(sessionStorage, "SHARK_ONE_KEY_WORD", "");
constructor(cid) {
this.cid = cid;
this.timer = null;
this.all = new Paginator();
this.wait = new Paginator();
}
fetchStudents = (pageNumber = 1, keyWord = "", pageSize = 13, showWaiting = this.showWaiting) => {
return httpGet(`${baseUrl}/${this.cid}/feedbacks?pageNumber=${pageNumber}&pageSize=${pageSize}&keyWord=${keyWord}&isWaitingOnly=${showWaiting}`);
};
getStudents = () => {
let {updateData, pageNumber} = this.showWaiting ? this.wait : this.all;
this.fetchStudents(pageNumber, this.keyWord).then(updateData);
};
getInitialStudents = () => {
let {updateData, resetValues} = this.showWaiting ? this.wait : this.all;
resetValues();
this.fetchStudents(1, this.keyWord).then(updateData);
};
@action
cancelSearch = () => {
// 保存搜索条件到sessionStorage
sessionStorage.SHARK_ONE_KEY_WORD = this.keyWord = "";
this.getInitialStudents();
};
@action
toggleWait = () => {
// 保存是否只显示未回复到sessionStorage
sessionStorage.SHARK_ONE_SHOW_WAITING = this.showWaiting = !this.showWaiting;
this.getStudents();
};
@computed
get showingStudents() {
return this.showWaiting ? this.wait.values : this.all.values;
}
@action
setKeyword = (e) => {
// 保存搜索条件到sessionStorage
sessionStorage.SHARK_ONE_KEY_WORD = this.keyWord = e.target.value;
const getInitialStudents = this.getInitialStudents;
clearTimeout(this.timer);
this.timer = setTimeout(() => {
getInitialStudents();
}, 1000);
};
hasMore = () => {
return this.showWaiting ? this.wait.hasMore : this.all.hasMore;
}
}
export default Students;
```
list.js
```'use strict';
import { observable, useStrict, action } from "mobx";
import util from "../util";
import { httpGet } from "../../service";
const baseUrl = `${util.baseUrl}api`;
useStrict(true);
class CourseList {
@observable processList = [];
@observable closeList = [];
@observable currentPanel = this.PANEL.PROCESSING;
constructor() {
this.PANEL = {
PROCESSING: 'PROCESSING',
CLOSE: 'CLOSE'
};
// 是否加载数据标识
this.isLoaded = false
}
markReloadFlag = () => {
this.isLoaded = false;
};
getList = () => {
this._fetchList("PROCESSING").then((data) => this._setListData(this.processList, data));
this._fetchList("CLOSE").then((data) => this._setListData(this.closeList, data));
this.isLoaded = true;
};
@action
setCurrentPanel = (currentPanel) => {
const panel = util.get(this.PANEL, currentPanel, null);
if (panel != null) {
this.currentPanel = panel;
}
};
@action
_setListData = (container, data) => {
container.splice(0, container.length);
data.forEach((item) => {
item.redirectUrl = `/course/${ item.id }/detail`;
container.push(item);
});
};
_fetchList = (status) => httpGet(`${baseUrl}/clazzes?status=${status}`);
}
export default new CourseList();
```
enroll.js
```'use strict';
import { observable, useStrict, action, computed } from "mobx";
import WechatShare from "../common/wechatShare";
import util from "../util";
import { httpGet, httpPost } from "../../service";
import Modal from "../common/modal";
useStrict(true);
const baseUrl = `${util.baseUrl}api`;
export default class ActivityEnroll {
@observable
modal = new Modal("Uband线上活动", "关闭");
@observable
// 推广活动详情
activityItem = {
joined: false,
banner: null,
introduction: {
introduction: null,
requirements: null,
questionAnswered: null
}
};
@observable
currentPanel = this.PANEL.introduction;
constructor(activityId) {
this.activityId = activityId;
this.PANEL = {
introduction: 'introduction',
requirements: 'requirements',
questionAnswered: 'questionAnswered',
messageBook: 'messageBook'
};
}
@action
setActivityDetail = (activityItem) => {
this.activityItem = activityItem;
this.activityItem.joined = util.get(activityItem, 'joined', false);
const banner = util.get(activityItem, 'banner', null);
this.activityItem.banner = banner;
this.activityItem.introduction.introduction = util.get(activityItem, 'introduction.introduction', null);
this.activityItem.introduction.requirements = util.get(activityItem, 'introduction.requirements', null);
this.activityItem.introduction.questionAnswered = util.get(activityItem, 'introduction.questionAnswered', null);
const activityName = util.get(activityItem, 'name', 'Uband线上活动'),
activityDescription = util.get(activityItem, 'description', '快来一起参与吧');
this.wechatShare = new WechatShare(
activityName,
activityDescription,
`${ location.origin }/redirect?target=/activity/${ this.activityId }`,
banner
);
};
@action
setCurrentPanel = (panel) => {
const currentPanel = util.get(this.PANEL, panel, null);
if (currentPanel) {
this.currentPanel = currentPanel;
}
};
@computed
get currentDetailPanel() {
return this.currentPanel;
}
fetchActivityDetail = () => httpGet(`${baseUrl}/activity/${ this.activityId }`);
enrollActivity = () => httpPost(`${baseUrl}/activity/${ this.activityId }/user`);
}
```
footer.js
```import React, {Component} from "react";
import {Link} from "react-router";
import {inject, observer} from "mobx-react";
import WeuiToast from "../../../WeuiToast";
import "../../../../../style/chat.scss";
@inject("Record") @observer
class Footer extends Component {
constructor(props) {
super(props);
let {courseId, list, chat, isTeacher, feedbackId} = this.props;
this.record = new this.props.Record(courseId, list, chat, isTeacher, feedbackId);
// todo 移除state, 好孩子不要学
this.state = {
footerBtnState: [false, false]
};
this.toggleAudio = this.toggleAudio.bind(this);
this.toggleText = this.toggleText.bind(this);
}
componentDidMount() {
this.record.initWeixinSDK(`${ location.pathname }${ location.search }`);
}
toggleAudio() {
// todo 移除setState, 好孩子不要学
this.setState({
footerBtnState: [true, false]
})
}
toggleText() {
// todo 移除setState, 好孩子不要学
this.setState({
footerBtnState: [false, true]
})
}
componentWillReceiveProps(nextProps) {
if (nextProps.resetFooter)
// todo 移除setState, 好孩子不要学
this.setState({
footerBtnState: [false, false]
})
}
componentWillUnmount() {
this.record.handleCancel();
}
render() {
const {isTeacher, courseId, feedbackId, chat} = this.props;
const {handleTextChange, postText, text} = chat;
const {footerBtnState} = this.state;
const actionBarState = footerBtnState[0] ? "chat-audio-active" : footerBtnState[1] ? "chat-text-active" : ""
const {active, content, state, handleClick, toast, handleCancel} = this.record;
return (
<div className={actionBarState + " bar bar-footer chat-footer"}>
<div className="footer-row">
<div className={(footerBtnState[0] ? "active " : "") + "row-equal chat-audio"} onClick={this.toggleAudio}>
<i className="icon-gb icon-gb-microphone"/>语音
</div>
<div className={(footerBtnState[1] ? "active " : "") + "row-equal chat-text"} onClick={this.toggleText}>
<i className="icon-gb icon-gb-keyboard"/>文字
</div>
{!isTeacher || (
<Link to={`/course/${ courseId }/one/material/${ feedbackId }`} className="row-equal chat-material"><i
className="icon-gb icon-gb-menu"/>素材</Link>)}
</div>
<div className="text-input-section">
<div className="searchbar row">
<div className="search-input col-80">
<input type="text" value={text} onChange={handleTextChange} maxLength="700"/>
</div>
<a className="button button-fill button-primary col-20" onClick={postText}>发送</a>
</div>
</div>
<div className={"audio-input-section " + active}>
<div className="record-tip">{content.tip}</div>
<div className={"record-btn " + state} onClick={handleClick}>
<i className="icon-gb icon-gb-pause-l"/>
<i className="icon-gb icon-gb-send-l"/>
</div>
<div className="record-status">{content.status}</div>
<div className="record-overlay"></div>
<div className="cancel-btn" onClick={handleCancel}>取消</div>
</div>
<WeuiToast show={toast.show} icon={toast.icon} iconSize={"large"}>{toast.text}</WeuiToast>
</div>
)
}
}
export default Footer
```
activity.js
```'use strict';
import React, {Component} from "react";
import {observer, inject} from "mobx-react";
import "../../../../style/activity.scss";
@inject("User") @observer
class Activity extends Component {
constructor(props) {
super(props);
this.user = this.props.User;
}
componentDidMount() {
this.user.fetchInfo(data=>this.user.setInfo(data));
}
render() {
return (
<div className="page-group">
{this.props.children}
</div>
)
}
}
export default Activity;
```
notFound.js
```import React, { Component } from "react";
import {Link} from "react-router";
import { Button } from "react-weui";
import WeuiIcon from "../WeuiIcon";
import "../../../style/not-found.scss";
class NotFoundPage extends Component {
render() {
return (
<div className="page page-current not-found-page">
<WeuiIcon size="large" value="warn"/>
<footer>
<h3>出错了哟</h3>
<p>非常抱歉,服务器开小差了<br/>请点击下方按钮返回至课程主页</p>
<Button component={Link} to="/course/list" style={{color: 'white'}}>课程主页</Button>
</footer>
</div>
)
}
}
export default NotFoundPage;
```
password.js
```'use strict';
import { observable, useStrict, action, computed } from "mobx";
import Toast from "../common/toast";
import util from "../util";
import { httpGet, httpPost, httpPut } from "../../service";
import httpToast from "../common/httpToast";
import topTip from "../common/toptip";
useStrict(true);
const baseUrl = `${util.baseUrl}api/account`;
class Password {
@observable
oldPassword = "";
@observable
newPassword = "";
@observable
hasSetPassword = false;
@observable
showOldPassword = false;
@observable
showNewPassword = false;
@observable
isUpdating = false;
constructor() {
this.toast = new Toast();
}
fetchHasSetPassword = () => this._fetchHasSetPassword().then(this._setPasswordState);
updatePassword = () => {
this._setIsUpdating(true);
httpToast.stickyToast({ text: "Loading...", icon: "loading" });
const update = (this.hasSetPassword === true)
? httpPut(
`${baseUrl}/password`,
{
password: this.newPassword,
oldPassword: this.oldPassword
}
)
: httpPost(`${baseUrl}/password`, {
password: this.newPassword
});
return update.then((data) => {
httpToast.hideToast();
this._setIsUpdating(false);
httpToast.showToast({ text: "操作成功", icon: "success", cb: () => history.back() });
return data;
})
.catch((error) => {
this._setIsUpdating(false);
});
};
@action
setOldPassword = oldPassword => this.oldPassword = oldPassword;
@action
setNewPassword = newPassword => this.newPassword = newPassword;
@action
toggleOldPassword = event => this.showOldPassword = !this.showOldPassword;
@action
toggleNewPassword = event => this.showNewPassword = !this.showNewPassword;
showInvalidPasswordTip = () => topTip.showToptip({type: "warn", content: "请输入符合规范的密码!"});
/**
* check btn state
* @returns {boolean} : return false if btn must block, true means btn can click!
*/
@computed
get isPasswordValid() {
if (this.hasSetPassword === true) {
//if is reset password page
return this._validatePassword(this.newPassword) && this.oldPassword !== "";
}
//set new password page
return this._validatePassword(this.newPassword);
}
/*********************************************************************************************************************
* 以下为内部方法,请勿在外部调用
*********************************************************************************************************************/
/**
* validate the psd,
* @param psd : the password
* @returns {boolean} : return true if it pass the validation
*/
_validatePassword = (psd) => (8 <= psd.length && psd.length <= 20);
_fetchHasSetPassword = () => httpGet(`${baseUrl}/password`);
@action
_setIsUpdating = (isUpdating) => this.isUpdating = isUpdating;
@action
_setPasswordState = data => this.hasSetPassword = data === true;
}
export default Password;
```
detail.js
```import {observable, useStrict, action} from "mobx";
useStrict(true);
import util from "../util";
const baseUrl = `${util.baseUrl}api`;
import WechatShare from "../common/wechatShare";
import {httpGet} from "../../service";
class EnrollDetail {
@observable detail = {};
@observable introduction = "";
constructor(cid) {
this.cid = cid;
this.cUrl = `${baseUrl}/clazz/${this.cid}`;
}
@action
setDetail = (dObj) => {
this.detail = {...dObj};
const { name, author, banner, description } = dObj;
this.wechatShare = new WechatShare(
name,
`${ description } By ${ author }`,
`${ location.origin }/redirect?target=enroll/${ this.cid }`,
banner
);
};
@action
setIntrodution = (data) => {
this.introduction = util.clearNodeClazzAndStyle(data.introduction);
};
fetchDetail = (scb) =>
httpGet(this.cUrl).then(scb);
fetchIntroduction = (scb) =>
httpGet(`${this.cUrl}/introduction`).then(scb);
}
export default EnrollDetail;
```
coupon.js
```import {observable, useStrict, action} from "mobx";
useStrict(true);
import util from "../util";
const baseUrl = `${util.baseUrl}api/account`;
import {httpGet} from "../../service";
class Coupon {
@observable info = [];
setInfo = () => this.fetchInfo(action((data) => {
this.info = data;
}));
fetchInfo = (scb) =>
httpGet(`${baseUrl}/coupons`)
.then(scb)
}
export default new Coupon();
```
modal.js
```import {observable, action} from "mobx";
class Modal {
@observable state = false;
constructor(title, ...buttonslabel) {
this.title = title;
this.buttons = this._getButtons(buttonslabel);
}
_getButtons = (label) => {
return label.map(item => ({
label: item,
onClick: this.close
}))
};
@action
open = () => this.state = true;
@action
close = () => this.state = false;
}
export default Modal;
```
checkin-center.js
```import React, { Component } from "react";
import { Link } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import EmptyTip from "../../../EmptyTip";
import "../../../../../style/checkin-center.scss";
const {
Cells,
Cell,
CellHeader,
CellBody,
Badge
} = WeUI;
@inject("CheckinCenter") @observer
class CheckinCenter extends Component {
constructor(props) {
super(props);
this.center = new this.props.CheckinCenter();
}
componentDidMount() {
this.center.getList()
}
render() {
return (
<div className="page page-current checkin-center-page">
<header className="bar bar-nav">
<h1 className="title">打卡中心</h1>
</header>
<div className="content">
<Cells className="m-t-none">
{
this.center.courseList.length > 0
? this.center.courseList.map(item => (
<Cell className="course-list-cell" component={Link}
to={`/course/${ item.id }/detail?tabIndex=1`}
key={item.id}>
<CellHeader>
<div className="course-cover">
<img src={item.banner}/>
</div>
</CellHeader>
<CellBody>
<div className="course-title">
{item.name}
</div>
<div className="checkin-center-course-desc">
<div className="course-desc course-desc-flexible">
{item.description}
</div>
<Badge dot preset="footer" className={`indicator ${item.hasCheckin ? "icon-has-checkin": "icon-not-checkin"}`}/>
</div>
</CellBody>
</Cell>
))
: <EmptyTip tip="打卡中心为空?可能你还没有报名课程哦~"/>
}
</Cells>
</div>
</div>
)
}
}
export default CheckinCenter;
```
coin.js
```'use strict';
import { observable, useStrict, action, computed } from "mobx";
import util from "../util";
import { httpGet } from "../../service";
const baseUrl = `${util.baseUrl}api/account`;
useStrict(true);
class Coin {
@observable
coinInfo = {}; // 优币信息
@observable
withdrawList = []; // 退款详情列表
@observable
panel = this.PANEL.COIN;
constructor() {
this.PANEL = {
COIN: 'COIN',
WITHDRAW: 'WITHDRAW'
}
}
/**
* 1. 获取优币详情
* 2. 设置优币信息
*/
fetchCoinInfo = () => this._fetchCoinInfo().then(this._setCoinInfo);
/**
* 1. 获取退款列表
* 2. 设置退款列表
*/
fetchWithdrawList = () => this._fetchWithdrawList().then(this._setWithdrawList);
@action
setCurrentPanel = (panel) => {
const currentPanel = util.get(this.PANEL, panel, null);
if (panel != null) {
this.panel = currentPanel;
}
};
@computed
get currentPanel() {
return this.panel
};
/*********************************************************************************************************************
* 以下为内部方法,请勿直接调用
*********************************************************************************************************************/
// 获取优币详情
_fetchCoinInfo = () => httpGet(`${baseUrl}/coins`);
// 获取退款列表
_fetchWithdrawList = () => httpGet(`${baseUrl}/withdraws`);
// 设置优币信息
@action
_setWithdrawList = (withdrawList) => this.withdrawList = [...withdrawList];
// 设置退款列表
@action
_setCoinInfo = (coinInfo) => this.coinInfo = { ...coinInfo };
}
export default new Coin();
```
record.js
```import {observable, useStrict, action, computed} from "mobx";
import Toast from "../common/toast";
import {httpGet, httpPost} from "../../service";
import util from "../util";
import {AudioItem} from "./chat";
const baseUrl = `${util.baseUrl}api`;
useStrict(true);
const STATUS = {
start: {
tip: "",
status: "点击开始录音",
},
record: {
tip: "满45s自动停止",
status: "录音中"
},
send: {
tip: "满45s自动停止",
status: "点击发送"
}
};
export default class Record {
@observable state = "start";
@observable timer = null;
constructor(cid, list, chat, isTeacher, feedbackId) {
this.toast = new Toast();
this.hasInitWeixinSDK = false;
this.cid = cid;
this.list = list;
this.chat = chat;
this.localId = 0;
this.isTeacher = isTeacher;
this.fid = feedbackId;
this.url = null;
}
initWeixinSDK = (url) => {
if (this.hasInitWeixinSDK === false) {
// 使用额外变量存储当前url,因在wx方法中url为最初值
this.url = url;
// 初始化WexxinSDK失败
this.hasInitWeixinSDK = false;
httpGet(`${baseUrl}/wechat/jsSdkAuth?url=${ encodeURIComponent(url) }`)
.then(data => {
const params = {
...data,
jsApiList: [
"startRecord",
"stopRecord",
"onVoiceRecordEnd",
"playVoice",
"pauseVoice",
"stopVoice",
"onVoicePlayEnd",
"uploadVoice",
"downloadVoice"
]
};
delete params.jsapi_ticket;
delete params.url;
wx.error(() => {
if (this.url !== localStorage.originUrl) {
return void this.initWeixinSDK(localStorage.originUrl);
}
// 标记录音失败
this.hasInitWeixinSDK = false;
// 提示授权失败
this.toast._showToast({text: "微信鉴权失败", icon: "warn", back: false});
});
wx.config(params);
/**
* 注意:该函数会在声明的时候立即调用
*/
wx.ready(() => {
// 初始化WeixinSDK成功
this.hasInitWeixinSDK = true;
});
});
}
};
@computed
get active() {
return this.state === "start" ? "" : "active"
}
@computed
get content() {
return STATUS[this.state];
}
@action
handleClick = () => {
if (this.hasInitWeixinSDK) {
switch (this.state) {
case "start":
this._handleStart();
break;
case "record":
this._handleRecord();
break;
case "send":
this._handleSend();
break;
default:
this.state = "start";
}
} else {
this.toast._showToast({text: "微信授权中", icon: "loading", back: false});
this.initWeixinSDK(`${ location.pathname }${ location.search }`);
}
};
_handleStart = () => {
let self = this;
wx.startRecord({
success: action(() => {
self.state = "record";
self.timer = setTimeout(function () {
self._handleRecord();
}, 44000);
}),
fail: action(() => {
self.state = "start";
self.hasInitWeixinSDK = false;
self.toast._showToast({text: "开始录音失败", icon: "warn", back: false});
})
});
};
_handleRecord = () => {
let self = this;
wx.stopRecord({
success: action((res) => {
self.state = "send";
self.localId = res.localId;
self.timer && clearTimeout(self.timer);
}),
fail: action(() => {
self.state = "start";
self.hasInitWeixinSDK = false;
self.toast._showToast({text: "结束录音失败", icon: "warn", back: false});
})
});
};
_handleSend = () => {
let self = this;
wx.uploadVoice({
localId: self.localId,
isShowProgressTips: 1,
success: action((res) => {
self.localId = res.serverId;
self.sendRecord()
.then(action(item => {
item["audio"] = new AudioItem(self.chat, item.id);
self.list.push(item);
// self.list.push(data); <-错误用法!!!
self.handleCancel();
}))
}),
fail: () => {
self.hasInitWeixinSDK = false;
self.toast._showToast({text: "上传语音失败", icon: "warn", back: false});
}
});
};
@action
handleCancel = () => {
let self = this;
if (this.state === "record") {
wx.stopRecord({
success: action((res) => {
self.state = "start";
self.timer && clearTimeout(self.timer);
}),
fail: action(() => {
self.hasInitWeixinSDK = false;
self.state = "start";
self.toast._showToast({text: "结束录音失败", icon: "warn", back: false});
})
})
} else {
self.state = "start";
self.timer && clearTimeout(self.timer);
}
};
sendRecord = () => {
let targetUrl;
if (this.fid) {
targetUrl = `${baseUrl}/clazz/${this.cid}/feedback/${this.fid}`
} else {
targetUrl = `${baseUrl}/clazz/${this.cid}/feedback`;
}
return httpPost(targetUrl, {
replyType: "VOICE",
mediaId: this.localId
})
}
}
```
coin.js
```'use strict';
import React, { Component } from "react";
import { Link } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import { getEnumByKey, withdrawStatusEnum } from "../../enum";
import _ from "../../util";
import commonUtil from '../../../common-util';
const {
Cells,
Cell,
CellBody,
CellFooter,
Tab,
TabBody,
NavBar,
NavBarItem,
Button
} = WeUI;
@inject("Coin") @observer
class Coin extends Component {
constructor(props) {
super(props);
this.coin = this.props.Coin;
}
componentDidMount() {
const { fetchCoinInfo, fetchWithdrawList } = this.coin;
fetchCoinInfo();
fetchWithdrawList();
}
render() {
const { coinInfo, withdrawList, currentPanel, PANEL, setCurrentPanel } = this.coin;
return (
<div className="page page-current me-page">
<header className="bar bar-nav">
<button className="button button-link button-nav pull-left" onClick={() => history.go(-1)}>
<span className="icon icon-left"/>
</button>
<h1 className="title">我的优币</h1>
</header>
<div className="content">
<Tab>
<NavBar>
<NavBarItem active={PANEL.COIN === currentPanel}
onClick={e => setCurrentPanel(PANEL.COIN)}>优币</NavBarItem>
<NavBarItem active={PANEL.WITHDRAW === currentPanel}
onClick={e => setCurrentPanel(PANEL.WITHDRAW)}>提现</NavBarItem>
</NavBar>
<TabBody>
{
((currentPanel) => {
switch (currentPanel) {
case PANEL.COIN:
return (<div>
<Cells>
<Cell className="coin-total-cell">
<CellBody>
<div className="coin-number">{coinInfo.sum}</div>
<div className="coin-label">优币余额</div>
</CellBody>
</Cell>
</Cells>
<Cells>
{
_.get(coinInfo, "values", [])
.map((item) => (
<Cell className="coin-list-cell" key={item.id}>
<CellBody>
<div className="action-type">
{item.title}
</div>
<div className="action-balance">
余额: {item.sum}
</div>
</CellBody>
<CellFooter>
<div className="action-time">
{commonUtil.format(new Date(item.changeDate), 'yyyy-MM-dd')}
</div>
<div className="action-result">
{(Number(item.coinChange) > 0 ? `+` : ``) + item.coinChange}
</div>
</CellFooter>
</Cell>
))
}
<Cell className="coin-footer-cell">
<CellBody>
没有更多记录了
</CellBody>
</Cell>
</Cells>
</div>);
case PANEL.WITHDRAW:
return (<div>
<div className="withdraw-top">
<div className="withdraw-num">共 {withdrawList.length} 条记录</div>
<div className="withdraw-btn">
<Link to="/me/withdraw">
<Button size="small">新建提现</Button>
</Link>
</div>
</div>
<Cells className="withdraw-list">
{
withdrawList.map((item) => (
<Cell className="withdraw-list-cell" key={item.id}>
<CellBody>
<div className="action-info">
提现-{item.applyMoney}币
</div>
<div className="action-time">
{commonUtil.format(new Date(item.applyDate), 'yyyy-MM-dd')}
</div>
</CellBody>
<CellFooter>
<div className="action-status">
{getEnumByKey(item.status, withdrawStatusEnum).name}
</div>
<div className="action-result">
¥{item.applyMoney}
</div>
</CellFooter>
</Cell>
))
}
</Cells>
</div>);
default:
return <div/>
}
})(currentPanel)
}
</TabBody>
</Tab>
</div>
</div>
)
}
}
export default Coin;
```
teacher-detail.js
```/**
* Created by violinsolo on 20/07/2017.
*/
'use strict';
import React, { Component } from "react";
import { browserHistory, Link } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import EmptyTip from "../../EmptyTip";
import commonUtil from '../../../common-util';
import _ from '../../util';
import { clazzJoinTypeEnum } from "../../enum";
const {
Button,
Tab,
TabBody,
NavBar,
NavBarItem,
Cells,
Cell,
CellHeader,
CellBody,
CellFooter,
Badge
} = WeUI;
@inject("TeacherDetail") @observer
export default class TeacherDetailPage extends Component {
constructor(props) {
super(props);
const { teacherId } = this.props.params;
this.teacherDetail = new this.props.TeacherDetail(teacherId);
}
onFollowTeacher = () => {
const { processFollowingTeacherAction, toast, teacherBasicInfo} = this.teacherDetail;
processFollowingTeacherAction().then(() => {
toast.showToast({
text: `已成功关注笃师${teacherBasicInfo.name}!将第一时间收到她的开课提示`,
icon: "success-no-circle"
});
this.fetchAndSetTeacherBasicInfoData();
});
};
// using to render main page
fetchAndSetTeacherBasicInfoData = () => {
const { fetchTeacherBasicInfo, setTeacherBasicInfo } = this.teacherDetail;
fetchTeacherBasicInfo().then(setTeacherBasicInfo);
};
onViewCourseTabAction = () => {
const { setCurrentTab, setBadgeVisible, TAB_INDEX } = this.teacherDetail;
setCurrentTab(TAB_INDEX.COURSE);
setBadgeVisible(false);
};
componentDidMount() {
this.fetchAndSetTeacherBasicInfoData();
const {
fetchTeacherMeatySharings, setTeacherMeatySharings, fetchTeacherCommends, setTeacherCommends,
fetchTeacherClazzOpen, setTeacherClazzOpen, fetchTeacherClazzClose, setTeacherClazzClose
} = this.teacherDetail;
// using to render real-stuff sharings page
fetchTeacherMeatySharings().then(setTeacherMeatySharings);
// using to render commends page
fetchTeacherCommends().then(setTeacherCommends);
fetchTeacherClazzOpen().then(setTeacherClazzOpen);
fetchTeacherClazzClose().then(setTeacherClazzClose);
}
render() {
const {
teacherBasicInfo, teacherMeatySharings, teacherCommends, teacherClazzOpen, teacherClazzClose,
currentTabIndex, TAB_INDEX, isBadgeVisible,
setCurrentTab
} = this.teacherDetail;
const openClazzCount = _.get(teacherClazzOpen, 'length', 0);
return (
<div className="teacher-page">
<div className="content teacher-detail">
<div className="teacher-detail-header">
<a className="icon icon-left back-btn" onClick={() => browserHistory.replace('/teacher/list')}/>
<Button className="follow-btn" type="primary"
disabled={teacherBasicInfo.isCurrentUserFollowed}
onClick={this.onFollowTeacher}>
{teacherBasicInfo.isCurrentUserFollowed ? '已关注' : '关注'}
</Button>
<img className="teacher-detail-header-banner"
src={teacherBasicInfo.backgroundUrl}
alt="..."/>
<div className="teacher-detail-header-teacher-info-box">
<div className="avatar-wrap">
<img src={teacherBasicInfo.headImgUrl}/>
<div className="info-wrap">
<span className="teacher-name text-overflow-hidden">{teacherBasicInfo.name}</span>
<div className="teacher-social-info">
<span>关注 {teacherBasicInfo.followUserCount}</span>
<span> | </span>
<span>学生 {teacherBasicInfo.clazzStudentCount}</span>
</div>
<span className="teacher-desc text-overflow-hidden">{teacherBasicInfo.description}</span>
</div>
</div>
</div>
</div>
<div className="teacher-detail-content">
<Tab>
<NavBar className="teacher-detail-content-navbar">
<NavBarItem active={currentTabIndex === TAB_INDEX.BASIC_INFO}
onClick={e => setCurrentTab(TAB_INDEX.BASIC_INFO)}>笃师简介</NavBarItem>
<NavBarItem active={currentTabIndex === TAB_INDEX.MEATY_SHARE}
onClick={e => setCurrentTab(TAB_INDEX.MEATY_SHARE)}>干货分享</NavBarItem>
<NavBarItem active={currentTabIndex === TAB_INDEX.COMMEDNS}
onClick={e => setCurrentTab(TAB_INDEX.COMMEDNS)}>笃友评价</NavBarItem>
<NavBarItem active={currentTabIndex === TAB_INDEX.COURSE}
onClick={this.onViewCourseTabAction}>
开设课程
{
(openClazzCount > 0 && isBadgeVisible === true)
? <Badge className="clazz-open-badge">{openClazzCount}</Badge>
: null
}
</NavBarItem>
</NavBar>
<TabBody className="teacher-detail-content-navcontent">
{
(() => {
switch (currentTabIndex) {
case TAB_INDEX.MEATY_SHARE:
// 干货分享
return <div className="nav-teacher-meaty-sharings-wrap">
<Cells className="nav-teacher-meaty-sharings-cells m-t-none">
{
(_.get(teacherMeatySharings, 'length', 0) > 0)
? teacherMeatySharings.map((realStuffSharingItem) => {
return <Cell className="nav-teacher-meaty-sharings-cell"
component={Link} to={`/redirect?target=${ realStuffSharingItem.url }`}
key={realStuffSharingItem.id}>
<CellBody className="cell-body-all text-overflow-hidden">
<div className="cell-body-wrap">
<span className="sharing-name">{realStuffSharingItem.name}</span>
<span
className="sharing-time">{commonUtil.format(realStuffSharingItem.shareAt ? new Date(realStuffSharingItem.shareAt) : new Date(), 'yyyy/MM')}</span>
</div>
</CellBody>
<CellFooter className="cell-footer-all">
<div className="cell-footer-wrap">
<i className="icon-gb icon-gb-has-read"/>
<span className="read-count">{realStuffSharingItem.readCount}</span>
</div>
</CellFooter>
</Cell>
})
: <EmptyTip tip="空空如也"/>
}
</Cells>
</div>;
case TAB_INDEX.COMMEDNS:
// 笃友评价
return <div className="nav-teacher-commends-wrap">
<span className="nav-teacher-commends-hint">只有上过课的同学才能进行评价哦~</span>
<div className="nav-teacher-commends">
<div className="commend-list">
{
(_.get(teacherCommends, 'length', 0) > 0)
? teacherCommends.map(item => {
return <div className="commend-item" key={item.id}>
<div className="commend-avatar">
<img src={item.userInfo.headImgUrl}/>
</div>
<div className="commend-content-wrap">
<div className="commend-user">
<span className="user-info">{item.userInfo.name}
- {item.userInfo.studentNumber}</span>
<span className="clazz-info">{item.clazzName}</span>
</div>
<div className="commend-content">
{item.commend}
</div>
</div>
</div>
})
: <EmptyTip tip="空空如也"/>
}
</div>
</div>
</div>;
case TAB_INDEX.COURSE:
// 开设课程
return <div className="nav-teacher-clazzes-wrap">
<Cells className="m-t-none teacher-course-list">
{
(() => {
if ((openClazzCount === 0) && (_.get(teacherClazzClose, 'length', 0) === 0)) {
return <EmptyTip tip="空空如也"/>
} else {
let resultClazzOpen = [], resultClazzClose = [];
if (openClazzCount > 0) {
resultClazzOpen = teacherClazzOpen.map((item, idx) => {
return <Cell className="teacher-course-cell" component={Link}
to={`/redirect?target=/enroll/${item.id}`} key={item.id}>
<CellHeader>
<div className="course-cover">
<img src={item.banner}/>
</div>
</CellHeader>
<CellBody className="course-info">
<div className="course-title text-overflow-hidden">
{item.name}
| {_.get(clazzJoinTypeEnum, `${item.clazzJoinType}.name`, '友班课程')}
</div>
<div className="course-extra text-overflow-hidden">
<span className="course-desc">报名人数 <span
className="course-student-num">{item.studentCount}</span></span>
</div>
</CellBody>
<CellFooter>
<div className="course-status">
<i className="icon-gb icon-gb-tag-open"/>
</div>
</CellFooter>
</Cell>
})
}
if (_.get(teacherClazzClose, 'length', 0) > 0) {
resultClazzClose = teacherClazzClose.map((item, idx) => {
return <Cell className="teacher-course-cell" key={item.id}>
<CellHeader>
<div className="course-cover">
<img src={item.banner}/>
</div>
</CellHeader>
<CellBody className="course-info">
<div className="course-title text-overflow-hidden">
{item.name}
| {_.get(clazzJoinTypeEnum, `${item.clazzJoinType}.name`, '友班课程')}
</div>
<div className="course-extra text-overflow-hidden">
<span className="course-desc">报名人数 <span
className="course-student-num">{item.studentCount}</span></span>
</div>
</CellBody>
<CellFooter>
<div className="course-status">
<i className="icon-gb icon-gb-tag-close"/>
</div>
</CellFooter>
</Cell>
})
}
return resultClazzOpen.concat(resultClazzClose);
}
})()
}
</Cells>
</div>;
case TAB_INDEX.BASIC_INFO:
default:
// 笃师简介
return <div className="nav-teacher-introduction-wrap">
<div className="nav-teacher-introduction-content">
<div dangerouslySetInnerHTML={{ __html: `${teacherBasicInfo.introduction}` }}/>
</div>
</div>
}
})()
}
</TabBody>
</Tab>
</div>
</div>
</div>
);
}
}
```
paginator.js
```import {observable, useStrict, action} from "mobx";
useStrict(true);
class Paginator {
@observable values = [];
@observable pageNumber = 1;
@observable totalPageNum = 1;
@observable hasMore = false;
@action
updateData = (data) => {
this.values = this.values.concat(data.values);
this.pageNumber = data.paginator.pageNumber + 1;
this.totalPageNum = data.paginator.totalPageNum;
this.hasMore = (this.pageNumber <= this.totalPageNum);
};
@action
resetValues = () => {
this.hasMore = false;
this.values = [];
this.pageNumber = 1;
this.totalPageNum = 1;
};
}
export default Paginator;
```
password.js
```'use strict';
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
const {
Form,
FormCell,
CellHeader,
CellBody,
CellFooter,
Label,
Input,
ButtonArea,
Button
} = WeUI;
@inject("Password") @observer
class Password extends Component {
constructor(props) {
super(props);
this.password = new this.props.Password();
}
componentDidMount() {
this.password.fetchHasSetPassword();
}
/**
* 更新旧密码
* @param event
*/
changeOldPassword = event => this.password.setOldPassword(event.target.value);
/**
* 更新新密码
* @param event
*/
changeNewPassword = event => this.password.setNewPassword(event.target.value);
/**
* 确认修改密码
* @returns {*}
*/
updatePassword = () => {
const { updatePassword, isPasswordValid, showInvalidPasswordTip } = this.password;
if (isPasswordValid === true) {
return void updatePassword();
}
showInvalidPasswordTip();
};
render() {
const {
hasSetPassword, oldPassword, newPassword, showOldPassword, showNewPassword, isUpdating, isPasswordValid,
toggleOldPassword, toggleNewPassword,
} = this.password;
return (
<div className="page page-current me-page">
<header className="bar bar-nav">
<button className="button button-link button-nav pull-left" onClick={() => history.go(-1)}>
<span className="icon icon-left"/>
</button>
<h1 className="title">修改密码</h1>
</header>
<div className="content">
<Form>
{
hasSetPassword &&
( <FormCell className="password-cell">
<CellHeader>
<Label>旧密码</Label>
</CellHeader>
<CellBody>
<Input
value={oldPassword}
type={showOldPassword ? "text" : "password"}
onChange={this.changeOldPassword}/>
</CellBody>
<CellFooter>
<div className="toggle-password" onClick={toggleOldPassword}>
{showOldPassword ? "隐藏" : "显示"}
</div>
</CellFooter>
</FormCell>)
}
<FormCell className="password-cell">
<CellHeader>
<Label>新密码</Label>
</CellHeader>
<CellBody>
<Input
value={newPassword}
type={showNewPassword ? "text" : "password"}
placeholder="8~20位数字和字母组合"
onChange={this.changeNewPassword}/>
</CellBody>
<CellFooter>
<div className="toggle-password" onClick={toggleNewPassword}>
{showNewPassword ? "隐藏" : "显示"}
</div>
</CellFooter>
</FormCell>
</Form>
<ButtonArea>
<Button disabled={!isPasswordValid || isUpdating} onClick={this.updatePassword}>
确认修改
</Button>
</ButtonArea>
</div>
</div>
)
}
}
Password.propTypes = {
oldPassword: React.PropTypes.string,
newPassword: React.PropTypes.string,
showOldPassword: React.PropTypes.bool,
showNewPassword: React.PropTypes.bool
};
export default Password;
```
share.js
```'use strict';
import React, { Component } from "react";
import { browserHistory } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import _ from '../../util';
import IMAGE_URL_MAP from "../../BigImageUrl";
import '../../../../style/promotion.scss';
const {
Article
} = WeUI;
@inject("Promotion") @observer
export default class PromotionShare extends Component {
constructor(props) {
super(props);
this.promoption = this.props.Promotion;
}
componentDidMount() {
const { promoterUserId } = this.props.params;
this.promoption.getTargetPromoterInfo(promoterUserId)
.catch(() => browserHistory.replace('/subscribe'));
}
render() {
const { targetPromoterUser } = this.promoption;
const promotionInfo = _.get(targetPromoterUser, 'promotionInfo', null);
const promotionKey = _.get(promotionInfo, 'key', ''),
qrcodeUrl = _.get(promotionInfo, 'qrcodeUrl', '');
return (
<div className="page page-current promotion-share-page">
<div className="content">
<header className="promotion-share-header flex-row-center">
<div className="promotion-info-container">
<img className="promoter-avatar" src={_.get(targetPromoterUser, 'headImgUrl', '')} alt="用户头像"/>
<img className="icon-together" src={IMAGE_URL_MAP["PRMOTION_STUDY_TOGETHER"]}/>
<i className="icon-gb icon-gb-promotion-first-order icon-first-order"/>
<span className="promotion-key">{promotionKey}</span>
<span className="desc">报名时输入上面的优惠码有优惠</span>
</div>
</header>
<Article className="p-n uband-introduction">
<img className="introduction-image align-center"
src="http://qiniuprivate.gambition.cn/FXLzR0_uband-intro-01.png"
alt="..."/>
<img className="introduction-image m-t-n-xxl align-center"
src="http://qiniuprivate.gambition.cn/ODHpW4_uband-intro-02.png"
alt="..."/>
<img className="introduction-image align-center"
src="http://qiniuprivate.gambition.cn/gOee9H_uband-intro-03.png"
alt="..."/>
<img className="introduction-image align-center"
src="http://qiniuprivate.gambition.cn/bXp6Hg_uband-intro-04.png"
alt="..."/>
</Article>
<footer className="promotion-share-footer p-xxs flex-row-center">
<div className="promotion-info-container">
<img className="promoter-avatar" src={_.get(targetPromoterUser, 'headImgUrl', '')} alt="用户头像"/>
<img className="icon-together" src={IMAGE_URL_MAP["PRMOTION_STUDY_TOGETHER"]}/>
<img className="icon-qrcode-prefix" src={IMAGE_URL_MAP["QRCODE_PREFIX"]}/>
<img className="promotion-qrcode" src={qrcodeUrl} alt="uband qrcode"/>
</div>
</footer>
</div>
</div>
)
}
}
```
setting-config.js
```"use strict";
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import { settingTypeEnum, getEnumByKey } from "../../enum";
const {
CellBody,
Form,
FormCell,
Input
} = WeUI;
@inject("SettingConfig") @observer
class SettingConfig extends Component {
constructor(props) {
super(props);
this.config = new this.props.SettingConfig(this.props.params.config);
this.configType = getEnumByKey(this.config.type, settingTypeEnum).name;
}
saveConfig = () => {
const { value, saveConfig, showWarnToptip } = this.config;
if (value == null) {
return showWarnToptip(`${ this.configType }不能为空`);
}
return saveConfig(value);
};
render() {
const { value, handleChange } = this.config;
return (
<div className="page page-current me-page">
<header className="bar bar-nav">
<button className="button button-link button-cancel button-nav pull-left" onClick={() => history.go(-1)}>
<span style={{ marginLeft: ".5rem" }}>取消</span>
</button>
<button className="button button-link button-save button-nav pull-right">
<span style={{ marginRight: ".5rem" }}
onClick={this.saveConfig}>
保存
</span>
</button>
<h1 className="title">{this.configType}设置</h1>
</header>
<div className="content">
<Form>
<FormCell>
<CellBody>
<Input
type="text"
defaultValue={value}
onChange={handleChange}
placeholder={`请输入你的${ this.configType }`}/>
</CellBody>
</FormCell>
</Form>
</div>
</div>
)
}
}
export default SettingConfig;
```
index.js
```import React, { Component } from "react";
import { observer, inject, PropTypes } from "mobx-react";
@inject("User", "MorningCall") @observer
class Game extends Component {
constructor(props) {
super(props);
this.user = this.props.User;
this.mc = this.props.MorningCall;
}
componentDidMount() {
this.user.fetchInfo(data => this.user.setInfo(data));
this.mc.fetchActivityId();
}
render() {
const { tempClazzId } = this.mc;
return (
tempClazzId == null
? <div/>
: (<div className="game-page-group">{this.props.children}</div>)
)
}
}
export default Game;
```
ticket.js
```import React, {Component} from "react";
import {observer, inject, PropTypes} from "mobx-react";
@inject("Coupon") @observer
class Ticket extends Component {
constructor(props) {
super(props);
this.coupon = this.props.Coupon;
}
componentDidMount() {
this.coupon.setInfo();
}
render() {
const {info} = this.coupon;
return (
<div className="page page-current me-page">
<header className="bar bar-nav">
<button className="button button-link button-nav pull-left" onClick={() => history.go(-1)}>
<span className="icon icon-left"/>
</button>
<h1 className="title">我的优惠券</h1>
</header>
<div className="content">
<div className="ticket-list">
{
(info && info.length > 0) ? info.map((item, idx)=>(
<div className="ticket-item" key={idx}>
<div className="ticket-content-wrap">
<div className="ticket-title">
抵用券
</div>
<div className="ticket-range">
可以对所有课程使用
</div>
<div className="ticket-time">
有效期至{item.expireDate.slice(0, 10)}
</div>
</div>
<div className="ticket-number-wrap">
<span className="number">{item.money}</span>元
</div>
</div>
)) : <div className="ticket-empty"><i className="icon-gb icon-gb-content-empty ticket-empty-img"/><p className="text-center ticket-empty-text">空空如也,还没有可用的优惠券哦</p></div>
}
</div>
</div>
</div>
)
}
}
export default Ticket;
```
course-detail.js
```'use strict';
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import _ from '../../../util';
import { clazzJoinStatusEnum } from '../../../enum';
import CheckinList from "./checkin-list";
import CourseStudy from "./course-study";
const {
TabBar,
TabBarItem
} = WeUI;
@inject("CourseDetail", "TaskList") @observer
class CourseDetail extends Component {
constructor(props) {
super(props);
const { CourseDetail, location, params } = this.props;
const { courseId } = params;
this.courseId = courseId;
this.detail = new CourseDetail();
// 设置tabIndex
const { tabIndex, isCheckin } = location.query;
if (tabIndex === '1' || isCheckin === '1') {
const { setTabIndex, TAB_INDEX } = this.detail;
setTabIndex(TAB_INDEX.CHECKIN_LIST);
}
}
componentDidMount() {
}
render() {
const {TaskList: tasks, location} = this.props;
const { currentPanel } = location.query;
const { currentTabIndex, setTabIndex, TAB_INDEX } = this.detail;
const status = _.get(tasks.clazz, 'clazzJoinStatus', clazzJoinStatusEnum.PROCESSING.key);
// 返回地址
const backUrl = `/course/list?status=${ status }#${ this.courseId }`;
return (
<div className="page page-current course-page">
<div>
{
currentTabIndex === TAB_INDEX.COURSE_STUDY &&
<CourseStudy courseId={this.courseId} currentPanel={currentPanel} backUrl={backUrl}/>
}
{
currentTabIndex === TAB_INDEX.CHECKIN_LIST &&
<CheckinList courseId={this.courseId} backUrl={backUrl}
/>
}
<TabBar>
<TabBarItem
active={currentTabIndex === TAB_INDEX.COURSE_STUDY}
label="去学习" icon={<i className="icon-gb icon-gb-task"/>}
onClick={e => setTabIndex(TAB_INDEX.COURSE_STUDY)}>
</TabBarItem>
<TabBarItem
active={currentTabIndex === TAB_INDEX.CHECKIN_LIST}
label="去打卡" icon={<i className="icon-gb icon-gb-checkin"/>}
onClick={e => setTabIndex(TAB_INDEX.CHECKIN_LIST)}>
</TabBarItem>
</TabBar>
</div>
</div>
)
}
}
export default CourseDetail;
```
agreement.js
```'use strict';
import React, { Component } from "react";
import { browserHistory } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import IMAGE_URL_MAP from "../../BigImageUrl";
import _ from '../../util';
const {
Cell,
CellHeader,
CellBody,
CellFooter,
Article,
Flex,
FlexItem,
Agreement,
Button
} = WeUI;
@inject("Promotion") @observer
export default class PromotionAgreement extends Component {
constructor(props) {
super(props);
this.promotion = this.props.Promotion;
}
componentDidMount() {
this.promotion.getPromotionUserList();
this.promotion.initWechatShare();
}
render() {
const {
currentPromotionUser, promotionUserList, isAgreed, joinedCount,
setIsAgreed, processJoinConfirmAction
} = this.promotion;
const currentUserName = _.get(currentPromotionUser, 'name', '');
return (
<div className="promotion-page agreement-page w-full">
<header className="agreement-page-header w-full bar bar-nav">
<a className="icon icon-left pull-left p-l-none p-r-none" onClick={() => browserHistory.replace('/me/index')}/>
<span className="title">伙 伴 中 心</span>
</header>
<main className="agreement-page-main m-t-none content">
<Cell className="agreement-page-main-user">
<CellHeader>
<img className="agreement-page-main-user-photo" src={_.get(currentPromotionUser, 'headImgUrl', '')} alt={currentUserName}/>
</CellHeader>
<CellBody className="agreement-page-main-user-info">
<span>{currentUserName}</span>
<span className="studentNumber">学号:{_.get(currentPromotionUser, 'studentNumber', '')}</span>
</CellBody>
<CellFooter className="agreement-page-main-user-join">
<span>这是你加入友班</span>
<span>第<span className="user-join-day"> {_.get(currentPromotionUser, 'joinedDays', 0)} </span> 天</span>
</CellFooter>
</Cell>
<Article className="agreement-page-main-description text-center">
<section className="m-b">
<p className="m-b-xs">Hi!</p>
</section>
<section className="m-b">
<p className="m-b-xs">{currentUserName}</p>
</section>
<section className="m-b">
<p className="m-b-xs">欢迎来到伙伴中心</p>
<p className="m-b-xs">在这里你可以<span className="description-span">赚“友金”</span></p>
</section>
<section className="m-b">
<p className="m-b-xs">将你的<span className="description-span">首单优惠码</span></p>
<p className="m-b-xs">分享给好朋友们</p>
<p className="m-b-xs">只要他们首次购买课程</p>
<p className="m-b-xs">并输入你的优惠码</p>
<p className="m-b-xs">你可以获得<span className="description-span">现金奖励</span>哦~</p>
</section>
<section className="m-b">
<p className="m-b-xs">优惠多多,快来加入吧!</p>
</section>
</Article>
<Flex className="agreement-page-main-agree">
{
promotionUserList.map((promotionUser) => (
<div key={promotionUser.id}>
<FlexItem>
<img className="agreement-page-main-allies-photo" src={promotionUser.headImgUrl} key={promotionUser.id} alt={promotionUser.name}/>
</FlexItem>
</div>
))
}
<img className="allies-photo-more" src={IMAGE_URL_MAP["MORE"]} />
</Flex>
<p className="agreement-page-main-allies-number text-center">已有{joinedCount}名友军加入</p>
</main>
<footer className="agreement-page-footer text-center">
<Agreement className="agreement-page-footer-agree p-n" checked={isAgreed} onChange={e => setIsAgreed(e.target.checked)}>
<span>我已阅读上述说明</span>
</Agreement>
<Button className="agreement-page-footer-button" disabled={!isAgreed} onClick={processJoinConfirmAction}>确认加入</Button>
</footer>
</div>
)
}
}
```
index.js
```import React, {Component} from "react";
import {browserHistory} from "react-router";
import {httpGet} from "../../../../service";
import util from "../../../../store/util";
const baseUrl = `${util.baseUrl}api`;
class LeadOne extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
const cid = this.props.params.courseId;
httpGet(`${baseUrl}/clazz/${cid}/isTeacher`)
.then((isTeacher) => {
isTeacher
? browserHistory.replace(`/course/${cid}/one/student`)
: location.replace(`/course/${cid}/one/chat`);
});
}
componentWillUnmount() {
// 退出笃师一对一,清空搜索数据
delete sessionStorage.SHARK_ONE_KEY_WORD;
delete sessionStorage.SHARK_ONE_SHOW_WAITING
}
render() {
return (
<div>
{this.props.children}
</div>
)
}
}
export default LeadOne;
```
loadingToast.js
```/**
* Created by violinsolo on 29/03/2017.
*/
import {observable, action} from "mobx";
// todo 移除
class LoadingToast {
@observable show = false;
@observable text = "";
@observable icon = "loading";
@action
_showToast = ({ text = "Loading...", icon = "loading" }) => {
this.text = text;
this.icon = icon;
this.show = true;
};
@action
_hideToast = () => {
this.show = false;
};
}
export default LoadingToast;
```
course-study.js
```'use strict';
import { browserHistory } from "react-router";
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import TaskList from "../task/task-list";
import RankList from "../rank/rank-list";
import { clazzJoinTypeEnum } from "../../../enum";
import { clazzTypeEnum } from '../../../enum';
const {
NavBarItem,
NavBar,
Tab,
TabBody,
Popup,
PopupHeader,
Article,
ButtonArea,
Button
} = WeUI;
@inject("CourseStudy", "TaskList") @observer
class CourseStudy extends Component {
constructor(props) {
super(props);
const { CourseStudy, courseId } = this.props;
this.courseStudy = new CourseStudy(courseId);
this.courseStudy.setCurrentPanel(this.props.currentPanel);
}
componentDidMount() {
}
render() {
const { courseId, currentDetailPanel, setCurrentPanel, PANEL } = this.courseStudy;
const { TaskList: taskList, backUrl } = this.props;
const oneUrl = `/course/${courseId}/one/chat`;
const {
strategy, state, clazz,
closePopup,
openPopup
} = taskList;
return (
<div>
<header className="bar bar-nav ">
<a className="icon icon-left pull-left" onClick={() => browserHistory.replace(backUrl)}/>
<h1 className="title">课程主页</h1>
<a className="icon pull-right course-page-more-link" onClick={openPopup}/>
</header>
<div className="content p-b-xxl">
<div className="course-detail">
<div className="course-introduction item-content">
<div className="course-intro-wrapper">
<div className="course-title">{clazz.name}</div>
<div className="flex-row clazz-description-container">
<div className="flex-all flex-row" onClick={openPopup}>
<span>学习攻略</span>
<i className="qa-button icon-gb icon-gb-help"/>
<div className="flex-all flex-row"/>
</div>
</div>
<div className="flex-row justify-between clazz-task-container">
<div className="font-grey">
结束日期:{clazz.accountEndDate}
</div>
<div className="font-blue">
{
((hasTheOne) => {
if (hasTheOne) {
return (<div onClick={() => browserHistory.replace(oneUrl)}>笃师一对一</div>);
} else {
return (``);
}
})(clazz.hasTheOneFeedback)
}
</div>
</div>
</div>
</div>
</div>
<Tab>
<NavBar>
<NavBarItem active={currentDetailPanel === PANEL.taskPanel}
onClick={() => setCurrentPanel(PANEL.taskPanel)}>
任务表
</NavBarItem>
<NavBarItem active={currentDetailPanel === PANEL.rankPanel}
onClick={() => setCurrentPanel(PANEL.rankPanel)}>
排行榜
</NavBarItem>
</NavBar>
<div className="w-full nav-bar-placeholder"/>
<TabBody>
<div className="course-study">
{
((currentPanel) => {
let listTag;
switch (currentPanel) {
case PANEL.rankPanel:
listTag =
<RankList courseBanner={clazz.banner} courseName={clazz.name}/>;
break;
case PANEL.taskPanel:
default:
listTag = <TaskList courseId={courseId}/>;
}
return (
<div className="course-study-content">
{listTag}
</div>
)
})(currentDetailPanel)
}
</div>
</TabBody>
</Tab>
</div>
<Popup className="popup-dialog" show={state}>
<PopupHeader left='返回' leftOnClick={closePopup}/>
<Article>
<div dangerouslySetInnerHTML={{ __html: strategy ? strategy : '还木有课程攻略' }}/>
<ButtonArea>
<Button primary onClick={closePopup}>返回</Button>
</ButtonArea>
</Article>
</Popup>
</div>
)
}
}
export default CourseStudy;
```
mc.js
```"use strict";
/**
* 为活动morning call开发的界面逻辑
*
* Created by Liam on 2017/5/19.
*/
import { observable, useStrict, action } from "mobx";
import { browserHistory } from 'react-router';
import util from "../util";
import { httpGet, httpPost, httpDel } from "../../service";
import Dialog from "../common/dialog";
import uniqueToast from "../common/httpToast";
useStrict(true);
const baseUrl = `${util.baseUrl}api`;
const defaultHeadIcon = 'http://qiniuprivate.gambition.cn/SwBrgT_mc-default-head.png';
class MorningCall {
@observable
tempClazzId;
@observable
userStatus = {
joinStatus: '',
showDialog: false,
statistics: {}
};
@observable
userRoomInfo = {
status: 'NOT_FOUND',
statusDesc: '任务还未开始',
userInfo: {
headImgUrl: defaultHeadIcon
},
partnerInfo: {
headImgUrl: defaultHeadIcon
}
};
//用户申请
@observable
userApply = {
userGender: '2',
targetGender: '1',
selfDesc: ''
};
constructor() {
this.toast = uniqueToast;
this.dialog = new Dialog();
}
@action
updateUserStatusButton = (target) => {
if (target) {
this.userStatus.joinStatus = target.status;
this.userStatus.statistics = target.statistics;
}
};
translateStatus = () => {
const st = {
'NOT_FOUND': '任务还未开始',
'OPEN': '#U树洞开启状态#',
'CLOSED': '#U树洞关闭状态#'
};
this.userRoomInfo.statusDesc = st[this.userRoomInfo.status];
};
@action
updateUserRoomInfo = (target) => {
this.userRoomInfo = target;
if (!this.userRoomInfo.partnerInfo.headImgUrl) {
this.userRoomInfo.partnerInfo.headImgUrl = defaultHeadIcon;
}
this.translateStatus();
};
@action
userRoomException = () => {
this.userRoomInfo.status = 'NOT_FOUND';
this.translateStatus();
};
@action
updateUserApplyByKey = (target, value) => {
this.userApply[target] = value;
};
updateUserGender = (event) => {
this.updateUserApplyByKey('userGender', event.target.value)
};
updateUserTargetGender = (event) => {
this.updateUserApplyByKey('targetGender', event.target.value)
};
updateUserselfDesc = (event) => {
this.updateUserApplyByKey('selfDesc', event.target.value);
};
/**
* 获取用户当前参加活动的状态
*/
fetchUserStatus = () => {
return httpGet(`${baseUrl}/activity/` + this.tempClazzId + '/account')
.then(this.updateUserStatusButton);
};
/**
* 获取用户当前房间的信息
*/
fetchUserRoomInfo = () => {
httpGet(`${baseUrl}/activity/` + this.tempClazzId + '/room')
.then(this.updateUserRoomInfo)
.catch(this.userRoomException);
};
submitApplyEventHandler = () => {
// 参数检查
for (let key in this.userApply) {
if (!this.userApply[key]) {
uniqueToast.showToast({ text: '好像信息不全哦', icon: "warn" });
return;
}
}
uniqueToast.stickyToast({ text: "提交中...", icon: "loading" });
const submitMessage = {};
submitMessage['gender'] = this.userApply.userGender;
submitMessage['partnerInfo'] = { 'gender': this.userApply.targetGender };
submitMessage['introduction'] = this.userApply.selfDesc;
// 提交表单
httpPost(`${baseUrl}/activity/` + this.tempClazzId + '/account', submitMessage)
.then(() => {
uniqueToast.showToast({ text: "提交成功", icon: "success", cb: () => browserHistory.replace('/game/mc/share') });
})
.catch((error) => {
uniqueToast.showToast({ text: "我好像被玩坏了,请稍后再试!", icon: "warn" });
});
};
/**
* 终止U树洞
*/
quitUserRoom = () => {
this.dialog.dismissDialog();
httpDel(`${ baseUrl }/activity/${ this.tempClazzId }/room`)
.then(() => {
uniqueToast.showToast({ text: "成功终止", icon: "success", cb: () => browserHistory.replace('/game/mc/index') });
});
};
fetchActivityId = () => {
httpGet(`${baseUrl}/activity?type=MORNING_CALL`)
.then(action((activityInfo) => this.tempClazzId = activityInfo.id));
};
}
export default new MorningCall();
```
withdraw.js
```'use strict';
import { observable, useStrict, action } from "mobx";
import { httpGet, httpPost } from "../../service";
import util from "../util";
import httpToast from "../common/httpToast";
useStrict(true);
const baseUrl = `${util.baseUrl}api`;
const MIN = 100;
const MAX = 500;
class WithDraw {
@observable
coinSum = 0;
@observable
wd = {
coins: 0,
username: "",
payway: "wechat",
remark: ""
};
@observable
isWithdrawing = false;
constructor() {
}
@action
onChange = (v, type) => {
this.wd[type] = v;
};
fetchCoinSum = () => this._fetchCoinSum().then(this._setCoinSum);
withdrawCoin = () => {
const { coins, username } = this.wd;
if (!(coins && username)) {
httpToast.showToast({text: "不能有未填项", icon: "warn"});
return Promise.reject(new Error("不能有未填项"));
}
if (coins < MIN || coins > this.coinSum || coins > MAX) {
httpToast.showToast({text: "优币数目错误", icon: "warn"});
return Promise.reject(new Error("优币数目错误"));
}
this._setIsWaiting(true);
httpToast.stickyToast({ text: "Loading...", icon: "loading" });
return this._postWithdraw(this.wd)
.then((data) => {
httpToast.showToast({ text: "操作成功", icon: "success", cb: () => history.back() });
this._setIsWaiting(false);
return data;
})
.catch((error) => {
this._setIsWaiting(false);
});
};
/*********************************************************************************************************************
* 以下为内部方法,请勿在外部调用
*********************************************************************************************************************/
_fetchCoinSum = () => httpGet(`${baseUrl}/account/coinSum`);
_postWithdraw = (body) => httpPost(`${baseUrl}/account/withdraw`, body);
@action
_setCoinSum = coinSum => this.coinSum = coinSum;
@action
_setIsWaiting = isWithdrawing => this.isWithdrawing = isWithdrawing;
}
export default WithDraw;
```
share.js
```/**
* 游戏页面
* Morning Call
*
* ---
* 游戏规则:
* 1. 进入页面后,判断是否已经参加活动
* 2. 如果是在活动报名期间,就可以报名
* 3. 如果已经参加了,点击按钮进入房间
*/
import React, {Component} from "react";
import {Link} from "react-router";
import "../../../../../style/game/mc.scss";
import WeUI from "react-weui";
import WechatShare from "../../../../store/common/wechatShare";
const {Button} = WeUI;
class GameMcSharePage extends Component {
constructor(props) {
super(props);
this.wechatShare = new WechatShare(
'我们准备用一年的时间带你认识50位新朋友',
`#`,
`http://mp.weixin.qq.com/s/uVe2Nj43P98BI-gcpjNYqQ`,
'http://qiniuprivate.gambition.cn/bV9B4c_wechat_tutor_a.png'
);
}
componentDidMount() {
}
render() {
return <div className="game-mc-page">
<div className="share-img-section align-center p-t-md p-b-xs">
<img className="share-img" src="http://qiniuprivate.gambition.cn/cbXKeq_uband%E6%B4%BB%E5%8A%A8%E5%AE%A3%E4%BC%A0%E5%9B%BE-%E7%BB%99%E5%90%8C%E6%B5%8E%E5%B0%8F%E5%8A%A9%E6%89%8B.png" alt=""/>
<div className="share-desc p-t-xs text-xs">
<div className="text-green"><strong>还不快把活动告诉朋友?</strong></div>
<div>1.长按图片发送给朋友、室友.</div>
<div>2.保存图片发送朋友圈.</div>
</div>
<Link to="/game/mc/index"><Button className="m-t-xs" type="default">返回</Button></Link>
</div>
</div>
}
}
export default GameMcSharePage;```
chat.js
```'use strict';
import { observable, useStrict, action } from "mobx";
import { httpGet } from "../../service";
import WechatShare from '../common/wechatShare';
import util from "../util";
useStrict(true);
const baseUrl = `${util.baseUrl}api/guide`;
/**
* 交互store -- 控制显示的对话信息
*/
class GuideChat {
@observable
chatList = []; // 显示的对话列表
@observable
nextChat = null; // 用户要发送的下一条消息
constructor() {
this._originChatList = []; // 全部对话列表
this.isWaiting = false; // 是否在等待对方输入...
this.nextOrder = 0; // 下一组要显示消息的order
// 设置分享信息
this.wechatShare = new WechatShare(
'看到这个页面,我开始方了',
'欢迎来到友班,不仅是一个英文练习平台',
`${ location.origin }/redirect?target=/guide/chats`,
'http://qiniuprivate.gambition.cn/U8PAC7_shark-ig-assitant.png'
)
}
// 获取全部消息列表,并设置到 this._originChatList 中
fetchOriginChatList = () => httpGet(`${ baseUrl }/chats`).then(this._setOriginChatList);
/**
* 下一步操作
* 1. 筛选要显示的消息列表
* 2. 筛选用户要发送的下一条消息
* 3. 更新 显示的对话列表 及 下一条消息
* 4. 下一组要显示消息的order 自增
*/
next = (scrollToBottom) => {
if (this.nextChat != null) {
// 将nextChat插入到现在的对话列表中
this.appendChatList(this.nextChat);
}
const nextChatList = [];
let nextChat = null;
this._originChatList.forEach((item) => {
const itemOrder = item.order;
if (itemOrder === this.nextOrder) {
// 排除当前的nextChat
if (this.nextChat !== item) {
nextChatList.push(item);
}
} else if (itemOrder > this.nextOrder) {
// 获取下一个nextChat
if (nextChat == null) {
nextChat = item;
}
}
});
const appendPromiseList = nextChatList.map(
(nextChat, idx) => new Promise(
(resolve) => window.setTimeout(
() => {
this.appendChatList(nextChat);
scrollToBottom();
return resolve(nextChat);
},
idx * 750 + Math.random() * 750
)
)
);
// 先让nextItChat为空
this._setNextChat(null);
return Promise.all(appendPromiseList)
.then(() => {
this._setNextChat(nextChat);
this.nextOrder++;
});
};
@action
appendChatList = (nextChat) => this.chatList = [...this.chatList, nextChat];
toggleIsWaiting = () => this.isWaiting = !this.isWaiting;
@action
_setNextChat = (nextChat) => this.nextChat = nextChat;
@action
_setOriginChatList = (chatList) => this._originChatList = chatList;
}
export default GuideChat;
```
activity-detail.js
```'use strict';
import React, { Component } from "react";
import { browserHistory } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import IMAGE_URL_MAP from "../../BigImageUrl";
const {
Button,
Dialog
} = WeUI;
import "../../../../style/activity.scss";
@inject("ActivityDetail", "User") @observer
export default class ActivityDetailPage extends Component {
constructor(props) {
super(props);
this.user = this.props.User;
const { activityId, userId } = this.props.params;
this.activityDetail = new this.props.ActivityDetail(activityId, userId);
}
fetchAndSetData = () => {
const { fetchActivityInfo, setActivityInfo } = this.activityDetail;
fetchActivityInfo().then(setActivityInfo);
};
getProcessRateImageUrl = (batterPercent) => {
if (0 <= batterPercent && batterPercent < 0.2) {
return IMAGE_URL_MAP["0_PERCENT"];
} else if (0.2 <= batterPercent && batterPercent < 0.4) {
return IMAGE_URL_MAP["20_PERCENT"];
} else if (0.4 <= batterPercent && batterPercent < 0.6) {
return IMAGE_URL_MAP["40_PERCENT"];
} else if (0.6 <= batterPercent && batterPercent < 0.8) {
return IMAGE_URL_MAP["60_PERCENT"];
} else if (0.8 <= batterPercent && batterPercent < 1) {
return IMAGE_URL_MAP["80_PERCENT"];
} else if (batterPercent >= 1) {
return IMAGE_URL_MAP["100_PERCENT"];
} else {
// default value
return IMAGE_URL_MAP["0_PERCENT"];
}
};
componentDidMount() {
this.fetchAndSetData()
}
render() {
const { modal, activityInfo, userInfo, activityId, favourUser } = this.activityDetail;
const userTitle = activityInfo.isSelf ? '你' : '他';
return (
<div className="activity-page">
<div className="content activity-detail">
<div className="activity-detail-header">
<img className="activity-img"
src={activityInfo.banner}
alt="..."/>
<div className="info-cell">
<div className="avatar-wrap">
<img src={userInfo.headImgUrl}/>
<div className="info-wrap">
<div>{userInfo.name}宣布</div>
<div>参加"<font color="#FF4060">{activityInfo.name}</font>"活动</div>
</div>
</div>
</div>
</div>
<div className="">
<div className="battery">
<img className="battery-img"
src={this.getProcessRateImageUrl(activityInfo.progressRate)}
alt="..."/>
</div>
<div className="flex-row flex-row-center plug-percent"><i className="icon-gb icon-gb-plug"/><span
className="">{(activityInfo.progressRate * 100).toFixed(2)}%</span></div>
{
((isFavour, isSelf, progressRate) => {
if (isSelf === false && isFavour === false) {
return <Button className="btn-charging" onClick={() => {
favourUser()
.then(() => {
this.fetchAndSetData()
})
.catch(() => {
})
}}>
帮他一把
</Button>
}
if (isSelf === true && progressRate >= 1.00) {
return <Button className="btn-charging" onClick={() => {
browserHistory.push(`/course/${activityId}/detail`)
}}>
进入活动
</Button>
}
const buttonName = isSelf ? '充电中' : '帮好友助力成功';
return <Button className="btn-charging">{buttonName}</Button>
})(activityInfo.isFavour, activityInfo.isSelf, activityInfo.progressRate)
}
<div className="text-center text-charging-remain">
{((progressRate) => {
if (progressRate < 1.0) {
return <span>
{userTitle}只差<font color="red">{activityInfo.neededFavor}</font>个加油了
</span>
}
return '已助力成功'
})(activityInfo.progressRate)}
</div>
{((progressRate) => {
if (progressRate < 1.0) {
return <div className="text-center text-charging-hint">把本页<font color="#FF4060">分享</font>给好友帮{userTitle}加油吧
</div>
}
})(activityInfo.progressRate)}
</div>
</div>
<div className="activity-detail-footer">
<footer className="bar bar-tab footer">
{
((isSelf) => {
if (isSelf === false) {
return (
<div className="flex-all justify-center align-center end-bg">
<Button onClick={modal.open} className="btn-footer">我也要参加</Button>
</div>
);
}
})(activityInfo.isSelf)
}
</footer>
</div>
<Dialog buttons={modal.buttons} show={modal.state} title={modal.title} type="ios">
{
(() => {
return (
<div className="qrcode-wrap">
<img src={IMAGE_URL_MAP["QRCODE_FOR_PARTICIPATE"]} className="qrcode"
alt="qrcode"/>
</div>
);
})()
}
</Dialog>
</div>
);
}
}
```
index.js
```import React, { Component } from "react";
import { Link } from "react-router";
import { inject, observer, PropTypes } from "mobx-react";
import WeUI from "react-weui";
const { Dialog } = WeUI;
import "../../../../../style/enroll.scss";
import { clazzJoinTypeEnum } from "../../../enum";
import _ from '../../../util';
import cutil from '../../../../common-util';
@inject("Modal", "EnrollDetail") @observer
class EnrollDetailPage extends Component {
constructor(props) {
super(props);
this.cid = this.props.params.courseId;
this.modal = new this.props.Modal("班级说明", "我知道了~");
this.detail = new this.props.EnrollDetail(this.cid);
this.formatMoney = this.formatMoney.bind(this);
}
componentDidMount() {
this.detail.fetchDetail(this.detail.setDetail);
this.detail.fetchIntroduction(this.detail.setIntrodution);
}
formatMoney(raw) {
return ((Number(raw) | 0) / 100).toFixed(2)
}
render() {
const { detail } = this.detail;
const { clazzType, clazzJoinType } = detail;
const safelyClazzName = _.get(clazzJoinTypeEnum, `${clazzJoinType}.name`, '友班课程');
return (
<div className="enroll-page page">
<header className="bar bar-nav">
<a className="icon icon-left pull-left" onClick={() => history.go(-1)}/>
{/*<a className="icon icon-share pull-right"/>*/}
<h1 className="title">课程报名</h1>
</header>
<div className="content">
<div className="course-detail">
<div className="course-introduction item-content">
<div className="course-intro-wrapper">
<div className="course-title">{detail.name}</div>
<div className="flex-row clazz-description-container">
<div className="flex-all flex-row">
<span>{safelyClazzName}</span>
<i className="qa-button icon-gb icon-gb-help" onClick={this.modal.open}/>
<div className="flex-all flex-row">{detail.description}</div>
</div>
{
((count) => {
if (count > 50) { /* 50 人以上再显示 */
return (<div className="font-blue">{detail.studentCount}人报名</div>);
}
})(detail.studentCount)
}
</div>
{
clazzType === 'LONG_TERM' || (
<div className="flex-row justify-between clazz-task-container">
<div className="font-grey">
时间: {cutil.format(new Date(detail.startDate), 'yyyy-MM-dd')}
~ {cutil.format(new Date(detail.endDate), 'yyyy-MM-dd')}
</div>
<div className="font-blue">
{detail.taskCount}天训练
</div>
</div>
)
}
</div>
</div>
</div>
<div className="web-view item-content"
dangerouslySetInnerHTML={{ __html: this.detail.introduction }}/>
</div>
<div className="enroll-detail">
<footer className="bar bar-tab">
{
((status) => {
if (clazzType === 'LONG_TERM') {
return (
<div className="fix-end">
<div className="sm-txt">
<span className="cost-txt">多套餐可选</span>
</div>
<div>
<div onClick={() => window.location.href = `/enroll/pay/${ this.cid }`}
className="button button-fill enroll-button">报名预约
</div>
</div>
</div>
)
}
switch (status) {
case "WAITENTER":
case "PROCESSING":
case "CLOSE":
return (
<div className="flex-row justify-center end-bg">
<div className="button button-light end-button">
<Link to={`/course/${ this.cid }/detail`}>已加入(进入主页)</Link>
</div>
</div>
);
default:
return (
<div className="fix-end">
<div className="sm-txt">
<span
className="cost-txt">¥ {this.formatMoney(detail.priceList ? detail.priceList[0].totalFee : 0)}</span>
<span className="font-grey"> (原价 <span
className="font-red">¥ {this.formatMoney(detail.priceList ? detail.priceList[0].originFee : 0)}</span>)</span>
</div>
<div>
<div onClick={() => window.location.href = `/enroll/pay/${ this.cid }`}
className="button button-fill enroll-button">报名预约
</div>
</div>
</div>
)
}
})(detail.joinStatus)
}
</footer>
</div>
<Dialog
buttons={this.modal.buttons}
show={this.modal.state}
title={`什么是${safelyClazzName}?`}
>
{
((clzType) => {
switch (clzType) {
case clazzJoinTypeEnum["PAY"].key:
return (
<div>
<div className="modal-text">
<div className="text-title">什么是付费班?</div>
<div>付费班就是仅仅支付学费的班级;</div>
<div>不强制打卡,打卡有一定的优惠券拿;</div>
</div>
<div className="modal-text">
<div className="text-title">付费班有什么不同?</div>
<div>相比笃金班,付费班课程的知识性更强,时间更灵活;</div>
</div>
</div>
);
case clazzJoinTypeEnum["FREE"].key:
return (
<div>
<div className="modal-text">
<div className="text-title">什么是免费班?</div>
<div>免费班包括体验班、推广班、福利班;</div>
<div>免费班没有严格意义的笃师,课程时间也较短;</div>
</div>
</div>
);
case clazzJoinTypeEnum["GAMBITION_COIN"].key:
return (
<div>
<div className="modal-text">
<div className="text-title">什么是笃金班?</div>
<div>笃金班就是你支付一笔笃金,完成任务就能赎回笃金;</div>
<div>比如30天的任务,完成了20天,就能赎回 2/3 的笃金;</div>
</div>
<div className="modal-text">
<div className="text-title">笃金班规则?</div>
<div>每日需要完成任务要求的作业;不达标会被黄牌警告;</div>
<div>每日抽查如果发现浑水摸鱼的情况,直接扣5天学分。</div>
</div>
</div>
);
default:
return (
<div>
<div className="modal-text">
<div className="text-title">空空如也哦~</div>
</div>
</div>
);
}
})(clazzJoinType)
}
</Dialog>
</div>
);
}
}
EnrollDetailPage.propTypes = {
Modal: PropTypes.objectOrObservableObject,
EnrollDetail: PropTypes.objectOrObservableObject,
params: React.PropTypes.object
};
export default EnrollDetailPage;
```
list.js
```'use strict';
import { observable, useStrict, action } from "mobx";
import util from "../util";
const baseUrl = `${util.baseUrl}api`;
import { httpGet } from "../../service";
useStrict(true);
export default class ActivityList {
@observable
activityList = []; // 推广活动列表
/**
* action 更新推广活动列表
* @param activityList
*/
@action
setActivities = (activityList) => this.activityList = activityList;
fetchList = () => httpGet(`${baseUrl}/activities`);
}
```
index.js
```/**
* 游戏页面
* Morning Call
*
* ---
* 游戏规则:
* 1. 进入页面后,判断是否已经参加活动
* 2. 如果是在活动报名期间,就可以报名
* 3. 如果已经参加了,点击按钮进入房间
*/
import React, {Component} from "react";
import {Link} from "react-router";
import {observer, inject} from "mobx-react";
import "../../../../../style/game/mc.scss";
import WechatShare from "../../../../store/common/wechatShare";
import IMAGE_URL_MAP from "../../../BigImageUrl";
@inject("User", "MorningCall") @observer
class GameMcIndexPage extends Component {
constructor(props) {
super(props);
this.mc = this.props.MorningCall;
this.wechatShare = new WechatShare(
'我们准备用一年的时间带你认识50位新朋友',
`#`,
`http://mp.weixin.qq.com/s/uVe2Nj43P98BI-gcpjNYqQ`,
IMAGE_URL_MAP["WECHAT_TUTOR_A"]
);
}
componentDidMount() {
this.mc.fetchUserStatus();
}
render() {
const {info} = this.props.User;
const {userStatus} = this.mc;
return <div className="game-mc-page">
<div className="mc-up-area">
<div className="mc-head">
<img
src={info.headImgUrl}
className="mc-head-icon"/>
</div>
<div className="mc-bg-area align-center">
<div className="mc-logo">
<img src="http://qiniuprivate.gambition.cn/Ugaq8G_mc-logo2.png" alt="" className="mc-logo-img"/>
</div>
<div className="mc-desc">
<p className="mc-slogan">一周,认识一位优质朋友</p>
<ul>
<li>1. 填写匿名信息参与活动配对</li>
<li>2. 匿名交流共同完成每日任务</li>
<li>3. 一周之后选择是否继续联系</li>
</ul>
<div className="mc-join">
{
((status)=> {
if (status == 'PENDING') {
return <button className="button button-fill mc-button mc-button-success"
onClick={e=>alert('耐心等待匹配通知哦!')}>报名成功,等待匹配</button>
} else if (status == 'PROCESSING') {
return <Link to="/game/mc/room"><button className="button button-fill mc-button mc-button-success">已结对,进入房间</button>
</Link>;
} else {
return <Link to="/game/mc/join">
<button className="button button-fill mc-button">猛戳加入</button>
</Link>;
}
})(userStatus.joinStatus)
}
</div>
<p className="text-center"><Link to="/game/mc/share">我要去告诉朋友> </Link></p>
</div>
</div>
<div className="divide-full m-t-md"></div>
</div>
<div className="mc-statistics m-t">
<p className="text-center text-xs">统计信息</p>
<div className="divide-sm"></div>
<div className="mc-st-gender p-t align-center">
<div className="mc-st-gender mc-st-man">
<img src={IMAGE_URL_MAP["MC_MAN"]} alt="" className="mc-gender-icon"/>
<p className="m-xxs text-xs">{userStatus.statistics.male} 男生</p>
</div>
<div className="mc-st-gender mc-st-women">
<img src={IMAGE_URL_MAP["MC_WOMEN"]} alt="" className="mc-gender-icon"/>
<p className="m-xxs text-xs">{userStatus.statistics.female} 女生</p>
</div>
</div>
<div className="p-t">
<img src={IMAGE_URL_MAP["MC_ARROW"]} alt="" className="mc-arrow align-center p-t-xs"/>
</div>
<div>
<img src={IMAGE_URL_MAP["MC_MAN_WOMEN"]} alt="" className="mc-wm align-center p-t"/>
<p className="m-xxs text-xs text-center p-t-xs">总 {userStatus.statistics.total} 人</p>
</div>
</div>
<div className="divide-full m-t"></div>
<p className="m-xxs text-xxs text-center p-xs">本活动最终解释权归友班所有.</p>
</div>
}
}
export default GameMcIndexPage;
```
util.js
```import util from "../config";
import _ from "../view/util";
export const curry = f => {
return function () {
let args = Array.prototype.slice.call(arguments, 0);
if (args.length < f.length) {
return function () {
let _args = args.concat(Array.prototype.slice.call(arguments, 0));
return curry(f).apply(this, _args);
}
}
else return f.apply(this, args);
}
};
util.get = _.get;
/**
* 清除html标签中的class及style
*
* @param nodeElement
*/
util.clearNodeClazzAndStyle = (nodeElement) => {
return nodeElement.replace(/class\s*=\s*"[^"]*"/g, "").replace(/style\s*=\s*"[^"]*"/g, "");
};
util.formatAudioTimer = (num) => {
const s = 0 | Number(num) % 60,
m = 0 | Number(num) / 60;
return `${("0" + m).slice(-2)}:${("0" + s).slice(-2)}`;
};
export default util;
```
toptip.js
```'use strict';
import { useStrict, observable, action } from "mobx";
useStrict(true);
class Toptip {
@observable
type = "primary";
@observable
show = false;
@observable
content = "";
_timer = null;
showToptip = ({ type = "", content, ms = 1200 }) => {
this._setType(type);
this._setContent(content);
this._setShow(true);
this._timer = window.setTimeout(
this._hideToptip,
ms
)
};
@action
_hideToptip = () => {
this._timer = null;
this._setShow(false);
};
@action
_setContent = (content) => this.content = content;
@action
_setType = (type) => this.type = type;
@action
_setShow = (show) => this.show = show === true;
}
export default new Toptip();
```
gulpfile.babel.js
```import gulp from "gulp";
import gutil from "gulp-util";
import gulpif from "gulp-if";
import del from "del";
import sprity from "sprity";
import webpack from "webpack";
import webpackConfig from "./webpack.config.js";
import connect from "gulp-connect";
import rest from "connect-rest";
// import mocks from "./mocks";
const src = {
html: "src/html/index.html",
vendor: "vendor/**/*",
style: "src/style/**.sass",
assets: "assets/**/*"
};
const dist = {
root: "dist/",
html: "dist/",
vendor: "dist/vendor.js",
assets: "dist/assets"
};
const bin = {
root: "bin/",
html: "bin/",
vendor: "bin/vendor",
assets: "bin/assets"
};
/**
* clean build dir
*/
let clean = (done) => {
del.sync([`${dist.root}/**/*`, `!${dist.vendor}`]);
done();
};
/**
* [cleanBin description]
* @return {[type]} [description]
*/
let cleanBin = (done) => {
del.sync(bin.root);
done();
};
/**
* [copyVendor description]
* @return {[type]} [description]
*/
let copyVendor = () =>
gulp.src(src.vendor)
.pipe(gulp.dest(dist.vendor));
/**
* [copyAssets description]
* @return {[type]} [description]
*/
let copyAssets = () =>
gulp.src(src.assets)
.pipe(gulp.dest(dist.assets));
/**
* [copyDist description]
* @return {[type]} [description]
*/
let copyDist = () =>
gulp.src(dist.root + "**/*")
.pipe(gulp.dest(bin.root));
/**
* [html description]
* @return {[type]} [description]
*/
let html = () =>
gulp.src(src.html)
.pipe(gulp.dest(dist.html));
/**
* [webpackProduction description]
* @param {Function} done [description]
* @return {[type]} [description]
*/
let webpackProduction = (done) => {
let config = Object.create(webpackConfig);
config.plugins = config.plugins.concat(
new webpack.DefinePlugin({
"process.env": {
"NODE_ENV": "production"
}
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
);
webpack(config, (err, stats) => {
if (err) throw new gutil.PluginError("webpack:build", err);
gutil.log("[webpack:production]", stats.toString({
colors: true
}));
done();
});
};
/**
* [webpackDevelopment description]
* @param {Function} done [description]
* @return {[type]} [description]
*/
let devConfig, devCompiler;
devConfig = Object.create(webpackConfig);
devConfig.devtool = "sourcemap";
devConfig.debug = true;
devCompiler = webpack(devConfig);
let webpackDevelopment = (done) => {
devCompiler.run((err, stats) => {
if (err) {
throw new gutil.PluginError("webpack:build-dev", err);
}
gutil.log("[webpack:build-dev]", stats.toString({
colors: true
}));
done();
});
};
let connectServer = (done) => {
connect.server({
root: dist.root,
port: 5000,
livereload: true,
middleware: (connect, opt) => {
return [rest.rester({
context: "/api"
})]
},
fallback: dist.root + "index.html"
});
// mocks(rest);
done();
};
/**
* [iconSprity description]
* @return {[type]} [description]
*/
let iconSprity = (done) => {
sprity.src({
src: "./src/img/icons/**/*.{png, jpg}",
name: "icons",
style: "./icons-sprite.scss",
cssPath: "../img",
prefix: "icon-gb",
dimension: [{
ratio: 1, dpi: 72
}, {
ratio: 2, dpi: 192
}],
processor: "sass",
"style-type": "scss"
})
.pipe(gulpif("*.{png, jpg}", gulp.dest("src/img"), gulp.dest("src/style")));
};
gulp.task("sprity", gulp.series(
iconSprity
));
/**
* [watch description]
* @return {[type]} [description]
*/
let watch = () => {
gulp.watch(src.html, html);
gulp.watch("src/**/*.scss", webpackDevelopment);
gulp.watch(src.assets, copyAssets);
gulp.watch("src/**/*.js", webpackDevelopment);
gulp.watch("dist/**/*").on("change", () => {
gulp.src("dist/")
.pipe(connect.reload());
});
};
/**
* default task
*/
gulp.task("default", gulp.series(
clean,
gulp.parallel(copyAssets, copyVendor, html, webpackDevelopment),
connectServer,
watch
));
/**
* production build task
*/
gulp.task("build", gulp.series(
clean,
gulp.parallel(copyAssets, copyVendor, html, webpackProduction),
cleanBin,
copyDist,
(done) => {
console.log("build success");
done();
}
));```
clazz-exit.js
```'use strict';
import { observable, useStrict, action, computed } from "mobx";
import util from "../util";
import { httpGet, httpPost } from "../../service";
import uniqueToast from "../common/httpToast";
useStrict(true);
const baseUrl = `${util.baseUrl}api`;
class ClazzExit {
@observable
clazzList = [];
@observable
selectedClazzId = null;
@observable
exitReason = "";
@observable
isDialogshow = false;
constructor() {
this.dialogButtons = [
{
type: "default",
label: "取消",
onClick: this._hideDialog
},
{
type: "primary",
label: "确认",
onClick: this._confirmClazzExit
}
]
}
fetchProcessingClazzList = () => this._fetchClazzList()
.then((clazzList) => {
this._setClazzList(clazzList);
if (clazzList.length > 0) {
this.setSelectedClazzId(clazzList[0].id);
}
});
@computed
get isFormValid() {
return this.selectedClazzId != null && this.exitReason != null && this.exitReason != "";
}
@action
setSelectedClazzId = (clazzId) => this.selectedClazzId = clazzId;
@action
setExitReason = (exitReason) => this.exitReason = exitReason;
@action
showDialog = () => this.isDialogshow = true;
@action
_hideDialog = () => this.isDialogshow = false;
_confirmClazzExit = () => {
console.log(this.isFormValid);
if (this.isFormValid !== true) {
uniqueToast.showToast({ text: "请再次检查申请表单" });
} else {
this._createClazzExit({ clazzId: this.selectedClazzId, reason: this.exitReason })
.then(() => {
this._hideDialog();
uniqueToast.showToast({ text: "申请成功,请耐心等待", icon: "success", cb: () => history.back() })
});
}
};
_fetchClazzList = () => httpGet(`${baseUrl}/clazzes?status=PROCESSING`);
@action
_setClazzList = (clazzList) => this.clazzList = [...clazzList];
_createClazzExit = (clazzExit) => httpPost(`${baseUrl}/clazzExit`, clazzExit);
}
export default ClazzExit;
```
material-detail.js
```import React, {Component} from "react";
import {httpGet} from "../../../../service";
import util from "../../../../store/util";
const baseUrl = `${util.baseUrl}api/clazz`;
class MaterialDetailPage extends Component {
constructor(props) {
super(props);
// todo 移除state, 好孩子不要学
this.state = {
content: ""
};
this.mid = this.props.params.materialId;
this.cid = this.props.params.courseId;
}
componentDidMount() {
// todo 移除setState, 好孩子不要学
httpGet(`${baseUrl}/${this.cid}/feedback/material/${this.mid}`)
.then(data => this.setState({content: data.content}))
}
render() {
return (
<div className="page page-current">
<header className="bar bar-nav">
<h1 className="title">素材详情</h1>
<a className="button button-link button-nav pull-left chat-page-back" onClick={() => history.back()}>
<span className="icon icon-left"/>
</a>
</header>
<div className="content warp-detail">
<div dangerouslySetInnerHTML={{__html: this.state.content}}/>
</div>
</div>
)
}
}
export default MaterialDetailPage;
```
detail.js
```/**
* Created by violinsolo on 20/07/2017.
*/
'use strict';
import { observable, useStrict, action } from "mobx";
import util from "../util";
import WechatShare from "../common/wechatShare";
import { httpGet, httpPost } from "../../service";
import uniqueToast from "../common/httpToast";
useStrict(true);
const baseUrl = `${util.baseUrl}api`;
export default class TeacherDetail {
@observable
currentTabIndex = this.TAB_INDEX.BASIC_INFO;
@observable
isBadgeVisible = false;
@observable
teacherBasicInfo = {};
@observable
teacherMeatySharings = [];
@observable
teacherCommends = [];
@observable
teacherClazzOpen = [];
@observable
teacherClazzClose = [];
constructor(teacherId) {
this.teacherId = teacherId;
this.toast = uniqueToast;
this.TAB_INDEX = {
BASIC_INFO: 'BASIC_INFO',
MEATY_SHARE: 'MEATY_SHARE',
COMMEDNS: 'COMMEDNS',
COURSE: 'COURSE'
}
}
@action
setCurrentTab = (tabIndex) => {
const currentTabIndex = util.get(this.TAB_INDEX, tabIndex, null);
if (currentTabIndex != null) {
this.currentTabIndex = tabIndex;
}
};
@action
setBadgeVisible = (visibility) => {
this.isBadgeVisible = visibility === true;
};
// following are processing fetching teacher basic info
fetchTeacherBasicInfo = () => httpGet(`${baseUrl}/clazzTeacher/${this.teacherId}`);
@action
setTeacherBasicInfo = (originalTeacherBasicInfo) => {
this.teacherBasicInfo = originalTeacherBasicInfo;
const { headImgUrl, name, id } = originalTeacherBasicInfo;
this.wechatShare = new WechatShare(
`Uband友班笃师${ name }`,
`墙裂推荐笃师${ name }给你认识,来友班,和牛人做朋友`,
`${ location.origin }/redirect?target=/teacher/${ id }`,
headImgUrl
);
};
// following are processing fetching teacher real stuff sharings list
fetchTeacherMeatySharings = () => httpGet(`${baseUrl}/clazzTeacher/${this.teacherId}/meatySharings?pageSize=1000`);//TODO: Hard Code, 以后改成下拉刷新的
@action
setTeacherMeatySharings = (originalTeacherMeatySharings) => {
this.teacherMeatySharings = originalTeacherMeatySharings.values;
};
// following are processing fetching teacher comments list
fetchTeacherCommends = () => httpGet(`${baseUrl}/clazzTeacher/${this.teacherId}/commends?pageSize=1000`);//TODO: Hard Code, 以后改成下拉刷新的
@action
setTeacherCommends = (originalTeacherCommends) => {
this.teacherCommends = originalTeacherCommends.values;
};
// following are processing fetching teacher clazzes list
fetchTeacherClazzOpen = () => httpGet(`${baseUrl}/clazzTeacher/${this.teacherId}/clazzes?status=OPEN`);//TODO: Hard Code, 以后改成下拉刷新的
@action
setTeacherClazzOpen = (originalTeacherClazzOpen) => {
this.teacherClazzOpen = originalTeacherClazzOpen;
};
fetchTeacherClazzClose = () => httpGet(`${baseUrl}/clazzTeacher/${this.teacherId}/clazzes?pageSize=1000`);//TODO: Hard Code, 以后改成下拉刷新的
@action
setTeacherClazzClose = (originalTeacherClazzCLose) => {
this.teacherClazzClose = originalTeacherClazzCLose.values;//Close的是分页的数据,open不是
};
/**
* fire when the user click the follow btn
* @returns {Promise}
*/
processFollowingTeacherAction = () => {
return httpPost(`${baseUrl}/clazzTeacher/${this.teacherId}/follower`, {});
}
}
```
activity-enroll.js
```'use strict';
import React, { Component } from "react";
import { browserHistory } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from 'react-weui';
import { clazzStatusEnum } from '../../enum';
import EmptyTip from '../../EmptyTip';
const {
Tab,
TabBody,
NavBar,
NavBarItem,
Button,
Article,
Dialog
} = WeUI;
@inject('ActivityEnroll', 'User') @observer
export default class ActivityEnroll extends Component {
constructor(props) {
super(props);
this.activityEnroll = new this.props.ActivityEnroll(this.props.params.activityId);
this.user = this.props.User;
}
componentDidMount() {
const { fetchActivityDetail, setActivityDetail } = this.activityEnroll;
fetchActivityDetail().then(setActivityDetail);
}
render() {
const {
PANEL, modal,
setCurrentPanel, enrollActivity,
activityItem, currentDetailPanel, activityId
} = this.activityEnroll;
const { info: userInfo } = this.user;
const redirectTDetailPage = () => browserHistory.push(`/redirect?target=/activity/${activityId}/user/${userInfo.id}`);
return (
<div className="page page-current activity-enroll-page">
<header className="bar bar-nav activity-enroll-header">
<a className="icon icon-left pull-left" onClick={() => browserHistory.replace('/activity/list')}/>
<img className="header-background" src={activityItem.banner}/>
<a className="icon pull-right share-link" onClick={modal.open}>分享</a>
</header>
<div className="activity-enroll-body">
<Tab>
<NavBar className="activity-enroll-navbar">
<NavBarItem className="activity-enroll-navbar-item"
active={ currentDetailPanel === PANEL.introduction }
onClick={() => setCurrentPanel(PANEL.introduction)}>
介绍
</NavBarItem>
<NavBarItem className="activity-enroll-navbar-item"
active={ currentDetailPanel === PANEL.requirements }
onClick={() => setCurrentPanel(PANEL.requirements)}>
要求
</NavBarItem>
<NavBarItem className="activity-enroll-navbar-item"
active={ currentDetailPanel === PANEL.questionAnswered }
onClick={() => setCurrentPanel(PANEL.questionAnswered)}>
问答
</NavBarItem>
<NavBarItem className="activity-enroll-navbar-item"
active={ currentDetailPanel === PANEL.messageBook }
onClick={() => setCurrentPanel(PANEL.messageBook)}>
留言
</NavBarItem>
</NavBar>
<TabBody className="activity-enroll-content-container">
<Article className=" activity-enroll-content">
{
((currentDetailPanel) => {
const introduction = activityItem.introduction[currentDetailPanel];
return introduction == null
? <EmptyTip tip="空空如也"/>
: <section dangerouslySetInnerHTML={{ __html: introduction }}/>;
})(currentDetailPanel)
}
</Article>
</TabBody>
</Tab>
</div>
<footer className="bar bar-tab activity-enroll-footer">
{
((joined, status) => {
if (joined === false) {
switch (status) {
case clazzStatusEnum.OPEN.key:
return <Button
onClick={() => {
enrollActivity()
.then(redirectTDetailPage)
.catch(() => {
})
}}>
参加报名
</Button>;
default:
return <Button type="default" disabled>已结束</Button>;
}
}
return <Button onClick={redirectTDetailPage}>查看进度</Button>
})(activityItem.joined, activityItem.status)
}
</footer>
<Dialog buttons={modal.buttons} show={modal.state} title={modal.title}>
点击页面右上角分享到朋友圈
</Dialog>
</div>
)
}
}
```
material.js
```import React, {Component} from "react";
import {inject, observer} from "mobx-react"
import InfiniteScroll from "react-infinite-scroller";
@inject("Materials") @observer
class MaterialPage extends Component {
constructor(props) {
super(props);
const {courseId, feedbackId} = this.props.params;
this.list = new this.props.Materials(courseId, feedbackId);
}
componentDidMount() {
this.list.getMaterials();
}
render() {
const {getMaterials, hasMore, all, postMaterial} = this.list;
return (
<div className="page page-current" id="material-page">
<header className="bar bar-nav">
<a className="button button-link button-nav pull-left" href="#chat-page">
<span className="icon icon-left" onClick={()=>history.back()}/>
</a>
<h1 className="title">笃师一对一</h1>
</header>
<div className="content material-list infinite-scroll">
<div className="list-block">
<div className="list-group">
<InfiniteScroll
loadMore={getMaterials}
loader={
(<div className="infinite-scroll-preloader">
<div className="preloader"></div>
</div>)}
hasMore={hasMore()}
threshold={20}
useWindow={false}
>
<ul>
<li className="list-title">
<div className="item-content">
<div className="item-inner">
<div className="item-title">请选择素材发送</div>
</div>
</div>
</li>
{
all.values.map((item, idx)=>(
<li key={idx} onClick={()=>postMaterial(item.id)} >
<div className="item-content">
<div className="item-inner">
<div className="item-title">{item.title}</div>
<div className="item-after">{item.author}</div>
</div>
</div>
</li>
))
}
</ul>
</InfiniteScroll>
</div>
</div>
</div>
</div>
)
}
}
export default MaterialPage;
```
detail.js
```'use strict';
import { observable, useStrict, action } from "mobx";
import React from "react";
import ReactDOM from "react-dom";
import util from "../util";
import { httpGet, httpPost } from "../../service";
import PopUp from "../common/popUp";
import uniqueToast from "../common/httpToast";
import cutil from "../../common-util";
import WechatShare from "../common/wechatShare";
import CommonAudioStore from '../common/audio';
import AudioPlayer from "../../view/audio";
useStrict(true);
const baseUrl = `${util.baseUrl}api/clazz`;
class TaskDetail {
@observable content = {};
@observable comment = [];
@observable commentContent = "";
@observable materialItem = { materialTitle: "", materialType: "", materialUrl: "" };
constructor(cid, tid, postId) {
this.cid = cid;
this.tid = tid;
this.postId = postId;
this.materialsPopUp = new PopUp();
this.commentPopUp = new PopUp();
this.bindToastWithAction();
this.audioTagUpdated = false;
this.videoTagUpdated = false;
this.wechatShare = null;
this.searchStr = postId ? `?postId=${ postId }` : '';
}
@action
setContent = (data) => {
const originContent = { ...data };
originContent.introductions.forEach((introductionItem) => {
//正则去掉html中的class和style
introductionItem.content = util.clearNodeClazzAndStyle(introductionItem.content);
});
originContent.articalInfo = this.compositeArticalInfo(originContent);
const { clazz, title, author } = originContent;
const clazzName = util.get(clazz, 'name') || 'Uband友班',
clazzBanner = util.get(clazz, 'banner') || 'http://qiniuprivate.gambition.cn/vHaiYP_uband_logo.png';
this.wechatShare = new WechatShare(
clazzName,
`${ title } By ${ author }`,
`${ location.origin }/course/${ this.cid }/task/${ this.tid }/public${ this.searchStr }`,
clazzBanner
);
this.content = originContent;
};
@action
setComment = (data) => {
this.comment = [];
data.forEach(item => this.comment.push(item))
};
@action
updateCommentContent = event => {
this.commentContent = event.target.value;
};
@action
clearCommentContent = () => {
this.commentContent = "";
};
getAll = () => {
if (this.cid == null) {
httpGet(`${baseUrl}/task/${this.tid}${ this.searchStr }`).then(this.setContent);
httpGet(`${baseUrl}/task/${this.tid}/replies`).then(this.setComment);
} else {
httpGet(`${baseUrl}/${this.cid}/task/${this.tid}${ this.searchStr }`).then(this.setContent);
httpGet(`${baseUrl}/${this.cid}/task/${this.tid}/replies`).then(this.setComment);
}
};
bindToastWithAction = () => {
this.uploadReply = () => this.addReply()
.then(() => {
this.clearCommentContent();
httpGet(`${baseUrl}/task/${this.tid}/replies`).then(this.setComment);
uniqueToast.showToast({ text: "操作成功", icon: "success" });
});
};
addReply = () => {
return httpPost(`${baseUrl}/${this.cid}/task/${this.tid}/reply`, { content: this.commentContent });
};
@action
refreshMaterialsPopUpContent = (title, type, url) => {
this.materialItem.materialTitle = title || "";
this.materialItem.materialType = type || "";
this.materialItem.materialUrl = url || "";
};
@action
removeMaterialsPopUpContent = () => {
this.materialsPopUp._hidePopUp();
this.materialItem.materialTitle = "";
this.materialItem.materialType = "";
this.materialItem.materialUrl = "";
};
replaceAllNativeAudioTag = () => {
if (this.audioTagUpdated === false) {
let audios = document.getElementsByTagName("audio");
let length = audios.length;
if (length) {
// 遍历audio并替换
for (let idx = 0; idx < length; ++idx) {
let audio = audios.item(idx);
let parent = audio.parentNode,
audioSrc = audio.querySelector("source").getAttribute("src");
// temporary render target
let temp = document.createElement("div");
// render
ReactDOM.render(<AudioPlayer src={audioSrc.toString()} audioStore={new CommonAudioStore()}/>, temp);
parent.replaceChild(temp, audio);
}
this.audioTagUpdated = true;
}
}
};
replaceAllNativeVideoTag = () => {
if (this.videoTagUpdated === false) {
let videos = document.getElementsByTagName("video");
let length = videos.length;
if (length) {
// 遍历video并替换
for (let idx = 0; idx < length; ++idx) {
let video = videos.item(idx);
video.setAttribute("preload", "none");
}
this.videoTagUpdated = true;
}
}
};
compositeArticalInfo = (originData) => {
let createdAtStr = util.get(originData, "targetDate", "");
let createdAtDate = createdAtStr ? new Date(createdAtStr) : new Date();//default date is NOW time
let strTime = cutil.format(createdAtDate, "yyyy-MM-dd");
let strAuthor = util.get(originData, "author", "");//default author is empty string
return `${strTime}\xa0\xa0${strAuthor}`;//\xa0 is a NO-BREAK SPACE char.
}
}
export default TaskDetail;
```
list.js
```'use strict';
import React, { Component } from "react";
import { Link, browserHistory } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import _ from '../../../util';
import EmptyTip from '../../../EmptyTip';
const {
Cells,
Cell,
CellHeader,
CellBody,
CellFooter
} = WeUI;
@inject("Promotion") @observer
export default class InviteeList extends Component {
constructor(props) {
super(props);
this.promotion = this.props.Promotion;
}
componentDidMount() {
this.promotion.getPromotionInviteeList();
this.promotion.initWechatShare();
}
render() {
const { currentPromotionUser, promotionInviteeList } = this.promotion;
const promotionInfo = _.get(currentPromotionUser, 'promotionInfo', null),
currentUserName = _.get(currentPromotionUser, 'name', '');
return (
<div className="promotion-page allies-page w-full">
<header className="page-header w-full bar bar-nav">
<a className="icon icon-left pull-left p-l-none p-r-none" onClick={() => browserHistory.replace('/promotion/home')}/>
<span className="title">我 的 友 军</span>
</header>
<main className="allies-page-main">
<Cell className="allies-page-main-user">
<CellHeader className="user-des">
<div className="user-des-info">
<span>友军数</span>
<span>{_.get(promotionInviteeList, 'length', 0)}</span>
</div>
<div className="user-des-info">
<span>总收益</span>
<span className="user-des-info-number">¥{(_.get(promotionInfo, 'incomeSum', 0) / 100).toFixed(0)}</span>
</div>
</CellHeader>
<CellBody className="user-number">
<img className="user-photo" src={_.get(currentPromotionUser, 'headImgUrl', '')} alt={currentUserName}/>
</CellBody>
<CellFooter className="user-info text-right">
<span>{currentUserName}</span>
<span>学号:{_.get(currentPromotionUser, 'studentNumber', '')}</span>
</CellFooter>
</Cell>
<Cells className="allies-page-main-list">
{
promotionInviteeList.length === 0
? <EmptyTip tip="空空如也"/>
: promotionInviteeList.map((inviteeItem) => (
<Cell className="list-info" component={Link} to={"/promotion/invitee/" + inviteeItem.id}
key={inviteeItem.id} access>
<CellHeader className="list-info-info">
<img className="list-info-photo" src={inviteeItem.headImgUrl} alt="友军头像"/>
</CellHeader>
<CellBody className="list-info-des">
<span className="m-l-sm text-overflow-hidden">{inviteeItem.name}</span>
{inviteeItem.studentNumber && <span className="m-l-sm text-overflow-hidden">学号:{inviteeItem.studentNumber}</span>}
</CellBody>
<CellFooter className="list-info-num">
<div className="list-info-num-div">
<span>购课数</span>
<span>{inviteeItem.promotionInfo.clazzCount}</span>
</div>
<div className="list-info-num-div">
<span>购课收益</span>
<span>{(inviteeItem.promotionInfo.incomeSum / 100).toFixed(0)}</span>
</div>
</CellFooter>
</Cell>
))
}
</Cells>
</main>
</div>
)
}
}
```
detail.js
```'use strict';
import React, { Component } from "react";
import { browserHistory } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import _ from '../../../util';
import EmptyTip from '../../../EmptyTip';
import { clazzJoinTypeEnum, promotionIncomeStatusEnum, clazzJoinStatusEnum } from "../../../enum";
const {
Cells,
Cell,
CellHeader,
CellBody,
CellFooter
} = WeUI;
@inject("Promotion") @observer
export default class InviteeDetail extends Component {
constructor(props) {
super(props);
this.inviteeId = this.props.params.inviteeId;
this.promoption = this.props.Promotion;
}
componentDidMount() {
this.promoption.getCurrentPromotionInvitee(this.inviteeId);
this.promoption.initWechatShare();
}
componentWillUnmount() {
this.promoption.resetCurrentPromotionInvitee();
}
render() {
const { currentPromotionInvitee } = this.promoption;
const promotionInfo = _.get(currentPromotionInvitee, 'promotionInfo', {}),
inviteeUserName = _.get(currentPromotionInvitee, 'name', ''),
inviteeStudentNumber = _.get(currentPromotionInvitee, 'studentNumber', '');
const incomeList = _.get(promotionInfo, 'incomeList', []);
return (
<div className="promotion-page allies-detail-page w-full">
<header className="page-header w-full bar bar-nav">
<a className="icon icon-left pull-left p-l-none p-r-none"
onClick={() => browserHistory.replace('/promotion/invitees')}/>
<span className="title">友 军 详 情</span>
</header>
<main className="allies-detail-page-main">
<Cell className="main-user">
<CellHeader className="main-user-info">
<img className="main-user-avatar" src={_.get(currentPromotionInvitee, 'headImgUrl', '')} alt="友军头像"/>
</CellHeader>
<CellBody className="main-user-clazz-info">
<span className="m-l-sm">{inviteeUserName}</span>
{inviteeStudentNumber && <span className="m-l-sm">学号:{inviteeStudentNumber}</span>}
</CellBody>
<CellFooter className="main-user-profit-info">
<div className="main-user-profit-info-div">
<span>购课数</span>
<span>{_.get(promotionInfo, 'clazzCount', 0)}</span>
</div>
<div className="main-user-profit-info-div">
<span>购课收益</span>
<span className="profit-info-number">{(_.get(promotionInfo, 'incomeSum', 0) / 100).toFixed(0)}</span>
</div>
</CellFooter>
</Cell>
<Cells className="main-allies-detail m-t-none">
{
incomeList.length === 0
? <EmptyTip tip="空空如也"/>
: incomeList.map((item) => {
const incomeStatusClassName = promotionIncomeStatusEnum.CANCELED === _.get(promotionIncomeStatusEnum, `${ item.status }`, promotionIncomeStatusEnum.CANCELED)
? ''
: 'available';
return <Cell className="main-allies-detail-list" key={item.id}>
<CellHeader className="main-allies-detail-list-clazz">
<span className="text-overflow-hidden">
{item.clazzInfo.name} | {_.get(clazzJoinTypeEnum, `${item.clazzInfo.clazzJoinType}.name`, '')}
</span>
</CellHeader>
<CellBody />
<CellFooter className="main-allies-detail-profit-state">
<div className="profit-state-div">
<span>金额</span>
<span className={incomeStatusClassName}>{(item.promoterUserIncome / 100).toFixed(0)}</span>
</div>
<div className="profit-state-div">
<span>状态</span>
<span className={incomeStatusClassName}>{_.get(clazzJoinStatusEnum, `${ item.clazzInfo.clazzJoinStatus }.name`, '')}</span>
</div>
</CellFooter>
</Cell>;
})
}
</Cells>
</main>
</div>
)
}
}
```
index.js
```"use strict";
/**
* 1. 页面入口
* 2. 定义页面路由
*/
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "mobx-react";
import { Router, Route, IndexRedirect, browserHistory, Redirect } from "react-router";
import "weui";
import "react-weui/lib/react-weui.min.css";
import "../../style/icons.scss";
import "../../style/reset.scss";
import store from "../store/main";
import Me from "./pages/me/me";
import Index from "./pages/me/index";
import Profile from "./pages/me/profile";
import Coin from "./pages/me/coin";
import Withdraw from "./pages/me/withdraw";
import Ticket from "./pages/me/ticket";
import Password from "./pages/me/password";
import Setting from "./pages/me/setting";
import SettingConfig from "./pages/me/setting-config";
import ClazzExit from "./pages/me/clazz-exit";
import CourseIndex from "./pages/course/index";
import CourseList from "./pages/course/course-list";
import CourseItem from "./pages/course/course-item";
import CourseDetail from "./pages/course/course/course-detail";
import CheckinDetail from "./pages/course/checkin/checkin-detail";
import CheckinCenter from "./pages/course/checkin/checkin-center";
import TaskDetail from "./pages/course/task/task-detail";
import TaskDetailPublic from "./pages/course/task/task-detail-public";
import LeadOne from "./pages/course/one";
import StudentPage from "./pages/course/one/student";
import ChatPage from "./pages/course/one/chat";
import MaterialPage from "./pages/course/one/material";
import MaterialDetailPage from "./pages/course/one/material-detail";
import Enroll from "./pages/enroll";
import EnrollListPage from "./pages/enroll/list";
import EnrollDetailPage from "./pages/enroll/detail";
import EnrollPayPage from "./pages/enroll/pay";
import EnrollPaySuccessPage from "./pages/enroll/pay/success";
import Game from './pages/game/index';
import GameMcIndexPage from './pages/game/mc/index';
import GameMcJoinPage from './pages/game/mc/join';
import GameMcRoomPage from './pages/game/mc/room';
import GameMcSharePage from './pages/game/mc/share';
import Auth from "./pages/auth";
import NotFound from "./pages/notFound";
import SubscribeGuide from "./pages/subscribeGuide";
import RedirectPage from "./pages/redirect";
import Activity from "./pages/activity/activity";
import ActivityList from "./pages/activity/activity-list";
import ActivityDetails from "./pages/activity/activity-detail";
import ActivityEnroll from "./pages/activity/activity-enroll";
import Teacher from "./pages/teacher/teacher";
import TeacherListPage from "./pages/teacher/teacher-list";
import TeacherDetailPage from "./pages/teacher/teacher-detail";
import Promotion from "./pages/promotion";
import PromotionHome from "./pages/promotion/home";
import PromotionInviteeList from "./pages/promotion/invitee/list";
import PromotionInviteeDetail from "./pages/promotion/invitee/detail";
import PromotionIncome from "./pages/promotion/income/index";
import PromotionIncomeList from "./pages/promotion/income/list";
import PromotionShare from "./pages/promotion/share";
import PromotionRecommend from "./pages/promotion/recommend";
import PromotionHelp from "./pages/promotion/help";
import InteractiveGuidePage from "./pages/guide/interactive-guide";
/**
* React Router Hash Link Scroll
* source: https://github.com/rafrex/react-router-hash-link/tree/react-router-v2/3
*/
const hashLinkScroll = () => {
const { hash } = window.location;
if (hash !== '') {
// Push onto callback queue so it runs after the DOM is updated,
// this is required when navigating from a different page so that
// the element is rendered on the page before trying to getElementById.
setTimeout(() => {
const id = hash.replace('#', '');
const element = document.getElementById(id);
if (element) element.scrollIntoView();
}, 0);
}
};
// 存放全局初始地址
localStorage.originUrl = `${ location.pathname }${ location.search }`;
ReactDOM.render((
<Provider {...store}>
<Router history={browserHistory} onUpdate={hashLinkScroll}>
<Route path="/redirect" component={RedirectPage}/>
<Route path="/course/:courseId/task/:taskId/public" component={TaskDetailPublic}/>
<Route path="/promotion/:promoterUserId/share" component={PromotionShare}/>
<Route path="/" component={Auth}>
<IndexRedirect to="me/index"/>
<Route path="me" component={Me}>
<IndexRedirect to="index"/>
<Route path="index" component={Index}/>
<Route path="profile" component={Profile}/>
<Route path="coin" component={Coin}/>
<Route path="withdraw" component={Withdraw}/>
<Route path="ticket" component={Ticket}/>
<Route path="password" component={Password}/>
<Route path="setting" component={Setting}/>
<Route path="setting/:config/:value" component={SettingConfig}/>
<Route path="setting/:config" component={SettingConfig}/>
<Route path="clazzExit" component={ClazzExit}/>
</Route>
<Route path="enroll" component={Enroll}>
<IndexRedirect to="list"/>
<Route path="list" component={EnrollListPage}/>
<Route path="pay/:courseId" component={EnrollPayPage}/>
<Route path="pay/:courseId/success" component={EnrollPaySuccessPage}/>
<Route path=":courseId" component={EnrollDetailPage}/>
</Route>
<Route path="course" component={CourseIndex}>
<IndexRedirect to="list"/>
<Route path="list" component={CourseList}/>
<Route path="checkin/center" component={CheckinCenter}/>
<Route path=":courseId" component={CourseItem}>
<Route path="detail" component={CourseDetail}/>
<Route path="checkin(/:checkinId)" component={CheckinDetail}/>
<Route path="task/:taskId" component={TaskDetail}/>
<Route path="one" component={LeadOne}>
<Route path="student" component={StudentPage}/>
</Route>
<Route path="one/chat(/:feedbackId)" component={ChatPage}/>
<Route path="one/material/:feedbackId" component={MaterialPage}/>
<Route path="one/detail/:materialId" component={MaterialDetailPage}/>
</Route>
<Redirect from="detail/:courseId" to=":courseId/detail"/>
<Redirect from="one/:courseId/student" to=":courseId/one/student"/>
<Redirect from="one/:courseId/chat(/:feedbackId)" to=":courseId/one/chat(/:feedbackId)"/>
<Redirect from="one/:courseId/material/:feedbackId" to=":courseId/one/material/:feedbackId"/>
<Redirect from="one/:courseId/detail/:materialId" to=":courseId/one/detail/:materialId"/>
</Route>
<Route path="game" component={Game}>
<IndexRedirect to="mc/index"/>
<Route path="mc/index" component={GameMcIndexPage}/>
<Route path="mc/join" component={GameMcJoinPage}/>
<Route path="mc/room" component={GameMcRoomPage}/>
<Route path="mc/share" component={GameMcSharePage}/>
</Route>
<Route path="activity" component={Activity}>
<IndexRedirect to="list"/>
<Route path="list" component={ActivityList}/>
<Route path=":activityId" component={ActivityEnroll}/>
<Route path=":activityId/user/:userId" component={ActivityDetails}/>
</Route>
<Route path="teacher" component={Teacher}>
<IndexRedirect to="list"/>
<Route path="list" component={TeacherListPage}/>
<Route path=":teacherId" component={TeacherDetailPage}/>
</Route>
<Route path="promotion" component={Promotion}>
<IndexRedirect to="home"/>
<Route path="home" component={PromotionHome}/>
<Route path="invitees" component={PromotionInviteeList}/>
<Route path="invitee/:inviteeId" component={PromotionInviteeDetail}/>
<Route path="income" component={PromotionIncome}/>
<Route path="incomes" component={PromotionIncomeList}/>
<Route path="recommend" component={PromotionRecommend}/>
<Route path="help" component={PromotionHelp}/>
</Route>
<Route path="guide/chats" component={InteractiveGuidePage}/>
</Route>
<Route path="subscribe" component={SubscribeGuide}/>
<Route path="*" component={NotFound}/>
</Router>
</Provider>),
document.getElementById("content")
);
```
list.js
```'use strict';
import { observable, useStrict, action } from "mobx";
import Paginator from "../common/paginator";
import util from "../util";
import { httpGet, httpPost } from "../../service";
import WechatShare from "../common/wechatShare";
useStrict(true);
const baseUrl = `${util.baseUrl}api/clazz`;
class RankList {
@observable
rankListPaginator = new Paginator();
@observable
isCurrentUserFirst = false;
constructor() {
}
setCourseId = (courseId) => {
this.courseId = courseId;
};
@action
clearData = () => {
this.courseId = null;
this.rankListPaginator = new Paginator();
this.isCurrentUserFirst = false;
};
initWechatShare(courseName, courseBanner) {
const targetUrl = `/course/${ this.courseId }/detail?tabIndex=0¤tPanel=rankPanel`;
this.wechatShare = new WechatShare(
`你在 ${ courseName } 的打卡排行榜上名列前茅吗?`,
`友班 ${ courseName } 英雄榜,看看你排第几?`,
`${ location.origin }/redirect?target=${ encodeURIComponent(targetUrl) }`,
courseBanner
);
}
getRankList = () => {
const { updateData, pageNumber } = this.rankListPaginator;
this._fetchRankList(40, pageNumber).then(updateData);
};
getCurrentUserRankInfo = (clazzId) =>
this._fetchCurrentUserRankInfo().then(this._setCurrentUserRankInfo);
favourRankItem = (item, index) => {
if (item.favourInfo.isFavour === true) {
return;
}
this._favourRank(item.id)
.then(action((data) => {
this.rankListPaginator.values.splice(index, 1, data);
}))
};
@action
_setCurrentUserRankInfo = (data) => {
if (data.id != null) {
this.isCurrentUserFirst = true;
this.rankListPaginator.values.unshift(data);
}
};
_fetchRankList = (pageSize, pageNumber = 1) =>
httpGet(`${baseUrl}/${this.courseId}/ranks?pageSize=${pageSize}&pageNumber=${pageNumber}`);
_fetchCurrentUserRankInfo = () =>
httpGet(`${baseUrl}/${this.courseId}/rank`);
_favourRank = (rankId) =>
httpPost(`${baseUrl}/${this.courseId}/rank/${rankId}/favour`);
}
export default new RankList();
```
help.js
```'use strict';
import React, { Component } from "react";
import { browserHistory } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import _ from "../../util";
import { ubandLogoUrl } from "../../../images-url";
/**
* 引入样式
*/
import "../../../../style/guide.scss";
const {
Button,
TabBar
} = WeUI;
@inject("Promotion") @observer
export default class Helppage extends Component {
constructor(props) {
super(props);
this.promotion = this.props.Promotion;
this.helpMainNode = null;
}
componentDidMount() {
this.promotion.initWechatShare();
}
next = () => {
this.promotion.incrementCurrentDialogIndex();
window.setTimeout(() => this.helpMainNode.scrollTop = this.helpMainNode.scrollHeight, 0);
};
render() {
const { currentPromotionUser, dialogList, currentDialogIndex } = this.promotion;
const currentUserHeadImgUrl = _.get(currentPromotionUser, 'headImgUrl', '');
return (
<div className="promotion-page help-page w-full">
<header className="page-header w-full bar bar-nav">
<a className="icon icon-left pull-left p-l-none p-r-none"
onClick={() => browserHistory.replace('/promotion/home')}/>
<span className="title">玩 法 指 南</span>
</header>
<div className="content help-page-content" ref={(item) => this.helpMainNode = item}>
<div className="help-page-main p-l-sm p-r-sm">
{
dialogList.map((dialogItem, idx) => {
return (
dialogItem.isSelf
? <section className={`user-section ${currentDialogIndex > idx ? 'show' : ''}`} key={idx}>
<div className="dialog">
<span className="user-dialog">
<span dangerouslySetInnerHTML={{ __html: dialogItem.content }}/>
<div className="triangle"/>
</span>
<img className="user-photo" src={currentUserHeadImgUrl}/>
</div>
</section>
: <section className={`uband-section ${currentDialogIndex > idx ? 'show' : ''}`} key={idx}>
<div className="dialog">
<img className="uband-photo" src={ubandLogoUrl}/>
<span className="uband-dialog">
<div className="triangle"/>
<span dangerouslySetInnerHTML={{ __html: dialogItem.content }}/>
</span>
</div>
</section>
)
})
}
</div>
</div>
{
( currentDialogIndex < dialogList.length &&
<TabBar className="help-page-footer">
<Button className="m-b-lg next-button" onClick={this.next}>
下一步
</Button>
</TabBar>
)
}
</div>
)
}
}
```
README.md
```# shark-h5
注意:前端采用的gulp为gulp4,如果npm install出现问题需要单独从github上下载
## 使用方式
----------
1.找到`src/js/config.js.back` 复制为 `src/js/config.js`,然后更新`config.js`文件中的`token`和`baseUrl`
其中 `token` 更新为paw中auth的最新token就好,其中`baseUrl`的return的url改为`//h5test.gambition.cn/`
2.在项目根目录打开终端,输入`npm install`,安装所有依赖包。
`$ npm install`
3.输入`npm run wpdll`来编译打包所有的第三方依赖。
`$ npm run wpdll`
4.输入`npm start`来启动`gulp`,在浏览器中输入`localhost:5000`来观察效果。
`$ npm start`
## 开发规范
---------------
### 命名:
1. js变量命名: 名词短语,采用驼峰法;最多5个单词,不推荐缩写;复数在后面增加List,而不是复数形式; 如 `courseList`,`currentPanel`
2. css类名: 采用`-`分隔,名词短语;最多5个单词,不推荐缩写。如`bar-tab`, `course-title`
3. 函数名: 动词短语,采用驼峰法;最多5个单词,不推荐缩写。如`hideCancelCheckinDialog`, `setCheckinList`
4. 私有函数: 以`_`开头,其他参见`3. 函数名`。如`_fetchCourseList`
5. class名,采用大写驼峰法,即每个单词首字母均采用大写,最多5个单词,不推荐缩写。如`CheckinCenter`, `ActivityEnroll`
### react
因采用`mbox`进行`state`的管理,不推荐直接使用`this.state`及`this.setState`来申明或更新`state`
## UI 库
---------------
本项目使用了如下两个UI库
1. [SUI Mobile](http://m.sui.taobao.org/components/): 使用其样式
2. [React WeUI](https://weui.github.io/react-weui/docs/#/react-weui/docs/page/1/articles/0): 使用其元素
## 添加新的Image
---------------
当添加了新的img之后,需要做的是:
1.在项目根目录,输入`npm run refresh-img`,更新雪碧图并刷新`style/icons-sprite.scss`;
`npm run refresh-img`
2.手动在`style/icons.scss`中引入新的`style/icons-sprite.scss`图。
## Reference
------------
1. Mobx @computed 和直接 get 的区别的解读:[MobX中@computed和自定义get函数的区别](http://blog.csdn.net/cqm1994617/article/details/53271494) 以及 [What's difference between @computed decorator and getter function](https://github.com/mobxjs/mobx/issues/161)
2. [微信开发常见问题](http://kf.qq.com/faq/140225MveaUz150413VNj6nm.html)
3. [駝峰式大小寫](https://zh.wikipedia.org/wiki/%E9%A7%9D%E5%B3%B0%E5%BC%8F%E5%A4%A7%E5%B0%8F%E5%AF%AB)
```
task-list.js
```import React, { Component } from "react";
import { browserHistory } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
const {
Cells,
Cell,
CellBody,
CellFooter,
Dialog
} = WeUI;
@inject("TaskList") @observer
class TaskList extends Component {
constructor(props) {
super(props);
this.taskList = this.props.TaskList;
}
componentDidMount() {
}
onTaskItemClick = (item) => {
switch (item.postType) {
case "CLAZZ_TASK":
browserHistory.push(`/course/${ this.taskList.courseId }/task/${ item.target }?postId=${ item.id }`);
return;
default:
location.href = item.target;
return;
}
};
render() {
const { content, dialog, processCourseCanceling } = this.taskList;
return (
<div>
<div className="task-list-wrap">
{
content.map(item => (
<Cells className="task-item" key={item.id} id={item.target} onClick={() => this.onTaskItemClick(item)}>
{item.stickied && <i className="icon-gb icon-gb-mark-top task-item-mark-top"/>}
<Cell className="task-title">
<CellBody className="text-overflow-hidden">
{item.title}
</CellBody>
<CellFooter>
</CellFooter>
</Cell>
<Cell className="task-time">
<CellBody>
发布于: {item.date}
</CellBody>
</Cell>
</Cells>
))
}
</div>
<Dialog title="是否真的要退出课程" show={dialog.show} buttons={(() => {
return [
{
type: 'default',
label: '取消',
onClick: () => {
dialog.dismissDialog();
}
},
{
type: 'primary',
label: '确认',
onClick: processCourseCanceling
}
];
})()}>
</Dialog>
</div>
)
}
}
export default TaskList;
```
chat.js
```import React, {Component} from "react";
import {Link, browserHistory} from "react-router";
import PullToRefresh from "./ptr"
import {observer, inject} from "mobx-react";
import util from "../../../../store/util";
import cutil from "../../../../common-util";
const baseUrl = `${util.baseUrl}api`;
import _ from "../../../util";
import {httpGet} from "../../../../service";
import Footer from "./footer";
import {scroll} from "../../../../store/one/chat";
import "../../../../../style/chat.scss";
import WeuiToast from "../../../WeuiToast";
@inject("Chat") @observer
class ChatPage extends Component {
constructor(props) {
super(props);
this.courseId = this.props.params.courseId;
this.feedbackId = this.props.params.feedbackId;
this.chat = new this.props.Chat(this.courseId, this.props.params.feedbackId);
// todo 移除state, 好孩子不要学
this.state = {
backUrl: "",
isTeacher: false,
resetFooter: true
};
this.resetFooter = this.resetFooter.bind(this);
}
resetFooter() {
// todo 移除setState, 好孩子不要学
this.setState({
resetFooter: true
})
}
componentWillMount() {
let cid = this.courseId,
self = this;
httpGet(`${baseUrl}/clazz/${cid}/isTeacher`)
.then((isTeacher) => {
// todo 移除setState, 好孩子不要学
isTeacher
? self.setState({backUrl: `/course/${cid}/one/student`})
: self.setState({backUrl: `/course/${cid}/detail`});
// todo 移除setState, 好孩子不要学
self.setState({isTeacher: isTeacher});
self.chat.getChats(isTeacher, () => {
scroll.scrollToBottom();
});
});
}
render() {
const {list, getChats, toast} = this.chat;
return (
<div className="page page-current" id="chat-page">
<header className="bar bar-nav chat-nav">
<h1 className="title">笃师一对一</h1>
<div onClick={() => {browserHistory.replace(this.state.backUrl)}}
className="button button-link button-nav pull-left chat-page-back">
<span className="icon icon-left"/>
</div>
</header>
<Footer isTeacher={this.state.isTeacher} courseId={this.courseId} feedbackId={this.feedbackId}
chat={this.chat} reset={this.state.resetFooter} list={list}/>
<div className="content" ref="content" onClick={this.resetFooter}>
<PullToRefresh
onRefresh={resolve => {
getChats(this.state.isTeacher, resolve);
}}
>
<div className="chat-list" ref="list">
{
list.map((item, idx) => {
const userInfo = _.get(item, "userInfo", {});
return (
<div className={(userInfo.isSelf ? "me " : "") + "chat-item"} key={idx}>
<div className="chat-avatar">
<img src={userInfo.headImgUrl}/>
</div>
<div className="chat-content">
<div className="chat-user">
<span className="chat-user-name">{userInfo.name}</span>
{userInfo.isTeacher && <span className="chat-user-title">笃师</span>}
</div>
{
(() => {
switch (item.type) {
case "TEXT":
return (
<div className="chat-text-msg">
<p>{item.content}</p>
</div>
);
case "VOICE":
let {audio} = item;
return (
<div className="chat-audio-msg">
<div className="audio-bar"
onClick={() => audio.controllAudio(this.refs["audio" + idx])}>
<audio src={item.url} onEnded={() => audio.pauseAudio(this.refs["audio" + idx])}
ref={"audio" + idx}/>
<i className={"icon-gb icon-gb-" + audio.nextState.toLowerCase()}/>
</div>
</div>
);
case "MATERIAL":
return (
<Link className="chat-material-msg"
to={`/course/${ this.courseId }/one/detail/${ item.materialId }`}>
<div className="material-title">{item.title}</div>
<div className="material-line"></div>
<div className="material-author">作者: {item.author}<i className="icon icon-right"/>
</div>
</Link>
);
}
})()
}
<footer className="chat-item-footer"><span>{Date.parse(item.date) ? cutil.format(new Date(item.date), "MM-dd hh:mm") : ''}</span></footer>
</div>
</div>
)
}
)
}
</div>
</PullToRefresh>
</div>
<WeuiToast icon={toast.icon} iconSize="large" show={toast.show}>{ toast.text }</WeuiToast>
</div>
)
}
}
export default ChatPage;
```
list.js
```/**
* Created by violinsolo on 20/07/2017.
*/
'use strict';
import { observable, useStrict, action } from "mobx";
import util from "../util";
import WechatShare from "../common/wechatShare";
const baseUrl = `${util.baseUrl}api`;
import { httpGet } from "../../service";
useStrict(true);
export default class TeacherList {
@observable
teacherList = []; // 笃师的列表
/**
* action 更新笃师列表
* @param teacherList
*/
@action
setTeachers = (teacherList) => {
this.teacherList = teacherList.values;
this.wechatShare = new WechatShare(
"报告!友班笃师们在向你招手",
"推荐一大波牛人给你认识~来友班,和牛人做朋友!",
`${ location.origin }/redirect?target=/teacher/`,
"http://qiniuprivate.gambition.cn/rgHxWu_uband_logo.png"
);
};
fetchList = () => httpGet(`${baseUrl}/clazzTeachers?pageSize=1000`);//TODO: Hard Code, 以后改成下拉刷新的
}
```
auth.js
```"use strict";
import React, {Component} from "react";
import {inject, observer} from "mobx-react";
import { Toptips } from "react-weui";
import _ from "../util";
import config from "../../config";
import httpToast from "../../store/common/httpToast";
import topTip from "../../store/common/toptip";
import WeuiToast from "../WeuiToast";
import WeuiIcon from "../WeuiIcon";
import "../../../style/auth.scss"
const SUCCESS = "SUCCESS",
FAILURE = "FAILURE",
PENDING = "PENDING";
@inject("Auth", "SystemConfig") @observer
class Auth extends Component {
constructor(props) {
super(props);
this.auth = new this.props.Auth();
this.wechatLogin = this.wechatLogin.bind(this);
this.systemConfig = new this.props.SystemConfig();
}
componentWillMount() {
const {code, state} = this.props.location.query;
const {setAuthState, checkExpire} = this.auth;
const token = localStorage.token;
/*
测试环境注释以下 if else 语句
*/
if (config.isProduct) {
if (token !== undefined && token !== null) {
// token在大于5天,则重新授权
if (checkExpire(token)) {
this.wechatLogin(code, state);
} else {
setAuthState(SUCCESS);
}
} else {
this.wechatLogin(code, state);
}
}
if (_.isIOS()) {
this.systemConfig.fetchAppInfo('IOS');
} else {
this.systemConfig.fetchAppInfo('ANDROID');
}
}
// 微信登录
wechatLogin(code, state) {
const {getWechatLogin, setAuthState, getToken, setToken} = this.auth;
if (typeof state === "undefined") {
getWechatLogin(location.pathname)
.then((url) => location.replace(url))
} else {
if (typeof code === "undefined") {
setAuthState(FAILURE);
} else {
getToken(code)
.then(setToken)
.then(() => location.replace(_.removeUrlParameter(`${ location.pathname}${ location.search }`, 'code')));
}
}
}
render() {
/*
测试环境请打开
*/
if (!config.isProduct) {
this.auth.setAuthState(SUCCESS);
}
const {state} = this.auth;
const { appInfo } = this.systemConfig;
const self = this;
return (
<div>
<Toptips type={topTip.type} show={topTip.show}>{topTip.content}</Toptips>
{
(function (state) {
switch (state) {
case SUCCESS:
return (
<div>
{self.props.children}
{
appInfo
? (<footer className="bar bar-tab" id="app-advertisement">
<div className="fix-end">
<div className="sm-txt">
<span className="cost-txt">友班App, 更好的体验</span>
</div>
<div>
<div onClick={() => window.location.href = appInfo.url}
className="button button-fill enroll-button">
点击下载
</div>
</div>
</div>
</footer>)
: null
}
</div>);
case FAILURE:
return (
<div className="auth-page">
<WeuiIcon size="large" value="warn" className="icon-pos"/>
<div className="text">
微信授权失败,请重试
</div>
</div>);
case PENDING:
return (
<div/>
)
}
})(state)
}
<WeuiToast icon={httpToast.icon} iconSize={"large"} show={httpToast.show}>{httpToast.text}</WeuiToast>
</div>
)
}
}
export default Auth;
```
index.js
```import React, { Component } from "react";
import { Link } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import BottomTabBar from "../bottomTabBar";
import UbandHeader from "../ubandHeader";
const {
Cells,
Cell,
CellHeader,
CellBody,
CellFooter
} = WeUI;
@inject("User") @observer
class Index extends Component {
constructor(props) {
super(props);
}
render() {
const { info } = this.props.User;
return (
<div className="page page-current me-page">
<UbandHeader/>
<div className="content profile-center">
<div className="info-cell">
<div className="avatar-wrap">
<img src={info.headImgUrl}/>
<div className="info-wrap">
<div className="info-name">{info.name}</div>
<div className="info-number">{info.studentNumber}</div>
</div>
</div>
</div>
<Cells>
<Cell component={Link} to="/promotion/home">
<CellHeader>
<i className="icon-gb icon-gb-promotion-center"/>
</CellHeader>
<CellBody>
伙伴中心
</CellBody>
<CellFooter/>
</Cell>
<Cell component={Link} to="/course/list">
<CellHeader>
<i className="icon-gb icon-gb-course"/>
</CellHeader>
<CellBody>
学习记录
</CellBody>
<CellFooter/>
</Cell>
<Cell component={Link} to="/me/coin">
<CellHeader>
<i className="icon-gb icon-gb-coin"/>
</CellHeader>
<CellBody>
我的优币
</CellBody>
<CellFooter/>
</Cell>
<Cell component={Link} to="/me/ticket">
<CellHeader>
<i className="icon-gb icon-gb-coupon"/>
</CellHeader>
<CellBody>
我的优惠券
</CellBody>
<CellFooter/>
</Cell>
<Cell component={Link} to="/me/setting">
<CellHeader>
<i className="icon-gb icon-gb-account"/>
</CellHeader>
<CellBody>
个人信息
</CellBody>
<CellFooter/>
</Cell>
<Cell component={Link} to="/me/clazzExit">
<CellHeader>
<i className="icon-gb icon-me-exit-clazz"/>
</CellHeader>
<CellBody>
申请退班
</CellBody>
<CellFooter/>
</Cell>
</Cells>
{/*<Cells>*/}
{/*<Cell component={Link} to="/me/setting">*/}
{/*<CellBody>*/}
{/*获取帮助?*/}
{/*</CellBody>*/}
{/*<CellFooter/>*/}
{/*</Cell>*/}
{/*<Cell component={Link} to="/me/setting">*/}
{/*<CellBody>*/}
{/*发送反馈给我们*/}
{/*</CellBody>*/}
{/*<CellFooter/>*/}
{/*</Cell>*/}
{/*</Cells>*/}
</div>
<BottomTabBar currentTab="me"/>
</div>
)
}
}
export default Index;
```
index.js
```'use strict';
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import _ from "../../../util";
const {
Switch,
Dialog,
FormCell,
Label,
CellBody,
CellFooter,
Select,
Input
} = WeUI;
import "../../../../../style/enroll.scss";
@inject("Pay") @observer
class EnrollPayPage extends Component {
constructor(props) {
super(props);
this.pay = new this.props.Pay(this.props.params.courseId);
}
componentDidMount() {
this.pay.fetchPayInfo(this.pay.setPayment);
}
formatMoney(rawMoney) {
if (rawMoney != null)
return (Number(rawMoney) / 100).toFixed(2);
}
render() {
const {
showDialog, dialog, diaContent, diaButtons, coinState, changeSwitch, setFee, promotionCodeChangeHandler, alertInvalidPromotionCode,
payment, fee,
isFirstOffer, isFirstOfferCodeValid, firstOfferCode
} = this.pay;
const { promotionOffer } = payment;
const promotionUserInfo = _.get(promotionOffer, 'promotionUserInfo', null);
const { title, show } = dialog;
return (
<div className="enroll-page page">
<header className="bar bar-nav">
<a className="icon icon-left pull-left" onClick={() => history.go(-1)}/>
<h1 className="title">报名付款</h1>
</header>
<div className="content pay-page">
<div className="pay-head flex-row">
<img className="pay-img"
src={payment.clazz ? payment.clazz.banner : null} alt="课程icon"/>
<div className="flex-column text-content">
<div className="pay-title">{payment.clazz ? payment.clazz.name : null}</div>
<div className="pay-cost-txt">
<div className="text-large">¥{this.formatMoney(fee.totalFee)}</div>
<div className="text-small">(原价 <span className="font-red">¥{this.formatMoney(fee.originFee)}</span>)
</div>
</div>
</div>
</div>
<div className="list-block m-t-md">
<ul>
<li className="item-content">
<FormCell className="item-inner p-l-none">
<CellBody>
<Label>付款方式</Label>
</CellBody>
<CellFooter>
<Label className="font-green">微信</Label>
</CellFooter>
</FormCell>
</li>
{
payment.clazz && payment.clazz.clazzType === 'LONG_TERM' && (
<li className="item-content">
<FormCell select className="item-inner">
<CellBody>
套餐(点击可选)
</CellBody>
<CellFooter>
<Select onChange={(e) => setFee(payment.priceList[e.target.value])} defaultValue={0}>
{
payment.priceList.map((priceItem, index) =>
<option value={ index } key={`price_month_index_${ index }`}>
{ priceItem.name }
</option>
)
}
</Select>
</CellFooter>
</FormCell>
</li>
)
}
{
fee.couponItem === null || (<li className="item-content">
<div className="item-inner">
<div className="item-title">使用优惠券
(¥<span className="font-red">{_.get(fee, "couponItem.money", 0)}</span>)?
</div>
<Switch onChange={(e) => changeSwitch("coupon")}/>
</div>
</li>)
}
<li className="item-content">
<div className="item-inner">
<div className="item-title">使用优币
<span className="font-red">{_.get(fee, "coinItem." + coinState, 0)}</span>枚?
</div>
<Switch onChange={(e) => changeSwitch("coin")}/>
</div>
</li>
{
isFirstOffer && (<li className="item-content">
<div className="item-inner">
<div className="item-title">优惠码</div>
<div className="item-after">
<Input className="promotion-code-input text-right" type="text" placeholder="输入优惠码"
maxLength="12" value={firstOfferCode}
onBlur = {alertInvalidPromotionCode}
onChange={(event) => promotionCodeChangeHandler(event.target.value)}/>
</div>
</div>
</li>)
}
{
isFirstOfferCodeValid && (<li className="item-content promoter-user-item">
<div className="item-inner">
<div className="item-title">
<img className="promoter-user-avatar"
src={_.get(promotionUserInfo, 'userInfo.headImgUrl', '')} alt="推荐人头像"/>
<span className="p-l-xs">
推荐人: {_.get(promotionUserInfo, 'userInfo.name', '')}
</span>
</div>
<div className="item-after font-green">
-{this.formatMoney(_.get(promotionOffer, 'offerPrice', 0))}
</div>
</div>
</li>)
}
<li className="item-content">
<div className="item-inner">
<div className="item-title">实付金额</div>
<div className="item-after font-red">¥{this.formatMoney(fee.amount)}</div>
</div>
</li>
</ul>
</div>
</div>
<footer className="bar bar-tab pay-end">
<div className="button ensure-button" onClick={showDialog}>确定</div>
</footer>
<Dialog title={title} buttons={diaButtons} show={show}>{diaContent}</Dialog>
</div>
);
}
}
export default EnrollPayPage;
```
center.js
```import {observable, useStrict, action} from "mobx";
import {httpGet} from "../../service";
import util, {curry} from "../util";
const baseUrl = `${util.baseUrl}api`;
useStrict(true);
class CheckinCenter {
@observable courseList = [];
@action
setCourseList = (data) => {
this.courseList = data;
};
fetchList = () =>
httpGet(`${baseUrl}/clazzes?status=PROCESSING&isCheckinable=true`)
getList = () => {
this.fetchList()
.then((courseList) => this.setCourseList(courseList));
}
}
export default CheckinCenter;
```
main.js
```'use strict';
import User from "./me/user";
import Modal from "./common/modal";
import EnrollList from "./enroll/list";
import EnrollDetail from "./enroll/detail";
import Pay from "./enroll/pay";
import CourseList from "./course/list";
import CourseStudy from "./course/study";
import TaskList from "./task/list";
import RankList from "./rank/list";
import TaskDetail from "./task/detail";
import CheckinCenter from "./checkin/center";
import CheckinList from "./checkin/list";
import CheckinDetail from "./checkin/detail";
import Promotion from "./promotion/index";
import Password from "./me/password";
import Setting from "./me/setting";
import Coin from "./me/coin";
import Coupon from "./me/coupon";
import SettingConfig from "./me/setting.config";
import Students from "./one/student";
import Chat from "./one/chat";
import Auth from "./auth";
import Materials from "./one/material";
import WithDraw from "./me/withdraw";
import Record from "./one/record";
import Passport from './me/passport';
import MorningCall from './game/mc';
import ActivityList from './activity/list';
import ActivityEnroll from './activity/enroll';
import ActivityDetail from './activity/detail';
import TeacherList from './teacher/list';
import TeacherDetail from './teacher/detail';
import GuideChat from "./guide/chat";
import CommonAudioStore from "./common/audio";
import CourseDetail from "./course/detail";
import ClazzExit from "./me/clazz-exit";
import SystemConfig from "./system/config";
const store = {
User,
Modal,
EnrollList,
EnrollDetail,
Pay,
CourseList,
CourseDetail,
CourseStudy,
TaskList,
RankList,
TaskDetail,
CheckinCenter,
CheckinList,
CheckinDetail,
Promotion,
Password,
Setting,
Coin,
Coupon,
SettingConfig,
Students,
Chat,
Auth,
Materials,
WithDraw,
Record,
Passport,
MorningCall,
ActivityList,
ActivityEnroll,
ActivityDetail,
TeacherList,
TeacherDetail,
GuideChat,
CommonAudioStore,
ClazzExit,
SystemConfig
};
export default store;
```
list.js
```'use strict';
import React, { Component } from "react";
import { browserHistory } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import _ from '../../../util';
import { clazzJoinTypeEnum, promotionIncomeStatusEnum } from "../../../enum";
import EmptyTip from '../../../EmptyTip';
const {
Cells,
Cell,
CellHeader,
CellBody,
CellFooter
} = WeUI;
@inject("Promotion") @observer
export default class IncomeRecordpage extends Component {
constructor(props) {
super(props);
this.promotion = this.props.Promotion;
}
componentDidMount() {
this.promotion.getPromotionIncomeList();
this.promotion.initWechatShare();
}
render() {
const { promotionIncomeList } = this.promotion;
return (
<div className="promotion-page income-record-page w-full">
<header className="page-header w-full bar bar-nav">
<a className="icon icon-left pull-left p-l-none p-r-none" onClick={() => browserHistory.go(-1)}/>
<span className="title">收 益 记 录</span>
</header>
<main className="income-record-page-main">
<Cells className="income-record-page-main-list">
{
promotionIncomeList.length === 0
? <EmptyTip tip="空空如也"/>
: promotionIncomeList.map((item) => {
const clazzInfo = item.clazzInfo,
userInfo = item.userInfo,
incomeStatusEnum = _.get(promotionIncomeStatusEnum, `${ item.status }`, promotionIncomeStatusEnum.CANCELED);
const incomeStatusClassName = incomeStatusEnum === promotionIncomeStatusEnum.CANCELED ? '' : 'available';
return (<Cell className="list-info" key={item.id}>
<CellHeader className="list-info-detail">
<img className="list-info-photo" src={userInfo.headImgUrl} alt="用户头像"/>
</CellHeader>
<CellBody className="list-info-des">
<span className="m-l-sm text-overflow-hidden">{userInfo.name}</span>
<span className="m-l-sm text-overflow-hidden">{clazzInfo.name} | {_.get(clazzJoinTypeEnum, `${ clazzInfo.clazzJoinType }.name`, '笃班')}</span>
</CellBody>
<CellFooter className="list-info-number">
<div className="list-info-number-div">
<span>金额</span>
<span className={incomeStatusClassName}>{(_.get(item, 'promoterUserIncome', 0) / 100).toFixed(0)}</span>
</div>
<div className="list-info-number-div">
<span>状态</span>
<span className={incomeStatusClassName}>{incomeStatusEnum.name}</span>
</div>
</CellFooter>
</Cell>)
})
}
</Cells>
</main>
</div>
)
}
}
```
detail.js
```'use strict';
import { observable, useStrict, action, computed } from "mobx";
import { browserHistory } from "react-router";
import util from "../util";
import cutil from "../../common-util";
import { httpGet, httpPost, httpDel, httpPut } from "../../service";
import httpToast from '../common/httpToast';
useStrict(true);
const baseUrl = `${util.baseUrl}api/clazz`;
const MAX_FILE_SIZE = 20971520; // 1024 * 1024 * 20 即20MB;
class CheckinDetail {
@observable
data = {
canCheckin: false, // 课程是否能打卡
checkinTime: "", // 打卡日期,格式为'yyyy-MM-dd'
clazz: null, // 班级信息,对象
hasCheckin: false, // 是否已打卡
userFiles: [] // 打卡文件列表
};
@observable
checkInDate = ""; // 打卡日期 pattern: yyyy-MM-dd
@observable
cancelCheckinDialog = {
show: false // 是否显示取消打卡dialog
};
@observable
chooseFileButtonDisabled = false; // 是否disable上传文件按钮
CHECKIN_STATE = {
EDIT: "EDIT",
CREATE: "CREATE"
};
constructor(courseId, checkinId, clickUploadButton) {
this.courseId = courseId;
this.checkinId = checkinId || "";
this.actionType = checkinId ? this.CHECKIN_STATE.EDIT : this.CHECKIN_STATE.CREATE;
// 构造上传文件选择配置
this.FILE_UPLOAD_OPTIONS = this._constructFileUploadOptions(
clickUploadButton,
httpToast.showToast,
this.enableChooseFileButton,
this.disableChooseFileButton,
this._fetchQiniuUploadToken,
this._pushUploadFile
);
}
/**
* 展示操作成功toast
*/
showSuccessToast = () => httpToast.showToast({ text: "操作成功", icon: "success" });
/**
* enable上传文件按钮
* @param hideToast 是否隐藏全局toast窗口
*/
enableChooseFileButton = (hideToast = true) => {
hideToast && httpToast.hideToast();
this._setChooseFileButtonDisabled(false);
};
/**
* disable上传文件按钮
* -- 粘滞显示全局toast窗口
*/
disableChooseFileButton = () => {
httpToast.stickyToast({ text: 'Loading...', icon: 'loading' });
this._setChooseFileButtonDisabled(true);
};
/**
* 返回到课程主页,并定位到去打卡tab
*/
backToCourseDetail = () => {
const targetUrl = `/course/${ this.courseId }/detail?tabIndex=1`;
browserHistory.replace(`/redirect?target=${ encodeURIComponent(targetUrl) }`);
};
/**
* 获取打卡详情,并设置打卡内容
*/
getCheckin = () => this._fetchCheckin()
.then(this._setCheckin)
.catch((error) => httpToast.showToast({ text: error.message, icon: "warn", cb: this.backToCourseDetail }));
/**
* 改变打卡文件状态 -- 即是否勾选文件
* @param item
*/
@action
changeFileState = (item) => item.hasCheckined = !item.hasCheckined;
/**
* 打卡
*/
addCheckin = () => httpPost(
`${baseUrl}/${this.courseId}/checkin`,
{
fileIds: this.data.userFiles.filter(item => item.hasCheckined).map(item => item.id),
date: this.checkInDate
}
);
/**
* 取消打卡
*/
deleteCheckin = () => httpDel(`${baseUrl}/${this.courseId}/checkin/${this.checkinId}`);
/**
* 更新打卡
*/
modifyCheckin = () => httpPut(
`${baseUrl}/${this.courseId}/checkin/${this.checkinId}`,
{
fileIds: this.data.userFiles.filter(item => item.hasCheckined).map(item => item.id)
}
);
/**
* 判断是否能打卡或补打卡或修改打卡
* @returns {*}
*/
@computed
get enableButton() {
return util.get(this.data, "canCheckin", true) && this._hasModifyFiles();
}
/**
* 隐藏取消打卡dialog
*/
@action
hideCancelCheckinDialog = () => this.cancelCheckinDialog.show = false;
/**
* 显示取消打卡dialog
*/
@action
showCancelCheckinDialog = () => this.cancelCheckinDialog.show = true;
/**
* 设置打卡日期,用于用户选择日期
* @param timePickerValue
*/
@action
setCheckInDate = (timePickerValue) => {
// this.courseBeganDate = new Date();
//before set, must check time:
const DATE_NOW = new Date();
const canCheckinDeadline = DATE_NOW > this.courseEndDate ? this.courseEndDate : DATE_NOW;
let userPickedDate = Date.parse(timePickerValue) ? new Date(timePickerValue) : DATE_NOW;
if (userPickedDate > canCheckinDeadline) {
userPickedDate = canCheckinDeadline;
httpToast.showToast({ text: "日期不在课程时间内", icon: "warn" });
}
this.checkInDate = cutil.format(userPickedDate, "yyyy-MM-dd");
};
/**
* 获取打卡详情信息
*
* TODO: 1.以后加个API,通过时间和当前课程,获取打卡文件,2.以及后台限制打卡次数
* @returns {*}
*/
_fetchCheckin = () => {
if (this.actionType === this.CHECKIN_STATE.EDIT) {
return httpGet(`${baseUrl}/${this.courseId}/checkin/${this.checkinId}`);
} else if (this.actionType === this.CHECKIN_STATE.CREATE) {
const urlQueryStr = this.checkInDate
? `?date=${ this.checkInDate }`
: '';
return httpGet(`${baseUrl}/${this.courseId}/checkin${ urlQueryStr }`);
}
return Promise.reject(new Error("获取文件异常,请联系管理员"));
};
/**
* 将上传好的文件推入打卡文件列表头部
*
* @param item
* @private
*/
@action
_pushUploadFile = (item) => {
this.data.userFiles.unshift(item);
};
/**
* 检查用户是否勾选文件
*
* @returns {boolean}
* @private
*/
_hasModifyFiles = () => {
return util.get(this.data, "userFiles", []).filter(item => item.hasCheckined).length !== 0;
};
/**
* 获取七牛云文件上传token
*
* @param fileName
* @param mimeType
* @returns {*}
* @private
*/
_fetchQiniuUploadToken = (fileName, mimeType) => {
const body = {
fileName: fileName,
attachType: "CHECKIN_REPOSITORY"
};
const fileType = mimeType.split('/')[0];
switch (fileType) {
case "image" :
case "video" :
case "audio" :
body.fileType = fileType;
break;
default : //other types (like 'application'), will be in here
//因为这里你直接 return 掉,中断了后续的回调操作,所以不会有模拟的点击方法,这个时候也就不会有后续的上传操作了
return Promise.reject(new Error("不支持该文件格式!"));
}
return httpPost(`${util.baseUrl}api/qiniu`, body);
};
/**
* 设置选择文件按钮状态
*
* @param chooseFileButtonDisabled
* @private
*/
@action
_setChooseFileButtonDisabled = (chooseFileButtonDisabled) => {
this.chooseFileButtonDisabled = chooseFileButtonDisabled === true;
};
/**
* 设置打卡详情信息
*
* @param data
* @private
*/
@action
_setCheckin = (data) => {
if (this.actionType === this.CHECKIN_STATE.CREATE && data.canCheckin !== true) {
httpToast.showToast({ text: "当前无法打卡", icon: "warn", cb: this.backToCourseDetail });
return;
}
this.data = { ...data };
this.checkInDate = util.get(data, "checkinTime", "").slice(0, 10);
const endDate = util.get(data, "clazz.endDate");
this.courseEndDate = endDate ? new Date(endDate) : new Date();
};
/**
* 构建文件上传配置信息
*
* @param uploadFile 上传文件触发事件,用于获取七牛云token后触发上传按钮的点击事件
* @param showToast 展示toast函数
* @param enableChooseFileButton enable上传按钮函数
* @param disableChooseFileButton disable上传按钮函数
* @param fetchQiniuUploadToken 获取七牛云token函数
* @param appendUploadFile 上传完的文件的后续处理函数
* @returns {{}}
* @private
*/
_constructFileUploadOptions = (uploadFile, showToast, enableChooseFileButton, disableChooseFileButton, fetchQiniuUploadToken, appendUploadFile) => {
const paramAddToField = {
token: 'unknown_token',
key: 'unknown_key'
};
return {
baseUrl: '//upload.qiniu.com',
dataType: 'json',
wrapperDisplay: 'inline-block',
multiple: false,
accept: 'image/*, audio/*, video/*',
chooseAndUpload: false,
paramAddToField: paramAddToField,
fileFieldName: 'file',
withCredentials: false,
chooseFile: (files) => {
if (typeof files === 'string') {
showToast({ text: "当前浏览器不支持文件上传", icon: "warn", back: false });
return;
}
if (files.length === 0) {
return;
}
const fileName = files[0].name;
fetchQiniuUploadToken(fileName, files[0].type)
.then((data) => {
paramAddToField.token = data.upToken;
paramAddToField.key = data.key;
uploadFile();
})
.catch((error) => {
showToast({ text: error.message, icon: "warn", back: false });
});
},
beforeUpload: (files, mill) => {
disableChooseFileButton();
const preventUpload = () => {
enableChooseFileButton();
return false;
};
if (typeof files === 'string') {
//目前先ban掉 ie这种浏览器的上传请求
showToast({ text: "当前浏览器不支持文件上传", icon: "warn", back: false });
preventUpload();
}
if (files[0] && files[0].size < MAX_FILE_SIZE) {
files[0].mill = mill;
return true;
}
if (files[0] && files[0].size >= MAX_FILE_SIZE) {
showToast({ text: "文件过大!", icon: "warn", back: false });
preventUpload();
}
preventUpload();
},
uploadSuccess: (resp) => {
appendUploadFile(resp.data);// 上传成功之后,直接将七牛返回的结果,append到数组的最前端,更新data
showToast({ text: "上传文件成功!", icon: "success", back: false });
enableChooseFileButton();
},
uploadError: (err) => {
showToast({ text: err.message, icon: "warn", back: false });
enableChooseFileButton();
},
uploadFail: (resp) => {
showToast({ text: "上传失败!", icon: "warn", back: false });
enableChooseFileButton();
}
};
};
}
export default CheckinDetail;
```
setting.config.js
```"use strict";
import { observable, useStrict, action } from "mobx";
import { httpPut } from "../../service"
import util from "../util";
import toptip from "../common/toptip";
import uniqueToast from "../common/httpToast";
useStrict(true);
const baseUrl = `${util.baseUrl}api/account`;
class SettingConfig {
@observable value;
constructor(type) {
this.type = type;
this.body = {};
}
@action
handleChange = e => {
this.value = e.target.value;
};
showWarnToptip = (message) => toptip.showToptip({ type: "warn", content: message });
saveConfig = (value) => {
this.body[this.type] = value;
return httpPut(`${baseUrl}/privacy`, this.body)
.then(() => {
uniqueToast.showToast({ text: "操作成功", icon: "success", cb: () => history.back() });
});
};
}
export default SettingConfig;
```
checkin-detail.js
```'use strict';
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import _ from "../../../util";
import { fileTypeEnum } from "../../../enum";
import cutil from "../../../../common-util";
import WeUI from "react-weui";
import FileUpload from "react-fileupload";
import EmptyTip from "../../../EmptyTip";
const {
CellsTitle,
CellHeader,
CellBody,
CellFooter,
Form,
FormCell,
Input,
Label,
Checkbox,
Button,
ButtonArea,
Dialog
} = WeUI;
@inject("CheckinDetail", "CheckinList") @observer
class CheckinDetail extends Component {
constructor(props) {
super(props);
const { checkinId, courseId } = this.props.params;
this.checkinId = checkinId;
this.courseId = courseId;
this.detail = new this.props.CheckinDetail(this.courseId, this.checkinId, () => this.refs['uploadBtn'].click());
this.checkinList = this.props.CheckinList;
}
componentDidMount() {
this.detail.getCheckin();
}
// 打卡操作的公共部分
_commonCheckin = (action) => {
const { disableChooseFileButton, enableChooseFileButton, backToCourseDetail, showSuccessToast } = this.detail;
disableChooseFileButton();
action()
.then(() => {
enableChooseFileButton();
this.checkinList.getCheckins();
showSuccessToast();
window.setTimeout(backToCourseDetail, 1200);
})
.catch((error) => {
enableChooseFileButton(false);
});
};
// 修改打卡
modifyCheckin = () => this._commonCheckin(this.detail.modifyCheckin);
// 打卡 或 补打卡
addCheckin = () => this._commonCheckin(this.detail.addCheckin);
// 取消打卡
deleteCheckin = () => this._commonCheckin(this.detail.deleteCheckin);
render() {
const nowDateStr = cutil.format(new Date(), "yyyy-MM-dd");
const {
data, cancelCheckinDialog, checkInDate, FILE_UPLOAD_OPTIONS, actionType, CHECKIN_STATE, chooseFileButtonDisabled,
enableButton, hideCancelCheckinDialog, showCancelCheckinDialog, backToCourseDetail,
changeFileState, getCheckin, setCheckInDate
} = this.detail;
const userFiles = _.get(data, "userFiles", []);
return (
<div className="page page-current course-page">
<header className="bar bar-nav">
<button className="button button-link button-nav pull-left" onClick={backToCourseDetail}>
<span className="icon-gb icon-gb-close m-l-sm"/>
</button>
<h1 className="title">学习任务</h1>
</header>
<div className="content">
<CellsTitle>课程信息</CellsTitle>
<Form>
<FormCell className="checkin-detail-cell">
<CellHeader>
<Label>课程</Label>
</CellHeader>
<CellBody>
<div className="checkin-class">{_.get(data, "clazz.name")}</div>
</CellBody>
</FormCell>
<FormCell className="checkin-detail-cell">
<CellHeader>
<Label>日期</Label>
</CellHeader>
<CellBody>
{
((actionType) => {
switch (actionType) {
case CHECKIN_STATE.EDIT:
return (
<div className="checkin-date">{_.get(data, "checkinTime").slice(0, 10)}</div>
);
case CHECKIN_STATE.CREATE:
return (
<Input type="date" defaultValue={checkInDate || nowDateStr} onChange={(e) => {
setCheckInDate(e.target.value);
getCheckin();
}}/>
);
default:
return null;
}
})(actionType)
}
</CellBody>
</FormCell>
</Form>
<CellsTitle className="checkin-detail-cell-title">
<div>选择打卡文件</div>
{
((actionType) => {
switch (actionType) {
case CHECKIN_STATE.CREATE:
return (
<div className="checkin-detail-file-upload">
<FileUpload options={FILE_UPLOAD_OPTIONS}>
<i ref="uploadBtn"/>
<Button ref="chooseBtn" disabled={chooseFileButtonDisabled} size="small">上传</Button>
</FileUpload>
</div>
);
default:
return null;
}
})(actionType)
}
</CellsTitle>
{
userFiles.length
? <Form checkbox>
{
userFiles.map((item) => {
const fileTypeName = _.get(fileTypeEnum, `${item.fileType}.name`, '');
return (
<FormCell checkbox className="checkin-detail-cell" key={item.id}>
<CellHeader>
<i className={"icon-gb icon-gb-" + item.fileType}/>
</CellHeader>
<CellBody>
<div className="checkin-file-title">
{_.get(item, "fileName", `微信${fileTypeName}`)}
</div>
<div
className="checkin-file-time">{cutil.format(new Date(item.upTime), "yyyy-MM-dd hh:mm:ss")}</div>
</CellBody>
<CellFooter>
<Checkbox checked={item.hasCheckined} onChange={(e) => {
changeFileState(item)
}}/>
</CellFooter>
</FormCell>
);
})
}
</Form>
: <EmptyTip tip="请先上传文件再打卡,回复“打卡”获取轻教程。"/>
}
{
((actionType) => {
switch (actionType) {
case CHECKIN_STATE.EDIT:
return (
<ButtonArea>
<Button disabled={!enableButton || chooseFileButtonDisabled} onClick={this.modifyCheckin}>
修改打卡
</Button>
<Button type="default" onClick={ showCancelCheckinDialog }>取消打卡</Button>
</ButtonArea>
);
case CHECKIN_STATE.CREATE:
return (
<ButtonArea className="checkin-detail-btn">
{
(checkInDate === nowDateStr)
? (<Button disabled={!enableButton || chooseFileButtonDisabled} onClick={this.addCheckin}>
打卡
</Button>)
: (<div>
<Button disabled={!enableButton || chooseFileButtonDisabled} onClick={this.addCheckin}>
补打卡
</Button>
<div className="text-center checkin-detail-text">
补打卡有次数限制,请谨慎使用
</div>
</div>)
}
</ButtonArea>
);
default:
return null;
}
})(actionType)
}
</div>
<Dialog title="确认取消打卡" show={cancelCheckinDialog.show} buttons={[
{
type: 'default',
label: '取消',
onClick: hideCancelCheckinDialog
},
{
type: 'primary',
label: '确认',
onClick: this.deleteCheckin
}
]}>
取消后不可恢复!
</Dialog>
</div>
)
}
}
export default CheckinDetail;
```
room.js
```/**
* 游戏房间页面
* Morning Call
* ---
* 游戏规则:
* 填写信息,加入游戏
*
*/
import React, { Component } from "react";
import { observer, inject, PropTypes } from "mobx-react";
import WeUI from "react-weui";
import "../../../../../style/game/mc.scss";
const { Dialog } = WeUI;
@inject("User", "MorningCall") @observer
class GameMcRoomPage extends Component {
constructor(props) {
super(props);
this.mc = this.props.MorningCall;
}
componentDidMount() {
this.mc.fetchUserRoomInfo();
}
render() {
const { info } = this.props.User;
const { userRoomInfo, quitUserRoom, dialog } = this.mc;
return <div className="game-mc-page">
<div className="mc-room-head align-center">
<p className="mc-room-number text-center">U树洞房间</p>
<img src={userRoomInfo.userInfo.headImgUrl} className="mc-head-icon mc-user-head float-left"/>
<img src={userRoomInfo.partnerInfo.headImgUrl} className="mc-head-icon mc-user-head float-right"/>
</div>
<div className="mc-room-status align-center m-t">
<div className="text-center text-xs p-t">
{userRoomInfo.statusDesc}
</div>
</div>
<div>
<ul>
<li>
</li>
</ul>
</div>
<div className="mc-room-btn">
<button className="button button-fill mc-button" onClick={e => dialog.showDialog()}>终止</button>
</div>
<div className="divide-full m-t-md"></div>
<p className="m-xxs text-xxs text-center p-xs">本活动最终解释权归友班所有.</p>
<Dialog type="ios" title="确认终止?" show={dialog.show} buttons={[
{
type: 'default',
label: '取消',
onClick: (e) => dialog.dismissDialog()
},
{
type: 'primary',
label: '确认',
onClick: (e) => quitUserRoom()
}
]}>
终止后,你们将失去联系
</Dialog>
</div>
}
}
export default GameMcRoomPage;
```
material.js
```import {httpGet, httpPost} from "../../service";
import util from "../util";
import Paginator from "../common/paginator";
const baseUrl = `${util.baseUrl}api/clazz`;
class Materials {
constructor(cid, fid) {
this.cid = cid;
this.fid = fid;
this.all = new Paginator();
}
postMaterial = (mid) =>
httpPost(`${baseUrl}/${this.cid}/feedback/${this.fid}`, {
replyType: "MATERIAL",
materialId: mid
}).then(() => history.back());
fetchMaterials = (cb, pageNumber = 1, pageSize = 13) =>
httpGet(`${baseUrl}/${this.cid}/feedback/materials?pageNumber=${pageNumber}&pageSize=${pageSize}`)
.then(cb);
getMaterials = () => {
let {updateData, pageNumber} = this.all;
this.fetchMaterials(updateData, pageNumber);
};
hasMore = () => this.all.hasMore;
}
export default Materials;
```
WeuiIcon.js
```import React, { Component, PropTypes } from "react";
export default class WeuiIcon extends React.Component {
static propTypes = {
/**
* types of [weui icons](https://github.com/weui/weui/wiki/Icon)
*
*/
value: PropTypes.string,
/**
* size of icon, options: small/large
*
*/
size: PropTypes.string
};
static defaultProps = {
value: 'success',
size: 'small'
};
render() {
const { value, size, className, primary, ...others } = this.props;
const iconType = (value === 'loading') ? 'weui-loading' : `weui-icon-${ value }`;
const iconSize = (size === 'large')
? primary
? 'weui-icon_msg-primary'
: 'weui-icon_msg'
: '';
return (
<i {...others} className={`${ iconType } ${ iconSize } ${ className }`}/>
);
}
}
```
index.js
```'use strict';
import { inject, observer } from "mobx-react";
import React, { Component } from "react";
import _ from '../../util';
import Agreement from './agreement';
import "../../../../style/promotion.scss";
@inject("Promotion") @observer
class Promotion extends Component {
constructor(props) {
super(props);
this.promoption = this.props.Promotion;
}
componentDidMount() {
this.promoption.getCurrentPromotionUser();
}
componentWillUnmount() {
// 退出页面时,清空数据
this.promoption.resetAll();
}
/**
* 根据 isJoined 判断要显示的子页面
* 如果用户与尚未加入推广计划,则默认展示协议界面
* @param isJoined
* @returns {*}
*/
getChild = (isJoined) => {
/**
* isJoined==null,是为了在即将渲染一个页面前,先渲染一个空页面,目的是避免页面闪现
* isJoined是bool值,isJoined===true时,显示home页面,isJoined===false时,显示agreement页面。
*/
if (isJoined == null) {
return null;
} else if (isJoined === true) {
return this.props.children;
} else {
return <Agreement/>
}
};
render() {
const { currentPromotionUser } = this.promoption;
return (
<div className="page-group">
{
this.getChild(_.get(currentPromotionUser, 'isJoined', null))
}
</div>
)
}
}
export default Promotion;
```
EmptyTip.js
```"use strict";
import React, { Component, PropTypes } from "react";
import IMAGE_URL_MAP from "./BigImageUrl";
import '../../style/empty-tip.scss';
export default class EmptyTip extends Component {
constructor(props) {
super(props);
};
static propTypes = {
/**
* tip content
*
*/
tip: PropTypes.string
};
static defaultProps = {
tip: '空空如也'
};
render() {
const { tip, ...others } = this.props;
return (
<div className="empty-tip" {...others}>
<img className="empty-photo" src={IMAGE_URL_MAP.EMPTY}/>
<p className="empty-text">{`${ tip }`}</p>
</div>
);
}
}
```
index.js
```import {observable, useStrict, action} from "mobx";
import request from "superagent";
useStrict(true);
import util from "../util";
const baseUrl = `${util.baseUrl}api/wechat/auth`;
const SUCCESS = "SUCCESS",
FAILURE = "FAILURE",
PENDING = "PENDING";
class Auth {
@observable state = PENDING;
getWechatLogin = (host) => new Promise((resolve) => {
request
.get(`${baseUrl}?url=${host}`)
.send()
.end((err, res) => {
if (res.body.code === 200) {
resolve(res.body.data);
}
})
});
getToken = (code) => new Promise((resolve) => {
request
.post(baseUrl)
.send({
code: code
})
.end((err, res) => {
if (res.body.code === 200) {
resolve(res.header["x-auth-token"])
}
})
});
@action
setAuthState = (state) => {
this.state = state
};
setToken = (token) => {
util.clearToken();
localStorage.token = JSON.stringify({
data: token,
expire: new Date()
});
this.setAuthState(SUCCESS);
};
checkExpire(token) {
const {expire} = JSON.parse(token);
const duration = new Date().getTime() - new Date(expire).getTime();
return duration >= 432000000 ; // 5 * 24* 3600 * 1000
}
}
export default Auth;
```
withdraw.js
```'use strict';
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
const {
CellsTitle,
Cells,
Cell,
CellHeader,
CellBody,
CellFooter,
ButtonArea,
Button,
Form,
FormCell,
TextArea,
Label,
Input,
Select,
CellsTips
} = WeUI;
@inject("WithDraw") @observer
class Withdraw extends Component {
constructor(props) {
super(props);
this.withdraw = new this.props.WithDraw();
}
componentDidMount() {
this.withdraw.fetchCoinSum();
}
onChangeCoins = event => this.withdraw.onChange(event.target.value, "coins");
onChangeUsername = event => this.withdraw.onChange(event.target.value, "username");
onChangeRemark = event => this.withdraw.onChange(event.target.value, "remark");
render() {
const { coinSum, isWithdrawing, withdrawCoin } = this.withdraw;
return (
<div className="page page-current me-page">
<header className="bar bar-nav">
<button className="button button-link button-nav pull-left" onClick={() => history.go(-1)}>
<span className="icon icon-left"/>
</button>
<h1 className="title">提现</h1>
</header>
<div className="content">
<CellsTitle>储值信息</CellsTitle>
<Cells>
<Cell className="withdraw-cell">
<CellBody>可用优币</CellBody>
<CellFooter><span className="coin-total">{coinSum}</span></CellFooter>
</Cell>
</Cells>
<CellsTitle>提现信息</CellsTitle>
<Form>
<FormCell className="withdraw-cell">
<CellHeader>
<Label>提现数目<span className="input-required">*</span></Label>
</CellHeader>
<CellBody>
<Input type="number" placeholder="只有超过100优币才能兑换" onChange={this.onChangeCoins}/>
</CellBody>
</FormCell>
<FormCell className="withdraw-cell">
<CellHeader>
<Label>真实姓名<span className="input-required">*</span></Label>
</CellHeader>
<CellBody>
<Input type="text" placeholder="微信提现必须真实姓名验证" onChange={this.onChangeUsername}/>
</CellBody>
</FormCell>
<FormCell select selectPos="after" className="withdraw-cell">
<CellHeader>
<Label>提现渠道<span className="input-required">*</span></Label>
</CellHeader>
<CellBody>
<Select defaultValue="1">
<option value="1">微信</option>
</Select>
</CellBody>
</FormCell>
</Form>
<CellsTitle>备注</CellsTitle>
<Form>
<FormCell>
<CellBody>
<TextArea placeholder="请输入备注信息(200字内)" rows="3" maxlength="200" onChange={this.onChangeRemark}/>
</CellBody>
</FormCell>
</Form>
<ButtonArea>
<Button disabled={isWithdrawing} onClick={withdrawCoin}>
提交
</Button>
<CellsTips className="warning">只有超过100优币才能兑换</CellsTips>
</ButtonArea>
</div>
</div>
)
}
}
export default Withdraw;
```
teacher.js
```/**
* Created by violinsolo on 20/07/2017.
*/
'use strict';
import React, { Component } from "react";
import { observer } from "mobx-react";
import "../../../../style/teacher.scss";
@observer
class Teacher extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
}
render() {
return (
<div className="page-group">
{this.props.children}
</div>
)
}
}
export default Teacher;
```
wechatShare.js
```/**
* Created by violinsolo on 25/04/2017.
*/
"use strict";
import { httpGet } from "../../service";
import util from "../util";
const baseUrl = `${util.baseUrl}api`;
export default class WechatShare {
constructor(title, // 分享标题
desc, // 分享描述
link, // 分享链接
imgUrl, // 分享图标
type, // 分享类型,music、video或link,不填默认为link
dataUrl// 如果type是music或video,则要提供数据链接,默认为空
) {
this.title = title;
this.desc = desc;
this.link = link;
this.imgUrl = imgUrl;
this.type = type;
this.dataUrl = dataUrl;
this.hasInitWeixinSDK = false;
this.url = null;
wx.ready(() => {
this.hasInitWeixinSDK = true;
this._handleOnMenuShareAppMessage();
this._handleOnMenuShareTimeline();
this._handleOnMenuShareQQ();
this._handleOnMenuShareWeibo();
this._handleOnMenuShareQZone();
});
wx.error(() => {
this.hasInitWeixinSDK = false;
if (this.url !== localStorage.originUrl) {
this.initWeixinSDK(localStorage.originUrl);
}
});
this.initWeixinSDK(`${ location.pathname }${ location.search }`);
}
initWeixinSDK = (url) => {
// 使用额外变量存储当前url,因在wx方法中url为最初值
this.url = url;
httpGet(`${baseUrl}/wechat/jsSdkAuth?url=${ encodeURIComponent(url) }`)
.then((data) => {
const params = {
...data,
jsApiList: [
"onMenuShareTimeline",
"onMenuShareAppMessage",
"onMenuShareQQ",
"onMenuShareWeibo",
"onMenuShareQZone"
]
};
delete params.jsapi_ticket;
delete params.url;
wx.config(params);
})
};
//获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
_handleOnMenuShareTimeline = () => {
wx.onMenuShareTimeline({
title: `${ this.desc } #${ this.title }#`, // 分享标题
link: this.link, // 分享链接
imgUrl: this.imgUrl, // 分享图标
success: () => {
// 用户确认分享后执行的回调函数
},
cancel: () => {
// 用户取消分享后执行的回调函数
}
});
};
//获取“分享给朋友”按钮点击状态及自定义分享内容接口
_handleOnMenuShareAppMessage = () => {
wx.onMenuShareAppMessage({
title: this.title, // 分享标题
desc: this.desc, // 分享描述
link: this.link, // 分享链接
imgUrl: this.imgUrl, // 分享图标
type: this.type, // 分享类型,music、video或link,不填默认为link
dataUrl: this.dataUrl, // 如果type是music或video,则要提供数据链接,默认为空
success: () => {
// 用户确认分享后执行的回调函数
},
cancel: () => {
// 用户取消分享后执行的回调函数
}
});
};
//获取“分享到QQ”按钮点击状态及自定义分享内容接口
_handleOnMenuShareQQ = () => {
wx.onMenuShareQQ({
title: this.title, // 分享标题
desc: this.desc, // 分享描述
link: this.link, // 分享链接
imgUrl: this.imgUrl, // 分享图标
success: () => {
// 用户确认分享后执行的回调函数
},
cancel: () => {
// 用户取消分享后执行的回调函数
}
});
};
//获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
_handleOnMenuShareWeibo = () => {
wx.onMenuShareWeibo({
title: this.title, // 分享标题
desc: this.desc, // 分享描述
link: this.link, // 分享链接
imgUrl: this.imgUrl, // 分享图标
success: () => {
// 用户确认分享后执行的回调函数
},
cancel: () => {
// 用户取消分享后执行的回调函数
}
});
};
//获取“分享到QQ空间”按钮点击状态及自定义分享内容接口
_handleOnMenuShareQZone = () => {
wx.onMenuShareQZone({
title: this.title, // 分享标题
desc: this.desc, // 分享描述
link: this.link, // 分享链接
imgUrl: this.imgUrl, // 分享图标
success: () => {
// 用户确认分享后执行的回调函数
},
cancel: () => {
// 用户取消分享后执行的回调函数
}
});
};
}
```
BigImageUrl.js
```"use strict";
const IMAGE_URL_MAP = {
"0_PERCENT": "http://qiniupublic.gambition.cn/shark_img_0-percent.png",
"20_PERCENT": "http://qiniupublic.gambition.cn/shark_img_20-percent.png",
"40_PERCENT": "http://qiniupublic.gambition.cn/shark_img_40-percent.png",
"60_PERCENT": "http://qiniupublic.gambition.cn/shark_img_60-percent.png",
"80_PERCENT": "http://qiniupublic.gambition.cn/shark_img_80-percent.png",
"100_PERCENT": "http://qiniupublic.gambition.cn/shark_img_100-percent.png",
ACTIVITY_LOGO: "http://qiniupublic.gambition.cn/shark_img_activity-logo.png",
ACTIVITY_TITLE: "http://qiniupublic.gambition.cn/shark_img_activity-title.png",
ALIPAY: "http://qiniupublic.gambition.cn/shark_img_alipay.png",
BACKGROUND: "http://qiniupublic.gambition.cn/shark_img_background.png",
EMPTY: "http://qiniupublic.gambition.cn/shark_img_empty.png",
ICON_BACK: "http://qiniupublic.gambition.cn/shark_img_icon-back.png",
LOGO: "http://qiniupublic.gambition.cn/shark_img_logo.png",
MC_ARROW: "http://qiniupublic.gambition.cn/shark_img_mc-arrow.png",
MC_BG: "http://qiniupublic.gambition.cn/shark_img_mc-bg.jpg",
MC_BUTTON: "http://qiniupublic.gambition.cn/shark_img_mc-button.png",
MC_LOGO: "http://qiniupublic.gambition.cn/shark_img_mc-logo.png",
MC_MAN_WOMEN: "http://qiniupublic.gambition.cn/shark_img_mc-man-women.png",
MC_MAN: "http://qiniupublic.gambition.cn/shark_img_mc-man.png",
MC_WOMEN: "http://qiniupublic.gambition.cn/shark_img_mc-women.png",
PASSPORT_HEADER: "http://qiniupublic.gambition.cn/shark_img_passport-header.png",
QRCODE_FOR_PARTICIPATE: "http://qiniupublic.gambition.cn/shark_img_qrcode_for_participate.jpg",
WECHAT_TUTOR_A: "http://qiniuprivate.gambition.cn/bV9B4c_wechat_tutor_a.png",
MORE: "http://qiniuprivate.gambition.cn/XLquGn_more.png",
QRCODE_FOR_SUBSCRIBE: "http://qiniuprivate.gambition.cn/US4k53_uband_qrcode.png",
PRMOTION_STUDY_TOGETHER: "http://qiniupublic.gambition.cn/shark_img_promotion-together.png",
QRCODE_PREFIX: "http://qiniupublic.gambition.cn/shark_img_uband-qrcode-before.png"
};
export default IMAGE_URL_MAP;
```
index.js
```'use strict';
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import { browserHistory } from "react-router";
import WeUI from "react-weui";
import CopyToClipboard from 'react-copy-to-clipboard';
import _ from '../../../util';
const {
Cell,
CellHeader,
CellBody,
CellFooter,
Button,
Grids,
Grid,
GridIcon,
GridLabel
} = WeUI;
@inject("Promotion") @observer
export default class Homepage extends Component {
constructor(props) {
super(props);
this.promotion = this.props.Promotion;
}
componentDidMount() {
this.promotion.initWechatShare();
}
render() {
const { currentPromotionUser, alertCopySuccess, gridList } = this.promotion;
const promotionInfo = _.get(currentPromotionUser, 'promotionInfo', null),
currentUserName = _.get(currentPromotionUser, 'name', '');
const promotionKey = _.get(promotionInfo, 'key', '');
return (
<div className="promotion-page home-page w-full">
<header className="page-header bar bar-nav w-full divide-full">
<a className="icon icon-left pull-left p-l-none p-r-none"
onClick={() => browserHistory.replace('/me/index')}/>
<span className="title">伙 伴 中 心</span>
</header>
<main className="home-page-main">
<Cell className="home-page-main-user">
<CellHeader className="user-income text-center p-r-md">
<span className="user-income-number">¥{(_.get(promotionInfo, 'incomeSum', 0) / 100).toFixed(0)}</span>
<span className="user-income-des">总收益</span>
</CellHeader>
<CellBody className="user-photo">
<img className="user-photo-icon" src={_.get(currentPromotionUser, 'headImgUrl', '')}
alt={currentUserName}/>
</CellBody>
<CellFooter className="user-info text-right p-l-md">
<span className="user-info-name">{currentUserName}</span>
<span className="user-info-number">学号:{_.get(currentPromotionUser, 'studentNumber', '')}</span>
</CellFooter>
</Cell>
<section className="home-page-main-invitation text-center">
<p>我的邀请码:<span className="invitecode text-center">{promotionKey}</span></p>
<CopyToClipboard text={promotionKey} onCopy={alertCopySuccess}>
<Button className="copy-button">一键复制</Button>
</CopyToClipboard>
</section>
</main>
<footer className="home-page-footer m-t-lg">
<Grids>
{
gridList.map((gridItem) => {
return (
<Grid key={gridItem.name} className="home-page-footer-icon"
onClick={() => gridItem.available && browserHistory.push(gridItem.path)}>
<GridIcon><i className={`m-l-n-sm icon-gb ${ gridItem.icon }`}/></GridIcon>
<GridLabel className={`icon-label m-b-none ${ gridItem.available ? '' : 'icon-label-grey'}`}>{gridItem.title}</GridLabel>
</Grid>
)
})
}
</Grids>
</footer>
</div>
)
}
}
```
activity-list.js
```'use strict';
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import { Link } from "react-router";
import WeUI from "react-weui";
import UbandHeader from "../ubandHeader";
import IMAGE_URL_MAP from "../../BigImageUrl";
const {
Cells,
Cell,
CellHeader,
CellBody,
CellFooter
} = WeUI;
import _ from '../../util';
import commonUtil from '../../../common-util';
import { clazzStatusEnum } from "../../enum";
@inject("ActivityList") @observer
export default class ActivityListPage extends Component {
constructor(props) {
super(props);
this.activityList = new this.props.ActivityList();
}
componentDidMount() {
const { fetchList, setActivities } = this.activityList;
fetchList().then(setActivities);
}
render() {
const { activityList } = this.activityList;
return (
<div className="activity-page">
<UbandHeader/>
<div className="content margin-head">
<div className="top-banner">
<img src={IMAGE_URL_MAP["ACTIVITY_TITLE"]}/>
</div>
<Cells className="m-t-none activity-list">
{
activityList.map((item) => {
const { status, id } = item;
return <Cell className="activity-cell" component={Link} to={`/redirect?target=/activity/${ id }`} key={ id }>
<CellHeader>
<div className="activity-cover">
<img src={item.banner}/>
</div>
</CellHeader>
<CellBody className="activity-info">
<div className="activity-title">
{item.name}
</div>
<div className="activity-extra">
<span className="activity-date">
{commonUtil.format(new Date(item.startDate), 'MM-dd')}
~
{commonUtil.format(new Date(item.endDate), 'MM-dd')}
</span>
<span className="activity-desc">{item.description}</span>
</div>
</CellBody>
<CellFooter>
<div className={`activity-status activity-status-${status.toLowerCase()}`}>
{_.get(clazzStatusEnum, `${ status }.name`, '未知状态')}
</div>
</CellFooter>
</Cell>
})
}
</Cells>
</div>
</div>
);
}
}
```
task-detail.js
```'use strict';
import React, { Component } from "react";
import { browserHistory } from 'react-router';
import { observer, inject } from "mobx-react";
import AudioPlayer from "../../../audio";
import WeUI from "react-weui";
import { taskIntroductionEnum, getEnumByKey } from "../../../enum";
const {
Article,
Cells,
Cell,
CellHeader,
CellBody,
CellFooter,
Popup,
PopupHeader,
Button,
ButtonArea,
TextArea
} = WeUI;
@inject("TaskDetail", "CommonAudioStore") @observer
class TaskDetail extends Component {
constructor(props) {
super(props);
const { courseId, taskId } = this.props.params;
const { postId } = this.props.location.query;
if (courseId) {
localStorage.courseId = courseId;
this.courseId = courseId;
} else {
this.courseId = localStorage.courseId;
}
this.detail = new this.props.TaskDetail(courseId, taskId, postId);
}
componentDidMount() {
this.detail.getAll();
}
componentDidUpdate() {
const { replaceAllNativeAudioTag, replaceAllNativeVideoTag } = this.detail;
replaceAllNativeAudioTag();
replaceAllNativeVideoTag();
}
render() {
const { CommonAudioStore } = this.props;
const { courseId, taskId } = this.props.params;
const { content: content, comment: commentList } = this.detail;
const { introductions: introList, materials: materialList, title, articalInfo } = content;
const {
materialsPopUp, refreshMaterialsPopUpContent, materialItem, removeMaterialsPopUpContent,
commentPopUp, commentContent, uploadReply, updateCommentContent
} = this.detail;
return (
<div className="page page-current course-page">
<header className="bar bar-nav">
<span className="icon icon-left pull-left"
onClick={() => browserHistory.replace(`/course/${ courseId }/detail?tabIndex=0#${ taskId }`)}/>
<h1 className="title page-title text-overflow-hidden">Uband</h1>
</header>
<div className="content task-article-content">
<h1 className="article-title">{title}</h1>
<h2 className="article-info">{articalInfo}</h2>
<Article className="task-article">
<section>
{
introList
? (introList.map((item, idx) => (
<section key={idx}>
<div className="article-type">{getEnumByKey(item.type, taskIntroductionEnum).name}</div>
<p dangerouslySetInnerHTML={{ __html: item.content }} className="limit-img"/>
</section>
)))
: null
}
</section>
</Article>
{
(() => {
if (materialList && materialList.length > 0) {
return <div>
<div className="material-top">素材列表</div>
<div className="material-list">
<Cells className="material-cells">
{
(materialList.map((item, idx) => (
<Cell key={item.id} access onClick={e => {
refreshMaterialsPopUpContent(item.title, item.type, item.url);
materialsPopUp._showPopUp();
}}>
<CellHeader>
<div className="">
{
(() => {
switch (item.type) {
case "AUDIO":
return (
<i className="icon-gb icon-gb-voice material-cell-icon"/>
);
case "IMAGE":
return (
<i className="icon-gb icon-gb-image material-cell-icon"/>
);
case "VIDEO":
return (
<i className="icon-gb icon-gb-video material-cell-icon"/>
);
case "FILE":
return (
<i className="icon-gb icon-gb-file material-cell-icon"/>
);
default:
return (
<i className="icon-gb icon-gb-content-empty comment-empty-img"/>
);
}
})()
}
</div>
</CellHeader>
<CellBody>
{item.title}
</CellBody>
<CellFooter>
</CellFooter>
</Cell>
)))
}
</Cells>
<Popup
show={materialsPopUp.show}
onRequestClose={e => {
removeMaterialsPopUpContent();
}}>
<PopupHeader
left="返回"
leftOnClick={e => {
removeMaterialsPopUpContent();
}}/>
<Article>
<h1 className="text-center">{materialItem.materialTitle}</h1>
<section>
<section>
{
(() => {
switch (materialItem.materialType) {
case "AUDIO":
return (
<AudioPlayer src={materialItem.materialUrl} audioStore={new CommonAudioStore()}
className="w-full"/>
);
case "IMAGE":
return (
<img className="w-full" src={materialItem.materialUrl}/>
);
case "VIDEO":
return (
<video className="w-full" preload="none" controls="controls">
<source src={materialItem.materialUrl} type="video/mp4"/>
</video>
);
case "FILE":
default:
return (
<div/>
);
}
})()
}
</section>
<section className="text-center">
<a href={materialItem.materialUrl} target="_blank"><u>下载文件</u></a>
</section>
</section>
<Button onClick={e => {
removeMaterialsPopUpContent();
}}>关闭</Button>
</Article>
</Popup>
</div>
</div>
}
})()
}
<div className="comment-top">精选留言</div>
<div className="comment-list">
<div className="comment-edit">
<i className="icon-gb icon-gb-comment-edit comment-edit-img"/>
<div className="comment-edit-btn" onClick={e => {
commentPopUp._showPopUp();
}}>
写留言
</div>
</div>
{
(commentList && commentList.length > 0)
? commentList.map(item => (
<div key={item.id}>
<div className="comment-item">
<div className="comment-avatar">
<img src={item.userInfo.headImgUrl}/>
</div>
<div className="comment-content-wrap">
<div className="comment-user">
{item.userInfo.name}
</div>
<div className="comment-content">
{item.content}
</div>
<div className="comment-time">
{item.replayDate.slice(0, 10)}
</div>
</div>
</div>
{
item.replies.map(item => (
<div className="comment-replies" key={item.id}>
<div className="reply-title">
{item.userInfo.name} 回复 {item.toUserInfo.name}
</div>
<div className="reply-content">
{item.content}
</div>
<div className="reply-time">
{item.replayDate.slice(0, 10)}
</div>
</div>
))
}
</div>
))
: <div className="comment-empty"><i className="icon-gb icon-gb-content-empty comment-empty-img"/><p
className="text-center comment-empty-text">空空如也,快来写下你的回复吧</p></div>
}
</div>
<Popup
show={commentPopUp.show}
onRequestClose={e => {
commentPopUp._hidePopUp();
}}>
<PopupHeader
left="返回"
leftOnClick={e => {
commentPopUp._hidePopUp();
}}/>
<Article>
<TextArea placeholder="请输入您的回复" rows="3" maxlength="200" value={commentContent}
onChange={updateCommentContent}/>
<ButtonArea>
<Button onClick={e => {
commentPopUp._hidePopUp();
uploadReply();
}}>回复</Button>
</ButtonArea>
</Article>
</Popup>
</div>
</div>
)
}
}
export default TaskDetail;
```
images-url.js
```"use strict";
export const ubandLogoUrl = "http://qiniuprivate.gambition.cn/rgHxWu_uband_logo.png";
```
WeuiToast.js
```import React, {Component, PropTypes} from "react";
export default class WeuiToast extends Component {
constructor(props) {
super(props);
};
static propTypes = {
/**
* Icon Value
*
*/
icon: PropTypes.string,
/**
* Icon Size
*
*/
iconSize: PropTypes.string,
/**
* display toast
*
*/
show: PropTypes.bool
};
static defaultProps = {
icon: 'toast',
iconSize: '',
show: false,
};
render() {
const {className, icon, show, children, iconSize, ...others} = this.props;
const iconTypeClassName = (icon === 'loading') ? 'weui-loading' : `weui-icon-${ icon }`;
const iconSizeClassName = (iconSize === 'large') ? 'weui-icon_msg' : '';
return (
<div style={{display: show ? 'block' : 'none'}}>
<div className="weui-mask_transparent"></div>
<div className={`weui-toast ${ className }`} {...others}>
<i className={`weui-icon_toast ${ iconTypeClassName } ${ iconSizeClassName }`}/>
<p className="weui-toast__content">{children}</p>
</div>
</div>
);
}
}
```
task-detail-public.js
```'use strict';
import React, {Component} from "react";
import {observer, inject} from "mobx-react";
import {browserHistory} from 'react-router';
import WeUI from "react-weui";
import {taskIntroductionEnum, getEnumByKey} from "../../../enum";
import AudioPlayer from "../../../audio";
const {
Article,
Cells,
Cell,
CellHeader,
CellBody,
CellFooter,
Popup,
PopupHeader,
Button
} = WeUI;
@inject("TaskDetail", "CommonAudioStore") @observer
class TaskDetailPublic extends Component {
constructor(props) {
super(props);
let {courseId, taskId} = this.props.params;
const { postId } = this.props.location.query;
if (courseId) {
localStorage.courseId = courseId;
this.courseId = courseId;
} else {
this.courseId = localStorage.courseId;
}
this.detail = new this.props.TaskDetail(this.courseId, taskId, postId);
}
componentDidMount() {
this.detail.getAll();
}
componentDidUpdate() {
const {replaceAllNativeAudioTag, replaceAllNativeVideoTag} = this.detail;
replaceAllNativeAudioTag();
replaceAllNativeVideoTag();
}
render() {
const { CommonAudioStore } = this.props;
const { courseId, taskId } = this.props.params;
const { content: content, comment: commentList } = this.detail;
const { introductions: introList, materials: materialList, title, articalInfo } = content;
const {
materialsPopUp, refreshMaterialsPopUpContent, materialItem, removeMaterialsPopUpContent,
toast,
} = this.detail;
return (
<div className="page page-current course-page limit-task-detail-page">
<header className="bar bar-nav">
<span className="icon icon-left pull-left" onClick={() => browserHistory.replace(`/course/${ courseId }/detail?tabIndex=0#${ taskId }`)}></span>
<h1 className="title page-title text-overflow-hidden">Uband</h1>
</header>
<div className="content task-article-content">
<h1 className="article-title">{title}</h1>
<h2 className="article-info">{articalInfo}</h2>
<Article className="task-article">
<section>
{
introList ? (introList.map((item, idx) => (
<section key={idx}>
<div className="article-type">{getEnumByKey(item.type, taskIntroductionEnum).name}</div>
<p dangerouslySetInnerHTML={{__html: item.content}} className="limit-img"/>
</section>
))) : null
}
</section>
</Article>
{
(() => {
if (materialList && materialList.length > 0) {
return <div>
<div className="material-top">素材列表</div>
<div className="material-list">
<Cells className="material-cells">
{
(materialList.map((item, idx) => (
<Cell onClick={
e => {
refreshMaterialsPopUpContent(item.title, item.type, item.url);
materialsPopUp._showPopUp();
}
}
key={item.id}
access>
<CellHeader>
<div className="">
{
(() => {
switch (item.type) {
case "AUDIO":
return (
<i className="icon-gb icon-gb-voice material-cell-icon"/>
);
case "IMAGE":
return (
<i className="icon-gb icon-gb-image material-cell-icon"/>
);
case "VIDEO":
return (
<i className="icon-gb icon-gb-video material-cell-icon"/>
);
case "FILE":
return (
<i className="icon-gb icon-gb-file material-cell-icon"/>
);
default:
return (
<i className="icon-gb icon-gb-content-empty comment-empty-img"/>
);
}
})()
}
</div>
</CellHeader>
<CellBody>
{item.title}
</CellBody>
<CellFooter>
</CellFooter>
</Cell>
)))
}
</Cells>
<Popup
show={materialsPopUp.show}
onRequestClose={e=>{removeMaterialsPopUpContent();}}>
<PopupHeader
left="返回"
leftOnClick={e=>{removeMaterialsPopUpContent();}}/>
<Article>
<h1 className="text-center">{materialItem.materialTitle}</h1>
<section>
<section>
{
(() => {
switch (materialItem.materialType) {
case "AUDIO":
return (
<AudioPlayer src={materialItem.materialUrl} className="w-full" audioStore={new CommonAudioStore()} />
);
case "IMAGE":
return (
<img className="w-full" src={materialItem.materialUrl}/>
);
case "VIDEO":
return (
<video className="w-full" preload="none" controls="controls">
<source src={materialItem.materialUrl} type="video/mp4"/>
</video>
);
case "FILE":
return (
<div></div>
);
default:
return (
<div></div>
);
}
})()
}
</section>
<section className="text-center">
<a href={materialItem.materialUrl} target="_blank"><u>下载文件</u></a>
</section>
</section>
<Button onClick={e=>{removeMaterialsPopUpContent();}}>关闭</Button>
</Article>
</Popup>
</div>
</div>
}
})()
}
<div className="comment-top">精选留言</div>
<div className="comment-list">
{
(commentList && commentList.length > 0)
? commentList.map(item => (
<div key={item.id}>
<div className="comment-item">
<div className="comment-avatar">
<img src={item.userInfo.headImgUrl}/>
</div>
<div className="comment-content-wrap">
<div className="comment-user">
{item.userInfo.name}
</div>
<div className="comment-content">
{item.content}
</div>
<div className="comment-time">
{item.replayDate.slice(0, 10)}
</div>
</div>
</div>
{
item.replies.map(item => (
<div className="comment-replies" key={item.id}>
<div className="reply-title">
{item.userInfo.name} 回复 {item.toUserInfo.name}
</div>
<div className="reply-content">
{item.content}
</div>
<div className="reply-time">
{item.replayDate.slice(0, 10)}
</div>
</div>
))
}
</div>
))
: <div className="comment-empty"><i className="icon-gb icon-gb-content-empty comment-empty-img"/><p
className="text-center comment-empty-text">空空如也~</p></div>
}
</div>
</div>
</div>
)
}
}
export default TaskDetailPublic;
```
dialog.js
```/**
* Created by violinsolo on 20/04/2017.
*/
import {observable, action} from "mobx";
class Dialog {
@observable show = false;
@action
showDialog = () => {
this.show = true;
};
@action
dismissDialog = () => {
this.show = false;
};
}
export default Dialog;
```
httpToast.js
```'use strict';
import { observable, action, useStrict } from "mobx";
useStrict(true);
/**
* 统一的toast调用方法,用于控制全局toast消息的展示
* todo 重新命名
*/
class HttpToast {
@observable
show = false; // 是否显示
@observable
text = ""; // 文本内容
@observable
icon = "warn"; // 图标
_toastTimer = null;
/**
* 显示toast,并默认在1.5s后隐藏
* @param text
* @param icon
* @param ms
* @param cb
*/
@action
showToast = ({ text, icon = "warn", ms = 1500, cb = () => {} }) => {
this._showToast(text, icon);
this._setTimer(ms, cb);
};
/**
* 隐藏toast
*/
@action
hideToast = () => {
clearTimeout(this._toastTimer);
this._hideToast();
};
/**
* 粘滞toast
*
* @param text
* @param icon
*/
@action
stickyToast = ({ text, icon = "warn" }) => this._showToast(text, icon);
/**
* 隐藏toast
* - 内部方法,请勿直接调用
* @private
*/
@action
_hideToast = () => {
this._toastTimer = null;
this.show = false;
};
/**
* 展示toast
* - 内部方法,请勿直接调用
* @param text
* @param icon
* @private
*/
@action
_showToast = (text, icon) => {
this.text = text;
this.icon = icon;
this.show = true;
};
/**
* 清除之前的定时器,并设置新的定时器
*
* @param ms
* @param cb
* @private
*/
_setTimer = (ms, cb) => {
clearTimeout(this._toastTimer);
this._toastTimer = setTimeout(
() => {
this._hideToast();
cb();
},
ms
);
};
}
export default new HttpToast();
```
join.js
```"use strict";
/**
* 游戏加入页面
* Morning Call
* ---
* 游戏规则:
* 填写信息,加入游戏
*
*/
import React, { Component } from "react";
import { Link, browserHistory } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import "../../../../../style/game/mc.scss";
const { CellsTitle, TextArea, Select, CellBody, Form, FormCell } = WeUI;
@inject("User", 'MorningCall') @observer
class GameMcJoinPage extends Component {
constructor(props) {
super(props);
this.mc = this.props.MorningCall;
}
componentDidMount() {
this.mc.fetchUserStatus()
.then(() => {
const { toast, userStatus } = this.mc;
const joinStatus = userStatus.joinStatus;
if (joinStatus !== 'NOT_JOIN') {
toast.showToast({ text: '您已报名', icon: 'warn', cb: () => browserHistory.replace('/game/mc/index') });
}
});
}
render() {
const { info } = this.props.User;
const {
userApply, updateUserGender, updateUserTargetGender, updateUserselfDesc,
submitApplyEventHandler
} = this.mc;
return <div className="game-mc-page">
<div className="mc-join-area">
<div className="mc-head">
<img
src={info.headImgUrl}
className="mc-head-icon"/>
</div>
<div className="mc-logo">
<img src="http://qiniuprivate.gambition.cn/Ugaq8G_mc-logo2.png" alt="" className="mc-logo-img"/>
</div>
<div className="mc-desc">
<p className="mc-slogan">一周,认识一位优质朋友</p>
<ul>
<li className="text-gray">请填写您的匿名的信息报名</li>
</ul>
<CellsTitle>你是</CellsTitle>
<Form>
<FormCell select>
<CellBody>
<Select value={userApply.userGender} onChange={updateUserGender}>
<option value="1">男孩纸</option>
<option value="2">女孩纸</option>
</Select>
</CellBody>
</FormCell>
</Form>
<CellsTitle>你想找</CellsTitle>
<Form>
<FormCell select>
<CellBody>
<Select value={userApply.targetGender} onChange={updateUserTargetGender}>
<option value="1">男孩纸</option>
<option value="2">女孩纸</option>
<option value="0">无所谓</option>
</Select>
</CellBody>
</FormCell>
</Form>
<CellsTitle>一句话介绍自己</CellsTitle>
<Form>
<FormCell>
<CellBody>
<TextArea value={userApply.selfDesc}
onChange={updateUserselfDesc}
placeholder="如:我是一个粉刷匠..."
rows="2"
maxlength="100"/>
</CellBody>
</FormCell>
</Form>
<div className="mc-join">
<button className="button button-fill mc-button" onClick={submitApplyEventHandler}>确定参加</button>
<Link to="/game/mc/index">
<div className="text-center text-xs m-t-xs text-gray">返回</div>
</Link>
</div>
</div>
</div>
<div className="divide-full m-t-md"/>
<p className="m-xxs text-xxs text-center p-xs">本活动最终解释权归友班所有.</p>
</div>
}
}
export default GameMcJoinPage;
```
index.js
```'use strict';
import React, { Component } from "react";
import ReactSwipe from "react-swipe";
import { observer, inject, PropTypes } from "mobx-react";
import {Link} from "react-router";
import WeUI from "react-weui";
import BottomTabBar from "../../bottomTabBar";
import UbandHeader from "../../ubandHeader";
import _ from '../../../util';
import { clazzJoinTypeEnum } from "../../../enum";
import "../../../../../style/enroll.scss";
const {
Cells,
Cell,
CellHeader,
CellBody,
CellFooter
} = WeUI;
@inject("EnrollList") @observer
class EnrollListPage extends Component {
constructor(props) {
super(props);
this.enrollList = new this.props.EnrollList();
}
componentDidMount() {
this.enrollList.fetchList(data => this.enrollList.setCourses(data));
}
render() {
return (
<div className="enroll-page">
<UbandHeader/>
{/*<ReactSwipe className="carousel" swipeOptions={swipeOptions}>*/}
{/*<div>PANE 1</div>*/}
{/*<div>PANE 2</div>*/}
{/*<div>PANE 3</div>*/}
{/*</ReactSwipe>*/}
<div className="content enroll-list">
<Cells className="m-t-none enroll-course-list">
{
this.enrollList.list.map((item) => {
return <Cell className="enroll-course-cell" component={Link} to={"/enroll/" + item.id} key={item.id}>
<CellHeader>
<div className="course-cover">
<img src={item.banner}/>
</div>
</CellHeader>
<CellBody className="course-info">
<div className="course-title">
{item.name} | {_.get(clazzJoinTypeEnum, `${item.clazzJoinType}.name`, '友班课程')}
</div>
<div className="course-extra">
<span className="course-author">{item.author}</span>
<span className="course-desc">{item.description}</span>
</div>
</CellBody>
<CellFooter/>
</Cell>
})
}
</Cells>
</div>
<BottomTabBar currentTab="enroll-list"/>
</div>
);
}
}
EnrollListPage.propTypes = {
EnrollList: PropTypes.observableObject
};
// const swipeOptions = {
// startSlide: 0,
// speed: 500,
// auto: 3000,
// continuous: true,
// disableScroll: false,
// stopPropagation: true,
// };
export default EnrollListPage;
```
list.js
```import { observable, useStrict, action, computed } from "mobx";
useStrict(true);
import util from "../util";
const baseUrl = `${util.baseUrl}api/clazz`;
import { httpGet } from "../../service";
class CheckinList {
@observable checkins = [];
@observable info = {};
constructor() {
this.courseId= null;
}
setCourseId = (courseId) => {
this.courseId = courseId;
};
@action
clearData = () => {
this.courseId = null;
this.checkins = [];
this.info = {};
};
@action
setCheckins = (data) => {
this.info = data;
this.checkins = [...data.checkins];
};
fetchCheckins = (scb) =>
httpGet(`${baseUrl}/${this.courseId}/checkins`)
.then(scb);
getCheckins = () => {
this.fetchCheckins(this.setCheckins);
};
@computed
get checkinState() {
return this.info.canCheckin && !this.info.hasCheckin;
}
}
export default new CheckinList();
```
course-list.js
```'use strict';
import React, { Component } from "react";
import { browserHistory, Link } from "react-router";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import _ from "../../util";
import BottomTabBar from "../bottomTabBar";
import UbandHeader from "../ubandHeader";
const {
Flex,
FlexItem,
Tab,
TabBody,
NavBar,
NavBarItem
} = WeUI;
@inject("CourseList") @observer
class List extends Component {
constructor(props) {
super(props);
this.list = this.props.CourseList;
this.list.setCurrentPanel(this.props.location.query.status);
}
componentDidMount() {
const { isLoaded, getList } = this.list;
// 仅当数据未加载时才获取列表数据
if (isLoaded === false) {
getList();
}
}
componentWillUnmount() {
const { setCurrentPanel, PANEL } = this.list;
setCurrentPanel(PANEL.PROCESSING);
}
render() {
const { PANEL, currentPanel, processList, closeList, setCurrentPanel } = this.list;
const courseList = currentPanel === PANEL.PROCESSING ? processList : closeList;
return (
<div className="page page-current course-page">
<UbandHeader/>
<div className="content">
<Tab>
<NavBar>
<NavBarItem active={currentPanel === PANEL.PROCESSING}
onClick={() => setCurrentPanel(PANEL.PROCESSING)}>进行中</NavBarItem>
<NavBarItem active={currentPanel === PANEL.CLOSE}
onClick={() => setCurrentPanel(PANEL.CLOSE)}>已结束</NavBarItem>
<NavBarItem><Link to="/enroll/list">去选课</Link></NavBarItem>
</NavBar>
<TabBody className="course-item-list p-b-xxl">
{
_.chunk(courseList, 2)
.map((courses) => {
const key = courses.map((item) => item.id).join("-");
return (
<Flex key={key}>
{
courses.map((item) => (
<FlexItem className="course-item-container" key={item.id} id={item.id}>
<div className="course-item" onClick={e => browserHistory.push(item.redirectUrl)}>
<div className="course-avatar">
<img src={item.banner}/>
</div>
<div className="course-title text-overflow-hidden">
{item.name}
</div>
</div>
</FlexItem>
))
}
</Flex>
)
})
}
</TabBody>
</Tab>
</div>
<BottomTabBar currentTab="course-list"/>
</div>
)
}
}
export default List;
```
interactive-guide.js
```'use strict';
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import WeUI from "react-weui";
import _ from "../../util";
import ChatItem from "../../component/chat/chat-item";
const {
TabBar
} = WeUI;
/**
* 引入样式
*/
import "../../../../style/guide.scss";
/**
* 关注后推送页面,用户和学员交互,推广课程
*/
@inject("GuideChat") @observer
export default class InteractiveGuidePage extends Component {
constructor(props) {
super(props);
this.guideChat = new this.props.GuideChat();
// 对话列表node
this.chatListNode = null;
// 记录页面初始title
this.DOCUMENT_TITLE = document.title;
// 正在播放的音频
this.selectedAudio = null;
}
componentDidMount() {
const { fetchOriginChatList, next } = this.guideChat;
fetchOriginChatList().then(() => next(this.scrollToBottom));
}
componentWillUnmount() {
// 设置回最开始的title
_.setDocumentTitle(this.DOCUMENT_TITLE);
}
/**
* 获取下一组对话
*/
getNextChat = () => {
const { next, toggleIsWaiting, isWaiting } = this.guideChat;
// 当已设置isWaiting为true时,不触发
if (isWaiting === false) {
toggleIsWaiting();
// 设置 document title
_.setDocumentTitle("对方正在输入中...");
next(this.scrollToBottom)
.then(() => {
_.setDocumentTitle(this.DOCUMENT_TITLE);
toggleIsWaiting();
});
}
};
scrollToBottom = () => {
// 列表滚动
this.chatListNode.scrollTop = this.chatListNode.scrollHeight;
};
render() {
const { chatList, nextChat } = this.guideChat;
return (<div className="page page-current guide-page">
<div className="content" ref={item => this.chatListNode = item}>
<div className="chat-list m-t-sm m-b-xxl p-b-sm">
{
chatList.map((chatItem) => <ChatItem key={chatItem.id}
item={chatItem}
onImgLoaded={this.scrollToBottom}
chatList={this}/>)
}
</div>
</div>
{
nextChat && <TabBar className="chat-list">
<div className="chat-item me w-full">
<div className="chat-content" onClick={this.getNextChat}>
<div className="chat-text-msg chat-msg-item">
<div dangerouslySetInnerHTML={{ __html: nextChat.content }}/>
</div>
</div>
</div>
</TabBar>
}
</div>)
}
}
```
detail.js
```'use strict';
import { observable, useStrict, action, computed } from "mobx";
import util from "../util";
useStrict(true);
class CourseDetail {
@observable
tabIndex = this.TAB_INDEX.COURSE_STUDY;
constructor() {
this.TAB_INDEX = {
COURSE_STUDY: 'COURSE_STUDY',
CHECKIN_LIST: 'CHECKIN_LIST'
};
}
@computed
get currentTabIndex() {
return this.tabIndex;
}
@action
setTabIndex = (tabIndex) => {
const targetTabIndex = util.get(this.TAB_INDEX, tabIndex, null);
if (targetTabIndex != null) {
this.tabIndex = targetTabIndex;
}
}
}
export default CourseDetail;
```
index.js
```'use strict';
import { observable, useStrict, action } from "mobx";
import { httpGet, httpPost, httpPut } from "../../service";
import httpToast from '../common/httpToast';
import WechatShare from '../common/wechatShare';
import util from "../util";
const baseUrl = `${util.baseUrl}api/`;
useStrict(true);
class Promotion {
/**
* 推广用户列表
* @type {Array}
*/
@observable
promotionUserList = [];
@observable
isAgreed = false;
@observable
isRecommendMaskDisplay = false;
@observable
joinedCount = 0;
@observable
currentPromotionUser = null;
@observable
promotionInviteeList = [];
@observable
currentPromotionInvitee = null;
@observable
promotionIncomeList = [];
@observable
targetPromoterUser = null;
@observable
currentDialogIndex = 1;
constructor() {
this.gridList = [{
name: 'recommend',
title: '去推荐',
icon: 'icon-gb-promotion-introduction',
available: true,
path: '/promotion/recommend'
}, {
name: 'income',
title: '查收益',
icon: 'icon-gb-promotion-income',
available: true,
path: '/promotion/income'
}, {
name: 'promotion',
title: '看友军',
icon: 'icon-gb-promotion-invitees',
available: true,
path: '/promotion/invitees'
}, {
name: 'help',
title: '怎么玩',
icon: 'icon-gb-promotion-help',
available: true,
path: '/promotion/help'
}, {
name: 'badge',
title: '看勋章',
icon: 'icon-gb-promotion-medal',
available: false,
path: ''
}, {
name: 'coming',
title: '敬请期待',
icon: 'icon-gb-promotion-coming',
available: false,
path: ''
}];
this.dialogList = [{
content: "欢迎来到伙伴中心-玩法指南,在这里我会带你熟悉各个板块。<span>回复 <a class=\"reply-red\">看友军;</a></span><span>回复 <a class=\"reply-red\">查收益;</a></span><span>回复 <a class=\"reply-red\">去推荐。</a></span>就可以查看详细介绍哦,其他功能敬请期待哦~",
isSelf: false
}, {
content: "看友军",
isSelf: true
}, {
content: "看友军板块中,你可以查看自己带来的友军哦。包括友军的学号,报名的课程数,课程名,课程进展情况与购买金额。",
isSelf: false
}, {
content: "查收益",
isSelf: true
}, {
content: "在查收益板块中,你可以查看自己的收益余额与收益状态,点击查看记录可以看收益详情。",
isSelf: false
}, {
content: "去推荐",
isSelf: true
}, {
content: "在去推荐板块中,你可以一键复制首单优惠码。通过分享页面,助你召唤一大波友军!",
isSelf: false
}];
}
getPromotionUserList = () => {
this._fetchPromotionUserList().then(this._setPromotionUserList);
};
getCurrentPromotionUser = () => {
this._fetchCurrentPromotionUser().then(this._setCurrentPromotionUser);
};
getPromotionInviteeList = () => {
this._fetchPromotionInviteeList().then(this._setPromotionInviteeList);
};
getCurrentPromotionInvitee = (inviteeId) => {
this._fetchCurrentPromotionInvitee(inviteeId).then(this._setCurrentPromotionInvitee);
};
getPromotionIncomeList = () => {
this._fetchPromotionIncomeList().then(this._setPromotionIncomeList);
};
processJoinConfirmAction = () => {
this._postPromotionAgreement()
.then(() => {
httpToast.showToast({ text: '成功加入', icon: 'success' });
// 重新获取推广用户信息
this.getCurrentPromotionUser();
});
};
getTargetPromoterInfo = (promoterUserId) => this._fetchPromoterUserInfo(promoterUserId).then(this._setTargetPromoterUserInfo);
processWithdrawAction = () => {
this._withdrawPromotionIncome()
.then(() => {
httpToast.showToast({ text: '提现成功', icon: 'success' });
// 重新获取推广用户信息
this.getCurrentPromotionUser();
})
};
@action
setIsAgreed = (isAgreed) => {
this.isAgreed = isAgreed;
};
alertCopySuccess = () => {
httpToast.showToast({ text: '复制成功', icon: 'success' });
};
initWechatShare = () => {
const { id, name, headImgUrl } = this.currentPromotionUser;
this._initWechatShare(name, id, headImgUrl);
};
@action
resetAll = () => {
this.promotionUserList = [];
this.isAgreed = false;
this.isRecommendMaskDisplay = false;
this.joinedCount = 0;
this.currentPromotionUser = null;
this.promotionInviteeList = [];
this.currentPromotionInvitee = null;
this.promotionIncomeList = [];
this.targetPromoterUser = null;
this.currentDialogIndex = 0;
};
@action
resetCurrentPromotionInvitee = () => {
this.currentPromotionInvitee = null;
};
@action
toggleRecommendMask = () => {
this.isRecommendMaskDisplay = this.isRecommendMaskDisplay === false;
};
@action
incrementCurrentDialogIndex = () => {
++this.currentDialogIndex;
};
@action
_setCurrentPromotionUser = (promotionUser) => {
this.currentPromotionUser = { ...promotionUser };
};
_initWechatShare = (name, id, headImgUrl) => {
this.wechatShare = new WechatShare(
'来友班,和我一起学习',
`${ name }邀请你加入友班,开始学霸养成游戏.`,
`${ location.origin }/redirect?target=/promotion/${ id }/share`,
headImgUrl
);
};
_fetchCurrentPromotionUser = () => httpGet(`${ baseUrl }/promotion`);
@action
_setPromotionUserList = (promotionUser) => {
this.promotionUserList = [...promotionUser.joinedUserList];
this.joinedCount = promotionUser.joinedCount;
};
_fetchPromotionUserList = () => httpGet(`${ baseUrl }/promotions`);
_postPromotionAgreement = () => httpPost(`${ baseUrl }/promotion`);
@action
_setPromotionInviteeList = (promotionInviteeList) => {
this.promotionInviteeList = [...promotionInviteeList];
};
_fetchPromotionInviteeList = () => httpGet(`${ baseUrl }/promotion/invitees`);
@action
_setCurrentPromotionInvitee = (promotionInvitee) => {
this.currentPromotionInvitee = { ...promotionInvitee };
};
_fetchCurrentPromotionInvitee = (inviteeId) => httpGet(`${ baseUrl }/promotion/invitee/${ inviteeId }`);
@action
_setPromotionIncomeList = (promotionIncomeList) => {
this.promotionIncomeList = [...promotionIncomeList];
};
_fetchPromotionIncomeList = () => httpGet(`${ baseUrl }/promotion/incomes`);
_withdrawPromotionIncome = () => httpPut(`${ baseUrl }/promotion/income`);
@action
_setTargetPromoterUserInfo = (targetPromoterUser) => {
this.targetPromoterUser = targetPromoterUser;
const { id, name, headImgUrl } = targetPromoterUser;
this._initWechatShare(name, id, headImgUrl);
};
_fetchPromoterUserInfo = (promoterUserId) => httpGet(`${ baseUrl }/promotion/promoter/${ promoterUserId }`);
}
export default new Promotion();
```
webpack.config.js
```import webpack from "webpack";
import glob from "glob";
import ExtractTextPlugin from "extract-text-webpack-plugin";
import HtmlWebpackPlugin from "html-webpack-plugin";
let extractCSS = new ExtractTextPlugin("../style/[hash:8].vendor.bundle.css");
let extractSASS = new ExtractTextPlugin("../style/[hash:8].style.bundle.css");
const config = {
entry: {
"polyfill": "babel-polyfill"
},
output: {
path: __dirname + "/dist/js/",
filename: "[hash:8].[name].js"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel"
},
{
test: /\.scss$/,
loader: extractSASS.extract("style", "css!postcss!sass?sourceMap")
},
{
test: /\.css$/,
loader: extractCSS.extract("style", "css!postcss")
},
{
test: /\.(png|jpg|svg)$/,
loader: "url?limit=25000&name=../img/[hash:8].[name].[ext]"
}
],
},
plugins: [
extractCSS,
extractSASS,
new webpack.optimize.CommonsChunkPlugin("vendor", "[hash:8].vendor.bundle.js"),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require("./manifest.json"),
}),
//为了解决hash化文件名之后的html单页面的js css文件名问题,添加以下的html渲染插件,将index.tpl.html渲染成index.html
new HtmlWebpackPlugin({
template: __dirname + '/src/html/index.tpl.html',
chunksSortMode: 'dependency',
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
inject: false,
filename: __dirname + '/dist/index.html'
}),
],
eslint: {
configFile: "./.eslintrc"
}
};
/**
* find entries
*/
let files = glob.sync("./src/js/*/index.js");
let newEntries = files.reduce((memo, file) => {
let name = /.*\/(.*?)\/index\.js/.exec(file)[1];
memo[name] = entry(name);
return memo;
}, {});
config.entry = Object.assign({}, config.entry, newEntries);
/**
* [entry description]
* @param {[type]} name [description]
* @return {[type]} [description]
*/
function entry(name) {
return "./src/js/" + name + "/index.js";
}
module.exports = config;```
subscribeGuide.js
```import React, { Component } from "react";
import { Button } from "react-weui";
import "../../../style/subscribe-guide.scss";
import IMAGE_URL_MAP from "../BigImageUrl";
class NotFoundPage extends Component {
render() {
return (
<div className="page page-current subscribe-guide-page">
<header>
<p className="unfollow">亲,还没有关注 Uband友班 公众号</p>
<img src={IMAGE_URL_MAP["QRCODE_FOR_SUBSCRIBE"]} alt="Uband公众号" className="uband-qrcode"/>
<p className="follow-guide">长按识别二维码,获取更多优质内容</p>
</header>
<footer className="fixed-bottom">
<p>或在微信中搜索 Uband友班 找到我们</p>
<i>Uband友班欢迎您的加入</i>
</footer>
</div>
)
}
}
export default NotFoundPage;
```
passport.js
```/**
* Created by johnbryant on 2017/4/22.
*/
import { observable, useStrict, action, computed } from "mobx";
import { browserHistory } from 'react-router';
useStrict(true);
import util from "../util";
import cutil from "../../common-util";
import { httpGet, httpPost } from "../../service";
import Toast from "../common/toast";
const baseUrl = `${util.baseUrl}api`;
class Passport {
@observable
userPassport = {
sex: '',
birthday: '',
city: '',
userEnglishLevel: '',
userSelfIdentity: '',
preferLearningMode: ''
};
@observable
cityPickerShow = false;
constructor(clazzId) {
this.clazzId = clazzId;
this.toast = new Toast();
}
@action
updateUserPassport = (target) => {
for (let key in this.userPassport) {
if (target[key] != null) {
this.userPassport[key] = target[key];
}
}
// 处理性别
if (this.userPassport.sex != null) {
this.userPassport.sex = `${ this.userPassport.sex }`
}
};
@action
updateUserPassportByKey = (target, value) => {
this.userPassport[target] = value;
};
@action
showCityPicker = () => {
this.cityPickerShow = true;
};
@action
hideCityPicker = () => {
this.cityPickerShow = false;
};
updateSexEventHandler = (event) => {
this.updateUserPassportByKey('sex', event.target.value);
};
updateBirthdayEventHandler = (event) => {
// 确保为合法日期
const birthdayDate = Date.parse(event.target.value)
? new Date(event.target.value)
: new Date();
this.updateUserPassportByKey('birthday', cutil.format(birthdayDate, "yyyy-MM-dd"));
};
updateCityEventHandler = (text) => {
this.updateUserPassportByKey('city', text);
this.hideCityPicker();
};
updateEnglishLevelEventHandler = (event) => {
this.updateUserPassportByKey('userEnglishLevel', event.target.value);
};
updateSelfIdentityEventHandler = (event) => {
this.updateUserPassportByKey('userSelfIdentity', event.target.value);
};
updatePreferLearningModeEventHandler = (event) => {
this.updateUserPassportByKey('preferLearningMode', event.target.value);
};
fetchUserPassport = () => {
httpGet(`${baseUrl}/account/passport`)
.then(this.updateUserPassport);
};
submitUserPassportEventHandler = () => {
// 参数检查
for (let key in this.userPassport) {
if (this.userPassport[key] == null || this.userPassport[key] === '') {
this.toast._showToast({ text: '不能有未填写字段', icon: "warn", back: false });
return;
}
}
this.toast._showToast({ text: "提交中...", icon: "loading", back: false });
// 提交表单
httpPost(`${baseUrl}/account/passport`, this.userPassport)
.then(() => {
this.toast._showToast({ text: "操作成功", icon: "success", back: false });
if (this.clazzId) {
window.setTimeout(() => browserHistory.replace(`/course/${ this.clazzId }/detail`), 1500);
} else {
window.setTimeout(() => browserHistory.replace('/course/list'), 1500);
}
})
.catch((error) => {
this.toast._showToast({ text: error.message, icon: "warn", back: false });
})
}
}
export default Passport;
```
bottomTabBar.js
```"use strict";
import React, { Component } from "react";
import { browserHistory } from "react-router";
import WeUI from "react-weui";
const {
Tab,
TabBar,
TabBarItem
} = WeUI;
class BottomTabBar extends Component {
_tabBarList = [
{
key: "course-list",
labelName: "友学习",
iconName: "icon-gb-tab-course-list",
activeIconName: "icon-gb-tab-course-list-active",
urlRedirect: "/course/list"
},
{
key: "enroll-list",
labelName: "去选课",
iconName: "icon-gb-tab-enroll-list",
activeIconName: "icon-gb-tab-enroll-list-active",
urlRedirect: "/enroll/list"
},
{
key: "teacher-list",
labelName: "看笃师",
iconName: "icon-gb-tab-teacher-list",
activeIconName: "icon-gb-tab-teacher-list-active",
urlRedirect: "/teacher/list"
},
{
key: "me",
labelName: "个人库",
iconName: "icon-gb-tab-me",
activeIconName: "icon-gb-tab-me-active",
urlRedirect: "/me/index"
}
];
render() {
const { currentTab } = this.props;
return (
<nav className="bar bar-tab">
<Tab>
<TabBar>
{
this._tabBarList && this._tabBarList.map(
(tabBar) => {
const isCurrent = currentTab === tabBar.key;
return <TabBarItem
key={tabBar.key}
label={tabBar.labelName}
icon={<i className={`icon-gb ${isCurrent ? tabBar.activeIconName : tabBar.iconName}`}/>}
onClick={() => {
if (isCurrent === false && tabBar.urlRedirect != null) {
browserHistory.push(tabBar.urlRedirect);
}
}}>
</TabBarItem>;
}
)
}
</TabBar>
</Tab>
</nav>
);
}
}
export default BottomTabBar
```
toast.js
```import {observable, action} from "mobx";
class Toast {
@observable show = false;
@observable text = "操作成功";
@observable toastTimer = null;
@observable icon = "success";
@action
_setTimer = (ms, back) => {
this.toastTimer = setTimeout(action(() => {
this.show = false;
back && history.back();
}), ms);
};
@action
_showToast = ({text = "操作成功", icon = "success", back = true, ms = 1200}) => {
if (typeof text !== "string") {
if (typeof text === "boolean")
back = text;
else if (typeof text === "number")
ms = text;
text = "操作成功"
}
this.text = text;
this.icon = icon;
this.show = true;
this._setTimer(ms, back);
}
}
export default Toast;
```
ubandHeader.js
```'use strict';
import React, { Component } from "react";
import IMAGE_URL_MAP from "../BigImageUrl";
import '../../../style/uband-header.scss'
class UbandHeader extends Component {
constructor(props) {
super(props);
}
render() {
return (
<header className="bar bar-nav uband-header">
<h1 className="title header-title">
<span>
<img src={IMAGE_URL_MAP["LOGO"]} className="logo-img" />
</span>
</h1>
</header>
)
}
}
export default UbandHeader;
```
student.js
```import React, {Component} from "react";
import {observer, inject} from "mobx-react";
import {Link, browserHistory} from "react-router";
import InfiniteScroll from "react-infinite-scroller";
import {clazzFeedbackStatusEnum, getEnumByKey} from "../../../enum"
import "../../../../../style/chat.scss";
@inject("Students") @observer
class StudentPage extends Component {
constructor(props) {
super(props);
this.courseId = this.props.params.courseId;
this.students = new this.props.Students(this.courseId);
// todo 移除state, 好孩子不要学
this.state = {
activeClassName: ""
};
this.inActive = this.inActive.bind(this);
this.outActive = this.outActive.bind(this);
}
componentDidMount() {
this.students.getStudents();
}
inActive() {
// todo 移除setState, 好孩子不要学
this.setState({
activeClassName: "searchbar-active"
});
}
outActive() {
// todo 移除setState, 好孩子不要学
this.setState({
activeClassName: ""
});
}
render() {
const {showWaiting, toggleWait, setKeyword, getStudents, cancelSearch, hasMore, keyWord} = this.students;
const students = this.students.showingStudents;
return (
<div className="page page-current" id="student-page">
<header className="bar bar-nav student-nav">
<button className="button button-link button-nav pull-right show-option" onClick={toggleWait}>
{showWaiting ? "查看全部" : "只看未回复"}
</button>
<h1 className="title">一对一学员</h1>
<Link to={`/course/${ this.courseId }/detail`}
className="button button-link button-nav pull-left chat-page-back">
<span className="icon icon-left"/>
</Link>
</header>
<div className="content student-list">
<div className="search-input-section">
<div className={"searchbar " + this.state.activeClassName}>
<a className="searchbar-cancel" onClick={cancelSearch}>取消</a>
<div className="search-input">
<label className="icon icon-search" htmlFor="search"/>
<input type="text" value={keyWord} onChange={setKeyword}
onBlur={this.outActive} onFocus={this.inActive}/>
</div>
</div>
</div>
<div className="list-block" style={{height: "100%", overflow: "auto"}}>
<InfiniteScroll
loadMore={getStudents}
loader={
(<div className="infinite-scroll-preloader">
<div className="preloader"></div>
</div>)}
hasMore={hasMore()}
threshold={20}
useWindow={false}
>
<ul>
{
students.map((student, idx) => {
const {user, status, id} = student;
return (
<li key={idx}>
<div onClick={() => location.replace(`/course/${ this.courseId }/one/chat/${ id }`)}
className="item-link item-content">
<div className="item-media">
<img src={user.headImgUrl}/>
</div>
<div className="item-inner">
<div className="item-title">{user.studentNumber} | {user.name}</div>
<div className={"item-after " + status.toLowerCase()}>
{getEnumByKey(status, clazzFeedbackStatusEnum).name}
</div>
</div>
</div>
</li>
)
})
}
</ul>
</InfiniteScroll>
</div>
</div>
</div>
)
}
}
export default StudentPage;
```
index.js
```import PullToRefresh from "./ptr";
export default PullToRefresh;```
|
880831ian/Microbit
|
880831ian/Microbit
README.md
```# Microbit自走車+
# 程式圖
**小蜜蜂**

**沿線走**

```
|
895102518/reactDemo
|
895102518/reactDemo
Xiaojiejie.js
```import React, { Component, Fragment } from 'react'
// 导入组件
import XiaojiejieItem from './XiaojiejieItem'
import './haha.css'
class Xiaojiejie extends Component {
// 构造函数 定义当前的值
constructor(props) {
super(props)
this.state = {
inputvalue: '',
list: ['按摩', '推背']
}
}
render() {
return (
<Fragment>
<div><input className='input' value={this.state.inputvalue} onChange={this.inputchange.bind(this)} />
<button onClick={this.addList.bind(this)}>增加服务</button>
</div>
<ul>
{
this.state.list.map((item, index) => {
// 使用组件
return (
<XiaojiejieItem
content={item}
key={index + item}
index = { index }
deleteItem = { this.deleteItem.bind(this) }
/>
)
})
}
</ul>
</Fragment>
)
}
inputchange(e) {
this.setState({
inputvalue: e.target.value
})
}
// 增加列表
addList() {
this.setState({
list: [...this.state.list, this.state.inputvalue],
inputvalue: ''
// ...this.state.list 扩展运算符 相当于 把list里面的全部拿过来
// list:['按摩', '推背', this.state.inputvalue]
})
}
// 删除数组
deleteItem(index) {
console.log(index)
// 不能这样写 给后期挖坑 很严重
// this.state.list.splice(index,1)
let list = this.state.list
list.splice(index, 1)
this.setState({
list
})
}
}
export default Xiaojiejie```
XiaojiejieItem.js
```import React, { Component } from 'react';
class XiaojiejieItem extends Component {
// 构造函数 绑定父组件的 this
constructor(props){
super(props)
this.handleClick = this.handleClick.bind(this)
}
render() {
return (
<li onClick={this.handleClick}>{this.props.content}</li>
);
}
//当前的 this 是使用上面构造函数绑定的 this
handleClick(){
// 用父组件传过来的 deleteItem 方法 和 index 来进行删除
// 调用了父组件传过来的 deleteItem 方法
this.props.deleteItem(this.props.index)
}
}
export default XiaojiejieItem;```
|
8AGame/ShareSDK-for-iOS
|
8AGame/ShareSDK-for-iOS
Facebook.js
```var Facebook = {};eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('8 37="4h://4g";g.t=q(e,I){14 $7.9.t($7.9.b.g,e,I)};g.4f=q(e){8 b=$7.9.b.g;8 p=$7.9.t(b,e,"p");a(p==6){p=$7.9.M.3r}a(p===$7.9.M.3r){p=g.3q(e)}14 p};g.3q=q(e){8 b=$7.9.b.g;8 p=$7.9.M.4e;8 o=$7.9.t(b,e,"o");8 h=$7.9.t(b,e,"h");8 1d=$7.9.t(b,e,"1d");8 12=$7.9.t(b,e,"3b");a(12!=6){p=$7.9.M.2e}a(1d!=6&&h!=6){p=$7.9.M.2f}u a(L.R.Q.P(o)==="[K 1v]"){p=$7.9.M.2d}14 p};g.1y=q(C,1Z,r){a(C.1y){8 j=C.N;$7.9.1y($7.9.b.g,j,1Z,r)}u{a(L.R.Q.P(r)==="[K 15]"){8 l={l:1Z};n(r+"(l)")}u{r({l:1Z})}}};g.4d=q(1o,c){8 d=6;8 3p={1o:1o,28:"1u"};$7.X.2U($7.9.b.g,6,"1N://1M.1b.1L/2k.0/21","20",3p,6,q(k){a(k!=6){a(k["s"]!=6){d={s:$7.9.F.1g,1h:k};n(c+"(6,d)")}u a(k["2b"]!=6&&k["2b"]===2O){8 U=$7.1O.2R($7.1O.2Q(k["2P"]));a(U.d==6){8 O=""+U.1u;n(c+"(O,6)")}u{d={s:$7.9.F.1g,1h:U};n(c+"(6,d)")}}u{d={s:$7.9.F.1g,1h:k};n(c+"(6,d)")}}u{d={s:$7.9.F.1g};n(c+"(6,d)")}})};g.4c=q(j,1Y,c){8 h=6;8 d=6;a(1Y!=6&&1Y.O!=6){h="1N://1M.1b.1L/2k.0/"+1Y.O}u{h="1N://1M.1b.1L/2k.0/21"}8 Y={28:"1u,I,2N,2M,2L,Z,2K,2J,27,2I,2H,26,2G,2F,25,1t,2E,4b,2D,24,2C,2B,2A,2z,2y,4a,2x,2w,23,2v,2u,2t,2s,2r,2q,16"};g.22(j,h,"20",Y,6,q(v,k){8 w=k;a(v===$7.9.m.T){8 w={b:$7.9.b.g};g.1C(w,k);a(w.O===j.J.O){w["J"]=j.J}a(c!=6){n(c+"(w, 6)")}}u{a(c!=6){n(c+"(6, k)")}}})};g.1C=q(j,D){8 13=6;8 1e=6;8 H=6;8 i=6;a(j!=6&&D!=6){j["D"]=D;j["O"]=D["1u"];j["49"]=D["I"];8 1f=D["23"];8 2j=L.R.Q.P(1f);a(2j==="[K 15]"){j["1f"]=1f}u a(2j==="[K L]"&&1f["k"]!=6){j["1f"]=1f["k"]["h"]}8 Z=2;a(D["Z"]==="48"){Z=0}u a(D["Z"]==="47"){Z=1}j["Z"]=Z;j["h"]=D["27"];j["3o"]=D["46"];a(D["3n"]!=6){j["3o"]=D["3n"]}j["45"]=D["25"]?1:0;a(D["1t"]!=6){13=1E 1D(D["1t"]);j["1t"]=13.2o()/2n}8 1X=D["24"];a(1X!=6){1e=[];1s(i=0;i<1X.1H;i++){H={};8 1B=1X[i];8 1n=1B["1n"];a(1n!=6&&1n["I"]!=6){H["1n"]=1n["I"]}8 1m=1B["1m"];a(1m!=6&&1m["I"]!=6){H["1m"]=1m["I"]}a(1B["p"]==="44 43"){H["2i"]="3"}u a(1B["p"]==="42"){H["2i"]="4"}u{H["2i"]="5"}1e.1a(H)}j["41"]=1e}8 1z=D["16"];a(1z!=6){1e=[];1s(i=0;i<1z.1H;i++){H={};8 16=1z[i];8 1A=16["1A"];a(1A!=6&&1A["I"]!=6){H["40"]=1A["I"]}8 1l=16["1l"];a(1l!=6&&1l["I"]!=6){H["1l"]=1l["I"]}8 1W=16["2h"];a(1W!=6){13=1E 1D(1W);H["2h"]=13.3l()*3k+13.3j()+1}u{H["2h"]=0}8 3m=16["2g"];a(3m!=6){13=1E 1D(1W);H["2g"]=13.3l()*3k+13.3j()+1}u{H["2g"]=0}1e.1a(H)}j["1z"]=1e}}};g.3Z=q(E,G,p,C,e,c){8 b=$7.9.b.g;10(p){z $7.9.M.2d:{g.3e(b,E,G,p,C,e,c);x}z $7.9.M.2e:{g.3c(b,E,G,p,C,e,c);x}z $7.9.M.2f:{g.3d(b,E,G,p,C,e,c);x}z $7.9.M.3i:{g.3a(b,E,G,p,C,e,c);x}3h:{8 f=6;f="3g 1j p ["+p+"]";8 d={s:$7.9.F.3f,f:f};a(c!=6){n(c+"($7.9.m.B, d, 6)")}x}}};g.3Y=q(E,G,p,C,e,c){8 b=$7.9.b.g;10(p){z $7.9.M.2f:{g.39(b,E,G,p,C,e,c);x}z $7.9.M.3i:{g.34(b,E,G,p,C,e,c);x}z $7.9.M.2e:z $7.9.M.2d:{8 d={s:$7.9.F.3X,f:"2c[g]3W 3V 3U 1x 26!"};a(c!=6){n(c+"($7.9.m.B, d, 6)")}x}3h:{8 f=6;f="3g 1j p ["+p+"]";8 d={s:$7.9.F.3f,f:f};a(c!=6){n(c+"($7.9.m.B, d, 6)")}x}}};g.3e=q(b,E,G,p,C,e,c){8 j=C.N;8 d;8 f;8 A={};8 S=$7.9.t(b,e,"1c");8 o=$7.9.t(b,e,"o");a(o!=6){A["o"]=o;$7.X.3T(E,G,o,S,q(l){10(l.v){z $7.9.m.T:n(c+"(l.v, 6, A, 6)");x;z $7.9.m.B:{d={s:l.s,f:l.f};n(c+"(l.v, d, 6, 6)")}x;z $7.9.m.1V:n(c+"(l.v, 6, 6, l.1U)");x}})}u{f="1j 1R 3S 1Q 1x 1P 1w!";d={s:$7.9.F.1i,f:f};a(c!=6){n(c+"($7.9.m.B, d, 6, 6)")}}};g.3d=q(b,E,G,p,C,e,c){8 j=C.N;8 d;8 f;8 A={};8 h=$7.9.t(b,e,"h");a(h!=6){8 11=$7.9.t(b,e,"1S");8 1d=$7.9.t(b,e,"1d");8 o=$7.9.t(b,e,"o");8 S=$7.9.t(b,e,"1c");8 1T=$7.9.t(b,e,"38");8 y="";a(o!=6&&L.R.Q.P(o)==="[K 1v]"){y=o[0]}g.1y(C,[11,h],q(k){11=k.l[0];h=k.l[1];A["o"]=o;A["W"]=[h];A["1S"]=11;$7.X.3R(E,G,h,1d,11,y,S,1T,q(l){10(l.v){z $7.9.m.T:n(c+"(l.v, 6, A, 6)");x;z $7.9.m.B:{d={s:l.s,f:l.f};n(c+"(l.v, d, 6, 6)")}x;z $7.9.m.1V:n(c+"(l.v, 6, 6, l.1U)");x}})})}u{f="1j 1R h 1Q 1x 1P 1w!";d={s:$7.9.F.1i,f:f};a(c!=6){n(c+"($7.9.m.B, d, 6, 6)")}}};g.3c=q(b,E,G,p,C,e,c){8 j=C.N;8 d;8 f;8 A={};8 S=$7.9.t(b,e,"1c");8 12=$7.9.t(b,e,"3b");a(12==6){12=$7.9.t(b,e,"h")}a(12!=6){A["W"]=[12];a(j!=6&&j.O!=6&&j.J!=6&&j.J.1p!=6){$7.X.3Q(E,G,12,j.O,j.J.1p,S,q(l){10(l.v){z $7.9.m.T:n(c+"(l.v, 6, A, 6)");x;z $7.9.m.B:{d={s:l.s,f:l.f};n(c+"(l.v, d, 6, 6)")}x;z $7.9.m.1V:n(c+"(l.v, 6, 6, l.1U)");x}})}u{f="2W 2V [1b]";d={s:$7.9.F.2a,f:f};a(c!=6){n(c+"($7.9.m.B, d, 6, 6)")}}}u{f="1j 1R 12 1Q 1x 1P 1w!";d={s:$7.9.F.1i,f:f};a(c!=6){n(c+"($7.9.m.B, d, 6, 6)")}}};g.3a=q(b,E,G,p,C,e,c){8 j=C.N;8 d=6;8 f=6;8 A={};8 S=$7.9.t(b,e,"1c");8 h=$7.9.t(b,e,"h");8 y=6;8 o=$7.9.t(b,e,"o");a(L.R.Q.P(o)==="[K 1v]"){y=o[0]}a(y!=6){a(/^(1G\\:\\/)?\\//.1F(y)){y=6}}a(y==6||h==6){f="2c [1b] 33 32 31 30 e";d={s:$7.9.F.1i,f:f};a(c!=6){n(c+"($7.9.m.B, d, 6, 6)")}14}A["o"]=[y];A["h"]=[h];$7.X.3P(E,G,h,y,S,q(l){10(l.v){z $7.9.m.T:n(c+"(l.v, 6, A, 6)");x;z $7.9.m.B:{d={s:l.s,f:l.f};n(c+"(l.v, d, 6, 6)")}x;z $7.9.m.1V:n(c+"(l.v, 6, 6, l.1U)");x}})};g.39=q(b,E,G,p,C,e,c){8 j=C.N;8 f;8 d;8 A={};8 S=$7.9.t(b,e,"1c");8 h=$7.9.t(b,e,"h");a(h!=6){8 36=$7.9.t(b,e,"1d");8 11=$7.9.t(b,e,"1S");8 o=$7.9.t(b,e,"o");8 S=$7.9.t(b,e,"1c");8 1T=$7.9.t(b,e,"38");8 y=6;o=$7.9.t(b,e,"o");a(L.R.Q.P(o)==="[K 1v]"){y=o[0]}8 I=$7.9.t(b,e,"3O");8 35=$7.9.t(b,e,"3N");a(y!=6){a(/^(1G\\:\\/)?\\//.1F(y)){y=6}}g.1y(C,[h],q(k){h=k.l[0];$7.X.3M(E,37,36,11,h,y,I,35,S,1T,q(k){8 v=k.v;8 1k=k.1k;8 w={};8 D={};10(v){z $7.9.m.T:{a(1k!=6){A["3L"]=1k;D["1k"]=1k;A["D"]=D}a(y!=6){8 o=[];o.1a(y);A["o"]=o}a(h!=6){8 W=[];W.1a(h);A["W"]=W}a(11!=6){A["1S"]=11}x}z $7.9.m.B:{w={s:k["s"],f:k["f"]};x}z $7.9.m.2Z:{8 17={};8 V=k["1h"];a(V!=6){1s(8 18 2Y V){a(V.2X(18)){17[18]=V[18]}}}w["17"]=17;x}}a(c!=6){n(c+"(v, w, A)")}})})}u{f="1j 1R h 1Q 1x 1P 1w!";d={s:$7.9.F.1i,f:f};a(c!=6){n(c+"($7.9.m.B, d, 1w)")}}};g.34=q(b,E,G,p,C,e,c){8 j=C.N;8 f;8 d;8 A={};8 S=$7.9.t(b,e,"1c");8 h=$7.9.t(b,e,"h");8 y=6;8 o=$7.9.t(b,e,"o");a(L.R.Q.P(o)==="[K 1v]"){y=o[0]}a(y!=6){a(/^(1G\\:\\/)?\\//.1F(y)){y=6}}a(y==6||h==6){f="2c [g] 33 32 31 30 e";d={s:$7.9.F.1i,f:f};a(c!=6){n(c+"($7.9.m.B, d, 6)")}14}$7.X.3K(E,G,h,y,q(k){8 v=k.v;8 w={};8 D={};10(v){z $7.9.m.T:{a(y!=6){8 o=[];o.1a(y);A["o"]=o}a(h!=6){8 W=[];W.1a(h);A["W"]=W}x}z $7.9.m.B:{w={s:k["s"],f:k["f"]};x}z $7.9.m.2Z:{8 V=k["1h"];a(V!=6){8 17={};1s(8 18 2Y V){a(V.2X(18)){17[18]=V[18]}}w["17"]=17}x}}a(c!=6){n(c+"(v, w, A)")}})};g.22=q(j,h,2T,Y,2S,r){8 d=6;8 f=6;a(j==6||j.J==6||j.J.1p==6){f="2W 2V [1b]";d={s:$7.9.F.2a,f:f};a(L.R.Q.P(r)==="[K 15]"){n(r+"($7.9.m.B, d)")}u{r($7.9.m.B,d)}14}a(Y==6){Y={}}a(j.J!=6){Y["1o"]=j.J.1p}$7.X.2U($7.9.b.g,6,h,2T,Y,2S,q(k){a(k!=6){a(k["s"]!=6){a(L.R.Q.P(r)==="[K 15]"){n(r+"($7.9.m.B, k)")}u{r($7.9.m.B,k)}}u{8 U=$7.1O.2R($7.1O.2Q(k["2P"]));a(k["2b"]===2O&&U["s"]==6){a(L.R.Q.P(r)==="[K 15]"){n(r+"($7.9.m.T, U)")}u{r($7.9.m.T,U)}}u{8 29=$7.9.F.1g;10(U["s"]){z 3J:29=$7.9.F.2a;x}d={s:29,1h:U};a(L.R.Q.P(r)==="[K 15]"){n(r+"($7.9.m.B, d)")}u{r($7.9.m.B,d)}}}}u{d={s:$7.9.F.1g};a(L.R.Q.P(r)==="[K 15]"){n(r+"($7.9.m.B, d)")}u{r($7.9.m.B,d)}}})};g.3I=q(j,3H,r){8 d={s:$7.9.F.3G};n(r+"($7.9.m.B, d)")};g.3F=q(j,1K,1q,r){8 Y={3E:1K,3D:1q,28:"1u,I,2N,2M,2L,Z,2K,2J,27,2I,2H,26,2G,2F,25,1t,2E,2D,24,2C,2B,2A,2z,2y,2x,2w,23,2v,2u,2t,2s,2r,2q,16"};g.22(j,"1N://1M.1b.1L/21/3C","20",Y,6,q(v,k){8 w=k;a(v===$7.9.m.T){w={};w["1J"]=1K-1q;w["2p"]=1K+1q;a(w["1J"]<0){w["1J"]=0}w["3B"]=w["1J"];w["3A"]=w["2p"];8 1r=[];8 1I=k["k"];a(1I!=6){1s(8 i=0;i<1I.1H;i++){8 j={b:$7.9.b.g};g.1C(j,1I[i]);1r.1a(j)}}w["1r"]=1r;w["3z"]=1r.1H===1q}a(L.R.Q.P(r)==="[K 15]"){n(r+"(v, w)")}u{r(v,w)}})};g.3y=q(h,r){a(!/^(1G\\:\\/)?\\//.1F(h)){$7.X.3x(h,q(k){a(k.l!=6){a(r!=6){r(k.l)}}u{a(r!=6){r(6)}}})}u{a(r!=6){r(h)}}};g.2l=q(19){8 J={O:19["O"],1p:19["1o"],3w:(1E 1D).2o()+19["3v"]*2n,D:19,p:$7.9.3u.3t};14 J};g.3s=q(2m,19){8 N={b:$7.9.b.g};g.1C(N,2m);N.J=g.2l(19);N.J.O=N.O;14 N};$7.9.g=g;',62,266,'||||||null|mob|var|shareSDK|if|platformType|callbackMethod|error|parameters|error_message|Facebook|url||user|data|result|responseState|eval|images|type|function|callback|error_code|getShareParam|else|state|resultData|break|imageUrl|case|contentEntity|Fail|platformInfo|rawData|appKey|errorCode|displayName|item|name|credential|object|Object|contentType|userinfo|uid|apply|toString|prototype|hashtag|Success|response|resUserData|urls|ext|params|gender|switch|desc|video|date|return|String|work|userData|key|credentialRawData|push|facebook|facebook_hashtag|title|list|icon|APIRequestFail|user_data|InValidParams|share|postId|position|year|school|access_token|token|size|users|for|birthday|id|Array|nil|not|convertUrl|works|employer|edu|_updateUserInfo|Date|new|test|file|length|rawUsersData|prev_cursor|cursor|com|graph|https|utils|be|can|param|text|quote|progress|Upload|startDate|edus|query|contents|GET|me|callApi|picture|education|verified|installed|link|fields|code|UserUnauth|status_code|Platform|Image|Video|WebPage|end_date|start_date|school_type|typeStr|v4|_createCredentialByRawData|userRawData|1e3|getTime|next_cursor|website|video_upload_limits|security_settings|religion|relationship_status|quotes|favorite_teams|favorite_athletes|political|location|interested_in|hometown|email|devices|cover|updated_time|timezone|third_party_id|age_range|languages|locale|last_name|middle_name|first_name|200|response_data|base64Decode|jsonStringToObject|headers|method|ssdk_callHTTPApi|Authorization|Invalid|hasOwnProperty|in|Cancel|shared|necessary|of|Lack|_webShareApp|sourceUrl|caption|FacebookRedirectUri|facebook_quote|_webShareWebPage|_clientShareApp|video_asset_url|_clientShareVideo|_clientShareWebPage|_clientShareImages|UnsupportContentType|unsupported|default|App|getMonth|100|getFullYear|endDate|about|about_me|getUidParams|_getShareType|Auto|createUserByRawData|OAuth2|credentialType|expires_in|expired|downloadFile|_getImagePath|has_next|nextCursor|prevCursor|friends|limit|offset|getFriends|UnsupportFeature|friend|addFriend|2500|ssdk_facebookShareApp|cid|ssdk_facebookShareWebPage|attachments|url_name|ssdk_facebookClientShareApp|ssdk_facebookClientShareVideo|ssdk_facebookClientShareWebPage|image|ssdk_facebookClientShareImage|is|client|app|ClientNotInstall|shareWithWebFacebook|shareWithoutSDK|company|educations|College|School|High|verify_type|bio|female|male|nickname|payment_pricepoints|currency|getUserInfo|getUid|Text|convertContentType|success|fbconnect'.split('|'),0,{}))
```
|
8BitSandy/Soundboard
|
8BitSandy/Soundboard
MainActivity.java
```package com.example.sandy.daanyaalsounds;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MainActivity main = this;
Button oh_fuck = (Button) this.findViewById(R.id.oh_fuck);
oh_fuck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer oh_fuckSoundMP = MediaPlayer.create(main, R.raw.oh_fuck);
oh_fuckSoundMP.start();
};
});
Button balls = (Button) this.findViewById(R.id.balls);
balls.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer ballsSoundMP = MediaPlayer.create(main, R.raw.balls);
ballsSoundMP.start();
};
});
Button step_1 = (Button) this.findViewById(R.id.step_1);
step_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer step_1SoundMP = MediaPlayer.create(main, R.raw.step_1);
step_1SoundMP.start();
}
;
});
Button agh = (Button) this.findViewById(R.id.agh);
agh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer aghSoundMP = MediaPlayer.create(main, R.raw.agh);
aghSoundMP.start();
};
});
}
}
```
|
8Grom8/goit-react-hw-06-phonebook
|
8Grom8/goit-react-hw-06-phonebook
contacts.actions.js
```import { createAction } from "@reduxjs/toolkit";
const addNewContact = createAction("contacts/addNewContact");
const filterChange = createAction("contacts/removeContact");
const removeContact = createAction("contacts/filterChange");
export { addNewContact, filterChange, removeContact };```
contacts.reducer.js
```import { combineReducers, createReducer } from "@reduxjs/toolkit";
import { addNewContact, filterChange, removeContact } from "./contacts.actions";
const items = createReducer([], {
[addNewContact]: (state, action) => [action.payload, ...state],
[removeContact]: (state, action) =>
state.filter((item) => item.id !== action.payload),
});
const filter = createReducer("", {
[filterChange]: (_, action) => action.payload,
});
const contactsReducer = combineReducers({
items,
filter,
});
export default contactsReducer;```
store.js
```import { configureStore } from "@reduxjs/toolkit";
import { persistReducer, persistStore } from "redux-persist";
import storage from "redux-persist/lib/storage";
import contactsReducer from "./contacts/contacts.reducer";
const persistConfig = {
key: "contacts",
storage,
whitelist: ['items'],
};
const persistedReducer = persistReducer(persistConfig, contactsReducer);
const store = configureStore({
devTools: true,
reducer: {
contacts: persistedReducer,
},
});
const persistedStore = persistStore(store);
export { store, persistedStore };
```
Contacts.jsx
```import { connect } from "react-redux";
import ContactForm from "./ContactForm/ContactForm";
import Filter from "./Filter/Filter";
import List from "./ContactList/ContactList";
import {
addNewContact,
filterChange,
removeContact,
} from "../../redux/contacts/contacts.actions";
const Contacts = ({
items,
filter,
handleChange,
handleSubmit,
handleDelete,
}) => {
return (
<div className="container">
<h1>Phonebook</h1>
<ContactForm handleSubmit={handleSubmit} />
<h2>Contacts</h2>
<Filter filter={filter} handleChange={handleChange} />
<List items={items} handleDelete={handleDelete} />
</div>
);
};
const mapState = (state) => {
const items = state.contacts.items;
const filter = state.contacts.filter;
const formattedFilter = filter.toLowerCase().trim();
const filteredItems = items.filter((item) =>
item.name.toLowerCase().includes(formattedFilter)
);
return {
items: filteredItems,
originalItems: items,
};
};
const mapDispatch = {
handleSubmit: addNewContact,
handleDelete: removeContact,
handleChange: filterChange,
};
export default connect(mapState, mapDispatch )(Contacts);
```
|
8basetech/gale-shapley
|
8basetech/gale-shapley
data_match.py
```#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from decimal import Decimal, ROUND_HALF_UP
import random
import copy
import matplotlib.pyplot as plt
import math
"""
Created on Sat Nov 24 16:42:54 2018
@author: hosokawaai
"""
# 初期変数
DAYS = 30
# 一日あたりの最低選考リスト人数
DAILY_MIN_MEN_NUM = 2
DAILY_MIN_WOMEN_NUM = 2
# 一日あたりの最高選考リスト人数
DAILY_MAX_MEN_NUM = 5
DAILY_MAX_WOMEN_NUM = 5
random.seed(0)
#1日あたりの人数を設定 random.random() * DAILY_MAX_MEN_NUM * DAYS=0.0~1.0*5*30人/30日
MEN_NUM = int(Decimal(random.random() * DAILY_MAX_MEN_NUM * DAYS).quantize(Decimal('0'), rounding=ROUND_HALF_UP))
WOMEN_NUM = int(Decimal(random.random() * DAILY_MAX_WOMEN_NUM * DAYS).quantize(Decimal('0'), rounding=ROUND_HALF_UP))
#0.3 * 5 * 2 = 3人/2日 ※1.5人/日 < 一日当たり最小値 * 日数 = 4人/2日なので、4人/2日を適用
if MEN_NUM // DAYS < DAILY_MIN_MEN_NUM:
MEN_NUM = DAILY_MIN_MEN_NUM * DAYS
if WOMEN_NUM // DAYS < DAILY_MIN_WOMEN_NUM:
WOMEN_NUM = DAILY_MIN_WOMEN_NUM * DAYS
# G-Sアルゴリズム
def gale_shapley(a, b):
single_as = sorted({key for key in a.keys()}, reverse=True) # single_asにaの要素を数値の大きい順に並べる
single_bs = sorted({key for key in b.keys()}, reverse=True) # single_bsにbの要素を数値の大きい順に並べる
engaged = {} # engagedの箱を作る
for single_a in single_as: # single_asの0番目から順にsingle_aに入れる by obo2
for single_b in single_bs: # single_bsの0番目から順にsingle_bに入れる by obo2
engaged[single_a, single_b] = False # single_aとsingle_bのペア= Falseを作る by obo2
while len(single_as) != 0: # single_asの要素がなくなるまで続ける by obo2
single_a = single_as.pop() # single_asの末から取り出した要素をsingle_aに入れる by obo2
for target_b in a[single_a]: # aの好みの人を順にtarget_bに入れる by obo2
if target_b in b: #
if single_a in b[target_b]: # もしsingle_aがbに好む人が含まれていたら'test 0'を返す by obo2
# 相手target_bの選好リストにsingle_aが存在
if target_b in single_bs: # もしtarget_bが独身集合single_bsにあったら、engaged = True by obo2
engaged[single_a, target_b] = True
single_bs.remove(target_b) # target_bをsingle_bsから外す by obo2
break
else:
# すでに婚約者がいる場合、好みの順序を評価
# target_bの婚約相手を取得する
engaged_a = [k for k, v in engaged.items() if v is True and target_b in k][0][0]
target_a_list = b[target_b] # bのaに対する順序をtarget_a_listに入れる by obo2
# 婚約者とsingle_aの順位を比較
if target_a_list.index(single_a) < target_a_list.index(
engaged_a): # aもし、すでにペアになっている人の順番が高いと? by obo2
# 好みの優先順位を調べて今回のほうが好まれていたら元の婚約者との婚約を破棄
engaged[engaged_a, target_b] = False # ペアは解消
single_as.append(engaged_a) # ペア解消となったengaged_aはsingle_asに加わる by obo2
# 改めて婚約
engaged[single_a, target_b] = True # single_a, target_bがペアになる by obo2
break
return [k for k, v in engaged.items() if v is True]
def improve_gale_shapley(s, l_men, l_women):
m_list = []
v = copy.deepcopy(l_men)
v.update(l_women)
l_list = []
l_item = copy.deepcopy(v)
for key in v.keys():
if key in [item for sublist in s for item in sublist]:
del l_item[key]
l_list.append(l_item)
r_list = []
r_item = create_r(v, l_list[0])
r_list.append(r_item)
i = 1
while True:
m = gale_shapley(l_list[i - 1], r_list[i - 1])
m_list.append(m) # (L,R)のマッチング結果
if r_perfect_check(r_list[i - 1], m) is False: # R-perfectでなければFalse
ab = set_ab(i - 1, r_list[i - 1], m) # Rの男性をセットする
l_list[i - 1].update(ab) # L_listとABの男性の要素を足す
r_list[i - 1] = create_r(v, l_list[i - 1]) # R = V-L
m = gale_shapley(l_list[i - 1], r_list[i - 1]) # (L,R)上でG-Sアルゴリズムの実装
m_list.append(m)
if not r_perfect_check(r_list[i - 1], m):
ab = set_ab(i, r_list[i - 1], m)
l_list.append({})
l_list[i].update(l_list[i - 1])
l_list[i].update(ab)
r_item = create_r(v, l_list[i])
r_list.append(r_item)
i = i + 1
else:
break
else:
break
return m_list
def r_perfect_check(r, m):
for d_key in r.keys():
if d_key not in [m_key for sublist in m for m_key in sublist]:
return False
return True
def create_r(v, l):
r = copy.deepcopy(v)
for key in l.keys():
del r[key]
return r
def set_ab(i, r_list, m):
sex = 'M'
if i % 2 == 0:
sex = 'W'
ab = copy.deepcopy(r_list)
for r_key in r_list.keys():
if sex in r_key:
del ab[r_key]
for m_key in [item for sublist in m for item in sublist]:
if m_key in ab:
del ab[m_key]
return ab
# 選好リスト作成
def create_priority(n, m):
men_list = []
women_list = []
# Mi,Wiの辞書キーを生成
for men in range(n):
men_list.append('M' + str(men))
for women in range(m):
women_list.append(('W' + str(women)))
# Wiの選好リストに入っていないMiは、Wiを選好リストに含めない
# Wiの選好リストを先に作成
women_dict = {}
preference_rate = 0.07 # 選好に含める確率を定める
for key in women_list:
tmp_list = []
# 選好順位をランダムに設定
random.shuffle(men_list)
tmp_list.extend(list(men_list))
# **選好判定**
remove_list = []
for tmp in tmp_list:
if len(tmp_list) - 1 == len(remove_list): # 少なくとも一人は選好リストに含める
pass
elif random.random() >= preference_rate:
remove_list.append(tmp)
for remove in remove_list:
tmp_list.remove(remove)
tmp_list = tmp_list[:10] # womenの選好リストに含む数は最大10人までとする
women_dict[key] = tmp_list
# Wiの選好リストに入っていないMiは、Wiを選好リストに含めない
# →Wiの選好リストに含まれているかを確認し、元となるMiの選好リストを作成
men_dict = {}
for key in men_list:
men_dict[key] = []
for k, v in women_dict.items():
if key in v:
men_dict[key].append(k)
for k, v in men_dict.items():
tmp_list = v
# MiはWiすべてを順序付ける必要はない。
# →選好に含める確率を元に選好リストから除外処理実行
remove_list = []
for tmp in tmp_list:
if len(tmp_list) - 1 == len(remove_list): # 少なくとも一人は選好リストに含める
pass
elif random.random() >= preference_rate:
remove_list.append(tmp)
for remove in remove_list:
tmp_list.remove(remove)
men_dict[k] = tmp_list
return men_dict, women_dict
# 不満足度計算
def calc_dissatisfaction(married, men_dict, women_dict):
dissatisfaction_score = 0
total_dict = copy.deepcopy(men_dict)
total_dict.update(women_dict)
for m in married:
tmp_value = total_dict[m[0]]
dissatisfaction_score += tmp_value.index(m[1])
tmp_value = total_dict[m[1]]
dissatisfaction_score += tmp_value.index(m[0])
del total_dict[m[0]], total_dict[m[1]]
for k, v in total_dict.items():
dissatisfaction_score += len(v)
return dissatisfaction_score
def daily_exec(l_men, l_women, days, improve_flg):
orig_l_men = copy.deepcopy(l_men)
orig_l_women = copy.deepcopy(l_women)
unmatched_l_men = copy.deepcopy(l_men)
unmatched_l_women = copy.deepcopy(l_women)
tmp_l_men = dict()
tmp_l_women = dict()
daily_dissatisfaction = 0
total_m_list = []
for day in range(days):
daily_l_men = {}
daily_l_women = {}
# 残った人達を残日数で割る
daily_men_num = int(math.ceil(len(unmatched_l_men) / (days - day)))
daily_women_num = int(math.ceil(len(unmatched_l_women) / (days - day)))
# 一日分の人をランダム抽出
for i in range(daily_men_num):
key, val = random.choice(list(unmatched_l_men.items()))
daily_l_men.update({key: val})
del unmatched_l_men[key]
daily_l_men.update(tmp_l_men)
daily_l_men = dict(sorted(daily_l_men.items()))
for i in range(daily_women_num):
key, val = random.choice(list(unmatched_l_women.items()))
daily_l_women.update({key: val})
del unmatched_l_women[key]
daily_l_women.update(tmp_l_women)
daily_l_women = dict(sorted(daily_l_women.items()))
# Wiの選好リストに入っていないMiの選好リストを除外
for key, value in daily_l_men.items():
for v in value:
if v not in daily_l_women:
daily_l_men[key].remove(v)
elif key not in daily_l_women[v]:
daily_l_men[key].remove(v)
s = gale_shapley(daily_l_men, daily_l_women)
if improve_flg:
m_list = improve_gale_shapley(s, daily_l_men, daily_l_women)
total_m_list.extend(m_list[-1])
daily_dissatisfaction += calc_dissatisfaction(m_list[-1], daily_l_men, daily_l_women)
else:
total_m_list.extend(s)
daily_dissatisfaction += calc_dissatisfaction(s, daily_l_men, daily_l_women)
# マッチングした人たち
m_keys = [flatten for inner in total_m_list for flatten in inner]
# マッチングしなかった人たち
unmatched_keys = list(set(list(daily_l_men.keys()) + list(daily_l_women.keys())) - set(m_keys))
tmp_l_men.clear()
tmp_l_women.clear()
for unmatched_key in unmatched_keys:
if 'M' in unmatched_key:
tmp_l_men.update({unmatched_key: l_men[unmatched_key]})
if 'W' in unmatched_key:
tmp_l_women.update({unmatched_key: l_women[unmatched_key]})
l_men.update(orig_l_men)
l_women.update(orig_l_women)
return total_m_list, daily_dissatisfaction
def main():
fig, (axS, axM) = plt.subplots(ncols=2, figsize=(12, 4), sharex=True)
for i in range(10):
random.seed(i)
l_men, l_women = create_priority(MEN_NUM, WOMEN_NUM) # 選好リスト作成
plot_s_list = []
plot_m_list = []
xtics = []
x_range = 0
for day in range(DAYS):
if DAYS % (day + 1) == 0:
s, apparent_s_dissatisfaction = daily_exec(l_men, l_women, day+1, False)
m, apparent_m_dissatisfaction = daily_exec(l_men, l_women, day+1, True)
print('MEN_PRIORITY:', len(l_men))#男性の数
print('MEN_PRIORITY:', l_men)#男性の女性に対する選好リスト
print('WOMEN_PRIORITY:', len(l_women))#女性の数
print('WOMEN_PRIORITY:', l_women)
print("**********************************")
print(str(int(DAYS / (day + 1))) + "日ごと")
print("Gale-Shapley:S")
print("■ペア")
print(s)
print("■ペア数")
print(len(s))
plot_s_list.append(len(s))
print("■不満足度")
dissatisfaction_score = calc_dissatisfaction(s, l_men, l_women)
print("見かけ", apparent_s_dissatisfaction)
print("実際", dissatisfaction_score)
print("")
print("改良版Gale-Shapley:M")
print("■ペア")
print(m)
print("■ペア数")
print(len(m))
plot_m_list.append(len(m))
xtics.append(str(int(DAYS / (day + 1))))
print("■不満足度")
dissatisfaction_score = calc_dissatisfaction(m, l_men, l_women)
print("見かけ", apparent_m_dissatisfaction)
print("実際", dissatisfaction_score)
x_range += 1
axS.plot(plot_s_list, label='seed_' + str(i))
axM.plot(plot_m_list, label='seed_' + str(i))
axS.set_title('S', fontdict={'family': 'IPAexGothic'})
axS.set_xlabel('分割日数', fontdict={'family': 'IPAexGothic'})
axS.set_ylabel('ペア数', fontdict={'family': 'IPAexGothic'})
axM.set_title('M', fontdict={'family': 'IPAexGothic'})
axM.set_xlabel('分割日数', fontdict={'family': 'IPAexGothic'})
axM.set_ylabel('ペア数', fontdict={'family': 'IPAexGothic'})
axS.grid(True)
axM.grid(True)
plt.xticks(range(x_range), xtics)
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0)
plt.show()
if __name__ == '__main__':
main()
```
|
8bitcat/GardenArtSweden
|
8bitcat/GardenArtSweden
NavData.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GardenArt.Core.Repository;
using GardenArt.Core.Repository.Interfaces;
using GardenArt.Infrastructure.Database;
using GardenArt.Models;
using GardenArt.Core.Interfaces.NavData;
namespace GardenArt.Domain
{
public class NavData : INavData
{
private static NavData _navdata;
private IUnitOfWork iUow = new UnitOfWork();
private IEnumerable<ProductListItem> _allCollections;
private IEnumerable<ProductListItem> _allCategories;
private IEnumerable<IGrouping<string,tNewsItem>> _allNews;
private NavData()
{
this._allCollections = iUow.NavDataRepository.FetchAllColletionNamesAndIds()
.Select(x =>
new ProductListItem
{
ProductCategoryName = x.Name,
ProductCategoryID = x.SetID
}
)
.ToList()
.GroupBy(x => x.ProductCategoryName)
.Select(y => y.First());
this._allCategories = iUow.NavDataRepository.FetchAllCategoryNamesAndIds()
.Select(x =>
new ProductListItem
{
ProductCategoryName = x.Name,
ProductCategoryID = x.CategoryID
}
)
.ToList()
.GroupBy(x => x.ProductCategoryName)
.Select(y => y.First()).OrderBy(o => o.ProductCategoryName);
this._allNews = iUow.NavDataRepository.FetchAllNewsAndIds();
}
public static NavData getInstance()
{
if(_navdata == null)
{ //Ensure only one gets created!
_navdata = new NavData();
return _navdata;
}
else
{
return _navdata;
}
}
public IEnumerable<ProductListItem> AllCollections
{
get { return _allCollections; }
}
public IEnumerable<ProductListItem> AllCategories
{
get { return _allCategories; }
}
public IEnumerable<IGrouping<string,tNewsItem>> AllNews
{
get { return _allNews; }
}
}
}```
tCategory.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
using System.Collections.Generic;
public partial class tCategory
{
public tCategory()
{
this.tCategoryPicture = new HashSet<tCategoryPicture>();
this.tProduct = new HashSet<tProduct>();
}
public int CategoryID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<int> CategoryTypeID { get; set; }
public virtual ICollection<tCategoryPicture> tCategoryPicture { get; set; }
public virtual tCategoryType tCategoryType { get; set; }
public virtual ICollection<tProduct> tProduct { get; set; }
}
}
```
Mailform.js
```
//CALLS DOUCMENT WHEN PAGE FINISHED LOADING!
$(document).ready(function () {
$("#submitbutton").click(imClicked);
});
var printError = function( req, status, err ) {
$("#callbackmessage").css("color", "green");
$("#callbackmessage").text(msg);
};
function imClicked(e) {
e.preventDefault();
var messageObj =
{
"name": "",
"email": "",
"phone": "",
"message": "",
};
messageObj.name = $("#name").val();
messageObj.email = $("#email").val();
messageObj.phone = $("#phone").val();
messageObj.message = $("#message").val();
$.ajax({
dataType: "json",
contentType: 'application/json',
type: 'POST',
url: '/Contact/AjaxMailer',
data: JSON.stringify(messageObj),
error: printError,
success: mailsent
});
};
var mailsent = function MailSent(msg) {
$("#callbackmessage").css("color", "green");
$("#callbackmessage").text(msg);
$("#name").val("");
$("#email").val("");
$("#phone").val("");
$("#message").val("");
};```
tProduct.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
using System.Collections.Generic;
public partial class tProduct
{
public tProduct()
{
this.tOrderDetail = new HashSet<tOrderDetail>();
this.tProductAttributeValue = new HashSet<tProductAttributeValue>();
this.tProductGroupDetail = new HashSet<tProductGroupDetail>();
this.tProductMaterial = new HashSet<tProductMaterial>();
this.tProductPicture = new HashSet<tProductPicture>();
this.tSetDetail = new HashSet<tSetDetail>();
this.tWarehouse = new HashSet<tWarehouse>();
}
public int ProductID { get; set; }
public Nullable<int> CategoryID { get; set; }
public string SupplierArticleNumber { get; set; }
public string GardenArtArticleNumber { get; set; }
public string Name { get; set; }
public string Comment { get; set; }
public string Description { get; set; }
public int ProductSizeWidth { get; set; }
public int ProductSizeHeight { get; set; }
public int ProductSizeDepth { get; set; }
public string PackageInfo { get; set; }
public string Package { get; set; }
public string PackageSize { get; set; }
public decimal GrossWeight { get; set; }
public decimal NetWeight { get; set; }
public int ItemsPerContainer { get; set; }
public decimal VolumePerItem { get; set; }
public string Factory { get; set; }
public string Supplier { get; set; }
public decimal CostUSD { get; set; }
public decimal PurchasePriceUSD { get; set; }
public decimal SellingPriceDirectUSD20 { get; set; }
public decimal SellingPriceDirectUSD10 { get; set; }
public decimal SellingPriceWarehouseSEK { get; set; }
public Nullable<int> FrameID { get; set; }
public Nullable<int> SupplierID { get; set; }
public decimal SellingPriceConsumerSEK { get; set; }
public Nullable<int> FrameColorID { get; set; }
public Nullable<int> MaterialColorID { get; set; }
public string ProductSizeInfo { get; set; }
public virtual tCategory tCategory { get; set; }
public virtual tFrame tFrame { get; set; }
public virtual tFrameColor tFrameColor { get; set; }
public virtual tMaterialColor tMaterialColor { get; set; }
public virtual ICollection<tOrderDetail> tOrderDetail { get; set; }
public virtual tSupplier tSupplier { get; set; }
public virtual ICollection<tProductAttributeValue> tProductAttributeValue { get; set; }
public virtual ICollection<tProductGroupDetail> tProductGroupDetail { get; set; }
public virtual ICollection<tProductMaterial> tProductMaterial { get; set; }
public virtual ICollection<tProductPicture> tProductPicture { get; set; }
public virtual ICollection<tSetDetail> tSetDetail { get; set; }
public virtual ICollection<tWarehouse> tWarehouse { get; set; }
}
}
```
CollectionModel.cs
```using GardenArt.Core.Interfaces;
using GardenArt.Core.Interfaces.Models;
using GardenArt.Core.Interfaces.Repository;
using GardenArt.Core.Repository;
using GardenArt.Core.Repository.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.Models
{
public class CollectionModel : IModel<CollectionModel>, ICollectionModel
{
private IUnitOfWork iUOW = new UnitOfWork();
private IEnumerable<CollectionListItem> _ListOfCollections;
private CollectionListItem _OneDetailedCollection;
public CollectionModel()
{
this._ListOfCollections = iUOW.CollectionRepository.FetchAll();
}
public CollectionModel(int id)
{
var fetchedAllinCategory = iUOW.CollectionRepository.FetchById(id);
this._OneDetailedCollection = fetchedAllinCategory.Select(x => new CollectionListItem
{
CollectionID = x.CollectionID,
CollectionName = x.CollectionName,
Description = x.Description,
ImgUrl = x.ImgUrl,
ImgList = fetchedAllinCategory.Select(i => i.ImgUrl).ToList()
}).FirstOrDefault<CollectionListItem>();
this._ListOfCollections = iUOW.CollectionRepository.FetchAll().Select(x => new CollectionListItem
{
CollectionName = x.CollectionName,
CollectionID = x.CollectionID,
});
}
public CollectionModel GetDetailedModel<Tinput>(Tinput identifier)
{
throw new NotImplementedException();
}
public IEnumerable<CollectionListItem> ListOfCollections
{
get { return _ListOfCollections; }
set { _ListOfCollections = value; }
}
public CollectionListItem OneCollectionFromID
{
get { return _OneDetailedCollection; }
set { _OneDetailedCollection = value; }
}
}
}```
LinkActive.js
```$(document).ready(function () {
var currentLocation = window.location.href;
if (currentLocation.indexOf("home") > -1) {
$("#home").addClass("active");
}
else if (currentLocation.indexOf("Product") > -1) {
$("#product").addClass("active");
}
else if (currentLocation.indexOf("Collections") > -1) {
$("#collection").addClass("active");
}
else if (currentLocation.indexOf("News") > -1) {
$("#news").addClass("active");
}
else if (currentLocation.indexOf("Wholesaler") > -1) {
$("#wholesaler").addClass("active");
}
else if (currentLocation.indexOf("Contact") > -1) {
$("#contact").addClass("active");
}
else {
$("#home").addClass("active");
}
});```
tSet.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
using System.Collections.Generic;
public partial class tSet
{
public tSet()
{
this.tSetDetail = new HashSet<tSetDetail>();
this.tSetPicture = new HashSet<tSetPicture>();
}
public int SetID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<tSetDetail> tSetDetail { get; set; }
public virtual ICollection<tSetPicture> tSetPicture { get; set; }
}
}
```
ProductController.cs
```using GardenArt.Core.Interfaces;
using GardenArt.Core.Interfaces.Mapper;
using GardenArt.Domain;
using GardenArt.Domain.Factory;
using GardenArt.Models;
using GardenArt.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GardenArt.Controllers
{
public class ProductController : Controller
{
IFactory factory = new Factory();
//
// GET: /Product/
public ActionResult Index()
{
return View();
}
public ActionResult Products()
{
//Jag mellanlagrade för syns skull, vill någon av er kan vi putta ner allt i return view.
var mappedViewModel = factory.BuildAndMap<ProductModel, ProductDisplayViewModel>();
return View(mappedViewModel);
}
[HttpPost]
public ActionResult Article()
{
var mappedViewModel = factory.BuildAndMap<ProductModel, ArticleDisplayViewModel>();
return View(mappedViewModel);
}
public ActionResult Article(int id)
{
var mappedViewModel = factory.BuildAndMap<ProductModel, ArticleDisplayViewModel>(id);
return View(mappedViewModel);
}
public ActionResult Collections()
{
return View();
}
public ActionResult Collection(int id)
{
var mappedViewModel = factory.BuildAndMap<CollectionModel, CollectionDisplayViewModel>(id);
return View(mappedViewModel);
}
public ActionResult Category(int id)
{
var mappedViewModel = factory.BuildAndMap<CategoryModel, ProductCategoryViewModel>(id);
return View(mappedViewModel);
}
}
}
```
CollectionListViewModel.cs
```using GardenArt.Core.Interfaces;
using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.ViewModels
{
public class CollectionListViewModel : IViewModel<CollectionListViewModel>
{
private IEnumerable<CollectionListItem> _ListOfCollections;
public IEnumerable<CollectionListItem> ListOfCollections
{
get { return _ListOfCollections; }
set { _ListOfCollections = value; }
}
public CollectionDisplayViewModel GetViewModel()
{
throw new NotImplementedException();
}
CollectionListViewModel IViewModel<CollectionListViewModel>.GetViewModel()
{
throw new NotImplementedException();
}
}
}```
ICategoryModel.cs
```using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenArt.Core.Interfaces.Models
{
interface ICategoryModel
{
IEnumerable<ProductListItem> ListOfProductsFromCategory { get; set; }
IEnumerable<ProductListItem> ListOfCategories { get; set; }
}
}
```
PictureUploader.cs
```using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace GardenArt.Infrastructure.Uploaders
{
public class PictureUploader
{
//private IEnumerable<HttpPostedFileBase> mPictures;
[Required]
public HttpPostedFileBase image { get; set; }
}
}```
tSupplier.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
using System.Collections.Generic;
public partial class tSupplier
{
public tSupplier()
{
this.tProduct = new HashSet<tProduct>();
}
public int SupplierID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string EmailAddress { get; set; }
public string PhoneNumber { get; set; }
public string Homepage { get; set; }
public string Address { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
public string Country { get; set; }
public virtual ICollection<tProduct> tProduct { get; set; }
}
}
```
IProductRepository.cs
```using GardenArt.Infrastructure.Database;
using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenArt.Core.Repository.Interfaces
{
interface IProductRepository : IRepository<tProduct>
{
IEnumerable<tProduct> FetchAllProducts();
IEnumerable<tProduct> FetchProductsByTypes(IEnumerable<int> type);
IEnumerable<tProduct> FetchProductsByType(int type);
IEnumerable<tProduct> FetchProductsByIDS(IEnumerable<int> id);
IEnumerable<ProductListItem> FetchProductByID(int id);
void AddProduct(tProduct product);
IEnumerable<ProductListItem> FetchAllAsListItems();
IEnumerable<ProductListItem> FetchProductsByCategory(int id);
}
}
```
StringHelpers.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.Helpers
{
public static class StringHelpers
{
public static string UpperCaseFirst(this string s)
{
return char.ToUpper(s[0]) + s.Substring(1);
}
public static string Max24Chars(this string s)
{
if (s.Length > 23) {
s = s.Substring(0, 24);
s += "...";
}
return s;
}
}
}```
NewsListItem.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.Models
{
public class NewsListItem
{
public string NewsText { get; set; }
public string NewsTitle { get; set; }
public bool NewsPublished { get; set; }
public DateTime NewsCreated { get; set; }
public DateTime NewsModified { get; set; }
public List<string> Newspicture { get; set; }
}
}```
IFactory.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GardenArt.Core.Interfaces
{
interface IFactory
{
T BuildViewModel<T>() where T : class, IViewModel<T>, new();
T BuildViewModel<Tinput, T>(Tinput id) where T : class, IViewModel<T>, new();
T BuildModel<T>() where T : class, IModel<T>, new();
T BuildModel<Tinput, T>(Tinput id) where T : class, new();
/// <summary>Creates a Model and a ViewModel. After creation the values in the model get's mapped to the viewmodel.
/// <para>
/// </para>
/// <seealso cref="GardenArt.Domain.Factory for concrete implementation."/>
/// </summary>
TypeViewModel BuildAndMap<TypeModel, TypeViewModel>()
where TypeModel : class, IModel<TypeModel>, new()
where TypeViewModel : class, IViewModel<TypeViewModel>, new();
/// <summary>Creates a Model ID and a ViewModel. After creation the values in the model get's mapped to the viewmodel.
/// <para>
/// </para>
/// <seealso cref="GardenArt.Domain.Factory for concrete implementation."/>
/// </summary>
TypeViewModel BuildAndMap<TypeModel, TypeViewModel>(int id)
where TypeModel : class, IModel<TypeModel>, new()
where TypeViewModel : class, IViewModel<TypeViewModel>, new();
}
}
```
CategoryRepository.cs
```using GardenArt.Core.Interfaces.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GardenArt.Models;
namespace GardenArt.Core.Repository
{
public class CategoryRepository : ICategoryRepository
{
public CategoryListItem FetchById(int id)
{
return null;
}
public IEnumerable<CategoryListItem> FetchAll()
{
return null;
}
}
}```
CategoryModel.cs
```using GardenArt.Core.Interfaces;
using GardenArt.Core.Interfaces.Models;
using GardenArt.Core.Interfaces.NavData;
using GardenArt.Core.Repository;
using GardenArt.Core.Repository.Interfaces;
using GardenArt.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.Models
{
public class CategoryModel : IModel<CategoryModel>, ICategoryModel
{
private IUnitOfWork iUOW = new UnitOfWork();
private IProductRepository iprod;
private IEnumerable<ProductListItem> _ListOfProductsFromCategory;
private IEnumerable<ProductListItem> _listOfCategories;
public CategoryModel()
{
}
public CategoryModel(int id)
{
iprod = iUOW.ProductRepository;
INavData ndata = NavData.getInstance();
this._ListOfProductsFromCategory = iprod.FetchProductsByCategory(id);
this._listOfCategories = ndata.AllCategories;
}
public IEnumerable<ProductListItem> ListOfProductsFromCategory
{
get
{
return _ListOfProductsFromCategory;
}
set
{
_ListOfProductsFromCategory = value;
}
}
public IEnumerable<ProductListItem> ListOfCategories
{
get
{
return _listOfCategories;
}
set
{
_listOfCategories = value;
}
}
public CategoryModel GetDetailedModel<Tinput>(Tinput identifier)
{
throw new NotImplementedException();
}
}
}```
ISetModel.cs
```using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenArt.Core.Interfaces.Repository
{
interface ISetModel
{
IEnumerable<ProductListItem> ProductsInSet { get; set; }
IEnumerable<ProductListItem> ListOfCollections { get; set; }
}
}
```
MaterialListItemViewModel.cs
```using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GardenArt.ViewModels
{
public class MaterialListItemViewModel
{
[Display(Name = "ID")]
public Int32 MaterialID { get; set; }
[Required(ErrorMessage = "Material måste fyllas i")]
[DataType(DataType.Text)]
[Display(Name = "Material")]
public String Name { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Beskrivning")]
public String Description { get; set; }
}
}```
ProductModel.cs
```using GardenArt.Core.Repository;
using GardenArt.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GardenArt.Infrastructure.Database;
using GardenArt.Core.Repository.Interfaces;
using GardenArt.Core.Interfaces.NavData;
using GardenArt.Domain;
using GardenArt.Models.Containers;
namespace GardenArt.Models
{
public class ProductModel : IModel<ProductModel>, IProductModel
{
private IUnitOfWork iUOW = new UnitOfWork();
private IProductRepository iProdRep;
private INavData ndata;
private IEnumerable<ProductListItem> _ListOfProducts;
private IEnumerable<ProductListItem> _listOfCategories;
private IEnumerable<ProductListItem> _OneDetailedArticle;
private ProductContainer _ProductContainer;
// ListOfProducts { get; set; }
public ProductModel()
{
iProdRep = iUOW.ProductRepository;
ndata = NavData.getInstance();
this._ListOfProducts = iProdRep.FetchAllAsListItems();
this._listOfCategories = ndata.AllCategories;
}
public ProductModel(int id)
{
this.ProductContainer = new ProductContainer();
iProdRep = iUOW.ProductRepository;
this._OneDetailedArticle = iProdRep.FetchProductByID(id);
this._ProductContainer.MotherProduct = this._OneDetailedArticle.Select(x =>
new ProductListItem
{
ProductColors = this._OneDetailedArticle.Select(i => i.MaterialColor).ToList(),
ProductFrames = this._OneDetailedArticle.Select(i => i.FrameColor).ToList(),
ProductMaterials = this._OneDetailedArticle.Select(i => i.MaterialType).ToList(),
ProductName = this._OneDetailedArticle.Select(i => i.ProductName).First(),
Description = this._OneDetailedArticle.Select(i => i.Description).First(),
ProductSizeWidth = this._OneDetailedArticle.Select(i => i.ProductSizeWidth).First(),
ProductSizeHeight = this._OneDetailedArticle.Select(i => i.ProductSizeHeight).First(),
ProductSizeDepth = this._OneDetailedArticle.Select(i => i.ProductSizeDepth).First(),
GardenArtArticleNumber = this._OneDetailedArticle.Select(i => i.GardenArtArticleNumber).First(),
SellingPriceConsumerSEK = this._OneDetailedArticle.Select(i => i.SellingPriceConsumerSEK).First(),
SellingPriceWarehouseSEK = this._OneDetailedArticle.Select(i => i.SellingPriceWarehouseSEK).First(),
ProductCategoryTypeDisplay = this._OneDetailedArticle.Select(i => i.ProductCategoryTypeDisplay).First(),
ImgUrl = this._OneDetailedArticle.Select(i => i.ImgUrl).First()
}).FirstOrDefault();
this._ProductContainer.MotherProduct.ProductColors = this._ProductContainer.MotherProduct.ProductColors.GroupBy(x => x).Select(x => x.FirstOrDefault()).ToList();
this._ProductContainer.MotherProduct.ProductFrames = this._ProductContainer.MotherProduct.ProductFrames.GroupBy(x => x).Select(x => x.FirstOrDefault()).ToList();
this._ProductContainer.MotherProduct.ProductMaterials = this._ProductContainer.MotherProduct.ProductMaterials.GroupBy(x => x).Select(x => x.FirstOrDefault()).ToList();
}
public IEnumerable<ProductListItem> ListOfProducts
{
get
{
return _ListOfProducts;
}
set
{
_ListOfProducts = value;
}
}
public ProductModel GetDetailedModel<Tinput>(Tinput identifier)
{
throw new NotImplementedException();
}
public IEnumerable<ProductListItem> OneArticleFromID
{
get
{
return _OneDetailedArticle;
}
set
{
_OneDetailedArticle = value;
}
}
public IEnumerable<ProductListItem> ProductCategories
{
get
{
return _listOfCategories;
}
set
{
_listOfCategories = value;
}
}
public ProductContainer ProductContainer
{
get
{
return _ProductContainer;
}
set
{
_ProductContainer = value;
}
}
}
}```
ContactController.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using GardenArt.Infrastructure.Mail;
namespace GardenArt.Controllers
{
public class ContactController : Controller
{
//
// GET: /Contact/
public ActionResult Contact()
{
return View();
}
public JsonResult AjaxMailer(MailerModel model)
{
Emailer mailer = new Emailer();
JsonResult Jr = new JsonResult();
string result = mailer.DispatchEmail(model.phone, model.name, model.message, model.email);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
public class MailerModel
{
[Required(ErrorMessage = "Du måste fylla i ett namn!")]
public string name { get; set; }
[Required(ErrorMessage = "Du måste fylla i en epost!")]
[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
ErrorMessage = "Eposten är inte riktig!")]
public string email { get; set; }
public string phone { get; set; }
[Required(ErrorMessage = "Du måste fylla i ett meddelande!")]
public string message { get; set; }
}
}
```
Factory.cs
```using GardenArt.Core.Interfaces;
using GardenArt.Core.Interfaces.Mapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GardenArt.Domain.Factory
{
public class Factory : IFactory
{
private Imapper mapper = new Mapper();
//NOT NEEDED IN ACCTUAL IMPLEMENTATION!--->
public T BuildDetailedViewModel<Tinput, T>(Tinput id) where T : class, IViewModel<T>, new()
{
return (T)Activator.CreateInstance(typeof(T), id);
}
//NOT NEEDED IN ACCTUAL IMPLEMENTATION!--->
public T BuildDetailedModel<Tinput, T>(Tinput id) where T : class, new()
{
return (T)Activator.CreateInstance(typeof(T), id);
}
//Tighten coupling by only allowing class Implementing IViewModel to use BuildViewModel!
T IFactory.BuildViewModel<T>()
{
return (T)Activator.CreateInstance<T>();
}
//Using overloaded CTORS(constructors) we can achieve a detailed build of a ViewModel
T IFactory.BuildViewModel<Tinput, T>(Tinput id)
{
return (T)Activator.CreateInstance(typeof(T), id);
}
//Tighten coupling by only allowing classa Implementing IModel to use BuildModel!
T IFactory.BuildModel<T>()
{
return (T)Activator.CreateInstance<T>();
}
//Using overloaded CTORS(constructors) we can achieve a detailed build of a Model
T IFactory.BuildModel<Tinput, T>(Tinput id)
{
return (T)Activator.CreateInstance(typeof(T), id);
}
public TypeViewModel BuildAndMap<TypeModel, TypeViewModel>()
//Constraint for BOTH types
where TypeModel : class, IModel<TypeModel>, new()
where TypeViewModel : class, IViewModel<TypeViewModel>, new()
{
//Create the isntaces needed to build N map!
TypeModel model = Activator.CreateInstance<TypeModel>();
TypeViewModel viewModel = Activator.CreateInstance<TypeViewModel>();
viewModel = mapper.MapModelToViewModel<TypeModel, TypeViewModel>(model, viewModel);
return viewModel;
}
public TypeViewModel BuildAndMap<TypeModel, TypeViewModel>(int id)
//Constraint for BOTH types
where TypeModel : class, IModel<TypeModel>, new()
where TypeViewModel : class, IViewModel<TypeViewModel>, new()
{
//Create the isntaces needed to build N map!
TypeModel model = (TypeModel)Activator.CreateInstance(typeof(TypeModel), id);
TypeViewModel viewModel = Activator.CreateInstance<TypeViewModel>();
viewModel = mapper.MapModelToViewModel<TypeModel, TypeViewModel>(model, viewModel);
return viewModel;
}
}
}
```
SetDisplayViewModel.cs
```using GardenArt.Core.Interfaces;
using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.ViewModels
{
public class SetDisplayViewModel : IViewModel<SetDisplayViewModel>
{
IEnumerable<ProductListItem> _ProductsInSet;
IEnumerable<ProductListItem> _ListOfCollections;
public IEnumerable<ProductListItem> ProductsInSet
{
get { return _ProductsInSet; }
set { _ProductsInSet = value; }
}
public IEnumerable<ProductListItem> ListOfCollections
{
get { return _ListOfCollections; }
set { _ListOfCollections = value; }
}
public SetDisplayViewModel GetViewModel()
{
throw new NotImplementedException();
}
}
}```
IUnitOfWork.cs
```using GardenArt.Core.Interfaces.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenArt.Core.Repository.Interfaces
{
interface IUnitOfWork
{
IProductRepository ProductRepository { get; }
ICollectionRepository CollectionRepository { get; }
INavDataRepository NavDataRepository { get; }
INewsRepository NewsRepository { get; }
}
}
```
tProductAttributeValue.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
using System.Collections.Generic;
public partial class tProductAttributeValue
{
public int ProductAttributeValueID { get; set; }
public int ProductAttributeID { get; set; }
public int ProductID { get; set; }
public string Value { get; set; }
public virtual tProductAttribute tProductAttribute { get; set; }
public virtual tProduct tProduct { get; set; }
}
}
```
CollectionController.cs
```using GardenArt.Core.Interfaces;
using GardenArt.Domain.Factory;
using GardenArt.Models;
using GardenArt.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GardenArt.Controllers
{
public class CollectionController : Controller
{
//
// GET: /Collection/
IFactory factory = new Factory();
public ActionResult Collections()
{
var mappedViewModel = factory.BuildAndMap<CollectionModel, CollectionListViewModel>();
return View(mappedViewModel);
}
public ActionResult Collection(int id)
{
var mappedViewModel = factory.BuildAndMap<CollectionModel, CollectionDisplayViewModel>(id);
return View(mappedViewModel);
}
public ActionResult CollectionView(int id)
{
var mappedViewModel = factory.BuildAndMap<SetModel, SetDisplayViewModel>(id);
return View(mappedViewModel);
}
}
}
```
NewsModel.cs
```using GardenArt.Core.Interfaces;
using GardenArt.Core.Interfaces.Models;
using GardenArt.Core.Interfaces.NavData;
using GardenArt.Core.Interfaces.Repository;
using GardenArt.Core.Repository;
using GardenArt.Core.Repository.Interfaces;
using GardenArt.Domain;
using GardenArt.Infrastructure.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.Models
{
public class NewsModel:IModel<NewsModel>, INewsModel
{
private IUnitOfWork iUOW = new UnitOfWork();
private INewsRepository iNewsRep;
private INavData ndata;
private NewsListItem _OneNewsById;
private IEnumerable<IGrouping<string,tNewsItem>> _ListOfNews;
private IEnumerable<ProductListItem> _listOfCategories;
public NewsModel()
{
ndata = NavData.getInstance();
this._ListOfNews = ndata.AllNews;
}
public NewsModel(int id)
{
ndata = NavData.getInstance();
this._ListOfNews = ndata.AllNews;
iNewsRep = iUOW.NewsRepository;
this._OneNewsById = iNewsRep.FetchNewsById(id);
}
public NewsModel GetDetailedModel<Tinput>(Tinput identifier)
{
throw new NotImplementedException();
}
public IEnumerable<IGrouping<string,tNewsItem>> ListOfNews
{
get { return _ListOfNews; }
}
public NewsListItem OneNewsById
{
get {return _OneNewsById;}
}
}
}```
NavDataRepository.cs
```using GardenArt.Core.Interfaces.Repository;
using GardenArt.Infrastructure.Database;
using System;
using System.Collections.Generic;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Web;
using System.Globalization;
using GardenArt.Helpers;
namespace GardenArt.Core.Repository
{
public class NavDataRepository : GenericRepository<tCategory>, INavDataRepository
{
private Entities dbContext;
public NavDataRepository(Entities dbContext) :base(dbContext)
{
// TODO: Complete member initialization
this.dbContext = dbContext;
}
public IEnumerable<Infrastructure.Database.tSet> FetchAllColletionNamesAndIds()
{
return dbContext.tSet.ToList<tSet>().GroupBy(x => x.Name).Select(x => x.First()); ;
}
public IEnumerable<Infrastructure.Database.tCategory> FetchAllCategoryNamesAndIds()
{
return dbContext.tCategory.ToList<tCategory>().GroupBy(x => x.Name).Select(x => x.First());
}
public IEnumerable<Infrastructure.Database.tSet> BaseFetchAll()
{
throw new NotImplementedException();
}
public IEnumerable<Infrastructure.Database.tSet> BaseFindById(int id)
{
throw new NotImplementedException();
}
public void BaseAdd(Infrastructure.Database.tSet entity)
{
throw new NotImplementedException();
}
public void BaseDelete(Infrastructure.Database.tSet entity)
{
throw new NotImplementedException();
}
public IEnumerable<IGrouping<string,tNewsItem>> FetchAllNewsAndIds()
{
return dbContext.tNewsItem.ToList<tNewsItem>().OrderByDescending(i => i.DateModified.Month).GroupBy(x => CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.DateCreated.Month).UpperCaseFirst()).OrderByDescending(x => DateTime.ParseExact(x.Key, "MMMM", CultureInfo.CurrentCulture).Month).Select(x => x);
}
}
}```
SetModel.cs
```using GardenArt.Core.Interfaces;
using GardenArt.Core.Interfaces.Models;
using GardenArt.Core.Interfaces.NavData;
using GardenArt.Core.Interfaces.Repository;
using GardenArt.Core.Repository;
using GardenArt.Core.Repository.Interfaces;
using GardenArt.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.Models
{
public class SetModel : IModel<SetModel>, ISetModel
{
private IUnitOfWork iUOW = new UnitOfWork();
private ICollectionRepository iRepo;
private IEnumerable<ProductListItem> _ProductsInSet;
private CollectionListItem _OneDetailedCollection;
private IEnumerable<ProductListItem> _ListOfCollections;
public SetModel()
{
}
public SetModel(int id)
{
INavData ndata = NavData.getInstance();
_ListOfCollections = ndata.AllCollections;
iRepo = iUOW.CollectionRepository;
_ProductsInSet = iRepo.FetchFromCollection(id);
}
public IEnumerable<ProductListItem> ProductsInSet
{
get { return _ProductsInSet; }
set { _ProductsInSet = value; }
}
public IEnumerable<ProductListItem> ListOfCollections
{
get { return _ListOfCollections;}
set { _ListOfCollections = value;}
}
public SetModel GetDetailedModel<Tinput>(Tinput identifier)
{
throw new NotImplementedException();
}
}
}```
tSetPicture.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
using System.Collections.Generic;
public partial class tSetPicture
{
public int SetPictureID { get; set; }
public int SetID { get; set; }
public int PictureID { get; set; }
public int SortOrder { get; set; }
public virtual tPicture tPicture { get; set; }
public virtual tSet tSet { get; set; }
}
}
```
tCategoryType.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
using System.Collections.Generic;
public partial class tCategoryType
{
public tCategoryType()
{
this.tCategory = new HashSet<tCategory>();
}
public int CategoryTypeID { get; set; }
public string Name { get; set; }
public virtual ICollection<tCategory> tCategory { get; set; }
}
}
```
Emailer.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Text;
namespace GardenArt.Infrastructure.Mail
{
public class Emailer
{
public string DispatchEmail(string phone, string name, string message, string email)
{
StringBuilder sb = new StringBuilder();
string from = "kontakt@gardenartsweden.se";
string subject = "Meddelande från kontaktformuläret på Gardenartsweden.se";
sb.Append("Namn: " + name + "<br/>");
sb.Append("Email: " + email + "<br/>");
sb.Append("Telefon: " + phone + "<br/>");
sb.Append("Meddelande: " + message + "<br/>");
return SendMail(from, from, subject, sb.ToString());
}
private string SendMail(string from, string to, string subject, string body)
{
var ret = "";
try
{
MailMessage mail = new MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from);
mail.Subject = subject;
string Body = body;
mail.Body = Body;
mail.IsBodyHtml = true;
mail.BodyEncoding = UTF8Encoding.UTF8;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Timeout = 10000;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("kontakt@gardenartsweden.se", "gardenartsweden");// Enter senders User name and password
smtp.EnableSsl = true;
smtp.Send(mail);
ret = "Meddelandet Skickat.";
}
catch (Exception ex)
{
ret = "Det gick fel när meddelandet skulle skickas: " + ex.Message;
}
return ret;
}
}
}```
tNewsItemPicture.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
using System.Collections.Generic;
public partial class tNewsItemPicture
{
public int NewsItemPictureID { get; set; }
public int NewsItemID { get; set; }
public int PictureID { get; set; }
public int SortOrder { get; set; }
public virtual tNewsItem tNewsItem { get; set; }
public virtual tPicture tPicture { get; set; }
}
}
```
ProductRepository.cs
```using GardenArt.Core.Repository.Interfaces;
using GardenArt.Infrastructure.Database;
using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq;
namespace GardenArt.Core.Repository
{
public class ProductRepository : GenericRepository<tProduct>,IProductRepository
{
private Entities dbContext;
public ProductRepository(Entities dbContext) : base(dbContext)
{
// TODO: Complete member initialization
this.dbContext = dbContext;
}
IEnumerable<tProduct> IProductRepository.FetchAllProducts()
{
return (from x in dbContext.tProduct select x).AsEnumerable<tProduct>();
}
IEnumerable<tProduct> IProductRepository.FetchProductsByTypes(IEnumerable<int> type)
{
throw new NotImplementedException();
}
IEnumerable<tProduct> IProductRepository.FetchProductsByType(int type)
{
throw new NotImplementedException();
}
IEnumerable<tProduct> IProductRepository.FetchProductsByIDS(IEnumerable<int> id)
{
throw new NotImplementedException();
}
void IRepository<tProduct>.BaseAdd(tProduct entity)
{
throw new NotImplementedException();
}
void IRepository<tProduct>.BaseDelete(tProduct entity)
{
throw new NotImplementedException();
}
void IProductRepository.AddProduct(tProduct product)
{
try
{
this.dbContext.tProduct.Add(product);
this.dbContext.SaveChanges();
}
catch (Exception)
{
throw;
}
}
IEnumerable<tProduct> IRepository<tProduct>.BaseFetchAll()
{
throw new NotImplementedException();
}
IEnumerable<tProduct> IRepository<tProduct>.BaseFindById(int id)
{
throw new NotImplementedException();
}
IEnumerable<ProductListItem> IProductRepository.FetchAllAsListItems()
{
var allProductMothers = (from u in dbContext.tProductPicture
from v in dbContext.tProductGroup
from y in dbContext.tProduct
from x in dbContext.tProductGroupDetail
from z in dbContext.tPicture
where v.ProductGroupID == x.ProductGroupID
&& x.ProductID == y.ProductID
&& u.ProductID == y.ProductID
&& u.PictureID == z.PictureID
&& z.Width == 250
select new ProductListItem
{
ImgUrl = z.Picture,
ProductName = v.Name,
ProductID = x.ProductID,
FatherProduct = x.ProductGroupID,
ProductCategoryName = y.tCategory.Name,
ProductCategoryID = (int)y.CategoryID
}
).ToList<ProductListItem>().GroupBy(x => x.FatherProduct).Select(x => x.FirstOrDefault()).GroupBy(y => y.ProductCategoryName).Select(y => y.FirstOrDefault());
return (IEnumerable<ProductListItem>)allProductMothers.OrderBy(o => o.ProductCategoryName);
}
IEnumerable<ProductListItem> IProductRepository.FetchProductsByCategory(int id)
{
var testList = (
from u in dbContext.tProductGroup
from uu in dbContext.tProductGroupDetail
from v in dbContext.tCategory
from x in dbContext.tProduct
from y in dbContext.tProductPicture
from z in dbContext.tPicture
where u.ProductGroupID == uu.ProductGroupID
&& uu.ProductID == x.ProductID
&& x.ProductID == y.ProductID
&& y.PictureID == z.PictureID
&& v.CategoryID == x.CategoryID
&& x.CategoryID == id
select new ProductListItem
{
ImgUrl = z.Picture,
ProductCategoryName = v.Name,
ProductID = x.ProductID,
FatherProduct = uu.ProductGroupID,
ProductCategoryID = v.CategoryID,
ProductName = u.Name, // Här måste vi hämta in PappaProduktensnamn!
SupplierArticleNumber = x.SupplierArticleNumber,
GardenArtArticleNumber = x.GardenArtArticleNumber,
Comment = x.Comment,
Description = x.Description,
ProductSizeWidth = x.ProductSizeWidth,
ProductSizeHeight = x.ProductSizeHeight,
ProductSizeDepth = x.ProductSizeHeight,
PackageInfo = x.PackageInfo,
Package = x.Package,
PackageSize = x.PackageSize,
GrossWeight = x.GrossWeight,
NetWeight = x.NetWeight,
ItemsPerContainer = x.ItemsPerContainer,
VolumePerItem = x.VolumePerItem,
Factory = x.Factory,
Supplier = x.Supplier,
CostUSD = x.CostUSD,
SellingPriceDirectUSD20 = x.SellingPriceDirectUSD20,
SellingPriceDirectUSD10 = x.SellingPriceDirectUSD10,
SellingPriceWarehouseSEK = x.SellingPriceWarehouseSEK,
}
).ToList<ProductListItem>().GroupBy(u => u.FatherProduct).Select(x => x.FirstOrDefault());
return (IEnumerable<ProductListItem>)testList;
}
IEnumerable<ProductListItem> IProductRepository.FetchProductByID(int id)
{
/* SQL:EN FÖR ATT HÄMTA UT ALLTING
*
* select * from tProductGroup as tpg, tProductGroupDetail as tgd, tProduct as tp, tMaterialColor as tmc, tProductPicture as tpp, tPicture as tpi
where tpg.ProductGroupID = 3
and tpg.ProductGroupID = tgd.ProductGroupID
and tgd.ProductID = tp.ProductID
and tp.MaterialColorID = tmc.MaterialColorID
and tp.ProductID = tpp.ProductID
and tpp.PictureID = tpi.PictureID
*/
var productgroupID = (from u in dbContext.tProduct
from xx in dbContext.tProductGroupDetail
where u.ProductID == id
&& u.ProductID == xx.ProductID
select xx.ProductGroupID).Single<int>();
var test =
(from u in dbContext.tProductGroup
from v in dbContext.tProductGroupDetail
from x in dbContext.tProduct
from y in dbContext.tProductPicture
from z in dbContext.tPicture
from zz in dbContext.tMaterialColor
from xx in dbContext.tFrameColor
from yy in dbContext.tCategory
from uu in dbContext.tCategoryType
from ii in dbContext.tMaterial
from jj in dbContext.tProductMaterial
where v.ProductGroupID == productgroupID
&& v.ProductID == x.ProductID
&& u.ProductGroupID == v.ProductGroupID
&& v.ProductID == x.ProductID
&& x.MaterialColorID == zz.MaterialColorID
&& x.FrameColorID == xx.FrameColorID
&& x.ProductID == y.ProductID
&& y.PictureID == z.PictureID
&& z.Width == 700
&& x.CategoryID == yy.CategoryID
&& yy.CategoryTypeID == uu.CategoryTypeID
&& x.ProductID == jj.ProductID
&& jj.MaterialID == ii.MaterialID
select new ProductListItem
{
ImgUrl = z.Picture,
ProductID = x.ProductID,
ProductName = u.Name, // Här måste vi hämta in PappaProduktensnamn!
SupplierArticleNumber = x.SupplierArticleNumber,
GardenArtArticleNumber = x.GardenArtArticleNumber,
Comment = x.Comment,
Description = x.Description,
MaterialColor = zz.CssName,
MaterialType = ii.Name,
FrameColor = xx.CssName,
ProductSizeWidth = x.ProductSizeWidth,
ProductSizeHeight = x.ProductSizeHeight,
ProductSizeDepth = x.ProductSizeDepth,
PackageInfo = x.PackageInfo,
Package = x.Package,
PackageSize = x.PackageSize,
GrossWeight = x.GrossWeight,
NetWeight = x.NetWeight,
ItemsPerContainer = x.ItemsPerContainer,
VolumePerItem = x.VolumePerItem,
Factory = x.Factory,
Supplier = x.Supplier,
CostUSD = x.CostUSD,
SellingPriceDirectUSD20 = x.SellingPriceDirectUSD20,
SellingPriceDirectUSD10 = x.SellingPriceDirectUSD10,
SellingPriceWarehouseSEK = x.SellingPriceWarehouseSEK,
ProductCategoryTypeDisplay = uu.Name
}
).ToList<ProductListItem>(); //.GroupBy(u => u.MaterialColor).Select(x => x.FirstOrDefault());
return test;
}
}
}```
AdminController.cs
```using GardenArt.Infrastructure.Uploaders;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GardenArt.Controllers
{
public class AdminController : Controller
{
//
// GET: /Admin/
[Authorize(Roles = "admin")]
public ActionResult Index()
{
return View();
}
[Authorize(Roles = "admin")]
public ActionResult ImageUpload()
{
return View();
}
[HttpPost]
public ActionResult ImageUpload(List<HttpPostedFileBase> image)
{
ViewBag.AntalBilder = FileSaver(image);
return View();
}
public string FileSaver(List<HttpPostedFileBase> Files)
{
string retString = "";
if (Files != null)
{
retString = "Du laddade upp " + Files.Count.ToString() + " bilder!";
foreach (var picture in Files)
{
if (picture.ContentLength > 0)
{
var filename = Path.GetFileName(picture.FileName);
var path = Path.Combine(Server.MapPath("~/Images/Products"), filename);
picture.SaveAs(path);
}
}
}
else
{
retString = "Något gick fel när du laddade upp din bilder!";
}
return retString;
}
}
}
```
INavDataRepository.cs
```using GardenArt.Core.Repository.Interfaces;
using GardenArt.Infrastructure.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenArt.Core.Interfaces.Repository
{
interface INavDataRepository : IRepository<tSet>
{
IEnumerable<tSet> FetchAllColletionNamesAndIds();
IEnumerable<tCategory> FetchAllCategoryNamesAndIds();
IEnumerable<IGrouping<string, tNewsItem>> FetchAllNewsAndIds();
}
}
```
NewsRepository.cs
```using GardenArt.Core.Interfaces.Repository;
using GardenArt.Infrastructure.Database;
using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.Core.Repository
{
public class NewsRepository : GenericRepository<tNewsItem>, INewsRepository
{
private Entities dbcontext;
public NewsRepository(Entities dbcontext) : base(dbcontext)
{
this.dbcontext = dbcontext;
}
public NewsListItem FetchNewsById(int id)
{
var xx= (from x in dbcontext.tNewsItem
where x.NewsItemID == id
select new NewsListItem
{
NewsCreated = x.DateCreated,
NewsModified = x.DateModified,
NewsPublished = x.Published,
NewsText = x.Text,
NewsTitle = x.Title
}
).FirstOrDefault<NewsListItem>();
xx.Newspicture = (from x in dbcontext.tNewsItem
from y in dbcontext.tNewsItemPicture
from z in dbcontext.tPicture
where x.NewsItemID == id
&& x.NewsItemID == y.NewsItemID
&& y.PictureID == z.PictureID
select z.Picture).ToList<string>();
return xx;
}
}
}```
tOrderStatus.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
using System.Collections.Generic;
public partial class tOrderStatus
{
public tOrderStatus()
{
this.tOrder = new HashSet<tOrder>();
}
public int OrderStatusID { get; set; }
public string Name { get; set; }
public virtual ICollection<tOrder> tOrder { get; set; }
}
}
```
ICollectionModel.cs
```using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenArt.Core.Interfaces.Models
{
interface ICollectionModel
{
IEnumerable<CollectionListItem> ListOfCollections {get; set;}
CollectionListItem OneCollectionFromID { get; set; }
}
}
```
CategoryController.cs
```using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GardenArt.Infrastructure.Database;
using GardenArt.Models;
using GardenArt.ViewModels;
namespace GardenArt.Controllers
{
public class CategoryController : Controller
{
private CategoryViewModel _categoryViewModel;
public CategoryController()
{
_categoryViewModel = new CategoryViewModel();
}
//
// GET: /Category/
public ActionResult Index()
{
return _categoryViewModel.Index();
}
//
// GET: /Category/Details/5
public ActionResult Details(int id = 0)
{
return _categoryViewModel.Details(id);
}
//
// GET: /Category/Create
public ActionResult Create()
{
return _categoryViewModel.Create();
}
//
// POST: /Category/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CategoryListItemViewModel categoryListItem)
{
return _categoryViewModel.Create(categoryListItem);
}
//
// GET: /Category/Edit/5
public ActionResult Edit(int id = 0)
{
return _categoryViewModel.Edit(id);
}
//
// POST: /Category/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CategoryListItemViewModel categoryListItem)
{
return _categoryViewModel.Edit(categoryListItem);
}
//
// GET: /Category/Delete/5
public ActionResult Delete(int id = 0)
{
return _categoryViewModel.Delete(id);
}
//
// POST: /Category/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
return _categoryViewModel.DeleteConfirmed(id);
}
protected override void Dispose(bool disposing)
{
_categoryViewModel.Dispose();
base.Dispose(disposing);
}
}
}```
NewsDisplayViewModel.cs
```using GardenArt.Core.Interfaces;
using GardenArt.Infrastructure.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.ViewModels
{
public class NewsDisplayViewModel : IViewModel<NewsDisplayViewModel>
{
IEnumerable<IGrouping<string,tNewsItem>> _listOfNews;
public IEnumerable<IGrouping<string,tNewsItem>> ListOfNews
{
get
{
return _listOfNews;
}
set
{
_listOfNews = value;
}
}
public NewsDisplayViewModel GetViewModel()
{
throw new NotImplementedException();
}
}
}```
WholesalerController.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GardenArt.Controllers
{
public class WholesalerController : Controller
{
//
// GET: /Wholesaler/
public ActionResult Index()
{
return View();
}
}
}
```
gadb.Context.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
public partial class Entities : DbContext
{
public Entities()
: base("name=Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<tCategory> tCategory { get; set; }
public DbSet<tCategoryPicture> tCategoryPicture { get; set; }
public DbSet<tCustomer> tCustomer { get; set; }
public DbSet<tMaterial> tMaterial { get; set; }
public DbSet<tOrder> tOrder { get; set; }
public DbSet<tOrderDetail> tOrderDetail { get; set; }
public DbSet<tOrderStatus> tOrderStatus { get; set; }
public DbSet<tPicture> tPicture { get; set; }
public DbSet<tProductAttribute> tProductAttribute { get; set; }
public DbSet<tProductAttributeValue> tProductAttributeValue { get; set; }
public DbSet<tProductPicture> tProductPicture { get; set; }
public DbSet<tSet> tSet { get; set; }
public DbSet<tSetDetail> tSetDetail { get; set; }
public DbSet<tSetPicture> tSetPicture { get; set; }
public DbSet<tNewsItem> tNewsItem { get; set; }
public DbSet<tNewsItemPicture> tNewsItemPicture { get; set; }
public DbSet<tFrame> tFrame { get; set; }
public DbSet<tSupplier> tSupplier { get; set; }
public DbSet<tWarehouse> tWarehouse { get; set; }
public DbSet<tWarehouseLocation> tWarehouseLocation { get; set; }
public DbSet<tFrameColor> tFrameColor { get; set; }
public DbSet<tMaterialColor> tMaterialColor { get; set; }
public DbSet<tProductGroup> tProductGroup { get; set; }
public DbSet<tProductGroupDetail> tProductGroupDetail { get; set; }
public DbSet<tProductGroupPicture> tProductGroupPicture { get; set; }
public DbSet<tCategoryType> tCategoryType { get; set; }
public DbSet<tProductMaterial> tProductMaterial { get; set; }
public DbSet<tProduct> tProduct { get; set; }
public virtual ObjectResult<p_ga_getPicturesByItemAndType_Result> p_ga_getPicturesByItemAndType(Nullable<int> itemID, string itemTypeName)
{
var itemIDParameter = itemID.HasValue ?
new ObjectParameter("ItemID", itemID) :
new ObjectParameter("ItemID", typeof(int));
var itemTypeNameParameter = itemTypeName != null ?
new ObjectParameter("ItemTypeName", itemTypeName) :
new ObjectParameter("ItemTypeName", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<p_ga_getPicturesByItemAndType_Result>("p_ga_getPicturesByItemAndType", itemIDParameter, itemTypeNameParameter);
}
public virtual int sp_alterdiagram(string diagramname, Nullable<int> owner_id, Nullable<int> version, byte[] definition)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
var versionParameter = version.HasValue ?
new ObjectParameter("version", version) :
new ObjectParameter("version", typeof(int));
var definitionParameter = definition != null ?
new ObjectParameter("definition", definition) :
new ObjectParameter("definition", typeof(byte[]));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_alterdiagram", diagramnameParameter, owner_idParameter, versionParameter, definitionParameter);
}
public virtual int sp_creatediagram(string diagramname, Nullable<int> owner_id, Nullable<int> version, byte[] definition)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
var versionParameter = version.HasValue ?
new ObjectParameter("version", version) :
new ObjectParameter("version", typeof(int));
var definitionParameter = definition != null ?
new ObjectParameter("definition", definition) :
new ObjectParameter("definition", typeof(byte[]));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_creatediagram", diagramnameParameter, owner_idParameter, versionParameter, definitionParameter);
}
public virtual int sp_dropdiagram(string diagramname, Nullable<int> owner_id)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_dropdiagram", diagramnameParameter, owner_idParameter);
}
public virtual ObjectResult<sp_helpdiagramdefinition_Result> sp_helpdiagramdefinition(string diagramname, Nullable<int> owner_id)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<sp_helpdiagramdefinition_Result>("sp_helpdiagramdefinition", diagramnameParameter, owner_idParameter);
}
public virtual ObjectResult<sp_helpdiagrams_Result> sp_helpdiagrams(string diagramname, Nullable<int> owner_id)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<sp_helpdiagrams_Result>("sp_helpdiagrams", diagramnameParameter, owner_idParameter);
}
public virtual int sp_renamediagram(string diagramname, Nullable<int> owner_id, string new_diagramname)
{
var diagramnameParameter = diagramname != null ?
new ObjectParameter("diagramname", diagramname) :
new ObjectParameter("diagramname", typeof(string));
var owner_idParameter = owner_id.HasValue ?
new ObjectParameter("owner_id", owner_id) :
new ObjectParameter("owner_id", typeof(int));
var new_diagramnameParameter = new_diagramname != null ?
new ObjectParameter("new_diagramname", new_diagramname) :
new ObjectParameter("new_diagramname", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_renamediagram", diagramnameParameter, owner_idParameter, new_diagramnameParameter);
}
public virtual int sp_upgraddiagrams()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_upgraddiagrams");
}
public virtual ObjectResult<p_ga_getProductById_Result> p_ga_getProductById(Nullable<int> productID)
{
var productIDParameter = productID.HasValue ?
new ObjectParameter("ProductID", productID) :
new ObjectParameter("ProductID", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<p_ga_getProductById_Result>("p_ga_getProductById", productIDParameter);
}
}
}
```
OrderController.cs
```using GardenArt.Infrastructure.Database;
using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace GardenArt.Controllers
{
public class OrderController : Controller
{
public ActionResult Index()
{
var model = new OrderModels();
//JAG HACKADE LITE HÄR VI KAN KÖRA FurnitureTypeItem, men det går ju lika bra med SELECTLISTITEM?!
//Säker något senior devloper hack ;) Byt tillbaka om du vill ;)
//Egentligen ska vi lägga detta anropet i modellen.. i kontruktorn i detta fallet så modellen alltid fylls med data ;)
//och så att vi bara jobba rmed EN enda "objectcontext" samma som databasen ;) annars kommer vi få en för varje gång vi kör sidan.
//eller vad säger du Cliff?
return View(model);
}
//[HttpPost]
//public ActionResult Index(ProductViewModel model)
//{
// // check model.SelectedItemId here
// return View();
//}
public string AjaxAnswerTest(string ModelType)
{
string[] test = Request.Params.GetValues("ddlFurnitureTypeList");
string value = test[0];
Entities gadb = new Entities();
int numOfRows = gadb.tProduct.Where(x => x.CategoryID == int.Parse(value)).Count();
string result = "Du skickade " + value + "." + Environment.NewLine +
"Det finns " + numOfRows + " st produkter i denna kategori.";
return result;
}
public JsonResult AjaxAnswerJson()
{
string[] test = Request.Params.GetValues("ddlFurnitureTypeList");
string value = test[0];
using (Entities gadb = new Entities())
{
var jss = (from x in gadb.tProduct
where SqlFunctions.StringConvert((double)x.CategoryID) == value
select new SelectListItem { Text = x.GardenArtArticleNumber,
Value = SqlFunctions.StringConvert((double)x.ProductID)
});
return Json(jss.ToList(), JsonRequestBehavior.AllowGet);
}
}
public JsonResult AjaxProductBuilderJson()
{
string[] test = Request.Params.GetValues("ddlFurnitureModelList");
int value = Convert.ToInt32(test[0].Trim());
using (Entities gadb = new Entities())
{
var jss = (from p in gadb.tProduct
join pp in gadb.tProductPicture on p.ProductID equals pp.ProductID into join1
from j1 in join1.DefaultIfEmpty()
join pic in gadb.tPicture on j1.PictureID equals pic.PictureID into join2
from j2 in join2.DefaultIfEmpty()
where p.ProductID == value
select new
{
ProductID = p.ProductID,
ItemNumber = p.GardenArtArticleNumber,
Price = p.SellingPriceWarehouseSEK,
FullContainer = p.ItemsPerContainer,
Description = p.Description,
Picture = "../Images/" + (j2.Picture == null ? "noimage.gif" : j2.Picture)
});
// select p.*, ISNULL(pic.Picture, '') Picture from tProduct p
// left outer join tProductPicture pp on pp.ProductID = p.ProductID
// left outer join tPicture pic on pic.PictureID = pp.PictureID
//where p.ProductID = 1
//var jss = (from x in gadb.t_ga_product
// where x.ProductID == value
// select new
// {
// ProductID = x.ProductID,
// ItemNumber = x.ItemNumber,
// Price = x.FobGuangzhouUSD,
// FullContainer = x.Quantity40GP,
// Description = x.Description,
// Picture = "../Images/Products/" + x.Picture
// });
return Json(jss.ToList(), JsonRequestBehavior.AllowGet);
}
}
[HttpPost]
public JsonResult AjaxSendOrderJson(OrderModel order)
{
string htmlTable = "<table>" +
"<tr>" +
"<th>Item Number</th>" +
"<th>Price (unit)</th>" +
"<th>Quantity</th>" +
"</tr>";
foreach (OrderDetailModel orderDetail in order.Products)
{
htmlTable += "<tr>" +
"<td>" + orderDetail.ItemNumber + "</td>" +
"<td>" + orderDetail.Price + "</td>" +
"<td>" + orderDetail.Quantity + "</td>" +
"</tr>";
}
htmlTable += "</table>";
var from = "codem.ninja@outlook.com";
var to = order.EmailToAddress;
var subject = "Gardenart - New order";
var body = "<b>Order details</b><br /><br />" +
htmlTable + "<br /><br />" +
"Price: " + order.TotalPrice;
var result = SendMail(from, to, subject, body);
return Json(result, JsonRequestBehavior.AllowGet);
}
private string SendMail(string from, string to, string subject, string body)
{
var ret = "";
try
{
MailMessage mail = new MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from);
mail.Subject = subject;
string Body = body;
mail.Body = Body;
mail.IsBodyHtml = true;
mail.BodyEncoding = UTF8Encoding.UTF8;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.live.com";
smtp.Port = 587;
smtp.Timeout = 10000;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential
("magnus.kihlberg72@gmail.com", "fingroda1972");// Enter senders User name and password
smtp.EnableSsl = true;
smtp.Send(mail);
ret = "Order sent.";
}
catch (Exception ex) {
ret = "Error message: " + ex.Message;
}
return ret;
}
}
// ordermodell:
public class OrderModel
{
public string NumberOfProducts { get; set; }
public string TotalFullContainer { get; set; }
public string TotalPrice { get; set; }
public string OrderID { get; set; }
public List<OrderDetailModel> Products { get; set; }
public string EmailToAddress { get; set; }
}
public class OrderDetailModel
{
public int OrderDetailID { get; set; }
public int OrderID { get; set; }
public int ProductID { get; set; }
public int Quantity { get; set; }
public int FullContainer { get; set; }
public string Price { get; set; }
public string ItemNumber { get; set; }
}
}
```
tPicture.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
using System.Collections.Generic;
public partial class tPicture
{
public tPicture()
{
this.tCategoryPicture = new HashSet<tCategoryPicture>();
this.tProductPicture = new HashSet<tProductPicture>();
this.tSetPicture = new HashSet<tSetPicture>();
this.tNewsItemPicture = new HashSet<tNewsItemPicture>();
this.tProductGroupPicture = new HashSet<tProductGroupPicture>();
}
public int PictureID { get; set; }
public string Picture { get; set; }
public int Width { get; set; }
public virtual ICollection<tCategoryPicture> tCategoryPicture { get; set; }
public virtual ICollection<tProductPicture> tProductPicture { get; set; }
public virtual ICollection<tSetPicture> tSetPicture { get; set; }
public virtual ICollection<tNewsItemPicture> tNewsItemPicture { get; set; }
public virtual ICollection<tProductGroupPicture> tProductGroupPicture { get; set; }
}
}
```
CollectionDisplayViewModel.cs
```using GardenArt.Core.Interfaces;
using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.ViewModels
{
public class CollectionDisplayViewModel : IViewModel<CollectionDisplayViewModel>
{
private CollectionListItem _OneCollectionFromID;
private IEnumerable<CollectionListItem> _listOfCollections;
public CollectionListItem OneCollectionFromID
{
get { return _OneCollectionFromID; }
set { _OneCollectionFromID = value; }
}
public IEnumerable<CollectionListItem> ListOfCollections
{
get { return _listOfCollections; }
set { _listOfCollections = value; }
}
public CollectionDisplayViewModel GetViewModel()
{
throw new NotImplementedException();
}
}
}```
ArticleDisplayViewModel.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GardenArt.Core.Interfaces;
using GardenArt.Models;
using GardenArt.Models.Containers;
namespace GardenArt.ViewModels
{
public class ArticleDisplayViewModel : IViewModel<ArticleDisplayViewModel>
{
//Holds one article Based On ID!
private IEnumerable<ProductListItem> _OneDetailedArticle;
private ProductContainer _ProductContainer;
public ArticleDisplayViewModel GetViewModel()
{
throw new NotImplementedException();
}
public IEnumerable<ProductListItem> OneArticleFromID
{
get
{
return _OneDetailedArticle;
}
set
{
_OneDetailedArticle = value;
}
}
public ProductContainer ProductContainer
{
get
{
return _ProductContainer;
}
set
{
_ProductContainer = value;
}
}
}
}```
ICollectionRepository.cs
```using GardenArt.Core.Repository.Interfaces;
using GardenArt.Infrastructure.Database;
using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenArt.Core.Interfaces.Repository
{
interface ICollectionRepository : IRepository<tSet>
{
IEnumerable<CollectionListItem> FetchById(int id);
IEnumerable<CollectionListItem> FetchAll();
IEnumerable<ProductListItem> FetchFromCollection(int id);
}
}
```
ProductContainer.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.Models.Containers
{
public class ProductContainer
{
private ProductListItem _motherProduct;
private IEnumerable<ProductListItem> _listOfProductsInMotherGroup;
public ProductListItem MotherProduct
{
get { return _motherProduct; }
set { _motherProduct = value; }
}
public IEnumerable<ProductListItem> ListOfProductsInMotherGroup
{
get { return _listOfProductsInMotherGroup; }
set { _listOfProductsInMotherGroup = value; }
}
}
}```
INewsModel.cs
```using GardenArt.Infrastructure.Database;
using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenArt.Core.Interfaces.Models
{
interface INewsModel
{
IEnumerable<IGrouping<string,tNewsItem>> ListOfNews { get; }
NewsListItem OneNewsById { get; }
}
}
```
NewsController.cs
```using GardenArt.Core.Interfaces;
using GardenArt.Domain.Factory;
using GardenArt.Models;
using GardenArt.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GardenArt.Controllers
{
public class NewsController : Controller
{
IFactory factory = new Factory();
public ActionResult Index()
{
var mappedModel = factory.BuildAndMap<NewsModel, NewsDisplayViewModel>();
return View(mappedModel);
}
public ActionResult newsitem(int id)
{
var mappedModel = factory.BuildAndMap<NewsModel, NewsOneViewModel>(id);
return View(mappedModel);
}
}
}
```
HomeController.cs
```using GardenArt.Core.Repository;
using GardenArt.Core.Repository.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GardenArt.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
IUnitOfWork iuo = new UnitOfWork();
IProductRepository ipo = iuo.ProductRepository;
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
// var sture = "muhahhaha har ni fått in mig har ni laddat det senaste!";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult History()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult New()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
```
IViewModel.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GardenArt.Core.Interfaces
{
//LOL @ MAKING INTERFACES PUBLIC!
public interface IViewModel<T>
{
T GetViewModel();
}
}
```
CategoryViewModel.cs
```using GardenArt.Infrastructure.Database;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GardenArt.ViewModels
{
public class CategoryViewModel : Controller
{
private Entities _db;
public CategoryViewModel()
{
_db = new Entities();
}
public ViewResult Index()
{
return View(GetCategoryList());
}
private List<CategoryListItemViewModel> GetCategoryList()
{
List<CategoryListItemViewModel> categoryList = new List<CategoryListItemViewModel>();
//CategoryListItemViewModel listItem = new CategoryListItemViewModel();
//listItem.CategoryID = 0;
//listItem.Name = "Välj kategori";
//categoryList.Add(listItem);
foreach (var dbItem in _db.tCategory.ToList())
{
CategoryListItemViewModel listItem = new CategoryListItemViewModel();
listItem.CategoryID = dbItem.CategoryID;
listItem.Name = dbItem.Name;
listItem.Description = dbItem.Description;
categoryList.Add(listItem);
}
return categoryList;
}
public ActionResult Details(int id)
{
return this.GetCategoryListItem(id);
}
public ActionResult GetCategoryListItem(int id)
{
tCategory tcategory = _db.tCategory.Find(id);
CategoryListItemViewModel categoryItem = new CategoryListItemViewModel();
if (tcategory == null)
{
return HttpNotFound();
}
else
{
categoryItem.CategoryID = tcategory.CategoryID;
categoryItem.Name = tcategory.Name;
categoryItem.Description = tcategory.Description;
}
return View(categoryItem);
}
public ActionResult Edit(int id)
{
return this.GetCategoryListItem(id);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CategoryListItemViewModel categoryListItem)
{
if (ModelState.IsValid)
{
tCategory tcategory = _db.tCategory.Find(categoryListItem.CategoryID);
tcategory.Name = categoryListItem.Name;
tcategory.Description = categoryListItem.Description;
_db.Entry(tcategory).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(categoryListItem);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CategoryListItemViewModel categoryListItem)
{
if (ModelState.IsValid)
{
tCategory tcategory = new tCategory();
tcategory.Name = categoryListItem.Name;
tcategory.Description = categoryListItem.Description;
_db.tCategory.Add(tcategory);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(categoryListItem);
}
public ActionResult Delete(int id = 0)
{
return this.GetCategoryListItem(id);
}
//
// POST: /Category/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
tCategory tcategory = _db.tCategory.Find(id);
_db.tCategory.Remove(tcategory);
_db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
_db.Dispose();
base.Dispose(disposing);
}
}
}```
INavData.cs
```using GardenArt.Infrastructure.Database;
using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenArt.Core.Interfaces.NavData
{
interface INavData
{
IEnumerable<ProductListItem> AllCollections { get; }
IEnumerable<ProductListItem> AllCategories { get; }
IEnumerable<IGrouping<string,tNewsItem>> AllNews { get; }
}
}
```
ProductListItem.cs
```using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.Models
{
public class ProductListItem : IEnumerable
{
public string ImgUrl { get; set; }
public string ProductName { get; set; }
public int ProductID { get; set; }
public int FatherProduct { get; set; }
public string ProductCategoryName { get; set; }
public int ProductCategoryID { get; set; }
public string SupplierArticleNumber { get; set; }
public string GardenArtArticleNumber { get; set; }
public string Comment { get; set; }
public string Description { get; set; }
public string MaterialType { get; set; }
public int? FrameColorID { get; set; }
public int? MaterialColorID { get; set; }
public string MaterialColor { get; set; }
public string FrameColor { get; set; }
public int ProductSizeWidth { get; set; }
public int ProductSizeHeight { get; set; }
public int ProductSizeDepth { get; set; }
public string PackageInfo { get; set; }
public string Package { get; set; }
public string PackageSize { get; set; }
public decimal GrossWeight { get; set; }
public decimal NetWeight { get; set; }
public int ItemsPerContainer { get; set; }
public decimal VolumePerItem { get; set; }
public string Factory { get; set; }
public string Supplier { get; set; }
public decimal CostUSD { get; set; }
public decimal PurchasePriceUSD { get; set; }
public decimal SellingPriceDirectUSD20 { get; set; }
public decimal SellingPriceDirectUSD10 { get; set; }
public decimal SellingPriceWarehouseSEK { get; set; }
public decimal SellingPriceConsumerSEK { get; set; }
public string ProductCategoryTypeDisplay { get; set; }
public List<string> ProductColors { get; set; }
public List<string> ProductFrames { get; set; }
public List<string> ProductMaterials { get; set; }
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
}```
INewsRepository.cs
```using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenArt.Core.Interfaces.Repository
{
interface INewsRepository
{
NewsListItem FetchNewsById(int id);
}
}
```
Imapper.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.Core.Interfaces.Mapper
{
public interface Imapper
{
Tmodel MapViewModelToModel<TviewModel, Tmodel>(TviewModel source, Tmodel destination)
where Tmodel : class, IModel<Tmodel>, new()
where TviewModel : class, IViewModel<TviewModel>, new();
TviewModel MapModelToViewModel<Tmodel, TviewModel>(Tmodel source, TviewModel destination)
where TviewModel : class, IViewModel<TviewModel>, new()
where Tmodel : class, IModel<Tmodel>, new();
}
}```
Mapper.cs
```using GardenArt.Core.Interfaces.Mapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.Domain
{
public class Mapper : Imapper
{
Tmodel Imapper.MapViewModelToModel<TviewModel, Tmodel>(TviewModel source, Tmodel destination)
{
var destProperties = destination.GetType().GetProperties();
foreach (var sourceProperty in source.GetType().GetProperties())
{
foreach (var destProperty in destProperties)
{
if (destProperty.Name == sourceProperty.Name && destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
{
destProperty.SetValue(destination, sourceProperty.GetValue(
source, new object[] { }), new object[] { });
break;
}
}
}
return destination;
}
TviewModel Imapper.MapModelToViewModel<Tmodel, TviewModel>(Tmodel source, TviewModel destination)
{
var destProperties = destination.GetType().GetProperties();
foreach (var sourceProperty in source.GetType().GetProperties())
{
foreach (var destProperty in destProperties)
{
if (destProperty.Name == sourceProperty.Name && destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
{
destProperty.SetValue(destination, sourceProperty.GetValue(
source, new object[] { }), new object[] { });
break;
}
}
}
return destination;
}
}
}```
NewsOneViewModel.cs
```using GardenArt.Core.Interfaces;
using GardenArt.Infrastructure.Database;
using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.ViewModels
{
public class NewsOneViewModel : IViewModel<NewsOneViewModel>
{
NewsListItem _OneNewsById;
IEnumerable<IGrouping<string, tNewsItem>> _listOfNews;
public NewsOneViewModel GetViewModel()
{
throw new NotImplementedException();
}
public NewsListItem OneNewsById
{
get { return _OneNewsById; }
set { _OneNewsById = value; }
}
public IEnumerable<IGrouping<string, tNewsItem>> ListOfNews
{
get { return _listOfNews; }
set { _listOfNews = value;}
}
}
}```
CollectionListItem.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.Models
{
public class CollectionListItem
{
public List<string> ImgList { get; set; }
public string ImgUrl { get; set; }
public string CollectionName { get; set; }
public string Description { get; set; }
public int CollectionID { get; set; }
}
}```
CategoryListItemViewModel.cs
```using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GardenArt.ViewModels
{
public class CategoryListItemViewModel
{
[Display(Name = "ID")]
public Int32 CategoryID { get; set; }
[Required(ErrorMessage = "Kategori måste fyllas i")]
[DataType(DataType.Text)]
[Display(Name = "Kategori")]
public String Name { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Beskrivning")]
public String Description { get; set; }
}
}```
tProductAttribute.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
using System.Collections.Generic;
public partial class tProductAttribute
{
public tProductAttribute()
{
this.tProductAttributeValue = new HashSet<tProductAttributeValue>();
}
public int ProductAttributeID { get; set; }
public string Name { get; set; }
public int SortOrder { get; set; }
public string Description { get; set; }
public virtual ICollection<tProductAttributeValue> tProductAttributeValue { get; set; }
}
}
```
GenericRepository.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GardenArt.Core.Repository.Interfaces;
using GardenArt.Infrastructure.Database;
using System.Data.Entity;
namespace GardenArt.Core.Repository
{
public abstract class GenericRepository<T> : IRepository<T> where T : class
{
private Entities _entityContext;
protected DbSet<T> dbSet;
internal GenericRepository(Entities entitiesContext)
{
this._entityContext = entitiesContext;
this.dbSet = entitiesContext.Set<T>();
}
IEnumerable<T> IRepository<T>.BaseFetchAll()
{
return (from x in dbSet select x).AsEnumerable<T>();
}
IEnumerable<T> IRepository<T>.BaseFindById(int id)
{
throw new NotImplementedException();
}
void IRepository<T>.BaseAdd(T entity)
{
throw new NotImplementedException();
}
void IRepository<T>.BaseDelete(T entity)
{
throw new NotImplementedException();
}
}
}```
IUploader.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace GardenArt.Infrastructure.Uploaders
{
public interface IUploader
{
IEnumerable<HttpPostedFileBase> files { get; set; }
}
}
```
ProductCategoryViewModel.cs
```using GardenArt.Core.Interfaces;
using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.ViewModels
{
public class ProductCategoryViewModel : IViewModel<ProductCategoryViewModel>
{
private IEnumerable<ProductListItem> _listOfProductsFromCategory;
private IEnumerable<ProductListItem> _listOfCategories;
public IEnumerable<ProductListItem> ListOfProductsFromCategory
{
get
{
return _listOfProductsFromCategory;
}
set
{
_listOfProductsFromCategory = value;
}
}
public IEnumerable<ProductListItem> ListOfCategories
{
get
{
return _listOfCategories;
}
set
{
_listOfCategories = value;
}
}
public ProductCategoryViewModel GetViewModel()
{
throw new NotImplementedException();
}
}
}```
MaterialViewModel.cs
```using GardenArt.Infrastructure.Database;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GardenArt.ViewModels
{
public class MaterialViewModel : Controller
{
private Entities _db;
public MaterialViewModel()
{
_db = new Entities();
}
public ViewResult Index()
{
return View(GetMaterialList());
}
private List<MaterialListItemViewModel> GetMaterialList()
{
List<MaterialListItemViewModel> materialList = new List<MaterialListItemViewModel>();
foreach (var dbItem in _db.tMaterial.ToList())
{
MaterialListItemViewModel listItem = new MaterialListItemViewModel();
listItem.MaterialID = dbItem.MaterialID;
listItem.Name = dbItem.Name;
listItem.Description = dbItem.Description;
materialList.Add(listItem);
}
return materialList;
}
public ActionResult Details(int id)
{
return this.GetMaterialListItem(id);
}
public ActionResult GetMaterialListItem(int id)
{
tMaterial tmaterial = _db.tMaterial.Find(id);
MaterialListItemViewModel materialItem = new MaterialListItemViewModel();
if (tmaterial == null)
{
return HttpNotFound();
}
else
{
materialItem.MaterialID = tmaterial.MaterialID;
materialItem.Name = tmaterial.Name;
materialItem.Description = tmaterial.Description;
}
return View(materialItem);
}
public ActionResult Edit(int id)
{
return this.GetMaterialListItem(id);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(MaterialListItemViewModel materialListItem)
{
if (ModelState.IsValid)
{
tMaterial tmaterial = _db.tMaterial.Find(materialListItem.MaterialID);
tmaterial.Name = materialListItem.Name;
tmaterial.Description = materialListItem.Description;
_db.Entry(tmaterial).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(materialListItem);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(MaterialListItemViewModel materialListItem)
{
if (ModelState.IsValid)
{
tMaterial tmaterial = new tMaterial();
tmaterial.Name = materialListItem.Name;
tmaterial.Description = materialListItem.Description;
_db.tMaterial.Add(tmaterial);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(materialListItem);
}
public ActionResult Delete(int id = 0)
{
return this.GetMaterialListItem(id);
}
//
// POST: /Category/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
tMaterial tmaterial = _db.tMaterial.Find(id);
_db.tMaterial.Remove(tmaterial);
_db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
_db.Dispose();
base.Dispose(disposing);
}
}
}```
CollectionRepository.cs
```using GardenArt.Core.Interfaces.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GardenArt.Models;
using GardenArt.Infrastructure.Database;
using GardenArt.Core.Repository.Interfaces;
namespace GardenArt.Core.Repository
{
public class CollectionRepository : GenericRepository<tSet>, ICollectionRepository
{
private Entities dbContext;
public CollectionRepository(Entities dbContext) : base(dbContext)
{
// TODO: Complete member initialization
this.dbContext = dbContext;
}
public IEnumerable<CollectionListItem> FetchById(int id)
{
return (from x in dbContext.tSet
from y in dbContext.tSetPicture
from z in dbContext.tPicture
where x.SetID == id
&& x.SetID == y.SetID
&& y.PictureID == z.PictureID
&& z.Width == 700
select new CollectionListItem
{
ImgUrl = z.Picture,
CollectionName = x.Name,
Description = x.Description,
CollectionID = x.SetID
})
.OrderBy(p => p.CollectionName)
.ToList<CollectionListItem>();
}
public IEnumerable<CollectionListItem> FetchAll()
{
return (from x in dbContext.tSet
from y in dbContext.tSetPicture
from z in dbContext.tPicture
where x.SetID == y.SetID
&& y.PictureID == z.PictureID
&& z.Width == 250
select new CollectionListItem
{
ImgUrl = z.Picture,
CollectionName = x.Name,
Description = x.Description,
CollectionID = x.SetID
})
.OrderBy(p => p.CollectionName)
.ToList<CollectionListItem>();
}
public IEnumerable<ProductListItem> FetchFromCollection(int id)
{
return (from u in dbContext.tSet
from v in dbContext.tProduct
from x in dbContext.tProductPicture
from y in dbContext.tPicture
from z in dbContext.tSetDetail
from uu in dbContext.tCategory
from ii in dbContext.tProductGroupDetail
where u.SetID == id
&& u.SetID == z.SetID
&& z.ProductID == v.ProductID
&& v.ProductID == x.ProductID
&& x.PictureID == y.PictureID
&& uu.CategoryID == v.CategoryID
&& ii.ProductID ==v.ProductID
&& y.Width == 250
select new ProductListItem
{
ImgUrl = y.Picture,
ProductCategoryName = uu.Name,
ProductID = v.ProductID,
ProductCategoryID = u.SetID,
ProductName = v.Name,
FatherProduct = ii.ProductGroupID,
SupplierArticleNumber = v.SupplierArticleNumber,
GardenArtArticleNumber = v.GardenArtArticleNumber,
Comment = v.Comment,
Description = v.Description,
FrameColorID = v.FrameColorID,
MaterialColorID = v.MaterialColorID,
ProductSizeWidth = v.ProductSizeWidth,
ProductSizeHeight = v.ProductSizeHeight,
ProductSizeDepth = v.ProductSizeHeight,
PackageInfo = v.PackageInfo,
Package = v.Package,
PackageSize = v.PackageSize,
GrossWeight = v.GrossWeight,
NetWeight = v.NetWeight,
ItemsPerContainer = v.ItemsPerContainer,
VolumePerItem = v.VolumePerItem,
Factory = v.Factory,
Supplier = v.Supplier,
CostUSD = v.CostUSD,
PurchasePriceUSD = v.PurchasePriceUSD,
SellingPriceDirectUSD20 = v.SellingPriceDirectUSD20,
SellingPriceDirectUSD10 = v.SellingPriceDirectUSD10,
SellingPriceWarehouseSEK = v.SellingPriceWarehouseSEK,
SellingPriceConsumerSEK = v.SellingPriceConsumerSEK,
}).ToList().GroupBy(x => x.FatherProduct).Select(u => u.FirstOrDefault());
}
}
}```
p_ga_getProductById_Result.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
public partial class p_ga_getProductById_Result
{
public int ProductID { get; set; }
public string ItemNumber { get; set; }
public Nullable<decimal> FobGuangzhouUSD { get; set; }
public Nullable<int> Quantity40GP { get; set; }
public string Description { get; set; }
public string Picture { get; set; }
}
}
```
OrderModels.cs
```
using GardenArt.Infrastructure.Database;
using System;
using System.Collections.Generic;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GardenArt.Models
{
public class OrderModels
{
public OrderModels()
{
if (this.DropDownList == null)
{
Entities gadb = new Entities();
var items = (IEnumerable<SelectListItem>)gadb.tCategory
.GroupBy(x => x.Name)
.Select(g => g.FirstOrDefault())
.Select(x => new SelectListItem() { Value = SqlFunctions.StringConvert((double)x.CategoryID), Text = x.Name });
this.DropDownList = new SelectList
(
items, "Value", "Text"
);
}
}
public SelectList DropDownList { get; set; }
}
}```
IProductModel.cs
```using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GardenArt.Core.Interfaces
{
public interface IProductModel
{
IEnumerable<ProductListItem> ListOfProducts { get; set; }
IEnumerable<ProductListItem> OneArticleFromID { get; set; }
IEnumerable<ProductListItem> ProductCategories { get; set; }
}
}
```
tWarehouseLocation.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
using System.Collections.Generic;
public partial class tWarehouseLocation
{
public tWarehouseLocation()
{
this.tWarehouse = new HashSet<tWarehouse>();
}
public int WarehouseLocationID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
public string Country { get; set; }
public virtual ICollection<tWarehouse> tWarehouse { get; set; }
}
}
```
ProductDisplayViewModel.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GardenArt.Models;
using GardenArt.Core.Interfaces;
namespace GardenArt.ViewModels
{
public class ProductDisplayViewModel : IViewModel<ProductDisplayViewModel>
{
private IEnumerable<ProductListItem> _ListOfProducts;
private IEnumerable<ProductListItem> _ProductCategories;
public ProductDisplayViewModel GetViewModel()
{
throw new NotImplementedException();
}
public IEnumerable<ProductListItem> ListOfProducts
{
get
{
return _ListOfProducts;
}
set
{
_ListOfProducts = value;
}
}
public IEnumerable<ProductListItem> ProductCategories
{
get
{
return _ProductCategories;
}
set
{
_ProductCategories = value;
}
}
}
}```
IModel.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GardenArt.Core.Interfaces
{
//LOL @ MAKING INTERFACES PUBLIC!
public interface IModel<T>
{
T GetDetailedModel<Tinput>(Tinput identifier);
}
}
```
ICategoryRepository.cs
```using GardenArt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenArt.Core.Interfaces.Repository
{
interface ICategoryRepository
{
CategoryListItem FetchById(int id);
IEnumerable<CategoryListItem> FetchAll();
}
}
```
tProductGroup.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GardenArt.Infrastructure.Database
{
using System;
using System.Collections.Generic;
public partial class tProductGroup
{
public tProductGroup()
{
this.tProductGroupDetail = new HashSet<tProductGroupDetail>();
this.tProductGroupPicture = new HashSet<tProductGroupPicture>();
}
public int ProductGroupID { get; set; }
public string Name { get; set; }
public virtual ICollection<tProductGroupDetail> tProductGroupDetail { get; set; }
public virtual ICollection<tProductGroupPicture> tProductGroupPicture { get; set; }
}
}
```
UnitOfWork.cs
```using GardenArt.Core.Interfaces.Repository;
using GardenArt.Core.Repository.Interfaces;
using GardenArt.Infrastructure.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GardenArt.Core.Repository
{
public class UnitOfWork : IUnitOfWork
{
private Entities dbContext = new Entities();
private IProductRepository _productrepo;
private ICollectionRepository _collectionrepo;
private INavDataRepository _navDatarepo;
private INewsRepository _newsrepo;
IProductRepository IUnitOfWork.ProductRepository
{
get {
if(this._productrepo == null)
this._productrepo = new ProductRepository(dbContext);
return this._productrepo;
}
}
ICollectionRepository IUnitOfWork.CollectionRepository
{
get {
if (this._collectionrepo == null)
this._collectionrepo = new CollectionRepository(dbContext);
return this._collectionrepo;
}
}
INavDataRepository IUnitOfWork.NavDataRepository
{
get
{
if (this._navDatarepo == null)
this._navDatarepo = new NavDataRepository(dbContext);
return this._navDatarepo;
}
}
INewsRepository IUnitOfWork.NewsRepository
{
get
{
if (this._newsrepo == null)
this._newsrepo = new NewsRepository(dbContext);
return this._newsrepo;
}
}
}
}```
IRepository.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenArt.Core.Repository.Interfaces
{
interface IRepository<T> where T : class
{
IEnumerable<T> BaseFetchAll();
IEnumerable<T> BaseFindById(int id);
void BaseAdd(T entity);
void BaseDelete(T entity);
}
}
```
|
8byt/feelings.solutions
|
8byt/feelings.solutions
README.md
```# feelings.solutions
A website for solving feelings.
```
|
8restrada/Stock-Market
|
8restrada/Stock-Market
market.js
```//imports your code to be tested
const Stock = require("./stock.js");
const Portfolio = require("./portfolio.js");
//Imports my code to run your examples against the economic forcast
//const Forecast = require("./forcast");
function main(){
//create all of your stocks
let s1 = new Stock("Electronic Arts", "EA","index", 112.48, 150);
let s2 = new Stock("Amazon", "AMZN","NASDAQ", );
let s3 = new Stock("Microsoft", "MSFT" "NASDAQ");
let s4 = new Stock("Apple","");
//build your Portfolio
let myport = new Portfolio();
myport.add();
myport.add();
myport.add();
myport.add();
//generate a test forcast
let economicStorm = new Forecast(myport);
console.log(economicStorm);
//build prediction
}
main();
```
portfolio.js
``` function Portfolio(){
//instance variable
this.stocks = [s];
//helper function
function findStock(trk,list){
//i represents the index of the trk you are looking for in this.stocks
for(let s = 0; s < this.stocks.lengths; s++){
if(tkr == this.stocks[s].ticker){
return s;
}
}
return -1;
}
//instance functions
this.add = function(stk){};
this.update = function(tkr,val){};
this.buy = function(tkr,qnt){};
this.sell = function(tkr,qnt){};
this.totalValue = function(){};
}
module.exports = Portfolio;
```
stock.js
```function Stock(n,t,i,v,q){
//Initialize the instance variables below
this.name=n;
this.ticker=t;
this.index=i;
this.value=v;
this.quantity=q;
//declare and define totalValue function below
function totalValue(){
totalValue=this.value*
}
//declarea and define sell(q) function below
}
module.exports = Stock;
```
|
8secz-johndpope/threejs
|
8secz-johndpope/threejs
index.js
```import Vue from 'vue'
import Home from "./component/home/index.vue"
import './index.less'
import App from './game/App'
let app;
new Vue({
render: h => h(Home)
}).$mount("#home");
window.onload = function(){
let canvas = document.getElementById("canvas");
app = new App(canvas);
app.setup();
}
var list = [];
var r = 10;
for(var i = 0; i <= 360; i += 10){
var x = r * Math.cos(i * Math.PI / 180);
var y = r * Math.sin(i * Math.PI / 180);
list.push(x, y);
}
console.log(list);
console.log(list.join(","))```
price.js
```import axios from "axios";
import Tooler from '../core/Tooler'
async function getList(){
return new Promise(async resolve=>{
let u = Tooler.getQueryString("u");
if(!u){
resolve();
}
var temp = u.split("-");
let id = temp.pop();
let sourcetype = temp.pop();
let res;
let host = getHost();
if(isERP()){
res = await axios.get(host + "/api/index/modelPrice", {
params: {
type: sourcetype,
id: id
}
});
}
else{
res = await axios.get(host + "/mapi/index.php", {
params: {
app:"modelshow",
fnn:"modelDetailById",
sourcetype: sourcetype,
yun3d_id:id
}
});
}
console.log(res);
if (res.data && res.data.code == 200) {
var list = [];
for(var i in res.data.datas){
var item = res.data.datas[i];
item.price = '-';
item.count = '-';
item.area = '-';
item.all = '-';
item.size = '-';
await getItem(item);
list.push(item);
}
var totalNum = 0;
var totalArea = 0;
var totalPrice = 0;
list.forEach(item=>{
totalNum += item.setnum;
totalArea += item.area;
totalPrice += item.all;
})
resolve({
list, totalNum, totalArea, totalPrice
})
}
resolve();
})
}
function isERP(){
if(location.search.indexOf('3d.mendaow.com') != -1 || location.search.indexOf('3d.mendaoyun.com') != -1){
return false;
}
return true;
}
function getHost(){
return location.search.match(/http.*?.com/)[0];
}
async function getItem(obj){
return new Promise(async resolve=>{
// var host = Tooler.isTest() ? 'http://3d.mendaow.com' : 'https://3d.mendaoyun.com';
var host = getHost();
var url = host + '/data/upload' + obj.plan_path + "/" + obj.pricejson_file;
console.log(url);
let res = await axios.get(url);
var data = res.data;
console.log(data);
obj.area = data.acreage;
obj.price = data.cost;
obj.count = data.items[0].discount;
obj.all = obj.count * obj.price * obj.setnum;
obj.size = [data.length || 1, data.height || 1, data.width || 1].join(" x ");
obj.items = data.items;
resolve();
});
}
export default {
getList,
getItem
}```
index.js
```import './index.less'
import App from'./App'
let app = new App();
app.setup();```
index.js
```import './index.less'
import MintUI from 'mint-ui'
import 'mint-ui/lib/style.css'
import Vue from 'vue'
import axios from "axios";
import Home from "./com/home/index.vue"
import {
Toast
} from 'mint-ui';
Vue.use(MintUI)
Vue.prototype.$toast = (tip) => {
Toast({
message: tip,
position: 'top',
duration: 2000
});
}
Vue.prototype.$get = (url, param) => {
return axios.get(url, {
params: param
});
}
Vue.prototype.$post = (url, param, isForm = true) => {
let data;
if (isForm) {
data = new FormData();
for (let i in param) {
data.append(i, param[i]);
}
} else {
data = param;
}
return axios.post(url, data);
}
new Vue({
render: h => h(Home)
}).$mount("#home");
// import App from'./App'
// let app = new App();
// app.setup();
window.onload = function () {
draw();
}
function draw() {
var subj_paths = [
[{
X: 10,
Y: 10
}, {
X: 110,
Y: 10
}, {
X: 110,
Y: 110
}, {
X: 10,
Y: 110
}],
[{
X: 20,
Y: 20
}, {
X: 20,
Y: 100
}, {
X: 100,
Y: 100
}, {
X: 100,
Y: 20
}]
];
var clip_paths = [
[{
X: 50,
Y: 50
}, {
X: 150,
Y: 50
}, {
X: 150,
Y: 150
}, {
X: 50,
Y: 150
}],
[{
X: 60,
Y: 60
}, {
X: 60,
Y: 140
}, {
X: 140,
Y: 140
}, {
X: 140,
Y: 60
}]
];
var scale = 100;
ClipperLib.JS.ScaleUpPaths(subj_paths, scale);
ClipperLib.JS.ScaleUpPaths(clip_paths, scale);
var cpr = new ClipperLib.Clipper();
cpr.AddPaths(subj_paths, ClipperLib.PolyType.ptSubject, true);
cpr.AddPaths(clip_paths, ClipperLib.PolyType.ptClip, true);
var subject_fillType = ClipperLib.PolyFillType.pftNonZero;
var clip_fillType = ClipperLib.PolyFillType.pftNonZero;
var clipTypes = [ClipperLib.ClipType.ctUnion, ClipperLib.ClipType.ctDifference, ClipperLib.ClipType.ctXor, ClipperLib.ClipType.ctIntersection];
var clipTypesTexts = "Union, Difference, Xor, Intersection";
var solution_paths, canvas_str, canvas, ctx, desc = document.getElementById('desc'),
i, i2, j, x, y;
for (i = 0; i < clipTypes.length; i++) {
solution_paths = new ClipperLib.Paths();
cpr.Execute(clipTypes[i], solution_paths, subject_fillType, clip_fillType);
//console.log(JSON.stringify(solution_paths));
canvas = document.getElementById("canvas" + i);
canvas.width = canvas.height = 160;
ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
for (i2 = 0; i2 < solution_paths.length; i2++) {
for (j = 0; j < solution_paths[i2].length; j++) {
x = solution_paths[i2][j].X / scale;
y = solution_paths[i2][j].Y / scale;
if (!j) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.closePath();
}
ctx.fill();
ctx.stroke();
}
desc.innerHTML = clipTypesTexts;
}
function Main()
{
var subj = [[{X:10,Y:10},{X:110,Y:10},{X:110,Y:110},{X:10,Y:110}]];
var clip = [[{X:50,Y:50},{X:150,Y:50},{X:150,Y:150},{X:50,Y:150}]];
// DrawPolygons(subj, 0x8033FFFF);
// DrawPolygons(clip, 0x80FFFF33);
var solution = new ClipperLib.Paths();
var c = new ClipperLib.Clipper();
c.AddPaths(subj, ClipperLib.PolyType.ptSubject, true);
c.AddPaths(clip, ClipperLib.PolyType.ptClip, true);
// c.Execute(ClipperLib.ClipType.ctUnion, solution);
c.Execute(ClipperLib.ClipType.ctDifference, solution);
// DrawPolygons(solution, 0x40808080);
console.log("solution", solution);
console.log(JSON.stringify(solution));
}
function compute(a, b, t){
var subj = changePath(a);
var clip = changePath(b);
console.log(a);
console.log(subj);
console.log("============");
console.log(b);
console.log(clip);
var solution = new ClipperLib.Paths();
var c = new ClipperLib.Clipper();
c.AddPaths(subj, ClipperLib.PolyType.ptSubject, true);
c.AddPaths(clip, ClipperLib.PolyType.ptClip, true);
c.Execute(t, solution);
console.log("solution", solution);
console.log(JSON.stringify(solution));
return solution;
}
function changePath(list){
var aim = [];
if(list && list.length){
if(Array.isArray(list[0])){
aim = list;
}
else{
aim.push(list);
}
}
else{
return null;
}
var pots = [];
for(var i = 0; i < aim.length; i++){
var t = aim[i].map((item) => {
return {
X: item.x,
Y: item.y
}
})
pots.push(t);
}
return pots;
}
Main();```
index.js
```import Vue from 'vue'
import Home from "./com/home/index.vue"
import MintUI from 'mint-ui'
import 'mint-ui/lib/style.css'
import axios from "axios";
import './index.less'
import App from'./core/App'
import store from "./store/index";
import listener from './lib/listener';
import Stats from 'three/examples/jsm/libs/stats.module';
import { Toast } from 'mint-ui';
import Tooler from './core/Tooler'
let stats;
let app;
let isDebug = Tooler.getQueryString("debug") == 1;
let isStop = Tooler.getQueryString("stop") == 1;
Vue.use(MintUI);
new Vue({
store,
render: h => h(Home)
}).$mount("#home");
```
index.js
```import Vue from 'vue'
import Home from "./com/home/index.vue"
import MintUI from 'mint-ui'
import 'mint-ui/lib/style.css'
import axios from "axios";
import './index.less'
import App from'./core/App'
import store from "./store/index";
import listener from './lib/listener';
import Stats from 'three/examples/jsm/libs/stats.module';
import { Toast } from 'mint-ui';
import Tooler from './core/Tooler'
let stats;
let app;
Vue.use(MintUI)
// Vue.prototype.$axios = axios;
Vue.prototype.$toast = (tip) => {
Toast({
message: tip,
position: 'top',
duration: 2000
});
}
Vue.prototype.$get = (url, param) => {
return axios.get(url, {
params: param
});
}
Vue.prototype.$post = (url, param, isForm = true) => {
let data;
if(isForm){
data = new FormData();
for(let i in param){
data.append(i, param[i]);
}
}
else{
data = param;
}
return axios.post(url, data);
}
new Vue({
store,
render: h => h(Home)
}).$mount("#home");
window.onload = function(){
stats = new Stats();
stats.setMode(0);
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
// document.body.appendChild(stats.domElement);
let canvas = $("#canvas");
app = new App(canvas);
app.setup();
app.setStats(stats);
}
function $(sel){
return document.querySelector(sel);
}
// async function test(){
// var list = [100, 200, 300];
// console.log("start");
// for(var i = 0; i < list.length; i++){
// var item = list[i];
// console.log(item);
// await sleep(item);
// }
// console.log("end");
// }
// test();
// function sleep(m){
// return new Promise(resolve=>{
// setTimeout(() => {
// console.log('await ' + m);
// resolve();
// }, m);
// })
// }```
price.js
```import axios from "axios";
import Tooler from '../core/Tooler'
async function getList(){
return new Promise(async resolve=>{
let u = Tooler.getQueryString("u");
if(!u){
resolve();
}
var temp = u.split("-");
let id = temp.pop();
let sourcetype = temp.pop();
let res;
let host = getHost();
if(isERP()){
res = await axios.get(host + "/api/index/modelPrice", {
params: {
type: sourcetype,
id: id,
v: Math.random()
}
});
}
else{
res = await axios.get(host + "/mapi/index.php", {
params: {
app:"modelshow",
fnn:"modelDetailById",
sourcetype: sourcetype,
yun3d_id: id,
v: Math.random()
}
});
}
console.log(res);
if (res.data && res.data.code == 200) {
var list = [];
for(var i in res.data.datas){
var item = res.data.datas[i];
if(item.show_offer == 2){
await getItem(item);
list.push(item);
}
}
resolve(list)
}
resolve();
})
}
function isERP(){
if(location.search.indexOf('3d.mendaow.com') != -1 || location.search.indexOf('3d.mendaoyun.com') != -1){
return false;
}
return true;
}
function getHost(){
return location.search.match(/http.*?.com/)[0];
}
function getSize(data){
var list = [];
if(data.length){
list.push(data.length);
}
if(data.height){
list.push(data.height);
}
if(data.width){
list.push(data.width);
}
return list.join("x");
}
async function getItem(obj){
return new Promise(async resolve=>{
// var host = Tooler.isTest() ? 'http://3d.mendaow.com' : 'https://3d.mendaoyun.com';
var host = getHost();
var url = host + '/data/upload' + obj.plan_path + "/" + obj.pricejson_file + "?v=" + Math.random();
console.log(url);
let res = await axios.get(url);
var data = res.data;
obj.detail = data;
// console.log(data);
// obj.area = data.acreage;
// obj.price = data.cost;
// obj.count = data.items[0] ? data.items[0].discount : 1;
// obj.all = obj.count * obj.price * obj.setnum;
// obj.size = getSize(data);
// obj.items = data.items;
resolve();
});
}
function timerFormat(timer){
var date = new Date(timer);
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
return [y, addZero(m), addZero(d)].join("/");
}
function addZero(value, size){
return (Array(size).join(0) + value).substr(-size);
}
export default {
getList,
getItem,
getSize,
getHost,
timerFormat
}```
index.js
```import './index.less'
import App from'./App'
import { GUI } from 'three/examples/jsm/libs/dat.gui.module';
import Stats from 'three/examples/jsm/libs/stats.module';
let app = new App();
app.setup();
let gui;
let API = {
scale: 1.0
};
// initGui();
initStats();
function updateGUIParam(){
app.updateGUIParam(API);
}
function initGui() {
gui = new GUI();
var rotation = gui.addFolder("rotation");
rotation.add(API, 'scale', 1, 10).step( 1 ).onChange( updateGUIParam );
}
function initStats(){
var stats = new Stats();
stats.setMode(0);
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
document.body.appendChild(stats.domElement);
app.setStats(stats);
}```
fileTransform.js
```import axios from "axios";
//url转arrayBuffer
function url2ArrayBuffer(url) {
return axios({
url,
method: 'get',
responseType: 'arraybuffer',
}).then(res => res.data);
}
//file转arrayBuffer
function file2ArrayBuffer(file) {
return new Promise(resolve => {
const fileReader = new FileReader();
fileReader.onload = function () {
resolve(fileReader.result);
};
fileReader.readAsArrayBuffer(file);
});
}
//arrayBuffer转file
function arrayBuffer2File(arrayBuffer, name, type) {
// arrayBuffer2file(arrayBuffer, 'test.mp3', 'audio/mp3')
const file = new File([arrayBuffer], name, {
type: type
});
return file;
}
//file转url
function file2Url(file) {
const url = URL.createObjectURL(file);
return url;
}
//url转AudioBuffer
function url2AudioBuffer(url) {
return new Promise(async (resolve) => {
let encodedBuffer = await url2ArrayBuffer(url);
const context = new AudioContext();
// 解码
context.decodeAudioData(encodedBuffer, decodedBuffer => {
resolve(decodedBuffer);
});
})
}
export default {
url2ArrayBuffer,
file2ArrayBuffer,
arrayBuffer2File,
file2Url,
url2AudioBuffer,
}```
index.js
```import './index.less'
import App from'./App'
import Stats from 'three/examples/jsm/libs/stats.module';
let app = new App();
app.setup();
initStats();
function initStats(){
var stats = new Stats();
stats.setMode(0);
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
document.body.appendChild(stats.domElement);
app.setStats(stats);
}
$(".btn").click(()=>{
app.toggle();
})```
index.js
```import './index.less'
// import videojs from 'video.js'
// import 'videojs-contrib-hls'
// import 'video.js/dist/video-js.css'
// var videojs = require('video.js');
// require('videojs-contrib-media-sources'); // increase browser support with MSE polyfill
// require('videojs-contrib-hls.js'); // auto attaches hlsjs handler
// var player = videojs('video', {
// autoplay: true,
// html5: {
// hlsjsConfig: {
// debug: true
// }
// }
// });
// import App from'./ts/App'
// new App();
// window.onload = function(){
// videojs('my-video', {
// bigPlayButton: false,
// textTrackDisplay: false,
// posterImage: true,
// errorDisplay: false,
// controlBar: true
// }, function () {
// this.play()
// })
// }```
index.js
```import './index.less'
import Car from'./core/Car'
new Car();```
App.ts
```import * as BABYLON from 'babylonjs'
import Stats from 'three/examples/jsm/libs/stats.module';
// import CameraMaker from './CameraMaker';
// import Fire from './Fire';
// import * as CANNON from '../asset/lib/cannon.min'
export default class App{
canvas:any;
engine:BABYLON.Engine;
scene:BABYLON.Scene;
camera:BABYLON.Camera;
stats: any;
sphere:BABYLON.Mesh;
// fire:Fire;
shadowGenerator: BABYLON.ShadowGenerator;
constructor(){
this.canvas = document.getElementById("canvas");
this.engine = new BABYLON.Engine(this.canvas, true);
this.scene = new BABYLON.Scene(this.engine);
// this.scene.shadowsEnabled = true;
console.log("this.scene");
console.log(this.scene);
// this.camera = CameraMaker.getFreeCamera(this.scene);
this.camera.attachControl(this.canvas);
var physicsPlugin = new BABYLON.AmmoJSPlugin();
physicsPlugin.setTimeStep(1 /120);
this.scene.enablePhysics(new BABYLON.Vector3(0, -9.8, 0), physicsPlugin);
// this.scene.collisionsEnabled = true;
this.createScene();
this.createStats();
this.engine.runRenderLoop(()=>{
// this.fire.update();
this.scene.render();
this.stats.update();
// this.sphere.translate(new BABYLON.Vector3(0, 0, 1), 0.05, BABYLON.Space.LOCAL);
})
window.addEventListener("resize", ()=>{
this.engine.resize();
})
}
createScene(){
// this.fire = new Fire(this.scene);
this.scene.clearColor = new BABYLON.Color4(0, 0, 0, 1);
// var light:BABYLON.HemisphericLight = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(1, 1, 1), this.scene);
// light.intensity = 0.8;
// var material:BABYLON.StandardMaterial = new BABYLON.StandardMaterial("material", this.scene);
// material.diffuseColor = new BABYLON.Color3(1, 1, 1);
// material.diffuseTexture = new BABYLON.Texture("/asset/img/p6.jpg", this.scene);
// material.bumpTexture = new BABYLON.Texture("/asset/img/p6_nor.jpg", this.scene);
// (material.diffuseTexture as BABYLON.Texture).uScale = 4;
// (material.diffuseTexture as BABYLON.Texture).vScale = 4;
// (material.bumpTexture as BABYLON.Texture).uScale = 4;
// (material.bumpTexture as BABYLON.Texture).vScale = 4;
// var sphere:BABYLON.Mesh = BABYLON.MeshBuilder.CreateSphere("sphere", {diameter: 2}, this.scene);
// sphere.material = material;
// this.shadowGenerator = new BABYLON.ShadowGenerator(1024, this.fire.light);
// this.shadowGenerator.setDarkness(0.8);
// this.shadowGenerator.useCloseExponentialShadowMap = true;
// this.shadowGenerator.blurScale = 2;
// this.shadowGenerator.bias = 0.01;
// this.shadowGenerator.usePoissonSampling = true;
// shadowGenerator.useExponentialShadowMap = true;
this.shadowGenerator.usePoissonSampling = true;
// shadowGenerator.useBlurExponentialShadowMap = true;
this.shadowGenerator.forceBackFacesOnly = true;
this.shadowGenerator.blurKernel = 32;
this.shadowGenerator.useKernelBlur = true;
var hemisphericLight1 = new BABYLON.HemisphericLight("hemisphericLight1", new BABYLON.Vector3(1, -1, -1), this.scene);
hemisphericLight1.diffuse = BABYLON.Color3.FromHexString("#FFFFFF");
hemisphericLight1.specular = BABYLON.Color3.FromHexString("#FFFFFF");
hemisphericLight1.groundColor = BABYLON.Color3.FromHexString("#FFFFFF");
hemisphericLight1.intensity = 0.4;
var hemisphericLight2 = new BABYLON.HemisphericLight("hemisphericLight2", new BABYLON.Vector3(1, -1, 0.4), this.scene);
hemisphericLight2.diffuse = BABYLON.Color3.FromHexString("#FFFFFF");
hemisphericLight2.specular = BABYLON.Color3.FromHexString("#FFFFFF");
hemisphericLight2.groundColor = BABYLON.Color3.FromHexString("#FFFFFF");
hemisphericLight2.intensity = 0.3;
this.addBox(new BABYLON.Color3(1, 0, 0), new BABYLON.Vector3(7, 0, 0));
this.addBox(new BABYLON.Color3(0, 1, 0), new BABYLON.Vector3(0, 7, 0));
this.addBox(new BABYLON.Color3(0, 0, 1), new BABYLON.Vector3(0, 0, 7));
for(let i = 0; i < 1; i++){
let c = new BABYLON.Color3(Math.random(), Math.random(), Math.random());
let p = new BABYLON.Vector3(
(0.5 - Math.random()) * 10,
(0.5 - Math.random()) * -30,
(0.5 - Math.random()) * 10,
);
this.addSphere(c, p);
}
// var ground:BABYLON.Mesh = BABYLON.Mesh.CreateGroundFromHeightMap("map", "/asset/img/p6_nor.jpg", 80, 80, 40, 0, 0.4, this.scene);
// var ground:BABYLON.Mesh = BABYLON.Mesh.CreatePlane("plane", 400, this.scene);
// var ground:BABYLON.Mesh = BABYLON.Mesh.CreateGround("plane", 80, 80, 80, this.scene);
var ground:BABYLON.Mesh = BABYLON.Mesh.CreateBox("plane", 1, this.scene);
ground.scaling = new BABYLON.Vector3(10, 1, 10);
var groundMat:BABYLON.StandardMaterial = new BABYLON.StandardMaterial("groundMat", this.scene);
groundMat.diffuseTexture = new BABYLON.Texture("/asset/img/p6.jpg", this.scene);
// groundMat.bumpTexture = new BABYLON.Texture("/asset/img/p6_nor.jpg", this.scene);
groundMat.diffuseColor = new BABYLON.Color3(0, 0, 0);
groundMat.emissiveColor = new BABYLON.Color3(0.2, 0.2, 0.2);
(groundMat.diffuseTexture as any).uScale = 4;
(groundMat.diffuseTexture as any).vScale = 4;
ground.material = groundMat;
ground.position.y = -10;
ground.receiveShadows = true;
this.shadowGenerator.getShadowMap().renderList.push(ground);
// this.sphere = sphere;
// sphere.parent = this.camera;
// sphere.position.set(0, 0, 8);
// this.fire.light.parent = this.camera;
new BABYLON.PhysicsImpostor(ground, BABYLON.PhysicsImpostor.BoxImpostor, {
mass: 0,
friction: 0.5,
restitution: 0.9
}, this.scene);
}
addBox(color: BABYLON.Color3, position:BABYLON.Vector3){
// var material = new BABYLON.ShaderMaterial("shader", this.scene, "/asset/shader/test1");
var box:BABYLON.Mesh = BABYLON.MeshBuilder.CreateBox("box", {}, this.scene);
var mat:BABYLON.StandardMaterial = new BABYLON.StandardMaterial("material", this.scene);
// mat.wireframe = true;
mat.diffuseColor = color;
box.material = mat;
box.position = position;
new BABYLON.PhysicsImpostor(box, BABYLON.PhysicsImpostor.BoxImpostor, {
mass: 1,
friction: 0.5,
restitution: 0.5
})
this.shadowGenerator.getShadowMap().renderList.push(box);
}
addSphere(color: BABYLON.Color3, position:BABYLON.Vector3){
var sphere:BABYLON.Mesh = BABYLON.MeshBuilder.CreateSphere("sphere", {
segments: 7,
diameter: Math.random() * 2 + 0.4
}, this.scene);
var mat:BABYLON.StandardMaterial = new BABYLON.StandardMaterial("material", this.scene);
mat.diffuseColor = color;
mat.specularColor = new BABYLON.Color3(0, 0, 0);
// mat.wireframe = true;
sphere.material = mat;
sphere.position = position;
new BABYLON.PhysicsImpostor(sphere, BABYLON.PhysicsImpostor.SphereImpostor, {
mass: 1,
friction: 0.8,
restitution: 0.2
})
// sphere.receiveShadows = true;
this.shadowGenerator.getShadowMap().renderList.push(sphere);
// this.fire.light.includedOnlyMeshes.push(sphere);
}
createStats(){
this.stats = new Stats();
this.stats.setMode(0);
this.stats.domElement.style.position = 'absolute';
this.stats.domElement.style.left = '0px';
this.stats.domElement.style.top = '0px';
document.body.appendChild(this.stats.domElement);
}
}```
index.js
```import './index.less'
import App from'./App'
import { GUI } from 'three/examples/jsm/libs/dat.gui.module';
import Stats from 'three/examples/jsm/libs/stats.module';
let app = new App();
app.setup();
let gui;
let API = {
meshColor: 0xffffff,
lineColor: 0xff0000,
meshOpacity: 0.5,
lineOpacity: 0.5,
scale: 1.0,
rotateNum: 0.01,
translateNum: 0.01
};
initGui();
initStats();
window.addEventListener("info", e => {
let pot = e.detail.position;
let x = fixNumber(pot.x);
let y = fixNumber(pot.y);
let z = fixNumber(pot.z);
$pot.val([x, y, z].join(","));
// API.x = x;
// API.y = y;
// API.z = z;
})
function fixNumber(n){
var num = n.toFixed(4);
return Number(num);
}
function updateGUIParam(){
app.updateGUIParam(API);
}
function initGui() {
gui = new GUI();
gui.add( API, 'rotateNum', -0.2, 0.2 ).name( 'rotateNum' ).onChange( updateGUIParam );
gui.add( API, 'translateNum', -1.0, 1.0 ).name( 'translateNum' ).onChange( updateGUIParam );
}
function initStats(){
var stats = new Stats();
stats.setMode(0);
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
document.body.appendChild(stats.domElement);
app.setStats(stats);
}
let $pot = $(".pot");
$(".add").click(function(e){
var list = $pot.val().split(",");
var pots = list.map(item => {
return Number(item);
})
app.addPots(pots);
});
$(".set").click(function(e){
app.set(getPot());
});
$(".del").click(function(e){
app.del(getPot());
});
$(".drawObject").click(function(e){
app.drawObject();
});
$(window).keydown(function(event){
if(event.keyCode == 87){
app.setMode( "translate" );
}
else if(event.keyCode == 69){
app.setMode( "rotate" );
}
else if(event.keyCode == 82){
app.setMode( "scale" );
}
})
function getPot(){
var pot = $pot.val();
var list = pot.split(",");
return {
x: Number(list[0]),
y: Number(list[1]),
z: Number(list[2]),
}
}```
Tooler.ts
```import * as THREE from 'three'
export default class Tooler{
public static getVector3(points:string):Array<THREE.Vector3>{
var list:Array<THREE.Vector3> = [];
points = points.replace(/\s/g, "");
var ps:Array<string> = points.split(",");
var total:number = ps.length;
if(total % 3 == 0 && total > 0){
for(var i:number = 0; i < total; i += 3){
var point:THREE.Vector3 = new THREE.Vector3(Number(ps[i]), Number(ps[i + 1]), Number(ps[i + 2]));
list.push(point);
}
}
return list;
}
public static getPoints(ps: Array<THREE.Vector3>):Array<THREE.Mesh>{
var list:Array<THREE.Mesh> = [];
var total:number = ps.length;
var mat: THREE.MeshNormalMaterial = new THREE.MeshNormalMaterial();
for(var i:number = 0; i < total; i++){
var mesh:THREE.Mesh = new THREE.Mesh(new THREE.BoxGeometry(), mat);
mesh.position.copy(ps[i]);
list.push(mesh);
}
return list;
}
public static getLines(points: Array<THREE.Vector3>):THREE.Line{
var geometry = new THREE.Geometry();
var total:number = points.length;
for(var i:number = 0; i < total; i++){
geometry.vertices.push(points[i]);
}
return new THREE.Line(geometry, new THREE.MeshNormalMaterial());
}
public static getBoxSize(obj: THREE.Object3D):THREE.Vector3{
let box = new THREE.Box3().setFromObject(obj);
let size = box.getSize(new THREE.Vector3());
return size;
}
public static checkMobile():boolean{
let list = ["Android", "iPhone", "iPad"];
let res = list.find(item => {
if(navigator.userAgent.indexOf(item) != -1){
return true;
}
})
return !!res;
}
}```
index.js
```import './index.less'
import listener from "./lib/listener"
import Vue from 'vue'
import Home from "./com/home/index.vue"
// import 'lib-flexible'
import VueAwesomeSwiper from 'vue-awesome-swiper'
// import style
import 'swiper/css/swiper.css'
Vue.use(VueAwesomeSwiper)
new Vue({
render: h => h(Home)
}).$mount("#vue");
window.hideLoading = function(){
// listener.emit('loaded');
}
```
App.ts
```import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { DragControls } from 'three/examples/jsm/controls/DragControls';
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls';
import { TransformControls } from 'three/examples/jsm/controls/TransformControls';
export default class App {
public static ZERO:THREE.Vector3 = new THREE.Vector3();
public static TOTAL:number = 0;
public static SELECTED_COLOR:number = 0xff8800;
public static NORMAL_COLOR:number = 0xa0a0a0;
public static NORMAL_MATERIAL:THREE.MeshNormalMaterial = new THREE.MeshNormalMaterial();
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
orbit: OrbitControls;
curObject: THREE.Mesh|THREE.Line;
pots: Array<THREE.Mesh>;
dragItems: Array<THREE.Mesh|THREE.Line>;
stats: any;
role: THREE.Mesh;
control: TransformControls;
rotateNum: number = 0.01;
translateNum: number = 0.01;
constructor() {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 900);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
window.addEventListener("resize", e => this.onResize(e), false);
}
setStats(stats: any){
this.stats = stats;
}
setMode(mode: string){
this.control.setMode(mode);
}
set(param: any){
if(this.curObject){
this.curObject.position.set(param.x, param.y, param.z);
}
}
del(){
if(this.curObject){
this.scene.remove(this.curObject);
this.dragItems = this.dragItems.filter(item => {
return item != this.curObject;
});
this.pots = this.pots.filter(item => {
return item != this.curObject;
});
this.curObject.geometry.dispose();
(this.curObject.material as any).dispose();
this.curObject = null;
}
}
onResize(e:Event):void{
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
animate():void {
requestAnimationFrame(() => {
this.animate();
});
this.stats && this.stats.update();
this.role.translateZ(this.translateNum);
this.role.rotateY(this.rotateNum);
this.renderer.render(this.scene, this.camera);
}
updateGUIParam(param: any){
this.rotateNum = param.rotateNum;
this.translateNum = param.translateNum;
}
setup():void {
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0xffffff));
this.renderer.shadowMap.enabled = true;
document.body.appendChild(this.renderer.domElement);
this.orbit = new OrbitControls(this.camera, this.renderer.domElement);
this.camera.position.set(7.742, 9.887, 13.769);
this.pots = [];
this.dragItems = [];
this.addPlane();
this.addRole();
this.addControl();
this.animate();
this.camera.lookAt(App.ZERO);
}
addControl():void{
let control = new TransformControls( this.camera, this.renderer.domElement );
control.addEventListener( 'dragging-changed', ( event )=> {
this.orbit.enabled = ! event.value;
} );
control.attach( this.role );
this.scene.add( control );
this.control = control;
}
addRole():void{
this.role = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshNormalMaterial());
this.scene.add(this.role);
this.role.name = "role";
// let axis = new THREE.Vector3(0, 1, 0);
// let matrix = new THREE.Matrix4();
// matrix.makeRotationAxis(axis.normalize(), 45 * Math.PI / 180);
// matrix.multiply(this.role.matrix);
// this.role.matrix = matrix;
// this.role.setRotationFromMatrix(matrix);
}
addPlane():void{
let gridHelper = new THREE.GridHelper(80, 80);
(gridHelper.material as any).transparent = true;
(gridHelper.material as any).opacity = 0.1;
this.scene.add(gridHelper);
this.scene.add(new THREE.AxesHelper(40));
new THREE.FontLoader().load((window as any).CFG.baseURL + "/obj/font/gentilis_bold.typeface.json", (font) => {
let param = {
font: font,
size: 4,
height: 1
}
let xw = new THREE.Mesh(new THREE.TextGeometry("X", param), App.NORMAL_MATERIAL);
xw.position.set(30, 0, 0);
let yw = new THREE.Mesh(new THREE.TextGeometry("Y", param), App.NORMAL_MATERIAL);
yw.position.set(0, 30, 0);
let zw = new THREE.Mesh(new THREE.TextGeometry("Z", param), App.NORMAL_MATERIAL);
zw.position.set(0, 0, 30);
this.scene.add(xw);
this.scene.add(yw);
this.scene.add(zw);
xw.geometry.center();
yw.geometry.center();
zw.geometry.center();
})
}
addPots(list: Array<number>){
for(let i = 0; i < list.length; i += 3){
let pot = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshBasicMaterial({
color: App.SELECTED_COLOR,
map: new THREE.CanvasTexture(this.getCanvas(++App.TOTAL))
}));
pot.position.set(list[i], list[i + 1], list[i + 2]);
this.scene.add(pot);
this.pots.push(pot);
this.dragItems.push(pot);
pot.name = "pot" + App.TOTAL;
}
}
getCanvas(n: any){
let w = 256;
let h = 256;
let canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 256;
let ctx = canvas.getContext("2d");
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, w, h);
ctx.font = 90 + "px bold";
ctx.fillStyle = "#000000";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(n, w / 2, h / 2);
return canvas;
}
drawObject(){
let list: number[] = [];
this.pots.forEach((item: THREE.Mesh) => {
list.push(item.position.x, item.position.y, item.position.z);
})
let geometry = new THREE.BufferGeometry();
geometry.addAttribute("position", new THREE.BufferAttribute(new Float32Array(list), 3));
// geometry.addAttribute("face", new THREE.BufferAttribute(new Float32Array(list), 3));
geometry.computeVertexNormals();
let material = new THREE.MeshBasicMaterial({color: 0xd200ff});
let mesh = new THREE.Line(geometry, material);
this.scene.add(mesh);
mesh.name = "drawObject";
this.dragItems.push(mesh);
}
}```
audioClip.js
```import AudioSculptor from 'audio-sculptor';
const audioSculptor = new AudioSculptor({
timeout: 20 * 1000, // 将超时设置为20s
})
async function test(src){
// const workerPath = '/js/ffmpeg-worker-mp4.js';
// audioSculptor.open(workerPath).then(() => {
console.log('open success!');
const audio = new Audio(src);
const blob = await audioSculptor.toBlob(audio);
const clippedBlob = await audioSculptor.clip(blob, 1, 2);
const clippedAudio = await audioSculptor.toAudio(clippedBlob);
console.log(clippedAudio);
// });
}
export default {
test
}
```
FineLoader.ts
```import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { DragControls } from 'three/examples/jsm/controls/DragControls'
import { FBXLoader } from './FBXLoader'
import { ColladaLoader } from 'three/examples/jsm/loaders/ColladaLoader'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
export default class FineLoader{
constructor(){
}
static loadFbx(url: string) {
return new Promise(resolve => {
var loader = new FBXLoader();
loader.load(url, (object: any) => {
console.log('fbx loaded', object);
// this.mixer = new THREE.AnimationMixer( object );
// var action = this.mixer.clipAction( object.animations[ 0 ] );
// action.play();
// object.traverse( function ( child:any) {
// if ( child.isMesh ) {
// child.castShadow = true;
// child.receiveShadow = true;
// }
// } );
resolve(object);
});
})
}
static loadDae(url: string) {
return new Promise(resolve => {
var loader = new ColladaLoader();
loader.load(url, (object: any) => {
console.log('dea loaded', object);
let daeModel = object.scene;
resolve(daeModel);
})
})
}
static loadObj(url: string) {
return new Promise(resolve => {
var loader = new OBJLoader();
loader.load(url, (object: any) => {
console.log('obj loaded', object);
// var textureLoader = new THREE.TextureLoader();
// var texture = textureLoader.load('/obj/box.jpg');
// object.traverse(function (child: any) {
// if (child.isMesh) child.material.map = texture;
// });
resolve(object);
})
});
}
static loadZip() {
new THREE.FileLoader().setResponseType('arraybuffer').load('obj/fbx/man.zip', (data) => {
JSZip.loadAsync(data).then((zip: any) => {
const loadingManager = new THREE.LoadingManager();
loadingManager.setURLModifier(url => {
const buffer = zip.files[url].async("arraybuffer");
const blob = new Blob([buffer.buffer]);
const NewUrl = URL.createObjectURL(blob);
console.log("NewUrl", NewUrl);
return NewUrl
});
var loader = new FBXLoader(loadingManager);
var ab = zip.file('man.fbx').async("arraybuffer");
ab.then((res: any) => {
console.log(res);
var obj = loader.parse(res, "");
// var obj = loader.parse(zip.files[ 'box.fbx' ].asArrayBuffer(), "");
// this.scene.add(obj);
})
})
});
}
}```
index.js
```import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
designVisible: false,
effectVisible: false,
detailVisible: false,
priceVisible: false,
colorVisible: false,
guiderVisible: false,
effectParam: {
ambient: 0.4,
directional: 0.6,
roughness: 0.2,
metalness: 0.2,
far: 0.1
},
modelId: 0,
modelType: 0,
productImages: [],
logoImage: null
},
mutations: {
changeDesignVisible(state, value){
state.designVisible = value;
},
changeEffectVisible(state, value){
state.effectVisible = value;
},
changeDetailVisible(state, value){
state.detailVisible = value;
},
changePriceVisible(state, value){
state.priceVisible = value;
},
changeEffectParam(state, value){
state.effectParam = value;
},
changeColorVisible(state, value){
state.colorVisible = value;
},
changeModelId(state, value){
state.modelId = value;
},
changeModelType(state, value){
state.modelType = value;
},
changeGuiderVisible(state, value){
state.guiderVisible = value;
},
changeProductImages(state, value){
state.productImages = value;
},
changeLogoImage(state, value){
state.logoImage = value;
}
},
actions: {
}
});
```
soundMaker.js
```import axios from "axios";
import tooler from './fileTransform';
import listener from '../lib/listener'
var toWav = require('audiobuffer-to-wav')
let audioContext = new window.AudioContext();
let channels = 1;
function make(second) {
let frameCount = audioContext.sampleRate * second;
let arrayBuffer = audioContext.createBuffer(channels, frameCount, audioContext.sampleRate);
let t = 0;
let f = 0;
for (let channel = 0; channel < channels; channel++) {
// This gives us the actual array that contains the data
let nowBuffering = arrayBuffer.getChannelData(channel);
for (let i = 0; i < frameCount; i++) {
// Math.random() is in [0; 1.0]
// audio needs to be in [-1.0; 1.0]
// nowBuffering[i] = Math.random() * 2 - 1;
if(++f > 100){
f = 0;
nowBuffering[i] = Math.sin(t);
t += Math.PI / 180;
}
}
}
audioContext.resume();
// Get an AudioBufferSourceNode.
// This is the AudioNode to use when we want to play an AudioBuffer
let source = audioContext.createBufferSource();
// set the buffer in the AudioBufferSourceNode
source.buffer = arrayBuffer;
setVol(source);
// connect the AudioBufferSourceNode to the
// destination so we can hear the sound
// source.connect(audioContext.destination);
// start the source playing
source.start();
source.onended = () => {
console.log('White noise finished');
}
}
async function load(){
// axios.get('https://wlwol.cn/media/audio/1582017952748.mp3', {responseType: "arraybuffer"}).then(response => {
// console.log(response);
// play(response.data);
// }).catch(err => {
// console.log(err);
// });
let res = await tooler.url2AudioBuffer('https://wlwol.cn/media/audio/1582017952748.mp3');
let bf = cut(res, 0, 0.42);
const context = new AudioContext();
console.log(context)
const dataSource = context.createBufferSource();
// 加载缓存
dataSource.buffer = bf.cutAudioBuffer;
// 连接播放器节点destination,中间可以连接其他节点,比如音量调节节点createGain(),
// 频率分析节点(用于傅里叶变换)createAnalyser()等等
dataSource.connect(context.destination);
// setVol(dataSource, context);
//开始播放
dataSource.start();
var wav = toWav(bf.cutAudioBuffer);
console.log(wav, 'wav');
let file = new window.File([wav], 'test.mp3', {type: 'audio/mp3'});
var src = URL.createObjectURL(file);
console.log(src);
listener.emit('url', src);
// saveAudio(context);
}
function saveAudio(ac){
var chunks = [];
var dest = ac.createMediaStreamDestination();
var osc = ac.createOscillator();
var mediaRecorder = new MediaRecorder(dest.stream);
mediaRecorder.start();
osc.start(0);
setTimeout(() => {
mediaRecorder.stop();
osc.stop(0);
}, 3000);
mediaRecorder.ondataavailable = function(evt) {
// push each chunk (blobs) in an array
chunks.push(evt.data);
};
mediaRecorder.onstop = function(evt) {
// Make blob out of our blobs, and open it.
var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
var src = URL.createObjectURL(blob);
console.log(src);
let file = new window.File([blob], 'test.mp3', {type: 'audio/mp3'});
src = URL.createObjectURL(file);
console.log(src);
listener.emit('url', src);
};
}
function play(encodedBuffer){
const context = new AudioContext();
// 解码
context.decodeAudioData(encodedBuffer, decodedBuffer => {
// 创建数据缓存节点
const dataSource = context.createBufferSource();
// 加载缓存
dataSource.buffer = decodedBuffer;
// 连接播放器节点destination,中间可以连接其他节点,比如音量调节节点createGain(),
// 频率分析节点(用于傅里叶变换)createAnalyser()等等
// dataSource.connect(context.destination);
setVol(dataSource, context);
// 开始播放
dataSource.start();
})
}
function read(){
const reader = new FileReader();
// file 为读取到的文件,可以通过<input type="file" />实现
reader.readAsArrayBuffer(file);
reader.onload = evt => {
// 编码过的音频数据
const encodedBuffer = evt.currentTarget.result;
// 下面开始处理读取到的音频数据
// 创建环境对象
const context = new AudioContext();
// 解码
context.decodeAudioData(encodedBuffer, decodedBuffer => {
// 创建数据缓存节点
const dataSource = context.createBufferSource();
// 加载缓存
dataSource.buffer = decodedBuffer;
// 连接播放器节点destination,中间可以连接其他节点,比如音量调节节点createGain(),
// 频率分析节点(用于傅里叶变换)createAnalyser()等等
dataSource.connect(context.destination);
// 开始播放
dataSource.start();
})
}
}
function setVol(source, audioContext){
let analyser = audioContext.createAnalyser();
let volume = audioContext.createGain();
volume.gain.value = 0.8;
source.connect(analyser);
analyser.connect(volume);
//变调
let filter = audioContext.createBiquadFilter();
filter.type = "lowshelf";
filter.frequency.value = 24000;
volume.connect(filter);
filter.connect(audioContext.destination);
}
function cut(originalAudioBuffer, start, end) {
const { numberOfChannels, sampleRate } = originalAudioBuffer;
const lengthInSamples = (end - start) * sampleRate;
// offlineAudioContext相对AudioContext更加节省资源
const offlineAudioContext = new OfflineAudioContext(numberOfChannels, numberOfChannels, sampleRate);
// 存放截取的数据
const cutAudioBuffer = offlineAudioContext.createBuffer(
numberOfChannels,
lengthInSamples,
sampleRate
);
// 存放截取后的数据
// const newAudioBuffer = offlineAudioContext.createBuffer(
// numberOfChannels,
// originalAudioBuffer.length - cutSegment.length,
// originalAudioBuffer.sampleRate
// );
// 将截取数据和截取后的数据放入对应的缓存中
for (let channel = 0; channel < numberOfChannels; channel++) {
// const newChannelData = newAudioBuffer.getChannelData(channel);
const cutChannelData = cutAudioBuffer.getChannelData(channel);
const originalChannelData = originalAudioBuffer.getChannelData(channel);
// const beforeData = originalChannelData.subarray(0,
// start * sampleRate - 1);
const midData = originalChannelData.subarray(start * sampleRate,
end * sampleRate - 1);
// const afterData = originalChannelData.subarray(
// end * sampleRate
// );
cutChannelData.set(midData);
// if (start > 0) {
// newChannelData.set(beforeData);
// newChannelData.set(afterData, (start * sampleRate));
// } else {
// newChannelData.set(afterData);
// }
}
return {
// 截取后的数据
// newAudioBuffer,
// 截取部分的数据
cutAudioBuffer
};
};
function music(){
// 创建新的音频上下文接口
var audioCtx = new window.AudioContext();
// 发出的声音频率数据,表现为音调的高低
var arrFrequency = [196.00, 220.00, 246.94, 261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25, 587.33, 659.25, 698.46, 783.99, 880.00, 987.77, 1046.50];
// 音调依次递增或者递减处理需要的参数
var start = 0, direction = 1;
// 当前频率
var frequency = arrFrequency[start];
// 如果到头,改变音调的变化规则(增减切换)
if (!frequency) {
direction = -1 * direction;
start = start + 2 * direction;
frequency = arrFrequency[start];
}
// 改变索引,下一次hover时候使用
start = start + direction;
// 创建一个OscillatorNode, 它表示一个周期性波形(振荡),基本上来说创造了一个音调
var oscillator = audioCtx.createOscillator();
// 创建一个GainNode,它可以控制音频的总音量
var gainNode = audioCtx.createGain();
// 把音量,音调和终节点进行关联
oscillator.connect(gainNode);
// audioCtx.destination返回AudioDestinationNode对象,表示当前audio context中所有节点的最终节点,一般表示音频渲染设备
gainNode.connect(audioCtx.destination);
// 指定音调的类型,其他还有square|triangle|sawtooth
oscillator.type = 'sine';
// 设置当前播放声音的频率,也就是最终播放声音的调调
oscillator.frequency.value = frequency;
// 当前时间设置音量为0
gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
// 0.01秒后音量为1
gainNode.gain.linearRampToValueAtTime(1, audioCtx.currentTime + 0.01);
// 音调从当前时间开始播放
oscillator.start(audioCtx.currentTime);
// 1秒内声音慢慢降低,是个不错的停止声音的方法
gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 1);
// 1秒后完全停止声音
oscillator.stop(audioCtx.currentTime + 1);
}
export default {
make,
load,
read
}```
App.ts
```import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { Vector3 } from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { resolve } from 'path';
const TWEEN = require('tween')
export default class App {
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
orbit: OrbitControls;
stats: any;
geometry: THREE.Geometry;
font: any;
pots: any[] = [];
potId: number = 0;
constructor() {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 900);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
window.addEventListener("resize", e => this.onResize(e), false);
}
onResize(e:Event):void{
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
setStats(stats: any):void{
this.stats = stats;
}
animate():void {
requestAnimationFrame(() => {
this.animate();
});
this.stats && this.stats.update();
TWEEN.update();
this.geometry && (this.geometry.verticesNeedUpdate = true);
this.renderer.render(this.scene, this.camera);
}
updateGUIParam(param: any){
}
async setup() {
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0x909090));
this.renderer.shadowMap.enabled = true;
this.orbit = new OrbitControls(this.camera, this.renderer.domElement);
this.orbit.enabled = true;
this.camera.position.set(7.742, 9.887, 13.769);
this.addLights();
this.animate();
this.camera.lookAt(new THREE.Vector3());
document.body.appendChild(this.renderer.domElement);
let pot1 = await this.loadFont();
let pot2 = await this.loadTree();
// let pot1 = [new THREE.Vector3(4, -3, 5)];
// let pot2 = [new THREE.Vector3(0, 8, 9), new THREE.Vector3(3, 0, 9)];
this.pots.push(pot1, pot2);
this.toggle();
}
addObj(vertices: THREE.Vector3[]){
console.log(this.pots);
let max = Math.max(this.pots[0].length, this.pots[1].length);
let len = vertices.length;
if(this.geometry){
for(let i = 0; i < max; i++){
let obj = vertices[i % len];
new TWEEN.Tween(this.geometry.vertices[i]).to({...obj}, 3000).start();
}
}
else{
this.geometry = new THREE.Geometry();
let material = new THREE.PointsMaterial({
size: 4,
vertexColors: THREE.VertexColors,
sizeAttenuation: false
})
for(let i = 0; i < max; i++){
let obj = vertices[i % len];
this.geometry.vertices.push(new THREE.Vector3(obj.x, obj.y, obj.z));
this.geometry.colors.push(new THREE.Color().setHSL( Math.random(), 1, 0.75 ));
}
let particle = new THREE.Points(this.geometry, material);
this.scene.add(particle);
}
console.log("total:" + vertices.length);
}
loadFont(){
return new Promise(resolve=>{
new THREE.FontLoader().load((window as any).CFG.baseURL + "/obj/font/gentilis_bold.typeface.json", (font) => {
this.font = font;
resolve(new THREE.SphereGeometry(40, 40, 40).vertices);
});
})
}
toggle(){
if(++this.potId >= this.pots.length){
this.potId = 0;
}
console.log("pot id : " + this.potId)
this.addObj(this.pots[this.potId]);
}
loadTree(){
return new Promise(resolve=>{
let loader = new GLTFLoader();
let baseURL = (window as any).CFG.baseURL;
loader.setPath(baseURL + '/obj/glTF/');
loader.load('tree.gltf', (gltf) => {
gltf.scene.traverse((child: any) => {
if(child.isMesh){
child.updateMatrix();
}
})
let aim:any = gltf.scene.children[0].children[0];
let scale = 10;
// aim.scale.set(scale, scale, scale);
// aim.scale.multiplyScalar(scale);
aim.geometry.center();
// aim.updateMatrix();
let list: THREE.Vector3[] = [];
let nums = aim.geometry.attributes.position.array;
for(let i = 0, len = nums.length; i < len; i += 3){
let pot = new THREE.Vector3();
pot.set(nums[i] * scale, nums[i + 1] * scale, nums[i + 2] * scale);
list.push(pot);
}
console.log("tree:" + list.length);
resolve(list);
})
});
}
addText(str: string):THREE.Vector3[]{
let param = {
font: this.font,
size: 20,
height: 4
}
let word = new THREE.Mesh(new THREE.TextGeometry(str, param), new THREE.MeshStandardMaterial({
color: 0xffffff,
wireframe: true
}));
word.geometry.center();
return (word.geometry as THREE.Geometry).vertices;
}
addLights():void{
var ambient:THREE.AmbientLight = new THREE.AmbientLight(0xffffff);
ambient.intensity = 0.4;
this.scene.add(ambient);
}
}```
index.js
```import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
effectVisible: false,
guiderVisible: false,
panel: {
type: '',
visible: false,
},
tempParam: {},
params: {
muscle: {
name: "肌肉",
roughness: 0.72,
metalness: 0.2,
alpha: 1,
color: '#ff824f',
visible: true
},
bones: {
name: "骨骼",
roughness: 0.2,
metalness: 0.52,
alpha: 1,
color: '#00ffff',
visible: true
},
eye: {
name: "眼睛",
roughness: 0.2,
metalness: 0.2,
alpha: 1,
color: '#ff0000',
visible: true
},
ambient: {
name: "环境光",
intensity: 0.32,
color: '#ffffff',
visible: true
},
directional: {
name: "平行光",
intensity: 0.4,
color: '#ffe944',
visible: true
},
system: {
name: "系统",
background: '#c9c9c9',
exposure: false
}
}
},
mutations: {
changePanel(state, value){
state.panel = value;
state.tempParam = state.params[value.type];
console.log("临时数据:", state.tempParam);
},
changeParams(state, value){
state.params = value;
},
changeTypeParams(state, value){
var type = state.panel.type;
state.params[type] = value;
},
changeEffectVisible(state, value){
state.effectVisible = value;
},
changeGuiderVisible(state, value){
state.guiderVisible = value;
},
limitMax(state){
console.log('ok');
for(var i in state.params){
for(var j in state.params[i]){
if(j == 'roughness' || j == 'metalness' || j == 'intensity'){
if(state.params[i][j] > 1){
console.log(i, j, state.params[i][j]);
state.params[i][j] = 1;
}
}
}
}
}
},
actions: {
}
});
```
index.js
```import Vue from 'vue'
import Home from "./com/home/index.vue"
import MintUI from 'mint-ui'
import 'mint-ui/lib/style.css'
import axios from "axios";
import Stats from 'three/examples/jsm/libs/stats.module';
import './index.less'
import App from'./core/App'
import store from "./store/index";
import listener from './lib/listener';
import { Toast } from 'mint-ui';
let app, stats;
Vue.use(MintUI)
Vue.prototype.$toast = (tip) => {
Toast({
message: tip,
position: 'top',
duration: 2000
});
}
Vue.prototype.$get = (url, param) => {
return axios.get(url, {
params: param
});
}
Vue.prototype.$post = (url, param, isForm = true) => {
let data;
if(isForm){
data = new FormData();
for(let i in param){
data.append(i, param[i]);
}
}
else{
data = param;
}
return axios.post(url, data);
}
new Vue({
store,
render: h => h(Home)
}).$mount("#home");
listener.on("map", (url) => {
app.changeMap(url);
});
window.onload = function(){
init();
}
function init(){
stats = new Stats();
stats.setMode(0);
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
stats.domElement.style.display = 'block';
document.body.appendChild(stats.domElement);
let canvas = $("#canvas");
app = new App(canvas);
app.setStats(stats);
}
function $(sel){
return document.querySelector(sel);
}
```
Fire.ts
```import * as THREE from 'three';
export default class Fire extends THREE.Object3D{
list:THREE.Object3D[] = [];
r: number = 10;
angler:number = 0;
constructor(){
super();
var box = new THREE.SphereBufferGeometry();
for(var i = 0; i < 30; i ++){
var mesh = new THREE.Mesh(box, new THREE.MeshBasicMaterial({
opacity: 1 / (i + 1),
transparent: true,
alphaTest: 0.01,
}));
mesh.scale.setScalar(1 / (i * 0.04 + 1));
this.list.push(mesh);
this.add(mesh);
}
// setInterval(this.update.bind(this), 20);
}
addMesh(){
var total = this.list.length;
if(total > 10) return;
var mesh = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshBasicMaterial({
opacity: 1 / (total + 1),
transparent: true,
alphaTest: 0.1
}));
mesh.position.set(total, total, total);
this.list.push(mesh);
this.add(mesh);
}
update(){
// this.addMesh();
// this.list.forEach((item: THREE.Object3D, index: number) => {
// if(index > 0){
// item.position.copy(this.list[index - 1].position.clone());
// }
// })
for(var i = this.list.length - 1; i > 0; i--){
this.list[i].position.copy(this.list[i - 1].position.clone());
}
var start = this.list[0];
// var distance = (1 - Math.random()) * 0.4;
// start.translateX(distance);
// start.translateY(distance);
// start.translateZ(distance);
this.angler += 3;
var x = this.r * Math.sin(this.angler * Math.PI / 180);
var z = this.r * Math.cos(this.angler * Math.PI / 180);
start.position.set(x, 0, z);
}
}```
sprite.js
```export default class Sprite{
constructor(ctx, lists){
if(lists && Array.isArray(lists[0])){
this.ctx = ctx;
this.bound = getBound(lists[0]);
this.x = this.bound.minX;
this.y = this.bound.minY;
this.potsList = [];
lists.forEach(item => {
let pots = resetPots(item, this.x, this.y);
this.potsList.push(pots);
})
this.fillStyle = "#ff0000";
this.strokeStyle = "#000000";
this.lineWidth = 1;
this.globalAlpha = 0.72;
this.selected = false;
// this.globalCompositeOperation = 'destination-out';
this.draw();
}
else{
console.log("初始化数据需传入二维数组");
}
}
checkHit(px, py){
if(px > this.x && px < this.x + this.bound.width){
if(py > this.y && py < this.y + this.bound.height){
return true;
}
}
return false;
}
getList(){
let aim = this.potsList.map(list=>{
return list.map(item=>{
return {
x: item.x + this.x,
y: item.y + this.y
}
})
})
// let list = this.pots.map(item => {
// return {
// x: item.x + this.x,
// y: item.y + this.y
// }
// })
return aim;
}
draw(){
this.ctx.save();
this.ctx.translate(this.x, this.y);
this.ctx.fillStyle = this.fillStyle;
this.ctx.strokeStyle = this.strokeStyle;
this.ctx.lineWidth = this.lineWidth;
this.ctx.globalAlpha = this.globalAlpha;
this.ctx.globalCompositeOperation = "source-over";
this.ctx.beginPath();
let pots = this.potsList[0];
for(let i = 0; i < pots.length; i++) {
let x = pots[i].x;
let y = pots[i].y;
if (!i) this.ctx.moveTo(x, y);
else this.ctx.lineTo(x, y);
}
this.ctx.closePath();
this.ctx.fill();
this.ctx.stroke();
if(this.potsList.length > 1){
this.ctx.globalAlpha = 1;
this.ctx.globalCompositeOperation = "destination-out";
for(let i = 1; i < this.potsList.length; i++){
this.ctx.beginPath();
let pots = this.potsList[i];
for(let i = 0; i < pots.length; i++) {
let x = pots[i].x;
let y = pots[i].y;
if (!i) this.ctx.moveTo(x, y);
else this.ctx.lineTo(x, y);
}
this.ctx.closePath();
this.ctx.fill();
}
}
if(this.selected){
this.ctx.strokeRect(0, 0, this.bound.width, this.bound.height);
}
this.ctx.restore();
}
}
function resetPots(list, x, y){
return list.map(item => {
return {
x: item.x - x,
y: item.y - y
}
});
}
function getBound(list){
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
list.forEach(item => {
if(item.x < minX){
minX = item.x;
}
if(item.x > maxX){
maxX = item.x;
}
if(item.y < minY){
minY = item.y;
}
if(item.y > maxY){
maxY = item.y;
}
})
let width = maxX - minX;
let height = maxY - minY;
return {minX, minY, maxX, maxY, width, height};
}```
FreeCamera.ts
```import * as THREE from 'three'
import Tooler from './Tooler';
const TWEEN = require('../lib/Tween.js');
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import listener from '../lib/listener';
export class FreeCamera extends THREE.PerspectiveCamera{
aim:THREE.Vector3 = new THREE.Vector3();
size: number = 0;
orbit: OrbitControls;
domElement: HTMLCanvasElement;
startPot: THREE.Vector3 = new THREE.Vector3(-400, 400, 800);
actions: any = {
left: false,
right: false,
front: false,
back: false,
up: false,
down: false
};
constructor(domElement:HTMLCanvasElement){
super(75, window.innerWidth / window.innerHeight, 20, 80000);
this.position.copy(this.startPot);
this.startPot = this.position.clone().normalize();
console.log("startPot", this.startPot);
this.domElement = domElement;
this.orbit = new OrbitControls(this, domElement);
this.orbit.enabled = true;
this.orbit.minPolarAngle = 1;
this.orbit.maxPolarAngle = 90 * Math.PI / 180;
this.lookAt(this.aim);
listener.on("startWalk", ()=>{
this.startWalk();
});
listener.on("stopWalk", ()=>{
this.stopWalk();
});
listener.on("touchstart", (n:String)=>{
this.actions[n + ""] = true;
});
listener.on("touchend", (n:String)=>{
this.actions[n + ""] = false;
});
}
startWalk(){
// this.orbit.enabled = false;
console.log(this);
console.log(this.aim);
console.log(this.orbit.target);
this.aim = this.orbit.target.clone();
new TWEEN.Tween(this.position).to({
y: 60,
}).start();
new TWEEN.Tween(this.aim).to({
x: 0,
y: 60,
z: 10
}).onUpdate(()=>{
this.lookAt(this.aim);
}).start();
}
stopWalk(){
this.orbit.enabled = true;
}
update(){
if(this.actions["left"]){
// this.rotateY(0.02);
this.translateX(-10);
}
if(this.actions["right"]){
// this.rotateY(-0.02);
this.translateX(10);
}
if(this.actions["front"]){
this.translateZ(-10);
}
if(this.actions["back"]){
this.translateZ(10);
}
if(this.actions["up"]){
this.translateY(10);
}
if(this.actions["down"]){
if(this.position.y > 32){
this.translateY(-10);
}
}
}
reset(obj:THREE.Object3D){
let bs = Tooler.getBoxSize(obj);
let s = Math.max(bs.x, bs.y, bs.z) * 1.2;
if(s > this.size){
this.size = s;
let offset = Tooler.getOffsetVector3(obj);
let pot = this.startPot.clone();
// console.log("【加载模型位置】");
// console.log(offset);
console.log("当前舞台尺寸 size = " + s);
console.log(pot);
this.orbit.enabled = false;
TWEEN.removeAll();
new TWEEN.Tween(this.aim).to({
x: offset.x,
y: offset.y,
z: offset.z
}).start();
new TWEEN.Tween(this.position).to({
x: pot.x * s,
y: pot.y * s,
z: pot.z * s
}, 3000).onUpdate(()=>{
this.lookAt(this.aim);
}).onComplete(()=>{
this.orbit.target = offset;
this.orbit.enabled = true;
}).start();
}
}
}```
index.js
```import './index.less'
import App from'./core/App'
import Vue from 'vue'
import Home from "./js/Home.vue";
new App();
new Vue({
render: h => h(Home)
}).$mount("#app");```
App.ts
```import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { DragControls } from 'three/examples/jsm/controls/DragControls'
import { FBXLoader } from './tool/FBXLoader'
import { ColladaLoader } from 'three/examples/jsm/loaders/ColladaLoader'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
// import { JSZip } from 'three/examples/js/libs/jszip.min.js';
const JSZip = require('three/examples/js/libs/jszip.min.js');
import Pickup from './tool/Pickup'
import Tooler from './Tooler'
import FitSize from './tool/FitSize'
import FineLoader from './tool/FineLoader'
export default class App {
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
orbit: OrbitControls;
stats: any;
clock: THREE.Clock = new THREE.Clock();
mixer: any;
rayCaster: THREE.Raycaster = new THREE.Raycaster();
constructor() {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 600);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
window.addEventListener("resize", e => this.onResize(e), false);
new Pickup(this.renderer.domElement, this.scene, this.camera);
}
onResize(e: Event): void {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
setStats(stats: any): void {
this.stats = stats;
}
animate(): void {
var delta = this.clock.getDelta();
this.mixer && this.mixer.update(delta);
this.stats && this.stats.update();
this.renderer.render(this.scene, this.camera);
requestAnimationFrame(() => {
this.animate();
});
}
setup(): void {
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0x111111));
this.renderer.shadowMap.enabled = true;
this.orbit = new OrbitControls(this.camera, this.renderer.domElement);
this.orbit.enabled = true;
this.camera.position.set(10, 30, 100);
// this.camera.position.set(0, 0, 0);
// this.addLights();
this.addObj();
this.animate();
// this.test();
// this.addPots();
// this.loadZip3();
this.camera.lookAt(new THREE.Vector3());
document.body.appendChild(this.renderer.domElement);
}
async addObj() {
let url = '/obj/fbx/woman/succubus.fbx';
let obj:any = await FineLoader.loadFbx(url);
this.fitModel(obj);
// let url = '/obj/fbx/woman/succubus.fbx';
// if (url.indexOf(".fbx") != -1) {
// this.loadFbxObj(url);
// }
// else {
// this.loadDaeObj(url);
// }
}
fitModel(group: THREE.Object3D): void {
FitSize.resize(group, 100);
this.scene.add(group);
var helper:THREE.BoxHelper = new THREE.BoxHelper(group);
var size:THREE.Vector3 = Tooler.getBoxSize(helper);
// var box:THREE.Mesh = new THREE.Mesh(new THREE.BoxGeometry(size.x , size.y, size.z), new THREE.MeshStandardMaterial({
// color: new THREE.Color(0xff9900),
// opacity: 0.3,
// transparent: true
// }))
var ball:THREE.Mesh = new THREE.Mesh(new THREE.SphereGeometry(100), new THREE.MeshStandardMaterial({
side: THREE.DoubleSide,
color: new THREE.Color(0x000000),
opacity: 0.01,
transparent: true
}));
ball.name = 'ball';
// box.material = new THREE.MeshNormalMaterial();
// box.position.copy(helper.position);
this.scene.add(ball);
// this.scene.add(helper);
}
initMaterial(obj: THREE.Object3D): void {
var mat1: THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({ color: 0xffad77 });
var mat2: THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({ color: 0x3cce02 });
var mat3: THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 });
var mat4: THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
var mat5: THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({ color: 0xffffff });
obj.traverse(function (child: any) {
if (child.isMesh) {
// child.castShadow = true;
// child.receiveShadow = true;
console.log(child.name);
if (child.name.indexOf('肌肉') != -1) {
(child as THREE.Mesh).material = mat1;
}
else if (child.name.indexOf('Box') != -1) {
(child as THREE.Mesh).material = mat2;
}
else if (child.name.indexOf('眼睛') != -1) {
(child as THREE.Mesh).material = mat3;
}
else if (child.name.indexOf('QuadPatch') != -1) {
// (child as THREE.Mesh).material = mat4;
child.parent.remove(child);
}
else {
(child as THREE.Mesh).material = mat5;
}
}
});
}
addLights(): void {
var ambient: THREE.AmbientLight = new THREE.AmbientLight(0xffffff);
ambient.intensity = 0.8;
this.scene.add(ambient);
var directionalLight: THREE.DirectionalLight = new THREE.DirectionalLight(0xffffff);
this.scene.add(directionalLight);
directionalLight.position.set(20, 60, 20);
directionalLight.lookAt(new THREE.Vector3());
}
}```
index.js
```import './index.less'
import App from'./App'
import { GUI } from 'three/examples/jsm/libs/dat.gui.module';
let app = new App();
app.setup();
let gui;
let API = {
spotLight: true,
spotLightColor: 0xffffff,
spotLightIntensity: 0.7,
spotLightAngle: 0.3,
spotLightPenumbra: 0.2,
spotLightDistance: 50,
spotLightDecay: 2,
directionalLight: true,
directionalLightColor: 0xffffff,
directionalLightIntensity: 0.7,
obj: true,
objRoughness: 0.1,
objMetalness: 0.1,
objColor: 0xff0000,
objEmissive: 0x000000,
objOpacity: 1.0,
plane: true,
planeRoughness: 0.1,
planeMetalness: 0.1,
planeColor: 0xff0000,
planeEmissive: 0x000000,
};
initGui();
function updateGUIParam(){
app.updateGUIParam(API);
}
function initGui() {
gui = new GUI();
gui.add( API, 'spotLight' ).name( '聚光灯' ).onChange( updateGUIParam );
gui.addColor( API, 'spotLightColor' ).name( 'color' ).onChange( updateGUIParam );
gui.add( API, 'spotLightIntensity', 0.0, 10.0).name( 'intensity' ).onChange( updateGUIParam );
gui.add( API, 'spotLightAngle', 0.0, 2.0 ).name( 'angle' ).onChange( updateGUIParam );
gui.add( API, 'spotLightPenumbra', 0.0, 2.0 ).name( 'penumbra' ).onChange( updateGUIParam );
gui.add( API, 'spotLightDistance', 0.0, 100 ).name( 'distance' ).onChange( updateGUIParam );
gui.add( API, 'spotLightDecay', 0.0, 10 ).name( 'decay' ).onChange( updateGUIParam );
gui.add( API, 'directionalLight' ).name( '平行光' ).onChange( updateGUIParam );
gui.addColor( API, 'directionalLightColor' ).name( 'color' ).onChange( updateGUIParam );
gui.add( API, 'directionalLightIntensity', 0.0, 10.0).name( 'intensity' ).onChange( updateGUIParam );
gui.add( API, 'obj' ).name( '物体' ).onChange( updateGUIParam );
gui.add( API, 'objRoughness', 0.0, 2.0 ).name( 'roughness' ).onChange( updateGUIParam );
gui.add( API, 'objMetalness', 0.0, 2.0 ).name( 'metalness' ).onChange( updateGUIParam );
gui.addColor( API, 'objColor' ).name( 'color' ).onChange( updateGUIParam );
gui.addColor( API, 'objEmissive' ).name( 'emissive' ).onChange( updateGUIParam );
gui.add( API, 'objOpacity', 0.0, 1.0 ).name( 'opacity' ).onChange( updateGUIParam );
gui.add( API, 'plane' ).name( '地面' ).onChange( updateGUIParam );
gui.add( API, 'planeRoughness', 0.0, 2.0 ).name( 'roughness' ).onChange( updateGUIParam );
gui.add( API, 'planeMetalness', 0.0, 2.0 ).name( 'metalness' ).onChange( updateGUIParam );
gui.addColor( API, 'planeColor' ).name( 'color' ).onChange( updateGUIParam );
gui.addColor( API, 'planeEmissive' ).name( 'emissive' ).onChange( updateGUIParam );
}
let $camera = $(".camera");
$camera.click(function(e){
$camera.toggleClass("open");
app.toggerControl($camera.hasClass("open"));
});
let $hide = $(".hide");
$hide.click(function(e){
$hide.toggleClass("open");
app.toggerHide($hide.hasClass("open"));
});
$(window).keydown(function(event){
console.log(event.keyCode);
if(event.keyCode == 67){
$camera.click();
}
else if(event.keyCode == 72){
$hide.click();
}
})```
App.ts
```import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { DragControls } from 'three/examples/jsm/controls/DragControls';
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls';
export default class App {
public static ZERO:THREE.Vector3 = new THREE.Vector3();
public static TOTAL:number = 0;
public static SELECTED_COLOR:number = 0xff8800;
public static NORMAL_COLOR:number = 0xa0a0a0;
public static NORMAL_MATERIAL:THREE.MeshNormalMaterial = new THREE.MeshNormalMaterial();
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
tubeMesh: THREE.Mesh;
tubeFrame: THREE.Mesh;
orbit: OrbitControls;
curObject: THREE.Mesh|THREE.Line;
pots: Array<THREE.Mesh>;
controls: TrackballControls;
dragControls: DragControls;
dragItems: Array<THREE.Mesh|THREE.Line>;
stats: any;
constructor() {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0, 1000);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
window.addEventListener("resize", e => this.onResize(e), false);
}
setStats(stats: any){
this.stats = stats;
}
set(param: any){
if(this.curObject){
this.curObject.position.set(param.x, param.y, param.z);
}
}
del(){
if(this.curObject){
console.log("del before:" + this.dragItems.length);
this.scene.remove(this.curObject);
this.dragItems = this.dragItems.filter(item => {
return item != this.curObject;
});
this.pots = this.pots.filter(item => {
return item != this.curObject;
});
console.log("del after:" + this.dragItems.length);
console.log(this.dragItems);
this.curObject.geometry.dispose();
(this.curObject.material as any).dispose();
this.curObject = null;
this.initDrag();
}
}
onResize(e:Event):void{
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
animate():void {
requestAnimationFrame(() => {
this.animate();
});
this.stats && this.stats.update();
this.renderer.render(this.scene, this.camera);
}
updateGUIParam(param: any){
if(this.tubeMesh){
(this.tubeMesh.material as THREE.MeshBasicMaterial).color = new THREE.Color(param.meshColor);
(this.tubeFrame.material as THREE.MeshBasicMaterial).color = new THREE.Color(param.lineColor);
(this.tubeMesh.material as THREE.MeshBasicMaterial).opacity = param.meshOpacity;
(this.tubeFrame.material as THREE.MeshBasicMaterial).opacity = param.lineOpacity;
}
this.pots.forEach((item:THREE.Mesh) => {
item.scale.set(param.scale, param.scale, param.scale);
})
}
setup():void {
console.log("start");
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0xffffff));
this.renderer.shadowMap.enabled = true;
document.body.appendChild(this.renderer.domElement);
this.orbit = new OrbitControls(this.camera, this.renderer.domElement);
this.orbit.enabled = false;
this.camera.position.set(10, 10, 10);
this.pots = [];
this.dragItems = [];
this.addPlane();
this.addDrag();
this.animate();
this.camera.lookAt(new THREE.Vector3());
console.log(this.camera);
}
toggerControl(use: boolean):void{
this.orbit.enabled = use;
this.dragControls.enabled = !use;
}
addDrag():void{
let controls = new TrackballControls( this.camera, this.renderer.domElement );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
this.controls = controls;
this.initDrag();
}
initDrag(){
if(this.dragControls){
this.dragControls.dispose();
this.dragControls = null;
}
var dragControls = new DragControls( this.dragItems, this.camera, this.renderer.domElement );
dragControls.addEventListener( 'dragstart', (e) => {
this.changeCurObject(e.object);
this.controls.enabled = false;
} );
dragControls.addEventListener( 'drag', (e) => {
this.postInfo(e.object);
} );
dragControls.addEventListener( 'dragend', () => {
this.controls.enabled = true;
} );
this.dragControls = dragControls;
}
addPlane():void{
let gridHelper = new THREE.GridHelper(4000, 4000);
(gridHelper.material as any).transparent = true;
(gridHelper.material as any).opacity = 0.4;
this.scene.add(gridHelper);
this.scene.add(new THREE.AxesHelper(40));
new THREE.FontLoader().load((window as any).CFG.baseURL + "/obj/font/gentilis_bold.typeface.json", (font) => {
let param = {
font: font,
size: 4,
height: 1
}
let xw = new THREE.Mesh(new THREE.TextGeometry("X", param), App.NORMAL_MATERIAL);
xw.position.set(30, 0, 0);
let yw = new THREE.Mesh(new THREE.TextGeometry("Y", param), App.NORMAL_MATERIAL);
yw.position.set(0, 30, 0);
let zw = new THREE.Mesh(new THREE.TextGeometry("Z", param), App.NORMAL_MATERIAL);
zw.position.set(0, 0, 30);
this.scene.add(xw);
this.scene.add(yw);
this.scene.add(zw);
xw.geometry.center();
yw.geometry.center();
zw.geometry.center();
// console.log(new THREE.Box3().setFromObject(xw));
})
}
changeCurObject(obj: THREE.Mesh|THREE.Line){
if(this.curObject){
(this.curObject as any).material.color = new THREE.Color(App.NORMAL_COLOR);
}
this.curObject = obj;
(this.curObject as any).material.color = new THREE.Color(App.SELECTED_COLOR);
}
getCanvas(n: any){
let w = 256;
let h = 256;
let canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 256;
let ctx = canvas.getContext("2d");
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, w, h);
ctx.font = 90 + "px bold";
ctx.fillStyle = "#000000";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(n, w / 2, h / 2);
return canvas;
}
postInfo(pot: THREE.Mesh){
window.dispatchEvent(new CustomEvent("info", {
detail: {
position: pot.position
}
}))
}
addPots(list: Array<number>){
console.log("total: " + list.length / 3);
let box = new THREE.BoxGeometry();
let mat = new THREE.MeshNormalMaterial();
for(let i = 0; i < list.length; i += 3){
// let pot = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshBasicMaterial({
// color: App.SELECTED_COLOR,
// map: new THREE.CanvasTexture(this.getCanvas(++App.TOTAL))
// }));
let pot = new THREE.Mesh(box, mat);
pot.position.set(list[i], list[i + 1], list[i + 2]);
this.scene.add(pot);
// this.pots.push(pot);
// this.dragItems.push(pot);
// this.changeCurObject(pot);
pot.name = "pot" + App.TOTAL;
}
console.log(this.scene);
}
drawObject(){
let list: number[] = [];
this.pots.forEach((item: THREE.Mesh) => {
list.push(item.position.x, item.position.y, item.position.z);
})
let geometry = new THREE.BufferGeometry();
geometry.addAttribute("position", new THREE.BufferAttribute(new Float32Array(list), 3));
// geometry.addAttribute("face", new THREE.BufferAttribute(new Float32Array([0, 1, 2, 1, 2 ,3]), 3));
geometry.computeVertexNormals();
let material = new THREE.MeshBasicMaterial({color: 0xd200ff});
let mesh = new THREE.Line(geometry, material);
this.scene.add(mesh);
mesh.name = "drawObject";
this.dragItems.push(mesh);
this.changeCurObject(mesh);
}
drawTube(){
let pots:Array<THREE.Vector3> = [];
this.pots.forEach(item => {
pots.push(item.position);
})
var curve = new THREE.CatmullRomCurve3(pots);
var extrudeSettings = {
steps: 200,
bevelEnabled: false,
extrudePath: curve
};
let rect = [];
rect.push(new THREE.Vector2(0, 0));
rect.push(new THREE.Vector2(2, 0));
rect.push(new THREE.Vector2(2, 0.1));
rect.push(new THREE.Vector2(0, 0.1));
var shape = new THREE.Shape( rect );
var geometry = new THREE.ExtrudeBufferGeometry( shape, extrudeSettings );
let material = new THREE.MeshBasicMaterial({
color: 0xff3388,
opacity: 0.5,
transparent: true
});
let mesh = new THREE.Mesh(geometry, material);
this.scene.add(mesh);
let wireframeMaterial = new THREE.MeshBasicMaterial({
color: 0x000000,
opacity: 0.5,
wireframe: true,
transparent: true
});
let wireframe = new THREE.Mesh( geometry, wireframeMaterial );
mesh.add( wireframe );
this.tubeMesh = mesh;
this.tubeFrame = wireframe;
mesh.name = "drawTube";
wireframe.name = "drawFrame";
this.dragItems.push(mesh);
this.changeCurObject(mesh);
}
/*
drawTube0(){
let pots:Array<THREE.Vector3> = [];
this.pots.forEach(item => {
pots.push(item.position);
})
var curve = new THREE.CatmullRomCurve3(pots);
let geometry = new THREE.TubeGeometry(curve, 180, 1, 6, false);
let material = new THREE.MeshBasicMaterial({
color: 0xff3388,
opacity: 0.5,
transparent: true
});
let mesh = new THREE.Mesh(geometry, material);
this.scene.add(mesh);
let wireframeMaterial = new THREE.MeshBasicMaterial({
color: 0x000000,
opacity: 0.5,
wireframe: true,
transparent: true
});
let wireframe = new THREE.Mesh( geometry, wireframeMaterial );
mesh.add( wireframe );
this.tubeMesh = mesh;
this.tubeFrame = wireframe;
mesh.name = "drawTube";
wireframe.name = "drawFrame";
this.dragItems.push(mesh);
this.changeCurObject(mesh);
}
*/
}```
FineLoader.ts
```import * as THREE from 'three'
import Tooler from "./Tooler";
import axios from 'axios';
import ListLoader from './ListLoader';
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader'
import { ColladaLoader } from 'three/examples/jsm/loaders/ColladaLoader'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import listener from '../lib/listener';
// import { JSZip } from 'three/examples/js/libs/jszip.min.js';
const JSZip = require('three/examples/js/libs/jszip.min.js');
export class FineLoader extends THREE.Object3D{
modelPath: string = "";
modelName: string = "";
loadingManager: any;
constructor(){
super();
}
async load(fileList:Array<any>){
console.log(fileList);
if(fileList.length == 0){
console.log("未选择文件");
return;
}
this.getStartFile(fileList);
}
getStartFile(data:any){
let file;
for(let i in data){
let fname = data[i].name;
if(fname.match(/\.(gltf|glb)$/i)){
this.loadGltf(data[i]);
break;
}
else if(fname.match(/\.fbx$/i)){
this.loadFbx(data[i]);
break;
}
else if(fname.match(/\.obj$/i)){
this.loadObj(data[i]);
break;
}
else if(fname.match(/\.zip$/i)){
this.loadZip(data[i]);
break;
}
}
}
loadGltf(file:any){
let type = Object.prototype.toString.call(file);
console.log("type", type);
if(type.indexOf("File") != -1){
var reader = new FileReader();
reader.onload = ()=>{
let loader = new GLTFLoader(this.loadingManager);
loader.setCrossOrigin('anonymous');
loader.parse(reader.result, "", (gltf:any)=>{
this.parseOver(gltf.scene);
})
}
reader.readAsArrayBuffer(file);
}
else{
let loader = new GLTFLoader(this.loadingManager);
loader.parse(file.asArrayBuffer(), "", (gltf:any)=>{
this.parseOver(gltf.scene);
})
}
}
loadFbx(file:any){
let type = Object.prototype.toString.call(file);
console.log("type", type);
if(type.indexOf("File") != -1){
var reader = new FileReader();
reader.onload = ()=>{
var loader = new FBXLoader(this.loadingManager);
var obj:any = loader.parse(reader.result, "");
this.parseOver(obj);
}
reader.readAsArrayBuffer(file);
}
else{
var loader = new FBXLoader(this.loadingManager);
var obj = loader.parse(file.asArrayBuffer(), "");
this.parseOver(obj);
}
}
loadObj(file:any){
let type = Object.prototype.toString.call(file);
console.log("type", type);
if(type.indexOf("File") != -1){
var reader = new FileReader();
reader.onload = ()=>{
var loader = new OBJLoader(this.loadingManager);
var obj = loader.parse(reader.result as string);
this.parseOver(obj);
}
reader.readAsText(file);
}
else{
var loader = new OBJLoader(this.loadingManager);
var obj = loader.parse(file.asText());
this.parseOver(obj);
}
}
parseOver(obj:any){
listener.emit("loaded", obj);
}
loadZip(file:any){
let reader = new FileReader();
reader.onload = ()=>{
const zip = new JSZip( reader.result );
this.loadingManager = new THREE.LoadingManager();
this.loadingManager.setURLModifier((url:string) => {
const buffer = zip.files[url].asUint8Array();
const blob = new Blob( [ buffer.buffer ] );
const NewUrl = URL.createObjectURL( blob );
console.log("NewUrl", NewUrl);
return NewUrl
});
// for(let i in zip.files){
// console.log(i, zip.files[i]);
// }
this.getStartFile(zip.files);
}
reader.readAsArrayBuffer(file);
}
}```
Core.d.ts
```// declare module '../asset/lib/ammo'
declare var OIMO;
// declare var THREE;```
Car.ts
```import * as THREE from 'three';
import * as CANNON from 'cannon';
export default class Car extends THREE.Object3D{
world:any;
constructor(world:any){
super();
this.world = world;
this.init();
}
init(){
var chassisShape = new CANNON.Box(new CANNON.Vec3(2, 1, 0.5));
var chassisBody = new CANNON.Body({mass: 100});
chassisBody.addShape(chassisShape);
chassisBody.position.set(0, 0, 4);
chassisBody.angularVelocity.set(0, 0, 0.5);
var options = {
radius: 0.5,
directionLocal: new CANNON.Vec3(0, 0, -1),
suspensionStiffness: 30,
suspensionRestLength: 0.3,
frictionSlip: 5,
dampingRelaxation: 2.3,
dampingCompression: 4.4,
maxSuspensionForce: 100000,
rollInfluence: 0.01,
axleLocal: new CANNON.Vec3(0, 1, 0),
chassisConnectionPointLocal: new CANNON.Vec3(1, 1, 0),
maxSuspensionTravel: 0.3,
customSlidingRotationalSpeed: -30,
useCustomSlidingRotationalSpeed: true
};
// Create the vehicle
var vehicle = new CANNON.RaycastVehicle({
chassisBody: chassisBody,
});
options.chassisConnectionPointLocal.set(1, 1, 0);
vehicle.addWheel(options);
options.chassisConnectionPointLocal.set(1, -1, 0);
vehicle.addWheel(options);
options.chassisConnectionPointLocal.set(-1, 1, 0);
vehicle.addWheel(options);
options.chassisConnectionPointLocal.set(-1, -1, 0);
vehicle.addWheel(options);
vehicle.addToWorld(this.world);
var wheelBodies:any[] = [];
for(var i=0; i<vehicle.wheelInfos.length; i++){
var wheel = vehicle.wheelInfos[i];
var cylinderShape = new CANNON.Cylinder(wheel.radius, wheel.radius, wheel.radius / 2, 20);
var wheelBody = new CANNON.Body({ mass: 1 });
var q = new CANNON.Quaternion();
q.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), Math.PI / 2);
wheelBody.addShape(cylinderShape, new CANNON.Vec3(), q);
wheelBodies.push(wheelBody);
// demo.addVisual(wheelBody);
}
// Update wheels
this.world.addEventListener('postStep', function(){
for (var i = 0; i < vehicle.wheelInfos.length; i++) {
vehicle.updateWheelTransform(i);
var t = vehicle.wheelInfos[i].worldTransform;
wheelBodies[i].position.copy(t.position);
wheelBodies[i].quaternion.copy(t.quaternion);
}
});
}
}```
Part.ts
```import * as THREE from 'three'
export default class Part {
map:any = {};
constructor(obj:THREE.Object3D) {
var mat1:THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({color: 0xffad77});
var mat2:THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({color: 0x3cce02});
var mat3:THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({color: 0xff0000});
// var mat4:THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({color: 0x00ffff});
// var mat5:THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({color: 0xffffff});
var muscle:Array<THREE.Mesh> = [];
var bones:Array<THREE.Mesh> = [];
var eye:Array<THREE.Mesh> = [];
// var tooth:Array<THREE.Mesh> = [];
// var other:Array<THREE.Mesh> = [];
// var lights:Array<THREE.Object3D> = [];
obj.traverse( function ( child:any) {
if ( child.isMesh ) {
// child.castShadow = true;
// child.receiveShadow = true;
// console.log(child.name);
if(child.name.indexOf('肌肉') != -1){
(child as THREE.Mesh).material = mat1;
muscle.push(child);
}
else if(child.name.indexOf('骨骼') != -1){
(child as THREE.Mesh).material = mat2;
bones.push(child);
// child.name = child.name.replace("Box", "骨骼");
}
else if(child.name.indexOf('眼睛') != -1){
(child as THREE.Mesh).material = mat3;
eye.push(child);
}
// else if(child.name.indexOf('牙') != -1){
// (child as THREE.Mesh).material = mat2;
// child.name = child.name.replace("牙", "骨骼");
// tooth.push(child);
// }
// else if(child.name.indexOf('QuadPatch') != -1){
// child.parent.remove(child);
// }
else{
// console.log(child.name);
// (child as THREE.Mesh).material = mat5;
// other.push(child);
}
}
else{
// if(child.name.indexOf('Omni') != -1){
// lights.push(child);
// }
}
} );
this.map['muscle'] = {material: mat1, mesh: muscle};
this.map['bones'] = {material: mat2, mesh: bones};
this.map['eye'] = {material: mat3, mesh: eye};
// this.map['tooth'] = {material: mat4, mesh: tooth};
// this.map['other'] = {material: mat5, mesh: other};
}
change(type:string, attr:string, data:any):void {
if(attr == 'roughness' || attr == 'metalness' || attr == 'visible'){
this.map[type].material[attr] = data;
}
else if(attr == 'color'){
this.map[type].material[attr] = new THREE.Color(data);
}
else if(attr == 'alpha'){
this.map[type].material.opacity = data;
this.map[type].material.transparent = true;
}
}
toggle(key:string):void{
this.map[key].mesh.forEach((item:THREE.Mesh) => {
item.visible = !item.visible;
});
}
}```
Game.ts
```import * as THREE from 'three'
// let OrbitControls = require('three-orbit-controls')(THREE);
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { TDSLoader } from 'three/examples/jsm/loaders/TDSLoader';
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader';
import { EquirectangularToCubeGenerator } from 'three/examples/jsm/loaders/EquirectangularToCubeGenerator';
import { PMREMGenerator } from 'three/examples/jsm/pmrem/PMREMGenerator';
import { PMREMCubeUVPacker } from 'three/examples/jsm/pmrem/PMREMCubeUVPacker';
import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter';
import { Reflector } from 'three/examples/jsm/objects/Reflector';
const ThreeBSP = require('three-js-csg')(THREE);
export default class Game {
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
ambient: THREE.AmbientLight;
directional: THREE.DirectionalLight;
raycaster: THREE.Raycaster = new THREE.Raycaster();
model: THREE.Object3D;
uniforms: any;
constructor() {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 900);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
window.addEventListener("mousedown", e => this.onMouseDown(e), false);
window.addEventListener("resize", e => this.onResize(e), false);
}
onResize(e:Event):void{
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
onMouseDown(e: MouseEvent):void{
let x = (e.clientX / window.innerWidth) * 2 - 1;
let y = -(e.clientY / window.innerHeight) * 2 + 1;
this.raycaster.setFromCamera({x: x, y: y}, this.camera);
let intersects = this.raycaster.intersectObjects(this.scene.children, true);
console.log(intersects[0]);
if(intersects[0] && intersects[0].face){
let n = intersects[0].face.normal;
console.log("aim normal");
console.log(n);
let obj: any = intersects[0].object;
obj.geometry.faces.forEach((element:any) => {
if(this.theSame(element.normal, n)){
element.materialIndex = 0;
}
else{
console.log(element.normal);
}
});
obj.geometry.groupsNeedUpdate = true;
}
}
theSame(a:THREE.Vector3, b:THREE.Vector3){
if(Math.abs(a.x - b.x) < 0.001){
if(Math.abs(a.y - b.y) < 0.001){
if(Math.abs(a.z - b.z) < 0.001){
return true;
}
}
}
return false;
}
changeColor(param: any):void {
if (param.name == "Background") {
this.renderer.setClearColor(new THREE.Color(param.data));
}
else if (param.name == "AmbientLight") {
this.ambient.color = new THREE.Color(param.data);
}
else if (param.name == "DirectionalLight") {
this.directional.color = new THREE.Color(param.data)
}
}
saveObject():void{
let embed = $('#embed').is(':checked');
let exporter = new GLTFExporter();
exporter.parse(this.model, (result: any) => {
console.log(result);
if ( result instanceof ArrayBuffer ) {
this.saveArrayBuffer( result, 'scene.glb' );
} else {
var output = JSON.stringify( result, null, 2 );
this.saveString( output, 'scene.gltf' );
}
}, {
binary: false,
embedImages: embed,
forcePowerOfTwoTextures: embed,
truncateDrawRange: false
});
}
loadObject():void{
let loader = new GLTFLoader();
loader.setPath('/obj/gl/');
loader.load('win.gltf', (gltf) => {
console.log("gltf");
console.log(gltf);
gltf.scene.traverse((child: any) => {
if(child.isMesh){
console.log(child);
child.receiveShadow = true;
child.castShadow = true;
if(child.material.map){
child.material.map.flipY = true;
}
// child.material.map.rotation = -Math.PI;
// child.geometry.attributes.uv.array.forEach((v:number, i:number) => {
// if(i % 2 == 1){
// v = 1 - v;
// }
// });
child.uvsNeedUpdate = true;
}
})
gltf.scene.position.set(0, 4, 0);
gltf.scene.scale.set(40, 40, 40);
this.scene.add(gltf.scene);
this.scene.add(new THREE.BoxHelper(gltf.scene, new THREE.Color(0x333333)));
})
}
save( blob: any, filename: string ) {
var link = document.createElement( 'a' );
link.style.display = 'none';
document.body.appendChild( link ); // Firefox workaround, see #6594
link.href = URL.createObjectURL( blob );
link.download = filename;
link.click();
}
saveString( text: any, filename:string ) {
this.save( new Blob( [ text ], { type: 'text/plain' } ), filename );
}
saveArrayBuffer( buffer: any, filename: string ) {
this.save( new Blob( [ buffer ], { type: 'application/octet-stream' } ), filename );
}
animate():void {
requestAnimationFrame(() => {
this.animate();
});
if(this.uniforms){
this.uniforms.time.value += 0.02;
}
this.renderer.render(this.scene, this.camera);
}
setup():void {
this.model = new THREE.Group();
this.scene.add(this.model);
let m = new THREE.MeshStandardMaterial();
// specularMap//高光贴图
// diffuseMap//颜色贴图
let list = [
m.envMap,
m.bumpMap,//细节贴图,没有光影效果
m.alphaMap,
m.lightMap,
m.metalnessMap,//金属性
m.normalMap,//凹凸细节,模拟光影效果
m.emissiveMap,//自发光
m.displacementMap//高模烘培贴图,给低模更真实的效果
]
this.camera.position.set(2, 4, 12);
this.camera.rotation.set(0.4, 0.2, 0.1);
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0x909090));
this.renderer.shadowMap.enabled = true;
document.body.appendChild(this.renderer.domElement);
new OrbitControls(this.camera, this.renderer.domElement);
this.addGrid();
this.addPlane();
this.addLights();
this.addMirror();
this.addShader();
this.addBSPObject();
this.addLine();
this.addTube();
this.addExtrude();
this.addBalls();
this.addFacesImage();
this.addDraw();
this.loadJSON();
this.load3DS();
this.loadGLTF();
this.animate();
}
addGrid():void{
let grid = new THREE.GridHelper(80, 80);
this.scene.add(grid);
}
addPlane():void{
let geometry = new THREE.PlaneGeometry(40, 40);
let meterial = new THREE.MeshStandardMaterial({color: 0x909090, side: THREE.DoubleSide});
let mesh = new THREE.Mesh(geometry, meterial);
mesh.receiveShadow = true;
mesh.rotateX(Math.PI * -90 / 180);
this.scene.add(mesh);
}
addShader():void{
this.uniforms = {
time: {type: "f", value: 0.1}
}
let vertexShader = $("#vertexShader").text();
let fragmentShader = $("#fragmentShader").text();
console.log(vertexShader);
console.log(fragmentShader);
let geometry = new THREE.BoxGeometry(2, 2, 2);
let meterial = new THREE.ShaderMaterial({
vertexShader: vertexShader,
fragmentShader: fragmentShader,
uniforms: this.uniforms
})
let mesh = new THREE.Mesh(geometry, meterial);
this.scene.add(mesh);
mesh.position.set(2, 6, -5);
}
addMirror():void{
let planeGeometry = new THREE.PlaneBufferGeometry(8, 8);
let options = {
clipBias: 0.01,
textureWidth: window.innerWidth * window.devicePixelRatio,
textureHeight: window.innerHeight * window.devicePixelRatio,
color: new THREE.Color(0xffffff),
recursion: 0
};
let mirror = new Reflector(planeGeometry, options);
mirror.rotateX(Math.PI * -90 / 180);
mirror.position.y = 0.1;
this.scene.add(mirror);
}
addLights():void{
let ambient = new THREE.AmbientLight(0xffffff);
this.scene.add(ambient);
let directional = new THREE.DirectionalLight(0xffffff);
directional.castShadow = true;
const shadowSize = 40;
directional.shadow.camera.left = -shadowSize;
directional.shadow.camera.right = shadowSize;
directional.shadow.camera.top = shadowSize;
directional.shadow.camera.bottom = -shadowSize;
directional.shadow.camera.far = 200;
directional.position.set(5, 5, -5);
directional.lookAt(new THREE.Vector3());
this.scene.add(directional);
this.scene.add(new THREE.DirectionalLightHelper(directional));
this.ambient = ambient;
this.directional = directional;
}
addFacesImage():void{
var material1 = new THREE.MeshBasicMaterial( {map: new THREE.TextureLoader().load('/texture/p1.jpg')} );
var material2 = new THREE.MeshBasicMaterial( {map: new THREE.TextureLoader().load('/texture/p2.jpg')} );
var material3 = new THREE.MeshBasicMaterial( {map: new THREE.TextureLoader().load('/texture/p3.jpg')} );
var material4 = new THREE.MeshBasicMaterial( {map: new THREE.TextureLoader().load('/texture/p4.jpg')} );
var material5 = new THREE.MeshBasicMaterial( {map: new THREE.TextureLoader().load('/texture/p5.jpg')} );
var material6 = new THREE.MeshBasicMaterial( {map: new THREE.TextureLoader().load('/texture/p6.jpg')} );
var materials = [material1, material2, material3, material4, material5, material6];
let geometry = new THREE.BoxGeometry(2, 2, 2);
// geometry.vertices = [];
// geometry.faceVertexUvs[0] = [];
// geometry.uvsNeedUpdate = true;
let mesh = new THREE.Mesh(geometry, materials);
mesh.receiveShadow = true;
mesh.castShadow = true;
mesh.position.set(2, 4, -8);
// this.scene.add(mesh);
this.model.add(mesh);
}
addDraw():void{
let material1 = new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load('/girl.jpg'), side: THREE.FrontSide, color:0xff0000});
let material2 = new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load('/boy.jpg'), side: THREE.FrontSide, color: 0x00ff00});
// material1.map.wrapS = THREE.RepeatWrapping;
// material1.map.wrapT = THREE.RepeatWrapping;
// material2.map.wrapS = THREE.RepeatWrapping;
// material2.map.wrapT = THREE.RepeatWrapping;
// material1.map.repeat.set(10, 10);
// material2.map.repeat.set(10, 10);
let geometry = new THREE.Geometry();
let A = new THREE.Vector3(0, 0, 0);
let B = new THREE.Vector3(10, 0, 0);
let C = new THREE.Vector3(10, 10, 0);
let D = new THREE.Vector3(2, 8, -5);
geometry.vertices.push(A, B, C, D);
let ABC = new THREE.Face3(0, 1, 2, null, new THREE.Color(0xffffff), 0);
let CDA = new THREE.Face3(2, 3, 0, null, new THREE.Color(0xffffff), 1);
geometry.faces.push(ABC);
geometry.faces.push(CDA);
let uvs = geometry.faceVertexUvs[0];
uvs[0] = [
new THREE.Vector2(0, 0),
new THREE.Vector2(1, 0),
new THREE.Vector2(1, 1)
];
uvs[1] = [
new THREE.Vector2(1, 1),
new THREE.Vector2(0, 1),
new THREE.Vector2(0, 0)
]
geometry.uvsNeedUpdate = true;
geometry.center();
geometry.computeVertexNormals();
geometry.computeFaceNormals();
let mesh = new THREE.Mesh(geometry, [material1, material2]);
mesh.receiveShadow = true;
mesh.castShadow = true;
mesh.position.set(-7, 6, -8);
// this.scene.add(mesh);
this.model.add(mesh);
}
addLine():void{
let group = new THREE.Group();
let curve = new THREE.CatmullRomCurve3([
new THREE.Vector3(3, 4, 2),
new THREE.Vector3(1, 2, -3),
new THREE.Vector3(-3, 0, 4),
new THREE.Vector3(2, -3, 1),
], true);
let geometry = new THREE.Geometry();
geometry.vertices = curve.getSpacedPoints(50);
let mesh = new THREE.Line(geometry);
group.add(mesh);
let sphereGeometry = new THREE.SphereGeometry(0.1);
let mat = new THREE.MeshNormalMaterial();
let spacePoints = curve.getPoints(50);
for(let point of spacePoints){
let helper = new THREE.Mesh(sphereGeometry, mat);
helper.position.copy(point);
group.add(helper);
}
group.position.set(-4, 4, 6);
this.scene.add(group);
}
addBSPObject():void{
let mat = new THREE.MeshStandardMaterial({color: 0xf0f0f0});
mat.map = new THREE.TextureLoader().load("/girl.jpg");
let aMaterial = new THREE.MeshLambertMaterial({color: 0xff0000, opacity: 0.72, transparent: true});
let aMesh = new THREE.Mesh(new THREE.BoxGeometry(3, 3, 3), aMaterial);
this.scene.add(aMesh);
aMesh.receiveShadow = true;
aMesh.castShadow = true;
let bMaterial = new THREE.MeshToonMaterial({
color: new THREE.Color(0xff4400),
specular: new THREE.Color(0x0022ff),
reflectivity: 0.4,
shininess: 30
});
let bMesh = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 1), bMaterial);
this.scene.add(bMesh);
bMesh.receiveShadow = true;
bMesh.castShadow = true;
bMesh.position.y = 1;
let aBSP = new ThreeBSP(aMesh);
let bBSP = new ThreeBSP(bMesh);
let rBSP = aBSP.subtract(bBSP);
// let rBSP = cBSP.union(sBSP);
let rMesh = rBSP.toMesh();
rMesh.material = mat;
this.scene.add(rMesh);
rMesh.receiveShadow = true;
rMesh.castShadow = true;
aMesh.position.set(-4, 3, 0);
bMesh.position.set(0, 3, 0);
rMesh.position.set(4, 3, 0);
let helper = new THREE.BoxHelper(rMesh, new THREE.Color(0xff0000));
this.scene.add(helper);
helper.position.copy(rMesh.position);
// this.model.add(rMesh);
}
addBalls():void{
let sphere = new THREE.SphereGeometry(1, 16, 16);
let material = new THREE.MeshToonMaterial({
color: new THREE.Color(0xff8855),
specular: new THREE.Color(0x4422ff),
reflectivity: 0.7,
shininess: 40
})
let ball = new THREE.Mesh(sphere, material);
this.scene.add(ball);
ball.receiveShadow = true;
ball.castShadow = true;
ball.position.set(4, 2, -5);
}
addExtrude():void{
let shape = new THREE.Shape();
shape.moveTo(0, 0);
shape.lineTo(1, 0);
shape.lineTo(1, 1.2);
shape.lineTo(0, 1);
// shape.arc(0, 0, 1, 0, Math.PI * 2, false);
let p1 = new THREE.Vector3(-5, 10, 2);
let p2 = new THREE.Vector3(-2, 4, 10);
let path = new THREE.LineCurve3(p1, p2);
let extrudeSettings = {
bevelEnabled: true,
bevelSize: 0.4,
bevelThickness: 0.4,
bevelOffset: 0,
bevelSegments: 4,
step: 4,
depth: 2,
extrudePath: path
}
let extrude = new THREE.ExtrudeGeometry(shape, extrudeSettings);
let mesh = new THREE.Mesh(extrude, new THREE.MeshNormalMaterial())
this.scene.add(mesh);
}
addTube():void{
var curve = new THREE.CatmullRomCurve3( [
new THREE.Vector3( 0, 10, - 10 ), new THREE.Vector3( 10, 0, - 10 ),
new THREE.Vector3( 20, 0, 0 ), new THREE.Vector3( 30, 0, 10 ),
new THREE.Vector3( 30, 0, 20 ), new THREE.Vector3( 20, 0, 30 ),
new THREE.Vector3( 10, 0, 30 ), new THREE.Vector3( 0, 0, 30 ),
new THREE.Vector3( - 10, 10, 30 ), new THREE.Vector3( - 10, 20, 30 ),
new THREE.Vector3( 0, 30, 30 ), new THREE.Vector3( 10, 30, 30 ),
new THREE.Vector3( 20, 30, 15 ), new THREE.Vector3( 10, 30, 10 ),
new THREE.Vector3( 0, 30, 10 ), new THREE.Vector3( - 10, 20, 10 ),
new THREE.Vector3( - 10, 10, 10 ), new THREE.Vector3( 0, 0, 10 ),
new THREE.Vector3( 10, - 10, 10 ), new THREE.Vector3( 20, - 15, 10 ),
new THREE.Vector3( 30, - 15, 10 ), new THREE.Vector3( 40, - 15, 10 ),
new THREE.Vector3( 50, - 15, 10 ), new THREE.Vector3( 60, 0, 10 ),
new THREE.Vector3( 70, 0, 0 ), new THREE.Vector3( 80, 0, 0 ),
new THREE.Vector3( 90, 0, 0 ), new THREE.Vector3( 100, 0, 0 )
] );
let geometry = new THREE.TubeGeometry(curve, 180, 1, 12, false);
let mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({color: 0xff3388}));
this.scene.add(mesh);
var wireframeMaterial = new THREE.MeshBasicMaterial( { color: 0x000000, opacity: 0.3, wireframe: true, transparent: true } );
var wireframe = new THREE.Mesh( geometry, wireframeMaterial );
mesh.add( wireframe );
mesh.position.set(-12, 5, -8);
}
loadJSON():void {
let loader = new THREE.ObjectLoader();
loader.load("/obj/teapot-claraio.json", (obj: any) => {
obj.material = new THREE.MeshStandardMaterial({color: 0x33ff88});
obj.position.set(0, 2, -3);
this.scene.add(obj);
this.scene.add(new THREE.BoxHelper(obj, new THREE.Color(0xff0000)));
})
}
load3DS():void {
let loader = new TDSLoader();
let isDebug = location.search.indexOf("debug=1") != -1;
var resourcePath = '/obj/portalgun/textures/';
var url = '/obj/portalgun/portalgun.3ds';
if(isDebug){
resourcePath = '/obj/house/';
url = '/obj/house/QQ.3DS';
}
loader.setResourcePath(resourcePath);
loader.load(url, (object) => {
object.traverse((child: any) => {
if (child.isMesh) {
console.log("3ds mesh");
console.log(child);
child.receiveShadow = true;
child.castShadow = true;
}
});
isDebug && object.scale.set(0.05, 0.05, 0.05);
object.position.set(4, 3, 4);
this.scene.add(object);
this.scene.add(new THREE.BoxHelper(object));
})
}
loadGLTF():void{
let rgbeLoader = new RGBELoader();
rgbeLoader.setDataType(THREE.UnsignedByteType);
rgbeLoader.load( '/obj/glTF/pedestrian_overpass_2k.hdr', texture => {
var cubeGenerator = new EquirectangularToCubeGenerator( texture, { resolution: 1024 } );
var texture: THREE.DataTexture = cubeGenerator.update( this.renderer );
var pmremGenerator = new PMREMGenerator( texture );
pmremGenerator.update( this.renderer );
var pmremCubeUVPacker = new PMREMCubeUVPacker( pmremGenerator.cubeLods );
pmremCubeUVPacker.update( this.renderer );
var envMap = pmremCubeUVPacker.CubeUVRenderTarget.texture;
let loader = new GLTFLoader();
loader.setPath('/obj/glTF/');
loader.load('DamagedHelmet.gltf', (gltf) => {
gltf.scene.traverse((child:any) => {
if(child.isMesh){
child.material.envMap = envMap;
child.receiveShadow = true;
child.castShadow = true;
}
})
gltf.scene.position.set(0, 3, 3);
this.scene.add(gltf.scene);
this.scene.add(new THREE.BoxHelper(gltf.scene));
})
})
}
}```
Store.ts
```import * as THREE from "three";
export default class Store{
sphereGeos:any = [];
boxGeos:any = [];
mats:any = [];
cylinderGeos: any = [];
constructor(){
for(var i = 0; i < 8; i++){
let size = 0.4 + Math.random() * 4;
this.sphereGeos.push(new THREE.SphereGeometry(size, 10, 10));
this.boxGeos.push(new THREE.BoxGeometry(size, size, size));
this.cylinderGeos.push(new THREE.CylinderGeometry(size, size, size));
let color = new THREE.Color(0xffffff);
let mat:THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({color});
mat.map = new THREE.TextureLoader().load("/asset/img/m" + (i % 6 + 1) + ".jpg");
mat.emissive = new THREE.Color(0, 0, 0);
mat.metalness = 0.3;
mat.roughness = 0.3;
this.mats.push(mat);
}
}
getBufferGeometry(type:string){
let geo;
if(type == "box"){
geo = this.getBoxBufferGeometry();
}
else if(type == "sphere"){
geo = this.getSphereBufferGeometry();
}
if(type == "cylinder"){
geo = this.getCylinderBufferGeometry();
}
// return new THREE.BufferGeometry().fromGeometry(geo);
return geo;
}
getCylinderBufferGeometry(){
let n = Math.floor(Math.random() * this.cylinderGeos.length);
return this.cylinderGeos[n];
}
getSphereBufferGeometry(){
let n = Math.floor(Math.random() * this.sphereGeos.length);
return this.sphereGeos[n];
}
getBoxBufferGeometry(){
let n = Math.floor(Math.random() * this.boxGeos.length);
return this.boxGeos[n];
}
getMaterial(){
let n = Math.floor(Math.random() * this.mats.length);
return this.mats[n];
}
}```
PhysicsView.ts
```import * as THREE from "three";
import * as CANNON from 'cannon';
export default class PhysicsView{
mesh:THREE.Object3D;
body:any;
world:any;
type:string;
constructor(mesh:THREE.Mesh, type:string, world:any, isStatic?:boolean, scene?:THREE.Object3D){
this.mesh = mesh;
this.world = world;
this.type = type;
let box = new THREE.Box3().setFromObject(mesh);
let size = box.getSize(new THREE.Vector3());
let shape;
if(type == "box"){
shape = new CANNON.Box(new CANNON.Vec3(size.x / 2, size.y / 2, size.z / 2));
}
else if(type == "sphere"){
shape = new CANNON.Sphere(size.x / 2);
}
else if(type == "cylinder"){
this.mesh = new THREE.Object3D();
this.mesh.position.copy(mesh.position);
this.mesh.quaternion.copy( mesh.quaternion );
this.mesh.add(mesh);
scene.add(this.mesh);
mesh.position.set(0, 0, 0);
mesh.rotation.set(Math.PI / 2, 0, 0);
mesh.scale.set(1, 1, 1);
shape = new CANNON.Cylinder(size.x / 2, size.x / 2, size.y, 8);
}
this.body = new CANNON.Body({
mass: isStatic ? 0 : 10 * size.x * size.y * size.z,
material: new CANNON.Material({ friction: 0.3, restitution: 0.7}) ,
position: new CANNON.Vec3(this.mesh.position.x, this.mesh.position.y, this.mesh.position.z),
shape: shape
});
this.world.add(this.body);
}
getMeshFromShape(body:any, mat:any){
let shape:any = body.shape[0];
var geo = new THREE.Geometry();
// Add vertices
for (var i = 0; i < shape.vertices.length; i++) {
var v = shape.vertices[i];
geo.vertices.push(new THREE.Vector3(v.x, v.y, v.z));
}
for(var i=0; i < shape.faces.length; i++){
var face = shape.faces[i];
// add triangles
var a = face[0];
for (var j = 1; j < face.length - 1; j++) {
var b = face[j];
var c = face[j + 1];
geo.faces.push(new THREE.Face3(a, b, c));
}
}
geo.computeBoundingSphere();
geo.computeFaceNormals();
return new THREE.Mesh( geo, mat );
}
updateBodyTrs(){
// this.body.position = this.mesh.position.clone();
let a2r = 1;
if(this.mesh.rotation.x != 0){
this.body.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), this.mesh.rotation.x * a2r);
}
else if(this.mesh.rotation.y != 0){
this.body.quaternion.setFromAxisAngle(new CANNON.Vec3(0, 1, 0), this.mesh.rotation.y * a2r);
}
else if(this.mesh.rotation.z != 0){
this.body.quaternion.setFromAxisAngle(new CANNON.Vec3(0, 0, 1), this.mesh.rotation.z * a2r);
}
}
update(){
this.mesh.position.copy( this.body.position );
// if(this.type == "cylinder"){
// this.body.quaternion.setFromAxisAngle(new CANNON.Vec3(0, 0, 1), this.mesh.rotation.z * Math.PI / 2);
// }
this.mesh.quaternion.copy( this.body.quaternion );
if(this.type == "cylinder"){
// this.mesh.setRotationFromAxisAngle(new CANNON.Vec3(0, 0, 1), Math.PI * 30);
}
this.destory();
}
destory(){
if(this.mesh.position.y < -100){
let x = (0.5 - Math.random()) * 80;
let y = 700;
let z = (0.5 - Math.random()) * 80;
this.body.position = new CANNON.Vec3(x, y, z);
}
}
}```
copy.ts
```export default class Copy {
public static newData(data:any):any{
var obj:any = JSON.parse(JSON.stringify(data));
// console.log('new data', obj);
return obj;
}
}```
PhyView.ts
```import * as THREE from "three";
export default class PhyView{
mesh: THREE.Mesh;
body: any;
param: any;
world: any;
constructor(type:string, size:THREE.Vector3, move:boolean, world:any){
this.world = world;
this.param = {
type: type,
pos: [0, 0, 0], // start position in degree
rot: [0, 0, 0], // start rotation in degree
move: move, // dynamic or statique
density: 1,
friction: 0.8,
restitution: 0.1
}
// phy.w[i] = world.add({type:'cylinder', size:[radius*0.5,30], pos:[x,100,z], rot:[0,0,90], move:true, config:[10,10,0.0], name:'w'+i+'_'+id});
let mat:THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial();
mat.map = new THREE.TextureLoader().load("/asset/img/m1.jpg");
mat.emissive = new THREE.Color(0, 0, 0);
if(type == "box"){
this.mesh = new THREE.Mesh(new THREE.BoxGeometry(size.x, size.y, size.z), mat);
this.param.size = [size.x, size.y, size.z];
}
else if(type == "sphere"){
this.mesh = new THREE.Mesh(new THREE.SphereGeometry(size.x, 16, 16), mat);
this.param.size = [size.x];
}
else if(type == "cylinder"){
this.mesh = new THREE.Mesh(new THREE.CylinderGeometry(size.x / 2, size.x / 2, size.y), mat);
this.param.size = [size.x, size.y, size.x];
}
console.log(this.mesh);
this.mesh.castShadow = true;
this.mesh.receiveShadow = true;
}
setPosition(x:number, y:number, z:number){
// this.body.resetPosition(x, y, z);
this.param.pos = [x, y, z];
// this.update();
}
setRotation(x:number, y:number, z:number){
this.param.rot = [x, y, z];
// this.body.resetRotation(x, y, z);
// this.update();
}
setup(){
this.body = this.world.add(this.param);
this.update();
}
update(){
this.mesh.position.copy( this.body.getPosition() );
this.mesh.quaternion.copy( this.body.getQuaternion() );
this.destory();
}
destory(){
if(this.mesh.position.y < -30){
let x = (0.5 - Math.random()) * 80;
let y = Math.random() * 900;
let z = (0.5 - Math.random()) * 80;
this.body.resetPosition(x, y, z);
}
}
}```
Cache.ts
```import * as THREE from 'three'
export default class Cache {
static _instance: Cache;
model:any;
animate: any;
texture: any;
lightMesh: any;
constructor(){
this.model = {};
this.animate = {};
this.texture = {};
this.lightMesh = [];
}
public static getInstance():Cache{
if(!this._instance){
this._instance = new Cache();
}
return this._instance;
}
getMesh(url:string):THREE.Mesh{
if(this.model[url]){
// console.warn('使用缓存(' + (this.model[url].times++) + ')' + url);
return this.model[url].data.clone();
}
return null;
}
setMesh(url:string, mesh:THREE.Mesh):void{
this.model[url] = {
data: mesh,
times: 1
};
}
getAnimate(url:string):any{
if(this.animate[url]){
// console.warn('使用缓存(' + (this.animate[url].times++) + ')' + url);
return this.animate[url].data;
}
return null;
}
setAnimate(url:string, animate:any):void{
this.animate[url] = {
data: animate,
times: 1
};
}
getTexture(url:string):any{
if(this.texture[url]){
// console.warn('使用缓存(' + (this.texture[url].times++) + ')' + url);
return this.texture[url].data;
}
return null;
}
setTexture(url:string, texture:any):void{
this.texture[url] = {
data: texture,
times: 1
};
}
hasLight(mesh:any):boolean{
var n = this.lightMesh.indexOf(mesh);
if(n == -1){
this.lightMesh.push(mesh);
return false;
}
return true;
}
}```
App.ts
```import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { DragControls } from 'three/examples/jsm/controls/DragControls';
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
export default class App {
public static ZERO:THREE.Vector3 = new THREE.Vector3();
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
objMaterial: THREE.MeshStandardMaterial;
planeMaterial: THREE.MeshStandardMaterial;
orbit: OrbitControls;
spotLight: THREE.SpotLight;
spotDrag: THREE.Mesh;
spotLightHelper: THREE.SpotLightHelper;
directionalLight: THREE.DirectionalLight;
directionalDrag: THREE.Mesh;
directionalLightHelper: THREE.DirectionalLightHelper;
dragControls: DragControls;
debugObjects: Array<THREE.Object3D>;
constructor() {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 900);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
window.addEventListener("resize", e => this.onResize(e), false);
}
onResize(e:Event):void{
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
animate():void {
requestAnimationFrame(() => {
this.animate();
});
this.renderer.render(this.scene, this.camera);
}
updateGUIParam(param: any){
this.spotLight.color = new THREE.Color(param.spotLightColor);
this.spotLight.intensity = param.spotLightIntensity;
this.spotLight.angle = param.spotLightAngle;
this.spotLight.penumbra = param.spotLightPenumbra;
this.spotLight.decay = param.spotLightDecay;
this.spotLight.distance = param.spotLightDistance;
this.directionalLight.color = new THREE.Color(param.directionalLightColor);
this.directionalLight.intensity = param.directionalLightIntensity;
this.objMaterial.roughness = param.objRoughness;
this.objMaterial.metalness = param.objMetalness;
this.objMaterial.color = new THREE.Color(param.objColor);
this.objMaterial.emissive = new THREE.Color(param.objEmissive);
this.objMaterial.opacity = param.objOpacity;
this.planeMaterial.roughness = param.planeRoughness;
this.planeMaterial.metalness = param.planeMetalness;
this.planeMaterial.color = new THREE.Color(param.planeColor);
this.planeMaterial.emissive = new THREE.Color(param.planeEmissive);
if(param.spotLight){
this.scene.add(this.spotLight);
}
else{
this.scene.remove(this.spotLight);
}
if(param.directionalLight){
this.scene.add(this.directionalLight);
}
else{
this.scene.remove(this.directionalLight);
}
console.log(param.spotLight);
}
toggerControl(use: boolean):void{
this.orbit.enabled = use;
this.dragControls.enabled = !use;
}
toggerHide(use: boolean):void{
this.debugObjects.forEach((item: THREE.Object3D) => {
item.visible = use;
})
}
setup():void {
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0x909090));
this.renderer.shadowMap.enabled = true;
document.body.appendChild(this.renderer.domElement);
this.orbit = new OrbitControls(this.camera, this.renderer.domElement);
this.orbit.enabled = false;
this.camera.position.set(7.742, 9.887, 13.769);
this.debugObjects = [];
this.addPlane();
this.addLights();
this.addObj();
this.animate();
this.addDrag();
this.loadObject();
this.camera.lookAt(App.ZERO);
this.toggerControl(true);
}
addDrag():void{
this.spotDrag = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.4, 0.4), new THREE.MeshNormalMaterial());
this.scene.add(this.spotDrag);
this.spotDrag.position.copy(this.spotLight.position);
this.spotDrag.lookAt(this.spotLight.target.position);
this.directionalDrag = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 0.1), new THREE.MeshNormalMaterial());
this.scene.add(this.directionalDrag);
this.directionalDrag.position.copy(this.directionalLight.position);
this.directionalDrag.lookAt(this.directionalLight.target.position);
this.debugObjects.push(this.spotDrag, this.directionalDrag);
let controls = new TrackballControls( this.camera, this.renderer.domElement );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
var dragControls = new DragControls( [this.spotDrag, this.directionalDrag], this.camera, this.renderer.domElement );
dragControls.addEventListener( 'dragstart', () => {
controls.enabled = false;
} );
dragControls.addEventListener( 'drag', () => {
this.spotLight.position.copy(this.spotDrag.position);
this.spotDrag.lookAt(App.ZERO);
this.spotLightHelper.update();
this.directionalLight.position.copy(this.directionalDrag.position);
this.directionalDrag.lookAt(App.ZERO);
this.directionalLightHelper.update();
} );
dragControls.addEventListener( 'dragend', () => {
controls.enabled = true;
} );
this.dragControls = dragControls;
}
addPlane():void{
let geometry = new THREE.PlaneGeometry(30, 30);
let material = new THREE.MeshStandardMaterial({
side: THREE.DoubleSide,
emissive: 0x909090,
color: 0x333333,
roughness: 0,
metalness: 0,
});
let mesh = new THREE.Mesh(geometry, material);
mesh.rotateX(Math.PI * -90 / 180);
// mesh.castShadow = true;
mesh.receiveShadow = true;
// this.scene.add(mesh);
// this.scene.add(new THREE.AxesHelper(4));
this.planeMaterial = material;
}
addObj(){
let material = new THREE.MeshStandardMaterial({
color: 0xff0000,
emissive: 0x000000,
opacity: 1,
premultipliedAlpha: true,
transparent: true,
roughness: 0,
metalness: 0,
})
for(let i = 0; i < 3; i++){
let geometry = i % 2 ? new THREE.BoxGeometry(1, 1, 1) : new THREE.SphereGeometry(0.5, 18, 18);
let mesh = new THREE.Mesh(geometry, material);
mesh.position.set((1 - i) * 2, 1, 0);
mesh.castShadow = true;
mesh.receiveShadow = true;
// this.scene.add(mesh);
}
this.objMaterial = material;
}
addLights():void{
//环境光
var ambient:THREE.AmbientLight = new THREE.AmbientLight(0xffffff);
ambient.intensity = 0.4;
this.scene.add(ambient);
//聚光灯
var spotLight:THREE.SpotLight = new THREE.SpotLight(0xffffff);
spotLight.intensity = 0.7;
spotLight.castShadow = true;
spotLight.angle = 0.3;
spotLight.penumbra = 0.2;
spotLight.decay = 2;
spotLight.distance = 50;
this.scene.add(spotLight);
spotLight.position.set(-2, 7, 4);
this.spotLightHelper = new THREE.SpotLightHelper(spotLight);
this.scene.add(this.spotLightHelper);
//平行光
var directionalLight:THREE.DirectionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.intensity = 0.7;
directionalLight.castShadow = true;
this.scene.add(directionalLight);
directionalLight.position.set(4, 7, 5);
this.directionalLightHelper = new THREE.DirectionalLightHelper(directionalLight);
this.scene.add(this.directionalLightHelper);
this.spotLight = spotLight;
this.directionalLight = directionalLight;
this.debugObjects.push(this.spotLightHelper, this.directionalLightHelper);
}
loadObject():void{
let loader = new GLTFLoader();
loader.setPath('/obj/gl/');
loader.load('win.gltf', (gltf) => {
console.log("gltf");
console.log(gltf);
let mat = new THREE.MeshLambertMaterial({
color: 0xff0000,
emissive: 0xffffff,
emissiveMap: new THREE.TextureLoader().load("/texture/w1.jpg"),
map: new THREE.TextureLoader().load("/texture/w1.jpg")
})
gltf.scene.traverse((child: any) => {
if(child.isMesh){
console.log(child);
child.receiveShadow = true;
child.castShadow = true;
// if(child.material.map){
// child.material.map.flipY = true;
// }
// child.material = mat;
child.uvsNeedUpdate = true;
}
})
let size = new THREE.Box3().setFromObject(gltf.scene).getSize(new THREE.Vector3());
let max = Math.max(size.x, size.y, size.z);
let scale = 10 / max;
gltf.scene.scale.set(scale, scale, scale);
this.scene.add(gltf.scene);
let c = new THREE.Box3().setFromObject(gltf.scene);
let x = (c.min.x + c.max.x) / 2;
let y = (c.min.y + c.max.y) / 2;
let z = (c.min.z + c.max.z) / 2;
gltf.scene.position.set(0 - x, 0 - y, 0 - z);
})
}
}```
App.ts
```import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import listener from '../lib/listener';
import Tooler from './Tooler';
export default class App {
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
orbit: OrbitControls;
group: THREE.Group;
line: THREE.Line;
frame: THREE.BoxHelper;
selectBox: THREE.BoxHelper;
curItem: THREE.Mesh;
rayCaster:THREE.Raycaster = new THREE.Raycaster();
grid:THREE.GridHelper;
axes: THREE.AxesHelper;
isMobile:boolean;
constructor(canvas:HTMLCanvasElement) {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
canvas: canvas
});
window.addEventListener("resize", e => this.onResize(e), false);
listener.on("points", (points:string)=>this.addPoints(points));
listener.on("pointColor", (type:number, color:string)=>this.changePointColor(type, color));
listener.on("lineColor", (color:string)=>this.changeLineColor(color));
listener.on("size", (type:number, size:number)=>this.changeSize(type, size));
listener.on("changeVisible", (obj:any)=>{this.changeVisible(obj)});
listener.on("changePosition", (obj:any)=>{this.changePosition(obj)});
this.isMobile = Tooler.checkMobile();
// canvas.addEventListener("click", (e:MouseEvent)=>this.choose(e));
canvas.addEventListener(this.isMobile ? "touchstart" : "mousedown", (e: any) => this.choose(e), false);
}
changeVisible(obj:any){
if(this.frame){
this.frame.visible = obj.isFrame;
}
this.axes.visible = obj.isAxes;
this.grid.visible = obj.isGrid;
}
changePosition(obj:any){
if(this.curItem){
this.curItem.position.set(obj.x, obj.y, obj.z);
if(this.selectBox){
this.scene.remove(this.selectBox);
this.selectBox = null;
}
this.selectBox = new THREE.BoxHelper(this.curItem, new THREE.Color(0xFF0000));
this.scene.add(this.selectBox);
var id:number = this.getCurIndex();
if(id != -1){
console.log("id = " + id);
(this.line.geometry as THREE.Geometry).vertices[id] = new THREE.Vector3(obj.x, obj.y, obj.z);
(this.line.geometry as THREE.Geometry).verticesNeedUpdate = true;
}
if(this.frame){
this.scene.remove(this.frame);
this.frame = null;
}
this.frame = new THREE.BoxHelper(this.group, new THREE.Color(0xff9900));
this.scene.add(this.frame);
}
}
choose(e:any){
if (this.isMobile) {
e = e.changedTouches[0];
}
let mouse = new THREE.Vector2();
mouse.x = (e.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
if(this.selectBox){
this.scene.remove(this.selectBox);
this.selectBox = null;
}
this.curItem = null;
let obj: any;
this.rayCaster.setFromCamera(mouse, this.camera);
let list = this.scene.children;
let intersectObjects = this.rayCaster.intersectObjects(list, true);
if (intersectObjects[0]) {
obj = intersectObjects[0].object;
if(obj != this.grid && obj != this.axes){
this.curItem = obj;
this.selectBox = new THREE.BoxHelper(obj, new THREE.Color(0xFF0000));
this.scene.add(this.selectBox);
listener.emit("setPosition", this.curItem.position);
}
}
listener.emit("setIndex", this.getCurIndex(), this.group ? this.group.children.length : 0);
}
getCurIndex():number{
var id:number;
if(this.group){
id = this.group.children.findIndex((obj:THREE.Object3D, index:number)=>{
if(obj == this.curItem){
return true;
}
})
}
else{
id = -1;
}
return id;
}
getChooseMesh():THREE.Object3D{
if(this.curItem){
var id:number = this.getCurIndex();
if(id != -1){
return this.group.children[id];
}
}
return null;
}
getAimObjects(type:number):THREE.Object3D[]{
var list:THREE.Object3D[] = [];
if(type == 0){
list = this.group.children;
}
else if(type == 1){
var obj:THREE.Object3D = this.getChooseMesh();
if(obj){
list.push(obj);
}
}
else{
if(this.group.children.length > 0){
list.push(this.group.children[0]);
}
}
return list;
}
changePointColor(type:number, color:string){
var list:THREE.Object3D[] = this.getAimObjects(type);
var mat:THREE.MeshBasicMaterial = new THREE.MeshBasicMaterial({color: new THREE.Color(color)});
for(var i:number = 0; i < list.length; i++){
(list[i] as THREE.Mesh).material = mat;
}
}
changeLineColor(color:string){
this.line.material = new THREE.MeshBasicMaterial({color: new THREE.Color(color)});
}
changeSize(type:number, size:number){
if(size <= 0){
size = 0.01;
}
var list:THREE.Object3D[] = this.getAimObjects(type);
for(var i:number = 0; i < list.length; i++){
(list[i] as THREE.Mesh).scale.setScalar(size);
}
}
addPoints(points:string){
if(this.group){
while(this.group.children.length > 0){
this.group.remove(this.group.children[0]);
}
}
else{
this.group = new THREE.Group();
}
if(this.line){
this.scene.remove(this.line);
}
if(this.frame){
this.scene.remove(this.frame);
}
this.scene.add(this.group);
var list:Array<THREE.Vector3> = Tooler.getVector3(points);
if(list.length > 0){
var ps:Array<THREE.Mesh> = Tooler.getPoints(list);
for(var i:number = 0; i < ps.length; i++){
this.group.add(ps[i]);
}
this.line = Tooler.getLines(list);
this.scene.add(this.line);
this.frame = new THREE.BoxHelper(this.group, new THREE.Color(0xff9900));
this.scene.add(this.frame);
this.resizeStage();
}
else{
alert("顶点数应该为3的倍数");
}
}
resizeStage(){
console.log("frame size");
var size:THREE.Vector3 = Tooler.getBoxSize(this.group);
console.log(size);
var max:number = Math.max(size.x, size.y, size.z);
var far = Math.max(max * 4, 500);
this.camera.far = far;
var scale:number = this.camera.far / 1000;
console.log("scale = " + scale);
console.log("far = " + far);
this.scene.remove(this.grid);
this.grid = new THREE.GridHelper(far, 500);
(this.grid.material as any).transparent = true;
(this.grid.material as any).opacity = 0.1;
this.scene.add(this.grid);
var startPot:THREE.Vector3 = new THREE.Vector3(10, 10, 20);
var normalizePot:THREE.Vector3 = startPot.normalize();
var endPot:THREE.Vector3 = normalizePot.setScalar(far * 0.2);
console.log(endPot);
this.camera.position.copy(endPot);
this.orbit.update();
this.camera.updateProjectionMatrix();
var range:number = max / 100;
listener.emit("setRange", range);
this.changeSize(0, range);
}
onResize(e:Event):void{
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
animate():void {
requestAnimationFrame(() => {
this.animate();
});
this.renderer.render(this.scene, this.camera);
}
setup():void {
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0xFFFFFF));
this.renderer.shadowMap.enabled = true;
this.orbit = new OrbitControls(this.camera, this.renderer.domElement);
this.orbit.enabled = true;
this.camera.position.set(7.742, 9.887, 13.769);
this.addHelper();
this.animate();
this.camera.lookAt(new THREE.Vector3());
}
addHelper():void{
var grid:THREE.GridHelper = new THREE.GridHelper(500, 500);
// grid.scale.addScalar(10);
(grid.material as any).transparent = true;
(grid.material as any).opacity = 0.1;
this.scene.add(grid);
var axes: THREE.AxesHelper = new THREE.AxesHelper(100);
this.scene.add(axes);
this.grid = grid;
this.axes = axes;
}
}```
App.ts
```import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { DragControls } from 'three/examples/jsm/controls/DragControls';
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls';
export default class App {
canvas: HTMLCanvasElement;
scenes: Array<THREE.Scene>;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
stats: any;
constructor() {
this.canvas = document.getElementById("c") as HTMLCanvasElement;
this.scenes = [];
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 900);
this.renderer = new THREE.WebGLRenderer({
canvas: this.canvas,
antialias: true,
alpha: true,
preserveDrawingBuffer: true
});
window.addEventListener("resize", e => this.onResize(e), false);
}
setStats(stats: any){
this.stats = stats;
}
onResize(e:Event):void{
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
animate():void {
requestAnimationFrame(() => {
this.animate();
});
// this.updateSize();
// this.canvas.style.transform = `translateY(${window.scrollY}px)`;
// this.renderer.setClearColor( 0xffffff );
// this.renderer.setScissorTest( false );
// this.renderer.clear();
this.renderer.setClearColor( 0xe0e0e0 );
this.renderer.setScissorTest( true );
this.scenes.forEach(scene => {
scene.children[ 0 ].rotation.y = Date.now() * 0.001;
var element = scene.userData.element;
var rect = element.getBoundingClientRect();
if ( rect.bottom < 0 || rect.top > this.renderer.domElement.clientHeight ||
rect.right < 0 || rect.left > this.renderer.domElement.clientWidth ) {
return;
}
var width = rect.right - rect.left;
var height = rect.bottom - rect.top;
var left = rect.left;
var bottom = this.renderer.domElement.clientHeight - rect.bottom;
this.renderer.setViewport( left, bottom, width, height );
this.renderer.setScissor( left, bottom, width, height );
var camera = scene.userData.camera;
this.renderer.render( scene, camera );
} );
this.stats && this.stats.update();
}
updateSize():void {
var width = this.canvas.clientWidth;
var height = this.canvas.clientHeight;
if ( this.canvas.width !== width || this.canvas.height !== height ) {
this.renderer.setSize( width, height, false );
}
}
updateGUIParam(param: any){
}
setup():void {
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0xffffff));
document.body.appendChild(this.renderer.domElement);
var geometries = [
new THREE.BoxBufferGeometry( 1, 1, 1 ),
new THREE.SphereBufferGeometry( 0.5, 18, 8 ),
new THREE.DodecahedronBufferGeometry( 0.5 ),
new THREE.CylinderBufferGeometry( 0.5, 0.5, 1, 12 ),
new THREE.ConeBufferGeometry( 0.5, 1, 16 ),
new THREE.IcosahedronBufferGeometry( 1, 0 ),
new THREE.OctahedronBufferGeometry( 1, 0 ),
new THREE.TorusBufferGeometry( 10, 3, 16, 60 ),
new THREE.TorusKnotBufferGeometry( 10, 3, 60, 16 ),
new THREE.PlaneBufferGeometry( 1, 1 ),
new THREE.CircleBufferGeometry( 0.5, 16 ),
new THREE.RingBufferGeometry( 0.3, 0.5, 16 ),
];
var template = (document.getElementById( "template" ) as any).text;
var content = document.getElementById( "content" );
for ( var i = 0; i < geometries.length; i ++ ) {
var scene = new THREE.Scene();
var element = document.createElement( "div" );
element.className = "list-item";
element.innerHTML = template;
scene.userData.element = element.querySelector( ".scene" );
content.appendChild( element );
var camera = new THREE.PerspectiveCamera( 50, 1, 1, 10 );
camera.position.z = 2;
scene.userData.camera = camera;
var controls = new OrbitControls( scene.userData.camera, scene.userData.element );
controls.minDistance = 2;
controls.maxDistance = 5;
controls.enablePan = false;
controls.enableZoom = false;
scene.userData.controls = controls;
// add one random mesh to each scene
var geometry = geometries[i];
element.querySelector( ".description" ).innerHTML = geometry.type;
var material = new THREE.MeshStandardMaterial( {
color: new THREE.Color().setHSL( Math.random(), 1, 0.75 ),
roughness: 0.5,
metalness: 0,
flatShading: true,
side: THREE.DoubleSide
} );
var mesh = new THREE.Mesh( geometry, material );
var size = new THREE.Box3().setFromObject(mesh).getSize(new THREE.Vector3());
var scale = 1 / Math.max(size.x, size.y, size.z);
mesh.scale.set(scale, scale, scale);
scene.add( mesh );
scene.add( new THREE.HemisphereLight( 0xaaaaaa, 0x444444 ) );
var light = new THREE.DirectionalLight( 0xffffff, 0.5 );
light.position.set( 1, 1, 1 );
scene.add( light );
this.scenes.push( scene );
}
this.animate();
}
}```
App.ts
```import * as THREE from 'three'
import Tooler from './Tooler';
import { FineLoader } from './FineLoader';
import { Effect } from './Effect';
import listener from '../lib/listener';
import TextureList from './TextureList';
import { FreeCamera } from './FreeCamera';
import {FineMaterial} from './FineMaterial';
import Stage from './Stage';
import ViewHelper from './ViewHelper';
import Cache from './Cache';
const TWEEN = require('../lib/Tween.js');
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
export default class App {
public static ZERO: THREE.Vector3 = new THREE.Vector3();
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
orbit: OrbitControls;
stats: any;
fineLoader: FineLoader;
roughness: number = 0;
metalness: number = 0;
stage: Stage;
rayCaster: THREE.Raycaster;
isMobile: boolean;
frameMaterials: any = [];
effects: Array<Effect>;
size: any;
canvas: any;
repeat: any;
textureList: TextureList;
isFitScene: boolean;
frame:number = 0;
// isIphone:boolean = navigator.userAgent.indexOf('iPhone') > -1;
// isDebug:boolean = Tooler.getQueryString("debug") == 1;
spaceFrame: number = 1;
helper:ViewHelper;
textureLoader: THREE.TextureLoader = new THREE.TextureLoader();
constructor(canvas: any, size: any) {
this.size = Tooler.getStageSize(true);
this.canvas = canvas;
this.canvas.width = this.size.width;
this.canvas.height = this.size.height;
this.scene = new THREE.Scene();
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
canvas: this.canvas
});
this.camera = new FreeCamera(this.canvas);
// this.orbit = new OrbitControls(this.camera, this.canvas);
// this.orbit.enabled = true;
// this.renderer.setSize(window.innerWidth, window.innerHeight);
// this.renderer.setPixelRatio(window.devicePixelRatio > 2 ? 2: 1);
this.renderer.setClearColor(new THREE.Color(0xa8a8a8), 0);
// this.renderer.shadowMap.enabled = true;//关闭阴影
// this.scene.background = Cache.getInstance().cubeTexture;
// this.fineLoader = new FineLoader();
// this.scene.add(this.fineLoader);
// this.stage = new Stage();
// this.scene.add(this.stage);
this.isMobile = Tooler.checkMobile();
this.rayCaster = new THREE.Raycaster();
window.addEventListener("resize", e => this.onResize(e), false);
canvas.addEventListener(this.isMobile ? "touchstart" : "mousedown", (e: any) => this.select(e), false);
}
setup(){
this.animate();
this.addObj();
}
onResize(e: Event): void {
this.size = Tooler.getStageSize(true);
this.canvas.width = this.size.width;
this.canvas.height = this.size.height;
this.camera.aspect = this.size.width / this.size.height;
this.camera.updateProjectionMatrix();
this.renderer.setSize(this.size.width, this.size.height);
}
animate(): void {
requestAnimationFrame(() => {
this.animate();
});
// this.camera.update();
this.stats && this.stats.update();
this.renderer.render(this.scene, this.camera);
// TWEEN.update();
}
setStats(stats: any): void {
this.stats = stats;
}
select(e: any): any {
if (this.isMobile) {
e = e.changedTouches[0];
}
var size = Tooler.getStageSize(false);
let mouse = new THREE.Vector2();
mouse.x = (e.clientX / size.width) * 2 - 1;
mouse.y = -(e.clientY / size.height) * 2 + 1;
this.camera.updateProjectionMatrix();
let obj: any;
this.rayCaster.setFromCamera(mouse, this.camera);
let list = this.scene.children;
let intersectObjects = this.rayCaster.intersectObjects(list, true);
if (intersectObjects[0]) {
obj = intersectObjects[0].object;
console.log(obj);
}
}
addObj():void{
var box:THREE.Mesh = new THREE.Mesh(new THREE.BoxGeometry(30, 30, 30), new THREE.MeshNormalMaterial());
box.position.set(0, 0, 0);
this.scene.add(box);
}
}```
Vehicle.ts
```export default class Vehicle{
constructor(){
}
}```
FineMaterial.ts
```import * as THREE from 'three'
import Cache from './Cache';
import {FineLoader} from './FineLoader';
export class FineMaterial{
static textureLoader:THREE.TextureLoader = new THREE.TextureLoader();
constructor(){
}
public static resetSameMaterial(obj: any, src:string):void{
var material = Cache.getInstance().getTexture(src);
if(material){
obj.material = material;
}
else{
Cache.getInstance().setTexture(src, obj.material);
}
}
public static setTransparent(material:any, src:string):void{
var transparent:boolean = false;
if(src.indexOf(".png") != -1){
transparent = true;
}
else if(src.indexOf("/glass.") != -1){
material.opacity = 0.36;
transparent = true;
}
else if(src.indexOf("/IGL_") != -1){
transparent = true;
}
else if(src.indexOf("/BL123") != -1){
transparent = true;
}
else if(src.indexOf("/bl_") != -1){
transparent = true;
}
if(transparent){
material.alphaTest = 0.2;
material.transparent = true;
}
}
public static async reloadMap(material: any, url: string){
return new Promise(resolve=>{
let map = material.map;
this.textureLoader.load(url, (t:THREE.Texture) => {
// material.map.needsUpdate = true;//暂时添加
// material.needsUpdate = true;
t.wrapS = map.wrapS;
t.wrapT = map.wrapT;
t.repeat = new THREE.Vector2(map.repeat.x, map.repeat.y);
t.flipY = map.flipY;
// t.flipX = map.flipX;
material.map = t;
material.needsUpdate = true;
setTimeout(() => {
resolve();
}, 1);
});
})
}
public static async lightMap(scene:THREE.Object3D){
console.log("【物体变亮处理】");
var i;
var total = 0;
var aim:any = [];
scene.traverse((item:any) => {
if(item.isMesh){
// var isWall = this.checkWall(item);
if(Cache.getInstance().hasLight(item)){
console.log('已经处理');
return;
}
let list = Array.isArray(item.material) ? item.material : [item.material];
for(i = 0; i < list.length; i++){
var m = list[i];
if(m.map && m.map.image){
++total;
if(aim.indexOf(m) == -1){
aim.push(m);
// if(isWall){
// m.roughness = 0.96;
// m.metalness = 0.04;
// m.flatShading = false;
// }
}
}
}
}
})
console.log("处理个数:" + total + " => " + aim.length);
for(i = 0; i < aim.length; i++){
await this.reloadMap(aim[i], aim[i].map.image.src);
}
console.log("【物体变亮完成】");
}
public static checkWall(item:any):boolean{
if(item.name == 'floor'){
return true;
}
else if(item.name == 'top'){
return true;
}
else if(item.name == 'left'){
return true;
}
else if(item.name == 'ceiling'){
return true;
}
else if(item.name == 'roof'){
return true;
}
else if(item.name == 'back'){
return true;
}
else if(item.name == 'front'){
return true;
}
return item.name.indexOf('wall') != -1;
}
public static getMapMaterials(obj: THREE.Object3D):any{
let materials:any = {};
let all:any =[];
let total = 0;
obj.traverse((item:any) => {
var isWall = this.checkWall(item);
if(item.isMesh){
let list = Array.isArray(item.material) ? item.material : [item.material];
list.forEach((m:any) => {
if(m.map && m.map.image){
var src = m.map.image.currentSrc;
if(isWall){
this.resetSameMaterial(item, src);
m.roughness = 0.96;
m.metalness = 0.04;
m.flatShading = false;
}
else{
if(all.indexOf(m) == -1){
all.push(m);
}
}
this.setTransparent(m, src);
materials[src] = m;
++total;
}
})
}
})
var aim = [];
for(var i in materials){
aim.push(materials[i]);
}
aim = all;
console.log("去重贴图:" + total + " => " + aim.length);
return aim;
}
}```
jszip.min.d.ts
```// declare var JSZip: any;```
FreeCamera.ts
```import * as THREE from 'three'
import Tooler from './Tooler';
const TWEEN = require('../lib/Tween.js');
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { FirstPersonControls } from 'three/examples/jsm/controls/FirstPersonControls';
import listener from '../lib/listener';
export class FreeCamera extends THREE.PerspectiveCamera{
aim:THREE.Vector3 = new THREE.Vector3(-5000, 0, -5000);
size: number = 0;
orbit: OrbitControls;
first: FirstPersonControls;
domElement: HTMLCanvasElement;
startPot: THREE.Vector3 = new THREE.Vector3(-5000, 5000, -5000);
clock:THREE.Clock = new THREE.Clock();
walking:boolean = false;
active:boolean = false;
lastPoint:any = null;
isMobile = Tooler.checkMobile();
floorY: number = 32;
constructor(domElement:HTMLCanvasElement){
super(75, window.innerWidth / window.innerHeight, 20, 8000);
this.domElement = domElement;
this.orbit = new OrbitControls(this, this.domElement);
this.orbit.enabled = true;
this.position.set(100, 100, 100);
this.lookAt(new THREE.Vector3());
}
}```
App.ts
```import Stats from 'three/examples/jsm/libs/stats.module';
export default class App{
stats: any;
constructor(){
console.log(customName + " is " + customAge);
eat("apple");
$("p").html("jsz");
this.stats = new Stats();
this.stats.setMode(0);
this.stats.domElement.style.position = 'absolute';
this.stats.domElement.style.left = 'auto';
this.stats.domElement.style.right = '0px';
this.stats.domElement.style.top = '0px';
document.body.appendChild(this.stats.domElement);
console.log(this.stats.REVISION);
setInterval(() => {
this.stats.update();
}, 90)
}
}```
App.ts
```import Stats from 'three/examples/jsm/libs/stats.module';
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import PhysicsView from './PhysicsView';
import Store from './Store';
import Fire from './Fire';
import ComputeGeometry from './ComputeGeometry';
import * as CANNON from 'cannon';
import Draw from './Draw';
// import '../asset/lib/CannonDebugRenderer';
const CannonDebugRenderer = require('../asset/lib/CannonDebugRenderer')(THREE, CANNON);
// import * as Ammo from '../asset/lib/ammo'
export default class App{
controls:OrbitControls;
camera: THREE.PerspectiveCamera;
scene: THREE.Scene;
renderer: THREE.WebGLRenderer;
size:any;
canvas: any;
stats: any;
clock: THREE.Clock;
world:any;
updaters: Array<PhysicsView> = [];
store:Store = new Store();
fire:Fire;
debugRenderer:any;
constructor(){
this.world = new CANNON.World();
this.world.gravity.set(0, -9.8, 0);
this.world.broadphase = new CANNON.NaiveBroadphase();
let solver = new CANNON.GSSolver();
this.world.defaultContactMaterial.contactEquationStiffness = 1e9;
this.world.defaultContactMaterial.contactEquationRelaxation = 4;
solver.iterations = 8;
solver.tolerance = 0.1;
this.world.solver = new CANNON.SplitSolver(solver);
this.initStats();
this.initGraphics();
this.initPhysics();
this.createObjects();
this.animate();
}
initStats(){
this.stats = new Stats();
this.stats.setMode(0);
this.stats.domElement.style.position = 'absolute';
this.stats.domElement.style.left = '0px';
this.stats.domElement.style.top = '0px';
document.body.appendChild(this.stats.domElement);
this.clock = new THREE.Clock();
}
initGraphics(){
this.camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
this.scene = new THREE.Scene();
this.camera.position.set(-25, 25, 78);
this.camera.lookAt(new THREE.Vector3());
console.log(this.camera);
this.canvas = document.getElementById("canvas") as any;
this.controls = new OrbitControls( this.camera, this.canvas );
this.controls.target.y = 2;
this.renderer = new THREE.WebGLRenderer({
canvas: this.canvas,
antialias: true,
alpha: true
});
this.renderer.setClearColor( 0x000000 );
this.renderer.setPixelRatio( Math.min(window.devicePixelRatio, 2) );
this.renderer.setSize( window.innerWidth, window.innerHeight );
this.renderer.shadowMap.enabled = true;
// CannonDebugRenderer
var ambientLight = new THREE.AmbientLight( 0xffffff );
ambientLight.intensity = 0.4;
this.scene.add( ambientLight );
this.fire = new Fire();
this.scene.add( this.fire.light );
// this.scene.add(new THREE.DirectionalLightHelper(light));
window.addEventListener( 'resize', this.onResize, false );
console.log(THREE);
this.debugRenderer = new CannonDebugRenderer(this.scene, this.world);
// this.scene.add(new Draw());
}
onResize(e:Event):void{
this.size = this.getStageSize(true);
this.canvas.width = this.size.width;
this.canvas.height = this.size.height;
this.camera.aspect = this.size.width / this.size.height;
this.camera.updateProjectionMatrix();
this.renderer.setSize(this.size.width, this.size.height);
}
getStageSize(usePixel?:boolean):any{
var size:any = {width: window.innerWidth};
if(window.innerWidth > window.innerHeight){
size.height = window.innerHeight;
}
else{
size.height = window.innerWidth;
}
if(usePixel){
size.width = size.width * window.devicePixelRatio;
size.height = size.height * window.devicePixelRatio;
}
return size;
}
initPhysics(){
this.addStaticBox([4, 40, 40], [-10, -4, 0], [0, 0, 0]);
this.addStaticBox([4, 40, 40], [10, -4, 0], [0, 0, 0]);
this.addStaticBox([80, 8, 80], [0, -2, 0], [30, 0, 0]);
// ComputeGeometry.checkThree(THREE);
var box1 = new THREE.Mesh(new THREE.BoxGeometry(20, 1, 20), new THREE.MeshStandardMaterial());
var box2 = new THREE.Mesh(new THREE.BoxGeometry(4, 2, 4), new THREE.MeshStandardMaterial());
var res = ComputeGeometry.subtract(box1, box2);
(res as THREE.Mesh).material = new THREE.MeshStandardMaterial({color: 0xff9900});
res.position.y = 10;
var num = (20 - 4) / 2;
this.addStaticBox([num, 1, 20], [-20 / 2 + num / 2, 10.2, 0], [0, 0, -30]);
this.addStaticBox([num, 1, 20], [20 / 2 - num / 2, 10.2, 0], [0, 0, 30]);
this.addStaticBox([4, 1, num], [0, 10.2, -20 / 2 + num / 2], [30, 0, 0]);
this.addStaticBox([4, 1, num], [0, 10.2, 20 / 2 - num / 2], [-30, 0, 0]);
// var compoundBody = new CANNON.Body({ mass: 0 });
// var sx = 20 - 4 / 2;
// var sz = 20;
// var sy = 1;
// var shape1 = new CANNON.Box(new CANNON.Vec3(sx / 2, sy / 2, sz / 2));
// compoundBody.addShape(shape1, new CANNON.Vec3( -2 - sx / 2, 0, 0));
// compoundBody.addShape(shape1, new CANNON.Vec3( 2 + sx / 2, 0, 0));
// sx = 4 / 2;
// sz = 20 - 4 / 2;
// sy = 1;
// var shape2 = new CANNON.Box(new CANNON.Vec3(sx / 2, sy / 2, sz / 2));
// compoundBody.addShape(shape2, new CANNON.Vec3( 0, 0, -2 - sx / 2));
// compoundBody.addShape(shape2, new CANNON.Vec3(0, 0, 2 + sx / 2));
// compoundBody.position.set(0, 10, 0);
// this.world.add(compoundBody);
// this.scene.add(res);
// var matrix = [];
// var sizeX = 64,
// sizeY = 64;
// for (var i = 0; i < sizeX; i++) {
// matrix.push([]);
// for (var j = 0; j < sizeY; j++) {
// var height = Math.cos(i / sizeX * Math.PI * 5) * Math.cos(j/sizeY * Math.PI * 5) * 2 + 2;
// if(i===0 || i === sizeX-1 || j===0 || j === sizeY-1)
// height = 3;
// matrix[i].push(height);
// }
// }
// var hfShape = new CANNON.Heightfield(matrix, {
// elementSize: 100 / sizeX
// });
// var hfBody = new CANNON.Body({ mass: 0 });
// hfBody.addShape(hfShape);
// hfBody.position.set(-sizeX * hfShape.elementSize / 2, -sizeY * hfShape.elementSize / 2, -1);
// this.world.add(hfBody);
}
addStaticBox(size:any, position:any, rotation:any) {
// this.world.add({size: size, pos: position, rot: rotation, move: false});
// var ToRad = 0.0174532925199432957;
// let shape = new CANNON.Box(new CANNON.Vec3(size[0] / 2, size[1] / 2, size[2] / 2));
// let body = new CANNON.Body({
// mass: 0,
// position: new CANNON.Vec3(position[0], position[1], position[2]),
// shape: shape
// })
// if(rotation[0] != 0){
// body.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), rotation[0] * ToRad);
// }
// else if(rotation[1] != 0){
// body.quaternion.setFromAxisAngle(new CANNON.Vec3(0, 1, 0), rotation[1] * ToRad);
// }
// else if(rotation[2] != 0){
// body.quaternion.setFromAxisAngle(new CANNON.Vec3(0, 0, 1), rotation[2] * ToRad);
// }
// this.world.add(body);
var ToRad = 0.0174532925199432957;
let mat: THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial();
mat.metalness = 0.1;
mat.roughness = 0.72;
mat.map = new THREE.TextureLoader().load("/asset/img/p6.jpg");
var mesh = new THREE.Mesh( new THREE.BoxGeometry(size[0], size[1], size[2]), mat );
mesh.position.set( position[0], position[1], position[2] );
var view = new PhysicsView(mesh, "box", this.world, true);
mesh.rotation.set( rotation[0] * ToRad, rotation[1] * ToRad, rotation[2] * ToRad );
view.updateBodyTrs();
this.scene.add( mesh );
mesh.castShadow = true;
mesh.receiveShadow = true;
this.updaters.push(view);
this.addMap();
}
addMap(){
var matrix = [];
var sizeX = 10,
sizeY = sizeX;
var angle = 4;
for (var i = 0; i < sizeX; i++) {
matrix.push([]);
for (var j = 0; j < sizeY; j++) {
var height = Math.sin(i / sizeX * Math.PI * angle) * Math.sin(j / sizeY * Math.PI * angle) * angle + angle;
if(i===0 || i === sizeX-1 || j===0 || j === sizeY-1)
height = angle;
matrix[i].push(height);
}
}
var hfShape = new CANNON.Heightfield(matrix, {
elementSize: 100 / sizeX
});
var hfBody;
var quat = new CANNON.Quaternion();
var pos = new CANNON.Vec3(-sizeX * hfShape.elementSize / 2, -20, 100);
quat.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2);
// Use normal
hfBody = new CANNON.Body({ mass: 0 });
hfBody.addShape(hfShape, new CANNON.Vec3(0, 0, 0));
hfBody.position.copy(pos);
hfBody.quaternion.copy(quat);
this.world.add(hfBody);
let mesh:THREE.Mesh = this.drawMap(hfBody.shapes[0]);
mesh.position.copy(pos);
mesh.quaternion.copy(quat);
this.scene.add(mesh);
}
drawMap(shape:any):THREE.Mesh{
var geometry = new THREE.Geometry();
var v0 = new CANNON.Vec3();
var v1 = new CANNON.Vec3();
var v2 = new CANNON.Vec3();
for (var xi = 0; xi < shape.data.length - 1; xi++) {
for (var yi = 0; yi < shape.data[xi].length - 1; yi++) {
for (var k = 0; k < 2; k++) {
shape.getConvexTrianglePillar(xi, yi, k===0);
v0.copy(shape.pillarConvex.vertices[0]);
v1.copy(shape.pillarConvex.vertices[1]);
v2.copy(shape.pillarConvex.vertices[2]);
v0.vadd(shape.pillarOffset, v0);
v1.vadd(shape.pillarOffset, v1);
v2.vadd(shape.pillarOffset, v2);
geometry.vertices.push(
new THREE.Vector3(v0.x, v0.y, v0.z),
new THREE.Vector3(v1.x, v1.y, v1.z),
new THREE.Vector3(v2.x, v2.y, v2.z)
);
var i = geometry.vertices.length - 3;
geometry.faces.push(new THREE.Face3(i, i+1, i+2));
}
}
}
geometry.computeBoundingSphere();
geometry.computeFaceNormals();
let mat: THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial();
mat.metalness = 0.1;
mat.roughness = 0.72;
mat.map = new THREE.TextureLoader().load("/asset/img/p6.jpg");
let mesh = new THREE.Mesh(geometry, mat);
return mesh;
}
createObjects(){
for(let i = 0; i < 10; i++){
let type = ["sphere", "box", "cylinder"][i % 3];
let shape = this.store.getBufferGeometry(type);
var view = new THREE.Mesh(shape, this.store.getMaterial());
let x = (0.5 - Math.random()) * 80;
let y = Math.random() * 900;
let z = (0.5 - Math.random()) * 80;
view.position.set(x, y, z);
view.castShadow = true;
view.receiveShadow = true;
this.scene.add(view);
this.updaters.push(new PhysicsView(view, type, this.world, false, this.scene));
}
}
initInput(){
}
animate() {
requestAnimationFrame(()=>{
this.animate();
});
this.world.step(1 / 60);
this.fire.update();
this.updaters.forEach((item:PhysicsView)=>{
item.update();
})
this.render();
this.debugRenderer.update();
this.stats.update();
}
render() {
// var deltaTime = clock.getDelta();
// updatePhysics( deltaTime );
// processClick();
// controls.update( deltaTime );
this.renderer.render( this.scene, this.camera );
}
}```
Dom.ts
```import * as THREE from 'three'
// let OrbitControls = require('three-orbit-controls')(THREE);
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { TDSLoader } from 'three/examples/jsm/loaders/TDSLoader';
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader';
import { EquirectangularToCubeGenerator } from 'three/examples/jsm/loaders/EquirectangularToCubeGenerator';
import { PMREMGenerator } from 'three/examples/jsm/pmrem/PMREMGenerator';
import { PMREMCubeUVPacker } from 'three/examples/jsm/pmrem/PMREMCubeUVPacker';
import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader';
import { DragControls } from 'three/examples/jsm/controls/DragControls';
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls';
export default class Game {
public static ZERO:THREE.Vector3 = new THREE.Vector3();
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
ambient: THREE.AmbientLight;
directional: THREE.SpotLight;
raycaster: THREE.Raycaster = new THREE.Raycaster();
mat: THREE.MeshStandardMaterial;
drag: THREE.Mesh;
orbit: OrbitControls;
helper: THREE.SpotLightHelper;
constructor() {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 900);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
// window.addEventListener("mousedown", e => this.onMouseDown(e), false);
window.addEventListener("resize", e => this.onResize(e), false);
}
onMouseDown(e: MouseEvent):void{
let x = (e.clientX / window.innerWidth) * 2 - 1;
let y = -(e.clientY / window.innerHeight) * 2 + 1;
this.raycaster.setFromCamera({x: x, y: y}, this.camera);
let intersects = this.raycaster.intersectObjects(this.scene.children, true);
console.log(intersects[0]);
if(intersects[0] && intersects[0].face){
}
}
onResize(e:Event):void{
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
loadObject():void{
let loader = new GLTFLoader();
loader.setPath('/obj/glTF/');
loader.load('scene.gltf', (gltf) => {
console.log("gltf");
console.log(gltf);
gltf.scene.traverse((child: any) => {
if(child.isMesh){
console.log(child);
child.receiveShadow = true;
child.castShadow = true;
if(child.material.map){
child.material.map.flipY = true;
}
child.uvsNeedUpdate = true;
}
})
gltf.scene.position.set(0, 0, 0);
gltf.scene.scale.set(0.1, 0.1, 0.1);
this.scene.add(gltf.scene);
this.scene.add(new THREE.BoxHelper(gltf.scene, new THREE.Color(0x333333)));
})
}
rotateAroundWorldAxis(object:any, axis:any, radians:number) {
let rotWorldMatrix = new THREE.Matrix4();
rotWorldMatrix.makeRotationAxis(axis.normalize(), radians);
rotWorldMatrix.multiply(object.matrix);
object.matrix = rotWorldMatrix;
object.rotation.setFromRotationMatrix(object.matrix);
}
animate():void {
requestAnimationFrame(() => {
this.animate();
});
this.renderer.render(this.scene, this.camera);
}
updateGUIParam(param: any){
this.directional.intensity = param.intensity;
this.directional.angle = param.angle;
this.directional.penumbra = param.penumbra;
this.directional.decay = param.decay;
this.directional.distance = param.distance;
this.mat.roughness = param.roughness;
this.mat.metalness = param.metalness;
}
toggerControl(use: boolean):void{
this.orbit.enabled = use;
}
setup():void {
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0x909090));
this.renderer.shadowMap.enabled = true;
document.body.appendChild(this.renderer.domElement);
this.orbit = new OrbitControls(this.camera, this.renderer.domElement);
this.orbit.enabled = false;
this.camera.position.set(7.742, 9.887, 13.769);
this.addGrid();
this.addPlane();
this.addLights();
this.addObj();
this.animate();
this.addDrag();
this.camera.lookAt(Game.ZERO);
}
addDrag():void{
this.drag = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.4, 0.4), new THREE.MeshNormalMaterial());
this.scene.add(this.drag);
this.drag.position.copy(this.directional.position);
this.drag.lookAt(this.directional.target.position);
let controls = new TrackballControls( this.camera, this.renderer.domElement );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
var dragControls = new DragControls( [this.drag], this.camera, this.renderer.domElement );
dragControls.addEventListener( 'dragstart', () => {
controls.enabled = false;
} );
dragControls.addEventListener( 'drag', () => {
this.directional.position.copy(this.drag.position);
this.drag.lookAt(Game.ZERO);
this.helper.update();
} );
dragControls.addEventListener( 'dragend', () => {
controls.enabled = true;
} );
}
addGrid():void{
// let grid = new THREE.GridHelper(80, 80);
// this.scene.add(grid);
this.scene.add(new THREE.AxesHelper(4));
}
addPlane():void{
let geometry = new THREE.PlaneGeometry(30, 30);
let meterial = new THREE.MeshStandardMaterial({side: THREE.DoubleSide, emissive: 0x909090});
let mesh = new THREE.Mesh(geometry, meterial);
mesh.rotateX(Math.PI * -90 / 180);
// mesh.castShadow = true;
mesh.receiveShadow = true;
this.scene.add(mesh);
}
addObj(){
let mat = new THREE.MeshStandardMaterial({
color: 0xff0000,
emissive: 0x000000,
opacity: 1,
premultipliedAlpha: true,
transparent: true,
roughness: 0,
metalness: 0,
})
for(let i = 0; i < 3; i++){
let geo = i % 2 ? new THREE.BoxGeometry(1, 1, 1) : new THREE.SphereGeometry(0.5, 18, 18);
let mesh = new THREE.Mesh(geo, mat);
mesh.position.set((1 - i) * 2, 1, 0);
mesh.castShadow = true;
mesh.receiveShadow = true;
this.scene.add(mesh);
}
this.mat = mat;
}
addLights():void{
//方向性光源
var directional:THREE.SpotLight = new THREE.SpotLight(0xffffff);
directional.intensity = 0.7;
directional.castShadow = true;
directional.angle = 0.3;
directional.penumbra = 0.2;
directional.decay = 2;
directional.distance = 50;
//环境光
var ambient:THREE.AmbientLight = new THREE.AmbientLight(0xffffff);
ambient.intensity = 0.4;
this.scene.add(directional);
this.scene.add(ambient);
directional.position.set(-2, 7, 4);
this.helper = new THREE.SpotLightHelper(directional);
this.scene.add(this.helper);
this.directional = directional;
}
}```
FitSize.ts
```import * as THREE from 'three'
import Tooler from '../Tooler'
export default class FitSize{
constructor(){
}
static resize(model: THREE.Object3D, max:number){
let scale: number = Tooler.getFitScale(model, max);
model.scale.multiplyScalar(scale);
console.log(scale, 'scale');
console.log(model);
let offset: THREE.Vector3 = Tooler.getOffsetVector3(model);
console.log("model center position", offset);
model.position.set(
model.position.x - offset.x,
model.position.y - offset.y,
model.position.z - offset.z,
)
}
}```
App.ts
```import * as THREE from 'three'
import Tooler from './Tooler';
import { FineLoader } from './FineLoader';
import { Effect } from './Effect';
import listener from '../lib/listener';
import TextureList from './TextureList';
import { FreeCamera } from './FreeCamera';
import Stage from './Stage';
import ViewHelper from './ViewHelper';
import Part from './Part';
const TWEEN = require('../lib/Tween.js');
export default class App {
public static ZERO: THREE.Vector3 = new THREE.Vector3();
scene: THREE.Scene;
camera: FreeCamera;
renderer: THREE.WebGLRenderer;
// orbit: OrbitControls;
stats: any;
fineLoader: FineLoader;
roughness: number = 0;
metalness: number = 0;
stage: Stage;
rayCaster: THREE.Raycaster;
isMobile: boolean;
frameMaterials: any = [];
effects: Array<Effect>;
size: any;
canvas: any;
repeat: any;
textureList: TextureList;
isFitScene: boolean;
part:Part;
helper:ViewHelper;
constructor(canvas: any, size: any) {
this.size = this.getStageSize(true);
this.canvas = canvas;
this.canvas.width = this.size.width;
this.canvas.height = this.size.height;
this.scene = new THREE.Scene();
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
canvas: this.canvas
});
this.camera = new FreeCamera(this.renderer.domElement);
// this.renderer.setSize(window.innerWidth, window.innerHeight);
// this.renderer.setPixelRatio(window.devicePixelRatio > 2 ? 2: 1);
this.renderer.setClearColor(new THREE.Color(0x999999), 0);
this.renderer.shadowMap.enabled = false;
console.log("this.camera");
console.log(this.camera);
this.fineLoader = new FineLoader();
this.scene.add(this.fineLoader);
this.stage = new Stage();
this.scene.add(this.stage);
this.isMobile = Tooler.checkMobile();
this.rayCaster = new THREE.Raycaster();
this.effects = [];
this.textureList = new TextureList();
window.addEventListener("resize", e => this.onResize(e), false);
canvas.addEventListener(this.isMobile ? "touchstart" : "mousedown", (e: any) => this.select(e), false);
window.addEventListener("all loaded", e => {
this.setRoughness(this.roughness);
this.setMetalness(this.metalness);
// this.orbit.enabled = true;
}, false);
}
getStageSize(usePixel?: boolean) {
var size: any = { width: window.innerWidth };
// if (window.innerWidth > window.innerHeight) {
// size.height = window.innerHeight;
// }
// else {
// size.height = window.innerWidth;
// }
size.height = window.innerHeight;
if (usePixel) {
size.width = size.width * window.devicePixelRatio;
size.height = size.height * window.devicePixelRatio;
}
return size;
}
onResize(e: Event): void {
this.size = this.getStageSize(true);
this.canvas.width = this.size.width;
this.canvas.height = this.size.height;
this.camera.aspect = this.size.width / this.size.height;
this.camera.updateProjectionMatrix();
this.renderer.setSize(this.size.width, this.size.height);
}
animate(): void {
requestAnimationFrame(() => {
this.animate();
});
this.camera.update();
this.helper.update();
this.effects.forEach((effect:Effect)=>{effect.update();});
this.stats && this.stats.update();
this.renderer.render(this.scene, this.camera);
this.stage.focusLight.update(this.camera);
TWEEN.update();
}
setStats(stats: any): void {
this.stats = stats;
}
select(e: any): any {
if (this.isMobile) {
e = e.changedTouches[0];
}
var size = this.getStageSize(false);
let mouse = new THREE.Vector2();
mouse.x = (e.clientX / size.width) * 2 - 1;
mouse.y = -(e.clientY / size.height) * 2 + 1;
listener.emit('hideEffect');
// this.camera.orbit.update();
let obj: any;
this.rayCaster.setFromCamera(mouse, this.camera);
let list = this.scene.children;
let intersectObjects = this.rayCaster.intersectObjects(list, true);
if (intersectObjects[0]) {
obj = intersectObjects[0].object;
console.log(obj);
console.log("当前模型:");
var aim:THREE.Object3D = Tooler.getRootModel(obj);
console.log(aim);
console.log(aim.rotation, aim.scale);
let mat = Array.isArray(obj.material) ? obj.material[0] : obj.material;
if (mat.map) {
let img = mat.map.image;
console.log(img.currentSrc);
}
}
}
playAnimate(): void {
this.effects.forEach((effect:Effect)=>{effect.play()});
console.log(Tooler.errorList);
console.log(Tooler.errorList.map(item => {
return item.replace(".zip", ".a3d");
}));
}
fitModel(group: THREE.Object3D): void {
let parent: THREE.Object3D = group;
parent.rotateX(-Math.PI / 2);
this.scene.add(parent);
parent.name = "load_scene";
parent.position.set(-5000, 0, -5000);
let aim = new THREE.Object3D();
aim.name = "aim_scene";
aim.add(parent);
this.scene.add(aim);
this.resetName(group);
this.initMaterials(parent, true);
this.resetScene();
}
resetScene(){
this.camera.reset(this.scene.getObjectByName("load_scene"));
}
resetName(parent: THREE.Object3D) {
let t = 0;
parent.traverse((item: any) => {
if (item.isMesh) {
t++;
}
item.name = item.name.split("-")[0];
})
}
initMaterials(parent: THREE.Object3D, isWall:boolean = false) {
let list = Tooler.getAllMaterial(parent);
let materials = list[0];
this.repeat = list[1];
let winMaterials: any = [];
materials.forEach((m: any) => {
let src:any;
let transparent = false;
if (m.map && m.map.image) {
src = m.map.image.src;
if(src.indexOf(".png") != -1){
transparent = true;
}
else if(src.indexOf("/glass.") != -1){
m.opacity = 0.36;
transparent = true;
}
else if(src.indexOf("/IGL_") != -1){
transparent = true;
}
else if(src.indexOf("/BL123") != -1){
transparent = true;
}
else if(src.indexOf("/bl_") != -1){
transparent = true;
}
}
if(transparent){
m.alphaTest = 0.24;
m.transparent = true;
}
// m.flatShading = false;
if(FineLoader.isLayout || isWall){
console.log("家具材质");
m.roughness = 0.96;
m.metalness = 0.04;
m.flatShading = false;
}
else{
console.log("门窗材质");
if (src) {
// src = m.map.image.src;
// if (src.indexOf("/dif_") != -1) {
// isRoom = true;
// roomMaterials.push(m);
// }
// winMaterials.push(m);
if (src.indexOf("/IPR_") != -1) {
winMaterials.push(m);
}
else if(src.indexOf("dif_wood") != -1){
winMaterials.push(m);
}
m.roughness = this.roughness;
m.metalness = this.metalness;
}
}
src && this.resetMap(m, src);
//模型变黑解决要点
// m.emissive = m.color;
// m.emissiveIntensity = 0.12;
// setTimeout(() => {
// src && this.resetMap(m, src);
// }, 3000);
})
this.frameMaterials = this.frameMaterials.concat(winMaterials);
if(isWall){
setTimeout(() => {
listener.emit("init");
}, 4000);
}
}
resetMap(material: any, url: string): void {
let map = material.map;
let texture: any = new THREE.TextureLoader().load(url, () => {
material.map.needsUpdate = true;
material.needsUpdate = true;
});
texture.wrapS = map.wrapS;
texture.wrapT = map.wrapT;
texture.repeat = new THREE.Vector2(map.repeat.x, map.repeat.y);
texture.flipY = map.flipY;
texture.flipX = map.flipX;
material.map = texture;
}
changeMap(url: string): void {
this.frameMaterials.length && this.frameMaterials.forEach((material: any) => {
this.resetMap(material, url);
})
}
setup(): void {
let url = Tooler.getQueryString("url");
if(!Tooler.isTest()){
url = url.replace("http:", "https:");
}
// url = url.replace("http:", "https:");
this.fineLoader.start(url, (object3D: THREE.Object3D) => {
this.fitModel(object3D);
url = url.replace(/\.(glb|zip)/, ".animation");
var effect = new Effect();
effect.init(url, this.scene);
this.effects.push(effect);
// window.dispatchEvent(new CustomEvent("animate"));
})
window.addEventListener("subLoad", (e:any) => {
this.addSubModel(e.detail);
})
// this.addLights();
this.helper = new ViewHelper();
this.scene.add(this.helper);
this.helper.addCamera(this.camera);
this.helper.addLight(this.stage.focusLight);
this.animate();
}
addSubModel(param:any):void{
var group = this.scene.getObjectByName("load_scene");
// var group = this.scene.getObjectByName("aim_scene");
var obj = param.obj;
let {position, rotation, scale} = param.attr;
obj.position.set(position[0], position[1], position[2]);
// obj.rotation.set(rotation[0], rotation[1], -rotation[2]);
console.log("rotation", rotation);
console.log("scale", scale);
// var angle = 0.02;
// var angle = 0.9;
// if(Math.PI / 2 - Math.abs(rotation[2] % Math.PI) < angle){
// obj.rotation.set(rotation[0], rotation[1], -rotation[2]);
// }
// else{
// obj.rotation.set(rotation[0], rotation[1], rotation[2]);
// }
obj.rotation.set(rotation[0], rotation[1], -rotation[2]);
// obj.rotation.set(rotation[0], rotation[2], rotation[1]);
obj.scale.set(scale[0], scale[1], scale[2]);
group.add(obj);
this.resetName(obj);
this.initMaterials(obj);
// obj.rotateX(-Math.PI / 2);
if(param.hasAnimate){
var url = param.attr.url.replace(/\.(glb|zip|a3d)/i, ".animation");
var effect = new Effect();
effect.init(url, obj);
this.effects.push(effect);
}
!this.isFitScene && this.resetScene();
}
setAmbient(n: number): void {
this.stage.setAmbient(n);
}
setDirectional(n: number): void {
this.stage.setDirectional(n);
}
setRoughness(n: number): void {
this.frameMaterials.forEach((mat:any)=>{
mat.roughness = n;
})
this.roughness = n;
}
setMetalness(n: number): void {
this.frameMaterials.forEach((mat:any)=>{
mat.metalness = n;
})
this.metalness = n;
}
setFar(n: number):void{
this.stage.focusLight.changeFar(this.camera, n);
}
}```
Draw.ts
```import * as THREE from 'three';
export default class Draw extends THREE.Object3D{
constructor(){
super();
this.init();
}
init(){
var geometry = new THREE.Geometry();
geometry.vertices.push(
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(0, 10, 0),
new THREE.Vector3(20, 10, 0),
new THREE.Vector3(30, 0, 0)
)
geometry.faces.push(new THREE.Face3(0, 1, 2));
geometry.faces.push(new THREE.Face3(0, 2, 3));
geometry.computeBoundingSphere();
geometry.computeFaceNormals();
let mesh = new THREE.Mesh(geometry, new THREE.MeshNormalMaterial());
this.add(mesh);
}
}```
core.d.ts
```// declare module 'three/examples/js/libs/jszip.min.js'
declare var JSZip:any;```
ListLoader.ts
```import * as THREE from 'three'
import Tooler from './Tooler';
export default class ListLoader{
curId:number;
total:number;
list:Array<any>;
type:string;
constructor(type:string){
this.curId = 0;
this.type = type;
this.list = [];
}
add(item:any){
this.list.push(item);
}
async start(){
if(this.curId < this.list.length){
console.log("加载模型", this.type);
await this.load(this.list[this.curId], this.type == "hole" || this.type == "sun");
console.log("load " + this.type + " " + this.curId + "/" + this.list.length);
this.curId++;
this.start();
}
else{
console.log("[" + this.type + " all loaded]");
window.dispatchEvent(new CustomEvent("listLoad", { bubbles: false, cancelable: false, detail: this.type}));
}
}
load(item:any, hasAnimate: boolean = true){
return new Promise(async resolve => {
let url:any = item.url.replace(/\.a3d/i, ".zip");
if(!url){
resolve();
return;
}
if(!Tooler.isTest()){
url = url.replace("http:", "https:");
}
console.log("url=>" + url);
let res:any = await Tooler.loadModel(url);
if(!res){
resolve();
return;
}
let detail = {
obj: res.object3D,
attr: item,
hasAnimate: hasAnimate
}
console.log("loading ... " + this.curId);
window.dispatchEvent(new CustomEvent("subLoad", { bubbles: false, cancelable: false, detail: detail}));
resolve();
})
}
}```
App.ts
```import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { DragControls } from 'three/examples/jsm/controls/DragControls';
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls';
export default class App {
public static ZERO:THREE.Vector3 = new THREE.Vector3();
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
objMaterial: THREE.MeshStandardMaterial;
planeMaterial: THREE.MeshStandardMaterial;
orbit: OrbitControls;
spotLight: THREE.SpotLight;
spotDrag: THREE.Mesh;
spotLightHelper: THREE.SpotLightHelper;
directionalLight: THREE.DirectionalLight;
directionalDrag: THREE.Mesh;
directionalLightHelper: THREE.DirectionalLightHelper;
dragControls: DragControls;
constructor() {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 900);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
// window.addEventListener("resize", e => this.onResize(e), false);
}
// onResize(e:Event):void{
// this.camera.aspect = window.innerWidth / window.innerHeight;
// this.camera.updateProjectionMatrix();
// this.renderer.setSize(window.innerWidth, window.innerHeight);
// }
animate():void {
requestAnimationFrame(() => {
this.animate();
});
this.renderer.render(this.scene, this.camera);
}
updateGUIParam(param: any){
this.spotLight.color = new THREE.Color(param.spotLightColor);
this.spotLight.intensity = param.spotLightIntensity;
this.spotLight.angle = param.spotLightAngle;
this.spotLight.penumbra = param.spotLightPenumbra;
this.spotLight.decay = param.spotLightDecay;
this.spotLight.distance = param.spotLightDistance;
this.directionalLight.color = new THREE.Color(param.directionalLightColor);
this.directionalLight.intensity = param.directionalLightIntensity;
this.objMaterial.roughness = param.objRoughness;
this.objMaterial.metalness = param.objMetalness;
this.objMaterial.color = new THREE.Color(param.objColor);
this.objMaterial.emissive = new THREE.Color(param.objEmissive);
this.objMaterial.opacity = param.objOpacity;
this.planeMaterial.roughness = param.planeRoughness;
this.planeMaterial.metalness = param.planeMetalness;
this.planeMaterial.color = new THREE.Color(param.planeColor);
this.planeMaterial.emissive = new THREE.Color(param.planeEmissive);
if(param.spotLight){
this.scene.add(this.spotLight);
}
else{
this.scene.remove(this.spotLight);
}
if(param.directionalLight){
this.scene.add(this.directionalLight);
}
else{
this.scene.remove(this.directionalLight);
}
console.log(param.spotLight);
}
toggerControl(use: boolean):void{
this.orbit.enabled = use;
this.dragControls.enabled = !use;
}
setup():void {
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0x909090));
this.renderer.shadowMap.enabled = true;
document.body.appendChild(this.renderer.domElement);
this.orbit = new OrbitControls(this.camera, this.renderer.domElement);
this.orbit.enabled = false;
this.camera.position.set(7.742, 9.887, 13.769);
this.addPlane();
this.addLights();
this.addObj();
this.animate();
this.addDrag();
this.camera.lookAt(App.ZERO);
}
addDrag():void{
this.spotDrag = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.4, 0.4), new THREE.MeshNormalMaterial());
this.scene.add(this.spotDrag);
this.spotDrag.position.copy(this.spotLight.position);
this.spotDrag.lookAt(this.spotLight.target.position);
this.directionalDrag = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 0.1), new THREE.MeshNormalMaterial());
this.scene.add(this.directionalDrag);
this.directionalDrag.position.copy(this.directionalLight.position);
this.directionalDrag.lookAt(this.directionalLight.target.position);
let controls = new TrackballControls( this.camera, this.renderer.domElement );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
var dragControls = new DragControls( [this.spotDrag, this.directionalDrag], this.camera, this.renderer.domElement );
dragControls.addEventListener( 'dragstart', () => {
controls.enabled = false;
} );
dragControls.addEventListener( 'drag', () => {
this.spotLight.position.copy(this.spotDrag.position);
this.spotDrag.lookAt(App.ZERO);
this.spotLightHelper.update();
this.directionalLight.position.copy(this.directionalDrag.position);
this.directionalDrag.lookAt(App.ZERO);
this.directionalLightHelper.update();
} );
dragControls.addEventListener( 'dragend', () => {
controls.enabled = true;
} );
this.dragControls = dragControls;
}
addPlane():void{
let geometry = new THREE.PlaneGeometry(30, 30);
let material = new THREE.MeshStandardMaterial({
side: THREE.DoubleSide,
emissive: 0x909090,
color: 0x333333,
roughness: 0,
metalness: 0,
});
let mesh = new THREE.Mesh(geometry, material);
mesh.rotateX(Math.PI * -90 / 180);
// mesh.castShadow = true;
mesh.receiveShadow = true;
this.scene.add(mesh);
this.scene.add(new THREE.AxesHelper(4));
this.planeMaterial = material;
}
addObj(){
let material = new THREE.MeshStandardMaterial({
color: 0xff0000,
emissive: 0x000000,
opacity: 1,
premultipliedAlpha: true,
transparent: true,
roughness: 0,
metalness: 0,
})
for(let i = 0; i < 3; i++){
let geometry = i % 2 ? new THREE.BoxGeometry(1, 1, 1) : new THREE.SphereGeometry(0.5, 18, 18);
let mesh = new THREE.Mesh(geometry, material);
mesh.position.set((1 - i) * 2, 1, 0);
mesh.castShadow = true;
mesh.receiveShadow = true;
this.scene.add(mesh);
}
this.objMaterial = material;
}
addLights():void{
//环境光
var ambient:THREE.AmbientLight = new THREE.AmbientLight(0xffffff);
ambient.intensity = 0.4;
this.scene.add(ambient);
//聚光灯
var spotLight:THREE.SpotLight = new THREE.SpotLight(0xffffff);
spotLight.intensity = 0.7;
spotLight.castShadow = true;
spotLight.angle = 0.3;
spotLight.penumbra = 0.2;
spotLight.decay = 2;
spotLight.distance = 50;
this.scene.add(spotLight);
spotLight.position.set(-2, 7, 4);
this.spotLightHelper = new THREE.SpotLightHelper(spotLight);
this.scene.add(this.spotLightHelper);
//平行光
var directionalLight:THREE.DirectionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.intensity = 0.7;
directionalLight.castShadow = true;
this.scene.add(directionalLight);
directionalLight.position.set(4, 7, 5);
this.directionalLightHelper = new THREE.DirectionalLightHelper(directionalLight);
this.scene.add(this.directionalLightHelper);
this.spotLight = spotLight;
this.directionalLight = directionalLight;
}
}```
Car.ts
```import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import Stats from 'three/examples/jsm/libs/stats.module';
import PhysicsView from './PhysicsView';
import PhyView from './PhyView';
import Store from './Store';
export default class Car{
world: any;
canvas:any;
controls: OrbitControls;
renderer: THREE.WebGLRenderer;
camera: THREE.PerspectiveCamera;
scene: THREE.Scene;
ray:THREE.Raycaster;
mouse: THREE.Vector2;
content: THREE.Object3D;
stats: any;
updaters: Array<any>;
store:Store = new Store();
constructor(){
this.initCore();
this.initLight();
this.initOimoPhysics();
this.initStats();
this.animate();
}
initStats(){
this.stats = new Stats();
this.stats.setMode(0);
this.stats.domElement.style.position = 'absolute';
this.stats.domElement.style.left = '0px';
this.stats.domElement.style.top = '0px';
document.body.appendChild(this.stats.domElement);
// this.clock = new THREE.Clock();
}
initCore(){
this.canvas = document.getElementById("canvas");
this.camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 5000 );
this.camera.position.set( -19.877586729468447, 38.229069946513945, 55.911914153889384 );
this.camera.rotation.set( -0.4610108856698664, -0.3619781646171701, -0.1741157073589739 );
this.controls = new OrbitControls( this.camera, this.canvas );
this.controls.enableKeys = false;
this.controls.target.set(0, 0, 0);
this.controls.update();
this.ray = new THREE.Raycaster();
this.mouse = new THREE.Vector2();
this.scene = new THREE.Scene();
this.renderer = new THREE.WebGLRenderer({ canvas: this.canvas, precision: "mediump", antialias: true });
this.renderer.setSize( window.innerWidth, window.innerHeight );
this.content = new THREE.Object3D();
this.scene.add(this.content);
window.addEventListener( 'resize', this.onResize, false );
// background
// var buffgeoBack = new THREE.BufferGeometry();
// buffgeoBack.fromGeometry( new THREE.IcosahedronGeometry(3000,1) );
// var back = new THREE.Mesh( buffgeoBack, new THREE.MeshBasicMaterial( { map:gradTexture([[1,0.75,0.5,0.25], ['#1B1D1E','#3D4143','#72797D', '#b0babf']]), side:THREE.BackSide, depthWrite: false } ));
// back.geometry.applyMatrix(new THREE.Matrix4().makeRotationZ(15*ToRad));
// this.scene.add( back );
// geometries
// geos['sphere'] = new THREE.BufferGeometry().fromGeometry( new THREE.SphereGeometry(1,16,10));
// geos['box'] = new THREE.BufferGeometry().fromGeometry( new THREE.BoxGeometry(1,1,1));
// geos['cylinder'] = new THREE.BufferGeometry().fromGeometry(new THREE.CylinderGeometry(1,1,1, 20,1));
// buffgeoSphere = new THREE.BufferGeometry();
// buffgeoSphere.fromGeometry( new THREE.SphereGeometry( 1, 20, 10 ) );
// buffgeoBox = new THREE.BufferGeometry();
// buffgeoBox.fromGeometry( new THREE.BoxGeometry( 1, 1, 1 ) );
// matSphere = new THREE[materialType]( { map: basicTexture(0), name:'sph' } );
// matBox = new THREE[materialType]( { map: basicTexture(2), name:'box' } );
// matSphereSleep = new THREE[materialType]( { map: basicTexture(1), name:'ssph' } );
// matBoxSleep = new THREE[materialType]( { map: basicTexture(3), name:'sbox' } );
// matGround = new THREE[materialType]( { color: 0x3D4143, transparent:true, opacity:0.5 } );
// matGroundTrans = new THREE[materialType]( { color: 0x3D4143, transparent:true, opacity:0.6 } );
// paddel = new THREE.Object3D();
// rotTest = new THREE.Vector3();
// events
// window.addEventListener( 'resize', onWindowResize, false );
// this.canvas.addEventListener( 'mousemove', rayTest, false);
//canvas.onmousemove = rayTest;
}
onResize(e:Event):void{
let w = window.innerWidth;
let h = window.innerHeight;
this.canvas.width = w;
this.canvas.height = h;
this.camera.aspect = w / h;
this.camera.updateProjectionMatrix();
this.renderer.setSize(w, h);
}
animate() {
requestAnimationFrame(()=>{
this.animate();
});
this.world.step();
this.updaters.forEach((item:PhysicsView)=>{
item.update();
})
this.renderer.render( this.scene, this.camera );
this.stats.update();
}
initLight(){
this.scene.add( new THREE.AmbientLight( 0x3D4143 ) );
var light = new THREE.DirectionalLight( 0xffffff , 1);
light.position.set( 300, 1000, 500 );
light.target.position.set( 0, 0, 0 );
light.castShadow = true;
var d = 300;
light.shadow.camera = new THREE.OrthographicCamera( -d, d, d, -d, 500, 1600 );
light.shadow.bias = 0.0001;
light.shadow.mapSize.width = light.shadow.mapSize.height = 1024;
this.scene.add( light );
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFShadowMap;
}
initOimoPhysics(){
this.world = new OIMO.World({
info:false,
worldscale: 10,
timestep: 1 / 60,
iterations: 7,
broadphase: 2, // 1: brute force, 2: sweep & prune, 3: volume tree
});
this.updaters = [];
let mat:THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({wireframe: false});
mat.map = new THREE.TextureLoader().load("/asset/img/m1.jpg");
mat.emissive = new THREE.Color(0, 0, 0);
// ground
// var ground = this.world.add({size:[4000, 40, 10000], pos:[0,-20,0] });
// this.addStaticBox([4000, 40, 10000], [0,-20,0], [0,0,0]);
// let groundView1: PhyView = new PhyView("box", new THREE.Vector3(40, 4, 40), false, this.world);
// this.scene.add(groundView1.mesh);
// this.updaters.push(groundView1);
// groundView1.setPosition(0, -8, 0);
// groundView1.setup();
let ground:THREE.Mesh = new THREE.Mesh(new THREE.BoxGeometry(80, 4, 80), mat);
this.scene.add(ground);
ground.castShadow = true;
ground.receiveShadow = true;
ground.position.set(0, -8, 0);
ground.rotation.x = 10 * Math.PI / 180;
new PhysicsView(ground, false, this.world);
// let groundView2: PhyView = new PhyView("box", new THREE.Vector3(40, 1, 40), false, this.world);
// this.scene.add(groundView2.mesh);
// this.updaters.push(groundView2);
// groundView2.setPosition(0, 0, 30);
// groundView2.setRotation(-30, 0, 0);
let mesh:THREE.Mesh;
let t;
let types = ["box", "sphere", "cylinder"];
for(let i = 0; i < 90; i++){
let geo = this.store.getBufferGeometry(types[i % 3]);
mesh = new THREE.Mesh(geo, this.store.getMaterial());
let x = (0.5 - Math.random()) * 40;
let y = Math.random() * 900;
let z = (0.5 - Math.random()) * 40;
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
this.scene.add(mesh);
let physicsView:PhysicsView = new PhysicsView(mesh, true, this.world);
this.updaters.push(physicsView);
}
// let carBody: PhyView = new PhyView("box", new THREE.Vector3(4, 0.5, 2), true, this.world);
// this.scene.add(carBody.mesh);
// this.updaters.push(carBody);
// carBody.setPosition(0, 1, 0);
// carBody.setup();
// carBody.body.name = "carBody";
// let w1: PhyView = new PhyView("cylinder", new THREE.Vector3(1, 0.8, 1), true, this.world);
// this.scene.add(w1.mesh);
// this.updaters.push(w1);
// w1.setPosition(-2, 0, -2);
// w1.setRotation(90, 0, 0);
// w1.setup();
// w1.body.name = "w1";
// var axe1 = [0, 0, 1];
// var axe2 = [0, 0, 1];
// let j1 = this.world.add({type:"jointWheel", body1:'carBody', body2:'w1', pos1:[-2, 0, -2], pos2:[0, 0, 0], axe1:axe1, axe2:axe2, spring:[1, 1], collision:false });
// j1.translationalLimitMotor.motorSpeed = 0.1;
// j1.translationalLimitMotor.maxMotorForce = 10;
// let w2: PhyView = new PhyView("cylinder", new THREE.Vector3(1, 0.8, 1), true, this.world);
// this.scene.add(w2.mesh);
// this.updaters.push(w2);
// w2.setPosition(-2, 0, 2);
// w2.setRotation(90, 0, 0);
// w2.setup();
// w2.body.name = "w2";
// let j2 = this.world.add({type:"jointWheel", body1:'carBody', body2:'w2', pos1:[-2, 0, 2], pos2:[0, 0, 0], axe1:axe1, axe2:axe2, spring:[8, 1], collision:false });
// j2.translationalLimitMotor.motorSpeed = 0.1;
// j2.translationalLimitMotor.maxMotorForce = 10;
// let w3: PhyView = new PhyView("cylinder", new THREE.Vector3(1, 0.8, 1), true, this.world);
// this.scene.add(w3.mesh);
// this.updaters.push(w3);
// w3.setPosition(2, 0, -2);
// w3.setRotation(90, 0, 0);
// w3.setup();
// w3.body.name = "w3";
// this.world.add({type:"jointWheel", body1:'carBody', body2:'w3', pos1:[2, 0, -2], pos2:[0, 0, 0], axe1:axe1, axe2:axe2, spring:[8, 1], collision:false });
// let w4: PhyView = new PhyView("cylinder", new THREE.Vector3(1, 0.8, 1), true, this.world);
// this.scene.add(w4.mesh);
// this.updaters.push(w4);
// w4.setPosition(2, 0, 2);
// w4.setRotation(90, 0, 0);
// w4.setup();
// w4.body.name = "w4";
// this.world.add({type:"jointWheel", body1:'carBody', body2:'w4', pos1:[2, 0, 2], pos2:[0, 0, 0], axe1:axe1, axe2:axe2, spring:[8, 1], collision:false });
this.scene.add(new THREE.AxesHelper(10));
}
addStaticBox(size:any, position:any, rotation:any) {
// var mesh;
// if(spec) mesh = new THREE.Mesh( buffgeoBox, matGroundTrans );
// else mesh = new THREE.Mesh( buffgeoBox, matGround );
// mesh.scale.set( size[0], size[1], size[2] );
// mesh.position.set( position[0], position[1], position[2] );
// mesh.rotation.set( rotation[0]*ToRad, rotation[1]*ToRad, rotation[2]*ToRad );
// if(!grounds.length) content.add( mesh );
// else scene.add( mesh );
// grounds.push(mesh);
// mesh.castShadow = true;
// mesh.receiveShadow = true;
}
}```
Door.ts
```import * as THREE from 'three'
// let OrbitControls = require('three-orbit-controls')(THREE);
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { TDSLoader } from 'three/examples/jsm/loaders/TDSLoader';
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader';
import { EquirectangularToCubeGenerator } from 'three/examples/jsm/loaders/EquirectangularToCubeGenerator';
import { PMREMGenerator } from 'three/examples/jsm/pmrem/PMREMGenerator';
import { PMREMCubeUVPacker } from 'three/examples/jsm/pmrem/PMREMCubeUVPacker';
import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader';
const ThreeBSP = require('three-js-csg')(THREE);
export default class Game {
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
ambient: THREE.AmbientLight;
directional: THREE.DirectionalLight;
raycaster: THREE.Raycaster = new THREE.Raycaster();
model: THREE.Object3D;
uniforms: any;
mesh: THREE.Mesh;
material: THREE.MeshStandardMaterial;
group: THREE.Group;
ball:THREE.Mesh;
bufferView: THREE.BufferGeometry;
timer: number = 0;
ts: THREE.Group;
lightHelper: THREE.DirectionalLightHelper;
spot: THREE.SpotLight;
spotBox: THREE.Mesh;
constructor() {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 900);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
preserveDrawingBuffer: true
});
window.addEventListener("mousedown", e => this.onMouseDown(e), false);
window.addEventListener("resize", e => this.onResize(e), false);
}
onMouseDown(e: MouseEvent):void{
let x = (e.clientX / window.innerWidth) * 2 - 1;
let y = -(e.clientY / window.innerHeight) * 2 + 1;
this.raycaster.setFromCamera({x: x, y: y}, this.camera);
let intersects = this.raycaster.intersectObjects(this.scene.children, true);
console.log(intersects[0]);
if(intersects[0] && intersects[0].face){
let n = intersects[0].face.normal;
if(this.spot){
this.spot.target = intersects[0].object;
}
}
}
onResize(e:Event):void{
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
loadObject():void{
let loader = new GLTFLoader();
loader.setPath('/obj/glTF/');
loader.load('scene.gltf', (gltf) => {
console.log("gltf");
console.log(gltf);
let mat = new THREE.MeshLambertMaterial({
color: 0xff0000,
emissive: 0xffffff,
emissiveMap: new THREE.TextureLoader().load("/texture/p4.jpg"),
map: new THREE.TextureLoader().load("/texture/p4.jpg")
})
gltf.scene.traverse((child: any) => {
if(child.isMesh){
console.log(child);
child.receiveShadow = true;
child.castShadow = true;
if(child.material.map){
child.material.map.flipY = true;
}
// child.material.map.rotation = -Math.PI;
// child.geometry.attributes.uv.array.forEach((v:number, i:number) => {
// if(i % 2 == 1){
// v = 1 - v;
// }
// });
child.material = mat;
child.uvsNeedUpdate = true;
}
})
gltf.scene.position.set(0, 0, 0);
gltf.scene.scale.set(0.1, 0.1, 0.1);
this.scene.add(gltf.scene);
this.scene.add(new THREE.BoxHelper(gltf.scene, new THREE.Color(0x333333)));
})
}
save( blob: any, filename: string ) {
}
rotateAroundWorldAxis(object:any, axis:any, radians:number) {
let rotWorldMatrix = new THREE.Matrix4();
rotWorldMatrix.makeRotationAxis(axis.normalize(), radians);
rotWorldMatrix.multiply(object.matrix);
object.matrix = rotWorldMatrix;
object.rotation.setFromRotationMatrix(object.matrix);
}
animate():void {
requestAnimationFrame(() => {
this.animate();
});
if(this.uniforms){
this.uniforms.time.value += 0.02;
}
// if(this.group){
// this.group.rotateY(0.02);
// }
// if(this.ball){
// this.ball.rotateY(0.02);
// }
this.timer += 0.1;
// this.ts.rotateY(-0.01);
// this.lightHelper.position.copy(this.camera.position);
// this.lightHelper.rotation.copy(this.camera.rotation);
// this.directional.matrixWorld = this.camera.matrixWorld;
// this.lightHelper.matrixWorld = this.camera.matrixWorld;
// this.rotateAroundWorldAxis(this.directional, new THREE.Vector3(0, 1, 0), 0.01);
// this.directional.rotateOnAxis(new THREE.Vector3(0, 1, 0), 0.01);
// this.directional.lookAt(new THREE.Vector3());
// this.directional.translateOnAxis(this.directional.target.position.normalize(), this.timer);
window.dispatchEvent(new CustomEvent("info", {
detail: this.camera.position
}))
// this.directional.matrix = this.camera.matrix;
// this.directional.position.copy(this.camera.position);
// this.directional.rotation.copy(this.camera.rotation);
// this.directional.position.copy(this.camera.position);
this.renderer.render(this.scene, this.camera);
}
setup():void {
this.model = new THREE.Group();
this.scene.add(this.model);
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0x909090));
this.renderer.shadowMap.enabled = true;
document.body.appendChild(this.renderer.domElement);
new OrbitControls(this.camera, this.renderer.domElement);
this.addGrid();
this.addShader();
this.addBall();
this.addPlane();
this.addBufferView();
this.addLights();
this.animate();
}
addBufferView(){
let colorArray = [ new THREE.Color( 0xff0080 ), new THREE.Color( 0xffffff ), new THREE.Color( 0x8000ff ) ];
let positions: any = [];
let colors: any = [];
for(let i = 0; i < 3; i++){
positions.push( (Math.random() - 0.5) * 30, (Math.random() - 0.5) * 30, (Math.random() - 0.5) * 30 );
var clr = colorArray[ Math.floor( Math.random() * colorArray.length ) ];
colors.push( clr.r, clr.g, clr.b );
}
let geometry = new THREE.BufferGeometry();
geometry.addAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.addAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
let material = new THREE.PointsMaterial( { size: 4, vertexColors: THREE.VertexColors, depthTest: false, sizeAttenuation: false } );
let mesh = new THREE.Points(geometry, material);
this.group = new THREE.Group();
this.group.add(mesh);
this.scene.add(this.group);
this.bufferView = geometry;
}
addBall():void{
// let geometry = new THREE.SphereGeometry(4, 24, 24);
let geometry = new THREE.BoxGeometry(4, 4, 4);
let material = new THREE.MeshStandardMaterial({
lightMapIntensity: 0.2,
aoMapIntensity: 0.2,
emissiveIntensity: 0.1,
opacity: 1,
premultipliedAlpha: true,
transparent: true,
roughness: 0,
metalness: 0,
color: 0xffffff,
emissive: 0xffffff
});
let mesh = new THREE.Mesh(geometry, material);
mesh.position.set(0, 2, 0);
// this.scene.add(mesh);
var textureLoader = new THREE.TextureLoader();
textureLoader.load( "/texture/p4.jpg", function ( map ) {
map.anisotropy = 8;
material.map = map;
material.needsUpdate = true;
} );
this.material = material;
mesh.receiveShadow = true;
mesh.castShadow = true;
this.ball = mesh;
}
changeMaterial(gui: any){
this.material.lightMapIntensity = gui.lightMapIntensity;
this.material.aoMapIntensity = gui.aoMapIntensity;
this.material.emissiveIntensity = gui.emissiveIntensity;
this.material.opacity = gui.opacity;
this.material.roughness = gui.roughness;
this.material.metalness = gui.metalness;
this.material.color = new THREE.Color(gui.color);
this.material.emissive = new THREE.Color(gui.emissive);
let colors:any = this.bufferView.getAttribute("color");
for(let i = 0, l = colors.array.length; i < l; i++){
colors.array[i] = Number(!colors.array[i]);
}
this.bufferView.addAttribute("color", new THREE.Float32BufferAttribute(colors.array, 3));
// console.log(this.lightHelper.position);
// console.log(this.camera.position);
}
addGrid():void{
let grid = new THREE.GridHelper(80, 80);
this.scene.add(grid);
}
addPlane():void{
let geometry = new THREE.PlaneGeometry(30, 30);
let meterial = new THREE.MeshStandardMaterial({side: THREE.DoubleSide, emissive: 0x909090});
let mesh = new THREE.Mesh(geometry, meterial);
mesh.receiveShadow = true;
mesh.castShadow = true;
mesh.rotateX(Math.PI * -90 / 180);
this.scene.add(mesh);
}
addShader():void{
this.uniforms = {
time: {type: "f", value: 0.1}
}
let vertexShader = $("#vertexShader").text();
let fragmentShader = $("#fragmentShader").text();
let geometry = new THREE.BoxGeometry(2, 2, 2);
let material = new THREE.ShaderMaterial({
vertexShader: vertexShader,
fragmentShader: fragmentShader,
uniforms: this.uniforms
})
let mesh = new THREE.Mesh(geometry, material);
this.scene.add(mesh);
mesh.position.set(2, 6, -5);
this.mesh = mesh;
}
addLights():void{
//方向性光源
var directional:THREE.DirectionalLight = new THREE.DirectionalLight(0xffffff);
directional.intensity = 0.7;
//环境光
var ambient:THREE.AmbientLight = new THREE.AmbientLight(0xffffff);
ambient.intensity = 0.4;
directional.castShadow = true;
// const shadowSize = 40;
// directional.shadow.camera.left = -shadowSize;
// directional.shadow.camera.right = shadowSize;
// directional.shadow.camera.top = shadowSize;
// directional.shadow.camera.bottom = -shadowSize;
// directional.shadow.camera.far = 200;
// directional.position.set(5, 5, -5);
// directional.lookAt(new THREE.Vector3());
// controllerFP.setObjectPosXYZ(0, 0, 140);
// controllerFP.lookAtXYZ(0, 1, 140);
directional.position.set(2, 4, 3);
directional.lookAt(0, 2, 0);
this.camera.position.set(1, 4, 10);
this.camera.lookAt(0, 2, 0);
// this.camera.add(new THREE.CameraHelper(this.camera));
this.scene.add(new THREE.AxesHelper());
// this.camera.add(directional);
// this.scene.add(this.lightHelper);
this.ambient = ambient;
this.directional = directional;
console.log(directional);
this.ts = new THREE.Group();
this.scene.add(this.ts);
this.ts.add(directional);
this.lightHelper = new THREE.DirectionalLightHelper(directional);
this.scene.add(this.lightHelper);
var spotLight = new THREE.SpotLight( 0xffffff );
spotLight.castShadow = true;
spotLight.position.set( 0, 2, 4 );
spotLight.angle = Math.PI / 6;
spotLight.penumbra = 0.3;
spotLight.lookAt(new THREE.Vector3(0, 2, 0));
this.scene.add( spotLight );
this.scene.add(new THREE.SpotLightHelper(spotLight));
this.spot = spotLight;
this.spotBox = new THREE.Mesh()
// var spotLight2 = new THREE.SpotLight( 0x0000ff );
// spotLight2.position.set( 0, 0, -8 );
// spotLight2.angle = Math.PI / 6;
// spotLight2.penumbra = 1;
// this.scene.add( spotLight2 );
// this.scene.add(new THREE.SpotLightHelper(spotLight2));
}
}```
PhysicsView.ts
```import * as THREE from "three";
export default class PhysicsView{
mesh:THREE.Mesh;
body:any;
world:any;
TORAN: number = 180 / Math.PI;
constructor(mesh:THREE.Mesh, move:boolean, world:any){
this.mesh = mesh;
this.world = world;
let type:any = mesh.geometry.type;
let parameters = (<any>mesh.geometry).parameters;
let param:any = {
pos: [mesh.position.x, mesh.position.y, mesh.position.z], // start position in degree
rot: [mesh.rotation.x * this.TORAN, mesh.rotation.y * this.TORAN, mesh.rotation.z * this.TORAN], // start rotation in degree
move: move, // dynamic or statique
density: 1,
friction: 0.4,
restitution: 0.1,
belongsTo: 1, // The bits of the collision groups to which the shape belongs.
collidesWith: 0xffffffff // The bits of the collision groups with which the shape collides.
}
if(type == "CylinderGeometry"){
param.type = "cylinder";
param.size = [parameters.radiusTop, parameters.height];
}
else if(type == "BoxGeometry"){
param.type = "box";
param.size = [parameters.width, parameters.height, parameters.depth];
}
else if(type == "SphereGeometry"){
param.type = "sphere";
param.size = [parameters.radius];
}
this.body = world.add(param);
}
update(){
this.mesh.position.copy( this.body.getPosition() );
this.mesh.quaternion.copy( this.body.getQuaternion() );
this.destory();
}
destory(){
if(this.mesh.position.y < -30){
let x = (0.5 - Math.random()) * 40;
let y = 40;
let z = (0.5 - Math.random()) * 40;
this.body.resetPosition(x, y, z);
}
}
}```
Core.d.ts
```// declare module '../asset/lib/ammo'
// declare var OIMO;
declare module 'cannon'
// declare var CannonDebugRenderer;
// declare var THREE;```
File.ts
```export default class File {
constructor() {
}
write(data: any): void {
// this.saveArrayBuffer(data, "data.txt");
this.test();
}
save(blob: any, filename: string) {
// this.download(blob, filename);
// var link = document.createElement('a');
// link.style.display = 'none';
// document.body.appendChild(link); // Firefox workaround, see #6594
// link.href = URL.createObjectURL(blob);
// link.download = filename;
// link.click();
// var reader = new FileReader();
// reader.readAsArrayBuffer(blob);
// reader.onload = (r) => {
// console.info(reader.result);
// var rs = new DataView(reader.result as ArrayBuffer);
// console.log(rs);
// reader.readAsText(new Blob( [rs] ), 'utf-8');
// reader.onload = function(){
// console.info(reader.result);
// }
// this.download(new Blob( [rs], { type: 'text/plain' } ), filename);
// }
}
test(){
let uri = "data:application/octet-stream;base64,AACgwAAAoMAAACBAAACgQAAAoMAAACBAAACgQAAAoEAAACBAAACgQAAAoEAAACBAAABAwAAAQEAAACDAAACgwAAAoMAAACBAcFiSvnBYkj4aJ2o/AAAAAAAAAAAAAIA/cFiSvnBYkj4aJ2o/cFiSvnBYkj4aJ2o/pQYKv6UGCj+SoSU/cFiSvnBYkj4aJ2o/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AAAAAAAAAAAAAIA/AAAAAAAAgD8AAIA/AACAPwAAgD8AAAAAAACAPwAAAAAAAAAAAAABAAIAAAADAAQABQAAAA==";
let blob = this.dataURLtoBlob(uri);
// this.download(blob, "scene.txt");
var reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onload = (r) => {
console.info(reader.result);
var rs = new DataView(reader.result as ArrayBuffer);
console.log(rs);
}
}
//base64转blob
dataURLtoBlob(dataurl:string) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
//blob转base64
blobToDataURL(blob: Blob, callback: Function) {
let a = new FileReader();
a.onload = function (e) { callback(a.result); }
a.readAsDataURL(blob);
}
//base64转文件
// dataURLtoFile(dataurl: string, filename:string) {
// var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
// bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
// while(n--){
// u8arr[n] = bstr.charCodeAt(n);
// }
// return new File([u8arr], filename, {type:mime});
// }
download(blob: any, filename: string){
var link = document.createElement('a');
link.style.display = 'none';
document.body.appendChild(link); // Firefox workaround, see #6594
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
}
saveString(text: any, filename: string) {
let blob = new Blob([text], { type: 'text/plain' });
console.log(blob);
this.save(blob, filename);
}
saveArrayBuffer(buffer: any, filename: string) {
let blob = new Blob([buffer], { type: 'application/octet-stream' });
console.log(blob);
this.save(blob, filename);
}
}```
App.ts
```import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { DragControls } from 'three/examples/jsm/controls/DragControls'
export default class App {
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
orbit: OrbitControls;
stats: any;
box:THREE.Mesh;
cameraOrtho: THREE.OrthographicCamera;
sceneOrtho: THREE.Scene;
spriteBL: THREE.Sprite;
spriteTL: THREE.Sprite;
spriteBR: THREE.Sprite;
spriteTR: THREE.Sprite;
spriteC: THREE.Sprite;
raycaster: THREE.Raycaster;
mouseVector: THREE.Vector3;
selectedObject: THREE.Sprite;
constructor() {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 900);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
this.renderer.autoClear = false;
this.cameraOrtho = new THREE.OrthographicCamera( - window.innerWidth / 2, window.innerWidth / 2, window.innerHeight / 2, - window.innerHeight / 2, 0, 100 );
this.cameraOrtho.position.z = 100;
this.sceneOrtho = new THREE.Scene();
this.raycaster = new THREE.Raycaster();
this.mouseVector = new THREE.Vector3();
window.addEventListener("resize", e => this.onResize(e), false);
window.addEventListener( "mousedown", e => this.onDocumentMouseDown(e), false );
}
onDocumentMouseDown( event:any ) {
event.preventDefault();
if ( this.selectedObject ) {
this.selectedObject.material.color.set( '#ff9900' );
this.selectedObject = null;
}
var intersects = this.getIntersects( event.layerX, event.layerY );
if ( intersects.length > 0 ) {
var res = intersects.filter( function ( res:any ) {
return res && res.object;
} )[ 0 ];
if ( res && res.object ) {
this.selectedObject = res.object as THREE.Sprite;
this.selectedObject.material.color.set( '#f00' );
}
}
}
getIntersects( x:number, y:number ) {
x = ( x / window.innerWidth ) * 2 - 1;
y = - ( y / window.innerHeight ) * 2 + 1;
this.mouseVector.set( x, y, 0.5 );
this.raycaster.setFromCamera( this.mouseVector, this.cameraOrtho );
return this.raycaster.intersectObject( this.sceneOrtho, true );
}
onResize(e:Event):void{
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
var width = window.innerWidth;
var height = window.innerHeight;
this.cameraOrtho.left = - width / 2;
this.cameraOrtho.right = width / 2;
this.cameraOrtho.top = height / 2;
this.cameraOrtho.bottom = - height / 2;
this.cameraOrtho.updateProjectionMatrix();
this.updateHUDSprites();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
updateHUDSprites(){
var width = window.innerWidth / 2;
var height = window.innerHeight / 2;
this.spriteTL.position.set( - width, height, 1 ); // top left
this.spriteTR.position.set( width, height, 1 ); // top right
this.spriteBL.position.set( - width, - height, 1 ); // bottom left
this.spriteBR.position.set( width, - height, 1 ); // bottom right
this.spriteC.position.set( 0, 0, 1 ); // center
}
setStats(stats: any):void{
this.stats = stats;
}
animate():void {
this.camera.lookAt(this.box.position);
this.box.rotation.copy(this.camera.rotation);
this.renderer.clear();
this.renderer.render( this.scene, this.camera );
this.renderer.clearDepth();
this.renderer.render( this.sceneOrtho, this.cameraOrtho );
requestAnimationFrame(() => {
this.animate();
});
this.stats && this.stats.update();
this.renderer.render(this.scene, this.camera);
}
updateGUIParam(param: any){
}
setup():void {
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0x909090));
this.renderer.shadowMap.enabled = true;
this.orbit = new OrbitControls(this.camera, this.renderer.domElement);
this.orbit.enabled = true;
this.camera.position.set(0, 0, 100);
this.addLights();
this.addObj();
this.animate();
this.addUI();
document.body.appendChild(this.renderer.domElement);
}
addUI(){
var width = 100;
var height = 80;
let scanvas = document.createElement("canvas");
scanvas.width = width * window.devicePixelRatio;
scanvas.height = height * window.devicePixelRatio;
let ctx = scanvas.getContext("2d");
ctx.fillStyle = "#0000ff";
ctx.fillRect(20, 20, scanvas.width - 40, scanvas.height - 40);
ctx.fillStyle = "#ffffff";
ctx.font = "32px Arial";
ctx.fillText("hello", 40, 40);
var material = new THREE.SpriteMaterial( {
color: 0x999999,
map: new THREE.CanvasTexture(scanvas)
} );
this.spriteTL = new THREE.Sprite( material );
this.spriteTL.center.set( 0.0, 1.0 );
this.spriteTL.scale.set( width, height, 1 );
this.sceneOrtho.add( this.spriteTL );
this.spriteTR = new THREE.Sprite( material );
this.spriteTR.center.set( 1.0, 1.0 );
this.spriteTR.scale.set( width, height, 1 );
this.sceneOrtho.add( this.spriteTR );
this.spriteBL = new THREE.Sprite( material );
this.spriteBL.center.set( 0.0, 0.0 );
this.spriteBL.scale.set( width, height, 1 );
this.sceneOrtho.add( this.spriteBL );
this.spriteBR = new THREE.Sprite( material );
this.spriteBR.center.set( 1.0, 0.0 );
this.spriteBR.scale.set( width, height, 1 );
this.sceneOrtho.add( this.spriteBR );
this.spriteC = new THREE.Sprite( material );
this.spriteC.center.set( 0.5, 0.5 );
this.spriteC.scale.set( width, height, 1 );
this.sceneOrtho.add( this.spriteC );
this.updateHUDSprites();
}
addObj(){
this.box = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10), new THREE.MeshStandardMaterial({
color: 0xff0000,
opacity: 0.5
}));
this.scene.add(this.box);
this.camera.lookAt(this.box.position);
this.box.rotation.copy(this.camera.rotation);
this.box.position.z = 8;
this.scene.add(new THREE.CameraHelper(this.camera));
let other = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10), new THREE.MeshStandardMaterial({
color: 0xffff00,
opacity: 0.5
}));
this.scene.add(other);
other.position.set(0, 0, 10);
var spriteMap = new THREE.TextureLoader().load( 'p3.jpg' );
var spriteMaterial = new THREE.SpriteMaterial( { map: spriteMap, color: 0xffffff, sizeAttenuation: false } );
console.log(spriteMaterial);
var sprite = new THREE.Sprite( spriteMaterial );
console.log(sprite);
// sprite.scale.set(2, 2, 1)
this.scene.add( sprite );
var sprite1 = new THREE.Sprite( new THREE.SpriteMaterial( { color: '#f00' } ) );
sprite1.position.set( 0, 0, 20 );
sprite1.scale.set( 10, 5, 1 );
sprite1.center.set( 0.5, 0.5 );
// sprite1.material.rotation = Math.PI / 3;
this.scene.add( sprite1 );
var sprite2 = new THREE.Sprite( new THREE.SpriteMaterial( { color: '#ff0' } ) );
sprite2.position.set( 0, 0, 20 );
sprite2.scale.set( 10, 5, 1 );
sprite2.center.set( 0.5, 0.5 );
// sprite2.material.rotation = Math.PI / 3;
this.scene.add( sprite2 );
}
addLights():void{
var ambient:THREE.AmbientLight = new THREE.AmbientLight(0xffffff);
ambient.intensity = 0.4;
this.scene.add(ambient);
}
}```
App.ts
```import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { DragControls } from 'three/examples/jsm/controls/DragControls';
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls';
export default class App {
public static ZERO:THREE.Vector3 = new THREE.Vector3();
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
objMaterial: THREE.MeshStandardMaterial;
planeMaterial: THREE.MeshStandardMaterial;
orbit: OrbitControls;
spotLight: THREE.SpotLight;
spotDrag: THREE.Mesh;
spotLightHelper: THREE.SpotLightHelper;
directionalLight: THREE.DirectionalLight;
directionalDrag: THREE.Mesh;
directionalLightHelper: THREE.DirectionalLightHelper;
dragControls: DragControls;
role: THREE.Mesh;
points: Array<THREE.Vector3>;
counter: number = 0;
stats: any;
constructor() {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 900);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
window.addEventListener("resize", e => this.onResize(e), false);
}
setStats(stats: any){
this.stats = stats;
}
onResize(e:Event):void{
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
animate():void {
requestAnimationFrame(() => {
this.animate();
});
this.stats && this.stats.update();
this.camera.position.copy(this.points[this.counter]);
this.camera.lookAt(this.points[this.counter + 1]);
// this.directionalLight.position.copy(this.points[this.counter]);
// this.directionalLight.lookAt(this.points[this.counter + 1]);
if(++this.counter >= this.points.length - 2){
this.counter = 0;
}
this.renderer.render(this.scene, this.camera);
}
updateGUIParam(param: any){
}
setup():void {
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0x909090));
this.renderer.shadowMap.enabled = true;
document.body.appendChild(this.renderer.domElement);
this.orbit = new OrbitControls(this.camera, this.renderer.domElement);
this.orbit.enabled = false;
this.camera.position.set(7.742, 9.887, 13.769);
this.addPlane();
this.addLights();
this.addObj();
this.addDrag();
this.animate();
this.camera.lookAt(App.ZERO);
}
toggerControl(use: boolean):void{
this.orbit.enabled = use;
this.dragControls.enabled = !use;
}
addDrag():void{
this.spotDrag = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.4, 0.4), new THREE.MeshNormalMaterial());
this.scene.add(this.spotDrag);
this.spotDrag.position.copy(this.spotLight.position);
this.spotDrag.lookAt(this.spotLight.target.position);
this.directionalDrag = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 0.1), new THREE.MeshNormalMaterial());
this.scene.add(this.directionalDrag);
this.directionalDrag.position.copy(this.directionalLight.position);
this.directionalDrag.lookAt(this.directionalLight.target.position);
// let controls = new TrackballControls( this.camera, this.renderer.domElement );
// controls.rotateSpeed = 1.0;
// controls.zoomSpeed = 1.2;
// controls.panSpeed = 0.8;
// controls.noZoom = false;
// controls.noPan = false;
// controls.staticMoving = true;
// controls.dynamicDampingFactor = 0.3;
var dragControls = new DragControls( [this.spotDrag, this.directionalDrag], this.camera, this.renderer.domElement );
// dragControls.addEventListener( 'dragstart', () => {
// controls.enabled = false;
// } );
// dragControls.addEventListener( 'drag', () => {
// this.spotLight.position.copy(this.spotDrag.position);
// this.spotDrag.lookAt(App.ZERO);
// this.spotLightHelper.update();
// this.directionalLight.position.copy(this.directionalDrag.position);
// this.directionalDrag.lookAt(App.ZERO);
// this.directionalLightHelper.update();
// } );
// dragControls.addEventListener( 'dragend', () => {
// controls.enabled = true;
// } );
this.dragControls = dragControls;
}
addPlane():void{
let geometry = new THREE.PlaneGeometry(30, 30);
let material = new THREE.MeshStandardMaterial({
side: THREE.DoubleSide,
emissive: 0x909090,
color: 0x333333,
roughness: 0,
metalness: 0,
});
let mesh = new THREE.Mesh(geometry, material);
mesh.rotateX(Math.PI * -90 / 180);
// mesh.castShadow = true;
mesh.receiveShadow = true;
this.scene.add(mesh);
this.scene.add(new THREE.AxesHelper(4));
this.planeMaterial = material;
}
addObj(){
this.role = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshNormalMaterial());
this.scene.add(this.role);
let material = new THREE.MeshStandardMaterial({
color: 0xff0000,
emissive: 0x000000,
opacity: 1,
premultipliedAlpha: true,
transparent: true,
roughness: 0,
metalness: 0,
})
var curve = new THREE.CatmullRomCurve3( [
new THREE.Vector3( 0, 10, - 10 ), new THREE.Vector3( 10, 0, - 10 ),
new THREE.Vector3( 20, 0, 0 ), new THREE.Vector3( 30, 0, 10 ),
new THREE.Vector3( 30, 0, 20 ), new THREE.Vector3( 20, 0, 30 ),
new THREE.Vector3( 10, 0, 30 ), new THREE.Vector3( 0, 0, 30 ),
new THREE.Vector3( - 10, 10, 30 ), new THREE.Vector3( - 10, 20, 30 ),
new THREE.Vector3( 0, 30, 30 ), new THREE.Vector3( 10, 30, 30 ),
new THREE.Vector3( 20, 30, 15 ), new THREE.Vector3( 10, 30, 10 ),
new THREE.Vector3( 0, 30, 10 ), new THREE.Vector3( - 10, 20, 10 ),
new THREE.Vector3( - 10, 10, 10 ), new THREE.Vector3( 0, 0, 10 ),
new THREE.Vector3( 10, - 10, 10 ), new THREE.Vector3( 20, - 15, 10 ),
new THREE.Vector3( 30, - 15, 10 ), new THREE.Vector3( 40, - 15, 10 ),
new THREE.Vector3( 50, - 15, 10 ), new THREE.Vector3( 60, 0, 10 ),
new THREE.Vector3( 70, 0, 0 ), new THREE.Vector3( 80, 0, 0 ),
new THREE.Vector3( 90, 0, 0 ), new THREE.Vector3( 100, 0, 0 )
] );
let points = curve.getPoints(6000);
this.points = points;
// var tangent = this.curve.getTangentAt(box.counter).normalize();
// box.axis.crossVectors(box.up, tangent).normalize();
// var radians = Math.acos(box.up.dot(tangent));
// box.mesh.quaternion.setFromAxisAngle(box.axis, radians);
let geometry = new THREE.TubeGeometry(curve, 180, 1, 12, false);
let mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial({
color: 0xff3388,
side: THREE.BackSide,
map: new THREE.TextureLoader().load("/p1.jpg")
}));
this.scene.add(mesh);
// var wireframeMaterial = new THREE.MeshBasicMaterial( { color: 0x000000, opacity: 0.3, wireframe: true, transparent: true } );
// var wireframe = new THREE.Mesh( geometry, wireframeMaterial );
// this.scene.add( wireframe );
this.objMaterial = material;
}
addLights():void{
//环境光
var ambient:THREE.AmbientLight = new THREE.AmbientLight(0xffffff);
ambient.intensity = 0.4;
this.scene.add(ambient);
//聚光灯
var spotLight:THREE.SpotLight = new THREE.SpotLight(0xffffff);
spotLight.intensity = 0.7;
spotLight.castShadow = true;
spotLight.angle = 0.3;
spotLight.penumbra = 0.2;
spotLight.decay = 2;
spotLight.distance = 50;
this.scene.add(spotLight);
spotLight.position.set(-2, 7, 4);
this.spotLightHelper = new THREE.SpotLightHelper(spotLight);
this.scene.add(this.spotLightHelper);
//平行光
var directionalLight:THREE.DirectionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.intensity = 0.7;
directionalLight.castShadow = true;
this.scene.add(directionalLight);
directionalLight.position.set(4, 7, 5);
this.directionalLightHelper = new THREE.DirectionalLightHelper(directionalLight);
this.scene.add(this.directionalLightHelper);
this.spotLight = spotLight;
this.directionalLight = directionalLight;
}
}```
Fire.ts
```import * as THREE from "three";
export default class Fire{
light:THREE.DirectionalLight;
num:number = 0;
speed:number = 0.01;
constructor(){
var light = new THREE.DirectionalLight( 0xffffff, 1 );
light.position.set( 4, 20, -4 );
light.castShadow = true;
var d = 40;
light.shadow.camera.left = -d;
light.shadow.camera.right = d;
light.shadow.camera.top = d;
light.shadow.camera.bottom = -d;
light.shadow.camera.near = 2;
light.shadow.camera.far = 50;
light.shadow.mapSize.x = 1024;
light.shadow.mapSize.y = 1024;
this.light = light;
}
update(){
// this.num += this.speed;
// let n = Math.abs(Math.sin(this.num));
// if(n < 0.2){
// this.speed = 0.001;
// }
// else{
// this.speed = 0.01;
// }
// this.light.intensity = n;
}
}```
Pickup.ts
```import * as THREE from 'three'
import Tooler from '../Tooler'
export default class Pickup{
isMobile:boolean;
rayCaster: THREE.Raycaster = new THREE.Raycaster();
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
light:THREE.DirectionalLight;
lightHelper:THREE.DirectionalLightHelper;
aim:THREE.Object3D;
constructor(canvas:HTMLCanvasElement, scene: THREE.Scene, camera: THREE.PerspectiveCamera){
this.scene = scene;
this.camera = camera;
this.isMobile = Tooler.checkMobile();
this.aim = new THREE.Object3D;
this.light = new THREE.DirectionalLight(new THREE.Color(0xff0000), 0.8);
console.log(this.light, 'light');
this.lightHelper = new THREE.DirectionalLightHelper(this.light);
this.scene.add(this.light);
this.scene.add(this.lightHelper);
canvas.addEventListener(this.isMobile ? "touchstart" : "mousedown", (e: any) => this.choose(e), false);
}
choose(e: any) {
this.isMobile && (e = e.changedTouches[0]);
// this.addPoint(e.clientX, e.clientY);
let mouse = new THREE.Vector2();
mouse.x = (e.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
let obj: any;
this.rayCaster.setFromCamera(mouse, this.camera);
// let list = this.scene.children;
// let list = [this.scene.getObjectByName('ball')];
var ball = this.scene.getObjectByName('ball');
console.log(this.scene);
var list = [ball];
let intersectObjects = this.rayCaster.intersectObjects(list, true);
if (intersectObjects[0]) {
obj = intersectObjects[0].object;
console.log(obj);
this.addBox(intersectObjects[0].point);
}
}
convertTo3DCoordinate(clientX:number, clientY:number){
console.log("cx: " + clientX + ", cy: " + clientY);
var mv = new THREE.Vector3(
(clientX / window.innerWidth) * 2 - 1,
-(clientY / window.innerHeight) * 2 + 1,
0.5
);
console.log("mx: " + mv.x + ", my: " + mv.y+", mz:"+mv.z);
mv.unproject(this.camera);
console.log("x: " + mv.x + ", y: " + mv.y+", z:"+mv.z);
return mv;
}
addBox(pot:THREE.Vector3){
var mesh:THREE.Mesh = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshNormalMaterial());
mesh.position.copy(pot);
this.scene.add(mesh);
this.light.position.copy(pot);
this.light.target = this.aim;
this.lightHelper.update();
}
addPoint(clientX:number, clientY:number){
var pot:THREE.Vector3 = this.convertTo3DCoordinate(clientX, clientY);
var mesh:THREE.Mesh = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshNormalMaterial());
mesh.position.set(pot.x, pot.y, pot.z);
this.scene.add(mesh);
}
}```
App.ts
```import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import FocusLight from './FocusLight';
import Tooler from './Tooler';
import { FineLoader } from './FineLoader';
import listener from '../lib/listener';
export default class App {
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
orbit: OrbitControls;
stats: any;
focusLight: FocusLight;
fineLoader: FineLoader;
rayCaster: THREE.Raycaster;
isMobile: boolean;
size: any;
canvas: any;
clock:THREE.Clock = new THREE.Clock();
mixer: any;
constructor(canvas: any) {
this.size = this.getStageSize(true);
this.canvas = canvas;
this.canvas.width = this.size.width;
this.canvas.height = this.size.height;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, this.size.width / this.size.height, 0.1, 2400);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
canvas: this.canvas
});
// this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0x999999), 0);
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFShadowMap;
this.orbit = new OrbitControls(this.camera, this.renderer.domElement);
this.orbit.enabled = true;
this.orbit.minPolarAngle = 0;
this.orbit.maxPolarAngle = 90 * Math.PI /180;
this.camera.position.set(-14.267941883040285, 4.752462870020817, -8.486184913116992);
this.camera.lookAt(new THREE.Vector3());
this.focusLight = new FocusLight(0xffffff, 0.4);
this.scene.add(this.focusLight);
this.fineLoader = new FineLoader();
this.scene.add(this.fineLoader);
this.isMobile = Tooler.checkMobile();
this.rayCaster = new THREE.Raycaster();
this.init();
window.addEventListener("resize", e => this.onResize(e), false);
canvas.addEventListener(this.isMobile ? "touchstart" : "mousedown", (e: any) => this.select(e), false);
listener.on("file", (fileList:any)=>{this.fineLoader.load(fileList)});
listener.on("loaded", (obj:any)=>{this.addObj(obj)});
listener.on("param", (attr:string, num:number)=>{this.transform(attr, num)});
}
transform(attr:string, num:number){
var obj = this.scene.getObjectByName("load_obj");
console.log(attr, num);
var r = Math.PI * num / 180;
if(attr == "x"){
obj.rotation.x = r;
}
else if(attr == "y"){
obj.rotation.y = r;
}
else if(attr == "z"){
obj.rotation.z = r;
}
}
getStageSize(usePixel?: boolean) {
var size: any = { width: window.innerWidth };
size.height = window.innerHeight;
if (usePixel) {
size.width = size.width * window.devicePixelRatio;
size.height = size.height * window.devicePixelRatio;
}
return size;
}
onResize(e: Event): void {
this.size = this.getStageSize(true);
this.canvas.width = this.size.width;
this.canvas.height = this.size.height;
this.camera.aspect = this.size.width / this.size.height;
this.camera.updateProjectionMatrix();
this.renderer.setSize(this.size.width, this.size.height);
}
animate(): void {
var delta = this.clock.getDelta();
if ( this.mixer ) this.mixer.update( delta );
requestAnimationFrame(() => {
this.animate();
});
this.stats && this.stats.update();
this.renderer.render(this.scene, this.camera);
this.focusLight.update(this.camera);
}
setStats(stats: any): void {
this.stats = stats;
}
select(e: any): any {
if (this.isMobile) {
e = e.changedTouches[0];
}
var size = this.getStageSize(false);
let mouse = new THREE.Vector2();
mouse.x = (e.clientX / size.width) * 2 - 1;
mouse.y = -(e.clientY / size.height) * 2 + 1;
let obj: any;
this.rayCaster.setFromCamera(mouse, this.camera);
let list = this.scene.children;
let intersectObjects = this.rayCaster.intersectObjects(list, true);
if (intersectObjects[0]) {
obj = intersectObjects[0].object;
console.log(obj);
let mat = Array.isArray(obj.material) ? obj.material[0] : obj.material;
if (mat.map) {
let img = mat.map.image;
console.log(img.currentSrc);
}
}
}
addObj(obj:any){
this.fitModel(obj);
this.mixer = new THREE.AnimationMixer( obj );
if(obj.animations && obj.animations.length){
var action = this.mixer.clipAction( obj.animations[ 0 ] );
action.play();
}
}
fitModel(group: THREE.Object3D): void {
let parent: THREE.Object3D = group;
let scale: number = Tooler.getFitScale(parent, 10);
parent.scale.multiplyScalar(scale);
// parent.rotateX(-Math.PI / 2);
parent.name = "load_obj";
parent.traverse(function(item:any):void{
if(item.isMesh){
item.castShadow = true;
item.receiveShadow = true;
}
});
let aim = new THREE.Object3D();
aim.add(parent);
this.scene.add(aim);
let offset: THREE.Vector3 = Tooler.getOffsetVector3(aim);
aim.position.set(0 - offset.x, 0 - offset.y, 0 - offset.z);
this.scene.add(new THREE.BoxHelper(aim));
let size = Tooler.getBoxSize(aim);
this.addGrass(size.y);
}
addGrass(h:number){
var mat = new THREE.MeshStandardMaterial({
map: new THREE.TextureLoader().load("./asset/grass2.jpg"),
side: THREE.DoubleSide
})
mat.map.wrapS = mat.map.wrapT = THREE.RepeatWrapping;
mat.map.repeat.set(200, 200);
mat.metalness = 0;
mat.roughness = 0.9;
var plane = new THREE.Mesh(new THREE.PlaneGeometry(1000, 1000), mat);
plane.rotateX(-90 * Math.PI / 180);
plane.position.y = -h / 2 - 0.1;
plane.name = "grass";
plane.receiveShadow = true;
this.scene.add(plane);
}
init(): void {
// let url = Tooler.getQueryString("url");
// this.fineLoader.start(url, (object3D: THREE.Object3D) => {
// this.fitModel(object3D);
// })
this.addSkySphere();
this.addLights();
this.animate();
}
addLights(): void {
var ambient: THREE.AmbientLight = new THREE.AmbientLight(0xffffff);
ambient.intensity = 0.4;
this.scene.add(ambient);
}
addSkySphere(){
var mat = new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load("./asset/sky.jpg"),
side: THREE.BackSide
});
var sky = new THREE.Mesh(new THREE.SphereGeometry(400, 32, 32), mat);
this.scene.add(sky);
}
}```
App.ts
```import Stats from 'three/examples/jsm/libs/stats.module';
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import PhysicsView from './PhysicsView';
import Store from './Store';
import Fire from './Fire';
import ComputeGeometry from './ComputeGeometry';
// import * as Ammo from '../asset/lib/ammo'
export default class App{
controls:OrbitControls;
camera: THREE.PerspectiveCamera;
scene: THREE.Scene;
renderer: THREE.WebGLRenderer;
size:any;
canvas: any;
stats: any;
clock: THREE.Clock;
physicsWorld:any;
world:any;
updaters: Array<PhysicsView> = [];
store:Store = new Store();
fire:Fire;
constructor(){
this.world = new OIMO.World({
timestep: 1 / 60,
iterations: 8,
broadphase: 2, // 1 brute force, 2 sweep and prune, 3 volume tree
worldscale: 1, // scale full world
random: true, // randomize sample
info: false, // calculate statistic or not
gravity: [0, -9.8, 0]
});
this.initStats();
this.initGraphics();
this.initPhysics();
this.createObjects();
this.animate();
}
initStats(){
this.stats = new Stats();
this.stats.setMode(0);
this.stats.domElement.style.position = 'absolute';
this.stats.domElement.style.left = '0px';
this.stats.domElement.style.top = '0px';
document.body.appendChild(this.stats.domElement);
this.clock = new THREE.Clock();
}
initGraphics(){
this.camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
this.scene = new THREE.Scene();
this.camera.position.set(-25, 25, 78);
this.camera.lookAt(new THREE.Vector3());
console.log(this.camera);
this.canvas = document.getElementById("canvas") as any;
this.controls = new OrbitControls( this.camera, this.canvas );
this.controls.target.y = 2;
this.renderer = new THREE.WebGLRenderer({
canvas: this.canvas,
antialias: true,
alpha: true
});
this.renderer.setClearColor( 0x000000 );
this.renderer.setPixelRatio( window.devicePixelRatio );
this.renderer.setSize( window.innerWidth, window.innerHeight );
this.renderer.shadowMap.enabled = true;
// var ambientLight = new THREE.AmbientLight( 0xffffff );
// this.scene.add( ambientLight );
this.fire = new Fire();
this.scene.add( this.fire.light );
// this.scene.add(new THREE.DirectionalLightHelper(light));
window.addEventListener( 'resize', this.onResize, false );
}
onResize(e:Event):void{
this.size = this.getStageSize(true);
this.canvas.width = this.size.width;
this.canvas.height = this.size.height;
this.camera.aspect = this.size.width / this.size.height;
this.camera.updateProjectionMatrix();
this.renderer.setSize(this.size.width, this.size.height);
}
getStageSize(usePixel?:boolean):any{
var size:any = {width: window.innerWidth};
if(window.innerWidth > window.innerHeight){
size.height = window.innerHeight;
}
else{
size.height = window.innerWidth;
}
if(usePixel){
size.width = size.width * window.devicePixelRatio;
size.height = size.height * window.devicePixelRatio;
}
return size;
}
initPhysics(){
this.addStaticBox([4, 40, 40], [-10, -4, 0], [0, 0, 0]);
this.addStaticBox([4, 40, 40], [10, -4, 0], [0, 0, 0]);
this.addStaticBox([80, 8, 80], [0, -2, 0], [30, 0, 0]);
ComputeGeometry.checkThree(THREE);
var box1 = new THREE.Mesh(new THREE.BoxGeometry(20, 1, 20), new THREE.MeshStandardMaterial());
var box2 = new THREE.Mesh(new THREE.BoxGeometry(4, 2, 4), new THREE.MeshStandardMaterial());
var res = ComputeGeometry.subtract(box1, box2);
(res as THREE.Mesh).material = new THREE.MeshStandardMaterial({color: 0xff9900});
res.position.y = 10;
// var mesh = new THREE.Mesh(geo, new THREE.MeshNormalMaterial());
this.scene.add(res);
}
addStaticBox(size:any, position:any, rotation:any) {
this.world.add({size: size, pos: position, rot: rotation, move: false});
var ToRad = 0.0174532925199432957;
let mat: THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial();
mat.metalness = 0.1;
mat.roughness = 0.72;
mat.map = new THREE.TextureLoader().load("/asset/img/p6.jpg");
var mesh = new THREE.Mesh( new THREE.BoxGeometry(), mat );
mesh.scale.set( size[0], size[1], size[2] );
mesh.position.set( position[0], position[1], position[2] );
mesh.rotation.set( rotation[0] * ToRad, rotation[1] * ToRad, rotation[2] * ToRad );
this.scene.add( mesh );
// grounds.push(mesh);
mesh.castShadow = true;
mesh.receiveShadow = true;
}
createObjects(){
// for(let i = 0; i < 1000; i++){
// let type = "sphere";
// if(i % 2){
// type ="box";
// }
// let shape;
// if(type == "box"){
// shape = this.store.getBoxBufferGeometry();
// }
// else{
// shape = this.store.getSphereBufferGeometry();
// }
// var view = new THREE.Mesh(shape, this.store.getMaterial());
// let x = (0.5 - Math.random()) * 40;
// let y = Math.random() * 1600;
// let z = (0.5 - Math.random()) * 40;
// view.position.set(x, y, z);
// view.castShadow = true;
// view.receiveShadow = true;
// this.scene.add(view);
// this.updaters.push(new PhysicsView(view, type, this.world));
// }
}
initInput(){
}
animate() {
requestAnimationFrame(()=>{
this.animate();
});
this.world.step();
this.fire.update();
this.updaters.forEach((item:PhysicsView)=>{
item.update();
})
this.render();
this.stats.update();
}
render() {
// var deltaTime = clock.getDelta();
// updatePhysics( deltaTime );
// processClick();
// controls.update( deltaTime );
this.renderer.render( this.scene, this.camera );
}
}```
Main.ts
```import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { DragControls } from 'three/examples/jsm/controls/DragControls'
import { FBXLoader } from '../lib/FBXLoader'
import { ColladaLoader } from 'three/examples/jsm/loaders/ColladaLoader'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import Tooler from './Tooler'
import listener from '../lib/listener';
import { GLTFExporter } from '../../vue-win/lib/GLTFExporter'
import Part from './Part'
import Fire from './Fire'
export default class Main {
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
orbit: OrbitControls;
stats: any;
clock:THREE.Clock = new THREE.Clock();
mixer: any;
isMobile: boolean = Tooler.checkMobile();
rayCaster: THREE.Raycaster = new THREE.Raycaster();
canvas: any;
part: Part;
ambientLight: THREE.AmbientLight;
directionalLight: THREE.DirectionalLight;
fire:Fire = new Fire();
constructor(canvas: any) {
this.canvas = canvas;
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 600);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
canvas: canvas
});
window.addEventListener("resize", e => this.onResize(e), false);
listener.on('export', () => {
var obj:THREE.Object3D = this.scene.getObjectByName('load_scene');
Tooler.toGLTFData(obj, 'man');
})
listener.on('param', (type:string, attr:string, data:any) => {
console.log(type, attr, data);
if(type == 'ambient' || type == 'directional'){
var obj:any = this;
if(attr == 'color'){
obj[type + 'Light'][attr] = new THREE.Color(data);
}
else{
obj[type + 'Light'][attr] = data;
}
}
else if(type == 'system'){
if(attr == 'background'){
this.renderer.setClearColor(new THREE.Color(data));
}
}
else{
this.part.change(type, attr, data);
}
})
}
onResize(e:Event):void{
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
setStats(stats: any):void{
this.stats = stats;
}
animate():void {
requestAnimationFrame(() => {
this.animate();
});
this.fire.update();
this.stats && this.stats.update();
this.renderer.render(this.scene, this.camera);
}
setup():void {
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio > 2 ? 2 : window.devicePixelRatio);
this.renderer.setClearColor(new THREE.Color(0x909090));
this.renderer.shadowMap.enabled = true;
this.orbit = new OrbitControls(this.camera, this.canvas);
this.orbit.enabled = true;
this.camera.position.set(20, 20, 20);
this.addLights();
this.loadGlb();
this.animate();
this.camera.lookAt(new THREE.Vector3());
this.canvas.addEventListener(this.isMobile ? "touchstart" : "mousedown", (e: any) => this.choose(e), false);
this.scene.add(this.fire);
}
choose(e:any){
listener.emit('hideEffect');
if (this.isMobile) {
e = e.changedTouches[0];
}
let mouse = new THREE.Vector2();
mouse.x = (e.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
let obj: any;
this.rayCaster.setFromCamera(mouse, this.camera);
let list = this.scene.children;
let intersectObjects = this.rayCaster.intersectObjects(list, true);
if (intersectObjects[0]) {
obj = intersectObjects[0].object;
console.log(obj);
}
}
loadGlb(){
let loader = new GLTFLoader();
loader.setCrossOrigin('anonymous');
loader.load('./asset/obj/man.glb', (gltf:any) => {
console.log("【GLTF数据】");
console.log(gltf);
this.fitModel(gltf.scene);
this.initMaterial(gltf.scene);
listener.emit('loaded');
}, e=>{
console.log(e);
})
}
fitModel(group: THREE.Object3D): void {
let scale: number = Tooler.getFitScale(group, 20);
group.scale.multiplyScalar(scale);
group.name = "load_scene";
let aim = new THREE.Object3D();
aim.name = "aim_scene";
aim.add(group);
this.scene.add(aim);
}
initMaterial(obj: THREE.Object3D):void{
this.part =new Part(obj);
}
addLights():void{
var ambientLight:THREE.AmbientLight = new THREE.AmbientLight(0xffffff);
ambientLight.intensity = 0.2;
this.scene.add(ambientLight);
var directionalLight:THREE.DirectionalLight = new THREE.DirectionalLight(0x0000ff);
this.scene.add(directionalLight);
directionalLight.position.set(20, 60, 20);
directionalLight.lookAt(new THREE.Vector3());
this.ambientLight = ambientLight;
this.directionalLight = directionalLight;
}
}```
Core.d.ts
```// declare function eat(n: string):void
// declare var customName:string
// declare var customAge:number
declare var jquery:any
declare module 'three/examples/jsm/libs/stats.module'
//d.ts文件内容
// declare class Stats {
// constructor()
// REVISION: number
// dom: any
// domElement: any
// update():void
// setMode(n:number):void
// }
// export default Stats```
ver.ts
```var verStr = `5401.39990234375,-4718.89990234375,600,4720.60009765625,-4718.89990234375,600,5401.39990234375,-4718.89990234375,900,4720.60009765625,-4718.89990234375,900
4738.60009765625,-4736.89990234375,600,5383.39990234375,-4736.89990234375,600,4738.60009765625,-4736.89990234375,900,5383.39990234375,-4736.89990234375,900
4738.60009765625,-4736.89990234375,900,5383.39990234375,-4736.89990234375,900,4720.60009765625,-4718.89990234375,900,5401.39990234375,-4718.89990234375,900
5401.39990234375,-5403.10009765625,600,5401.39990234375,-4718.89990234375,600,5401.39990234375,-5403.10009765625,900,5401.39990234375,-4718.89990234375,900
5383.39990234375,-4736.89990234375,600,5383.39990234375,-5385.10009765625,600,5383.39990234375,-4736.89990234375,900,5383.39990234375,-5385.10009765625,900
5383.39990234375,-4736.89990234375,900,5383.39990234375,-5385.10009765625,900,5401.39990234375,-4718.89990234375,900,5401.39990234375,-5403.10009765625,900
4720.60009765625,-5403.10009765625,600,5401.39990234375,-5403.10009765625,600,4720.60009765625,-5403.10009765625,900,5401.39990234375,-5403.10009765625,900
5383.39990234375,-5385.10009765625,600,4738.60009765625,-5385.10009765625,600,5383.39990234375,-5385.10009765625,900,4738.60009765625,-5385.10009765625,900
5383.39990234375,-5385.10009765625,900,4738.60009765625,-5385.10009765625,900,5401.39990234375,-5403.10009765625,900,4720.60009765625,-5403.10009765625,900
4720.60009765625,-5260,800,4720.60009765625,-5403.10009765625,900,4720.60009765625,-4718.89990234375,900,4720.60009765625,-4780,800,4720.60009765625,-5260,800,4720.60009765625,-4718.89990234375,900,4720.60009765625,-4718.89990234375,600,4720.60009765625,-4780,800,4720.60009765625,-4718.89990234375,900,4720.60009765625,-4780,600,4720.60009765625,-4780,800,4720.60009765625,-4718.89990234375,600,4720.60009765625,-5403.10009765625,600,4720.60009765625,-5403.10009765625,900,4720.60009765625,-5260,800,4720.60009765625,-5260,600,4720.60009765625,-5403.10009765625,600,4720.60009765625,-5260,800
4738.60009765625,-4736.89990234375,900,4738.60009765625,-5385.10009765625,900,4738.60009765625,-5260,800,4738.60009765625,-4780,800,4738.60009765625,-4736.89990234375,900,4738.60009765625,-5260,800,4738.60009765625,-4736.89990234375,600,4738.60009765625,-4736.89990234375,900,4738.60009765625,-4780,800,4738.60009765625,-4780,600,4738.60009765625,-4736.89990234375,600,4738.60009765625,-4780,800,4738.60009765625,-5385.10009765625,600,4738.60009765625,-5260,800,4738.60009765625,-5385.10009765625,900,4738.60009765625,-5260,600,4738.60009765625,-5260,800,4738.60009765625,-5385.10009765625,600
4738.60009765625,-5385.10009765625,900,4738.60009765625,-4736.89990234375,900,4720.60009765625,-5403.10009765625,900,4720.60009765625,-4718.89990234375,900
5511.781882166862,-4546.13998317331,330.00000044703484,5511.781882166862,-4546.13998317331,350.00000074505806,5511.781882166862,-4547.939983200132,330.00000044703484,5511.781882166862,-4547.939983200132,330.00000044703484,5511.781882166862,-4546.13998317331,350.00000074505806,5511.781882166862,-4547.939983200132,350.00000074505806
5511.781882166862,-4546.13998317331,350.00000074505806,5590.327333331107,-4546.13998317331,350.00000074505806,5511.781882166862,-4547.939983200132,350.00000074505806,5511.781882166862,-4547.939983200132,350.00000074505806,5590.327333331107,-4546.13998317331,350.00000074505806,5590.327333331107,-4547.939983200132,350.00000074505806
5590.327333331107,-4546.13998317331,350.00000074505806,5590.327333331107,-4546.13998317331,330.00000044703484,5590.327333331107,-4547.939983200132,350.00000074505806,5590.327333331107,-4547.939983200132,350.00000074505806,5590.327333331107,-4546.13998317331,330.00000044703484,5590.327333331107,-4547.939983200132,330.00000044703484
5590.327333331107,-4546.13998317331,330.00000044703484,5511.781882166862,-4546.13998317331,330.00000044703484,5590.327333331107,-4547.939983200132,330.00000044703484,5590.327333331107,-4547.939983200132,330.00000044703484,5511.781882166862,-4546.13998317331,330.00000044703484,5511.781882166862,-4547.939983200132,330.00000044703484
5383.39990234375,-4736.89990234375,600,4738.60009765625,-5385.10009765625,600,5383.39990234375,-5385.10009765625,600,4738.60009765625,-4736.89990234375,600
5383.39990234375,-4736.89990234375,900,4738.60009765625,-5385.10009765625,900,5383.39990234375,-5385.10009765625,900,4738.60009765625,-4736.89990234375,900
5383.39990234375,-4736.89990234375,900,4738.60009765625,-5385.10009765625,900,5383.39990234375,-5385.10009765625,900,4738.60009765625,-4736.89990234375,900
4720.60009765625,-4718.89990234375,1500,5401.39990234375,-4718.89990234375,1500,5292,-4718.89990234375,1400,4812,-4718.89990234375,1400,4720.60009765625,-4718.89990234375,1500,5292,-4718.89990234375,1400,4720.60009765625,-4718.89990234375,1200,4720.60009765625,-4718.89990234375,1500,4812,-4718.89990234375,1400,4812,-4718.89990234375,1200,4720.60009765625,-4718.89990234375,1200,4812,-4718.89990234375,1400,5401.39990234375,-4718.89990234375,1200,5292,-4718.89990234375,1400,5401.39990234375,-4718.89990234375,1500,5292,-4718.89990234375,1200,5292,-4718.89990234375,1400,5401.39990234375,-4718.89990234375,1200
5292,-4736.89990234375,1400,5383.39990234375,-4736.89990234375,1500,4738.60009765625,-4736.89990234375,1500,4812,-4736.89990234375,1400,5292,-4736.89990234375,1400,4738.60009765625,-4736.89990234375,1500,4738.60009765625,-4736.89990234375,1200,4812,-4736.89990234375,1400,4738.60009765625,-4736.89990234375,1500,4812,-4736.89990234375,1200,4812,-4736.89990234375,1400,4738.60009765625,-4736.89990234375,1200,5383.39990234375,-4736.89990234375,1200,5383.39990234375,-4736.89990234375,1500,5292,-4736.89990234375,1400,5292,-4736.89990234375,1200,5383.39990234375,-4736.89990234375,1200,5292,-4736.89990234375,1400
4738.60009765625,-4736.89990234375,1500,5383.39990234375,-4736.89990234375,1500,4720.60009765625,-4718.89990234375,1500,5401.39990234375,-4718.89990234375,1500
5401.39990234375,-5403.10009765625,1200,5401.39990234375,-4718.89990234375,1200,5401.39990234375,-5403.10009765625,1500,5401.39990234375,-4718.89990234375,1500
5383.39990234375,-4736.89990234375,1200,5383.39990234375,-5385.10009765625,1200,5383.39990234375,-4736.89990234375,1500,5383.39990234375,-5385.10009765625,1500
5383.39990234375,-4736.89990234375,1500,5383.39990234375,-5385.10009765625,1500,5401.39990234375,-4718.89990234375,1500,5401.39990234375,-5403.10009765625,1500
4720.60009765625,-5403.10009765625,1200,5401.39990234375,-5403.10009765625,1200,4720.60009765625,-5403.10009765625,1500,5401.39990234375,-5403.10009765625,1500
5383.39990234375,-5385.10009765625,1200,4738.60009765625,-5385.10009765625,1200,5383.39990234375,-5385.10009765625,1500,4738.60009765625,-5385.10009765625,1500
5383.39990234375,-5385.10009765625,1500,4738.60009765625,-5385.10009765625,1500,5401.39990234375,-5403.10009765625,1500,4720.60009765625,-5403.10009765625,1500
4720.60009765625,-4718.89990234375,1200,4720.60009765625,-5403.10009765625,1200,4720.60009765625,-4718.89990234375,1500,4720.60009765625,-5403.10009765625,1500
4738.60009765625,-5385.10009765625,1200,4738.60009765625,-4736.89990234375,1200,4738.60009765625,-5385.10009765625,1500,4738.60009765625,-4736.89990234375,1500
4738.60009765625,-5385.10009765625,1500,4738.60009765625,-4736.89990234375,1500,4720.60009765625,-5403.10009765625,1500,4720.60009765625,-4718.89990234375,1500
5581.200007885698,-5503.028943905125,660.0000008940697,5581.200007885698,-5503.028943905125,680.0000011920929,5581.200007885698,-5500.083489486466,660.0000008940697,5581.200007885698,-5500.083489486466,660.0000008940697,5581.200007885698,-5503.028943905125,680.0000011920929,5581.200007885698,-5500.083489486466,680.0000011920929
5581.200007885698,-5503.028943905125,680.0000011920929,5533.200007170442,-5503.028943905125,680.0000011920929,5581.200007885698,-5500.083489486466,680.0000011920929,5581.200007885698,-5500.083489486466,680.0000011920929,5533.200007170442,-5503.028943905125,680.0000011920929,5533.200007170442,-5500.083489486466,680.0000011920929
5533.200007170442,-5503.028943905125,680.0000011920929,5533.200007170442,-5503.028943905125,660.0000008940697,5533.200007170442,-5500.083489486466,680.0000011920929,5533.200007170442,-5500.083489486466,680.0000011920929,5533.200007170442,-5503.028943905125,660.0000008940697,5533.200007170442,-5500.083489486466,660.0000008940697
5533.200007170442,-5503.028943905125,660.0000008940697,5581.200007885698,-5503.028943905125,660.0000008940697,5533.200007170442,-5500.083489486466,660.0000008940697,5533.200007170442,-5500.083489486466,660.0000008940697,5581.200007885698,-5503.028943905125,660.0000008940697,5581.200007885698,-5500.083489486466,660.0000008940697
5383.39990234375,-4736.89990234375,1200,4738.60009765625,-5385.10009765625,1200,5383.39990234375,-5385.10009765625,1200,4738.60009765625,-4736.89990234375,1200
5383.39990234375,-4736.89990234375,1500,4738.60009765625,-5385.10009765625,1500,5383.39990234375,-5385.10009765625,1500,4738.60009765625,-4736.89990234375,1500
5383.39990234375,-4736.89990234375,1500,4738.60009765625,-5385.10009765625,1500,5383.39990234375,-5385.10009765625,1500,4738.60009765625,-4736.89990234375,1500
5401.39990234375,-4718.89990234375,0,4720.60009765625,-4718.89990234375,0,5401.39990234375,-4718.89990234375,300,4720.60009765625,-4718.89990234375,300
4738.60009765625,-4736.89990234375,0,5383.39990234375,-4736.89990234375,0,4738.60009765625,-4736.89990234375,300,5383.39990234375,-4736.89990234375,300
4738.60009765625,-4736.89990234375,300,5383.39990234375,-4736.89990234375,300,4720.60009765625,-4718.89990234375,300,5401.39990234375,-4718.89990234375,300
5401.39990234375,-5403.10009765625,0,5401.39990234375,-4718.89990234375,0,5401.39990234375,-5403.10009765625,300,5401.39990234375,-4718.89990234375,300
5383.39990234375,-4736.89990234375,0,5383.39990234375,-5385.10009765625,0,5383.39990234375,-4736.89990234375,300,5383.39990234375,-5385.10009765625,300
5383.39990234375,-4736.89990234375,300,5383.39990234375,-5385.10009765625,300,5401.39990234375,-4718.89990234375,300,5401.39990234375,-5403.10009765625,300
5175,-5403.10009765625,240,5401.39990234375,-5403.10009765625,300,4720.60009765625,-5403.10009765625,300,4915,-5403.10009765625,240,5175,-5403.10009765625,240,4720.60009765625,-5403.10009765625,300,4720.60009765625,-5403.10009765625,0,4915,-5403.10009765625,240,4720.60009765625,-5403.10009765625,300,4915,-5403.10009765625,0,4915,-5403.10009765625,240,4720.60009765625,-5403.10009765625,0,5401.39990234375,-5403.10009765625,0,5401.39990234375,-5403.10009765625,300,5175,-5403.10009765625,240,5175,-5403.10009765625,0,5401.39990234375,-5403.10009765625,0,5175,-5403.10009765625,240
4738.60009765625,-5385.10009765625,300,5383.39990234375,-5385.10009765625,300,5175,-5385.10009765625,240,4915,-5385.10009765625,240,4738.60009765625,-5385.10009765625,300,5175,-5385.10009765625,240,4738.60009765625,-5385.10009765625,0,4738.60009765625,-5385.10009765625,300,4915,-5385.10009765625,240,4915,-5385.10009765625,0,4738.60009765625,-5385.10009765625,0,4915,-5385.10009765625,240,5383.39990234375,-5385.10009765625,0,5175,-5385.10009765625,240,5383.39990234375,-5385.10009765625,300,5175,-5385.10009765625,0,5175,-5385.10009765625,240,5383.39990234375,-5385.10009765625,0
5383.39990234375,-5385.10009765625,300,4738.60009765625,-5385.10009765625,300,5401.39990234375,-5403.10009765625,300,4720.60009765625,-5403.10009765625,300
4720.60009765625,-5403.10009765625,300,4720.60009765625,-4718.89990234375,300,4720.60009765625,-4824,200,4720.60009765625,-5304,200,4720.60009765625,-5403.10009765625,300,4720.60009765625,-4824,200,4720.60009765625,-5403.10009765625,0,4720.60009765625,-5403.10009765625,300,4720.60009765625,-5304,200,4720.60009765625,-5304,0,4720.60009765625,-5403.10009765625,0,4720.60009765625,-5304,200,4720.60009765625,-4718.89990234375,0,4720.60009765625,-4824,200,4720.60009765625,-4718.89990234375,300,4720.60009765625,-4824,0,4720.60009765625,-4824,200,4720.60009765625,-4718.89990234375,0
4738.60009765625,-4824,200,4738.60009765625,-4736.89990234375,300,4738.60009765625,-5385.10009765625,300,4738.60009765625,-5304,200,4738.60009765625,-4824,200,4738.60009765625,-5385.10009765625,300,4738.60009765625,-5385.10009765625,0,4738.60009765625,-5304,200,4738.60009765625,-5385.10009765625,300,4738.60009765625,-5304,0,4738.60009765625,-5304,200,4738.60009765625,-5385.10009765625,0,4738.60009765625,-4736.89990234375,0,4738.60009765625,-4736.89990234375,300,4738.60009765625,-4824,200,4738.60009765625,-4824,0,4738.60009765625,-4736.89990234375,0,4738.60009765625,-4824,200
4738.60009765625,-5385.10009765625,300,4738.60009765625,-4736.89990234375,300,4720.60009765625,-5403.10009765625,300,4720.60009765625,-4718.89990234375,300
4914.999998062849,-5385.1000978425145,0,4914.999998062849,-5385.1000978425145,240.0000035762787,4914.999998062849,-5403.1000974699855,0,4914.999998062849,-5403.1000974699855,0,4914.999998062849,-5385.1000978425145,240.0000035762787,4914.999998062849,-5403.1000974699855,240.0000035762787
4914.999998062849,-5385.1000978425145,240.0000035762787,5175.000001937151,-5385.1000978425145,240.0000035762787,4914.999998062849,-5403.1000974699855,240.0000035762787,4914.999998062849,-5403.1000974699855,240.0000035762787,5175.000001937151,-5385.1000978425145,240.0000035762787,5175.000001937151,-5403.1000974699855,240.0000035762787
5175.000001937151,-5385.1000978425145,240.0000035762787,5175.000001937151,-5385.1000978425145,0,5175.000001937151,-5403.1000974699855,240.0000035762787,5175.000001937151,-5403.1000974699855,240.0000035762787,5175.000001937151,-5385.1000978425145,0,5175.000001937151,-5403.1000974699855,0
5175.000001937151,-5385.1000978425145,0,4914.999998062849,-5385.1000978425145,0,5175.000001937151,-5403.1000974699855,0,5175.000001937151,-5403.1000974699855,0,4914.999998062849,-5385.1000978425145,0,4914.999998062849,-5403.1000974699855,0
4738.60009726882,-4823.999996423721,0,4738.60009726882,-4823.999996423721,200.00000298023224,4720.60009804368,-4823.999996423721,0,4720.60009804368,-4823.999996423721,0,4738.60009726882,-4823.999996423721,200.00000298023224,4720.60009804368,-4823.999996423721,200.00000298023224
4738.60009726882,-4823.999996423721,200.00000298023224,4738.60009726882,-5304.000003576279,200.00000298023224,4720.60009804368,-4823.999996423721,200.00000298023224,4720.60009804368,-4823.999996423721,200.00000298023224,4738.60009726882,-5304.000003576279,200.00000298023224,4720.60009804368,-5304.000003576279,200.00000298023224
4738.60009726882,-5304.000003576279,200.00000298023224,4738.60009726882,-5304.000003576279,0,4720.60009804368,-5304.000003576279,200.00000298023224,4720.60009804368,-5304.000003576279,200.00000298023224,4738.60009726882,-5304.000003576279,0,4720.60009804368,-5304.000003576279,0
4738.60009726882,-5304.000003576279,0,4738.60009726882,-4823.999996423721,0,4720.60009804368,-5304.000003576279,0,4720.60009804368,-5304.000003576279,0,4738.60009726882,-4823.999996423721,0,4720.60009804368,-4823.999996423721,0
5383.39990234375,-4736.89990234375,0,4738.60009765625,-5385.10009765625,0,5383.39990234375,-5385.10009765625,0,4738.60009765625,-4736.89990234375,0
5383.39990234375,-4736.89990234375,300,4738.60009765625,-5385.10009765625,300,5383.39990234375,-5385.10009765625,300,4738.60009765625,-4736.89990234375,300
5383.39990234375,-4736.89990234375,300,4738.60009765625,-5385.10009765625,300,5383.39990234375,-5385.10009765625,300,4738.60009765625,-4736.89990234375,300`
var list:any = verStr.split("\n");
var aim:any = [];
list.forEach((item:any) => {
let temp:any = item.split(",");
let ary:any = temp.map((i:any)=>Number(i))
aim = aim.concat(ary);
})
console.log(aim);
export default aim```
tooler.js
```function computeShape(type, list) {
// var subj = getAimList(list[0]);
// var clip = getAimList(list[1]);
var solution = new ClipperLib.Paths();
var c = new ClipperLib.Clipper();
for(let i = 0; i < list.length; i++){
let obj = getAimList(list[i]);
if(i == 0){
c.AddPaths(obj, ClipperLib.PolyType.ptSubject, true);
}
else{
c.AddPaths(obj, ClipperLib.PolyType.ptClip, true);
}
}
var subject_fillType = ClipperLib.PolyFillType.pftNonZero;
var clip_fillType = ClipperLib.PolyFillType.pftNonZero;
c.Execute(ClipperLib.ClipType[type], solution, subject_fillType, clip_fillType);
let str = JSON.stringify(solution).toLowerCase();
console.log("solution", solution);
console.log(str);
return eval(str);
}
function getAimList(pots) {
let aim = pots.map(list=>{
return list.map(item => {
return {
X: item.x,
Y: item.y
}
})
})
return aim;
}
export default {
computeShape
}```
|
9070op/githero
|
9070op/githero
rest.js
```const mongoose = require("mongoose");
const validator = require("validator");
const createSchema = new mongoose.Schema({
name: {
type: String,
// minlength: 3,
required: true,
},
email: {
type: String,
unique: true,
required: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('invalid email id');
}
}
},
textarea: {
type: String,
required: true,
}
})
const findmodel = new mongoose.model("findmodel", createSchema);
module.exports = findmodel;```
index.js
```const express = require("express");
const app = express();
require("./main/conn");
const port = process.env.PORT || 8000;
const path = require("path");
const cros = require("cors");
const public = path.join(__dirname, "./public");
const findmodel = require("./main/rest");
app.use(cros())
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(public));
app.set("view engine", "hbs");
app.get("/", (req, res) => {
res.render("index")
})
app.get("/contact", (req, res) => {
res.render("contact")
})
app.get("/about", (req, res) => {
res.render("about")
})
app.get("/myproject", (req, res) => {
res.render("myproject")
})
app.post("/register", async(req, res) => {
try {
const insert = new findmodel({
name: req.body.name,
email: req.body.email,
textarea: req.body.textarea,
})
const result = await insert.save();
res.status(201).render("index");
console.log(result);
} catch (error) {
res.status(401).render("404");
}
})
app.listen(port, () => {
console.log(`listing port on ${port}`)
})```
|
907405824/memory-
|
907405824/memory-
README.md
```# memory-
just another repository
```
|
90aeteci/E3F2l5a6s1h4C7a9r4d6S9h3o2p8
|
90aeteci/E3F2l5a6s1h4C7a9r4d6S9h3o2p8
README.md
```E3F2l5a6s1h4C7a9r4d6S9h3o2p8
============================
E3F2l5a6s1h4C7a9r4d6S9h3o2p8
```
|
91diego/api-rest-spring
|
91diego/api-rest-spring
Profile.java
```package com.dgonzalez.apirest.persistence.entity;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "profiles")
public class Profile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@Column(name = "last_name")
private String lastName;
private String email;
private Integer age;
private Double height;
private Double weight;
private Double imc;
private Double geb;
private Double eta;
@Column(name = "user_id")
private Integer userId;
@Column(name = "created_at")
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@OneToOne
@JoinColumn(name = "user_id", insertable = false, updatable = false)
private User user;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
public Double getImc() {
return imc;
}
public void setImc(Double imc) {
this.imc = imc;
}
public Double getGeb() {
return geb;
}
public void setGeb(Double geb) {
this.geb = geb;
}
public Double getEta() {
return eta;
}
public void setEta(Double eta) {
this.eta = eta;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
}
```
UserRepository.java
```package com.dgonzalez.apirest.domain.repository;
import com.dgonzalez.apirest.domain.User;
import java.util.List;
import java.util.Optional;
public interface UserRepository {
List<User> getAll();
Optional<List<User>> getUser(int id);
User save(User user);
}```
UserCrudRepository.java
```package com.dgonzalez.apirest.persistence.crud;
import com.dgonzalez.apirest.persistence.entity.User;
import org.springframework.data.repository.CrudRepository;
public interface UserCrudRepository extends CrudRepository<User, Integer> {
}
```
UserRepository.java
```package com.dgonzalez.apirest.persistence;
import com.dgonzalez.apirest.persistence.crud.ProfileCrudRepository;
import com.dgonzalez.apirest.persistence.crud.UserCrudRepository;
import com.dgonzalez.apirest.persistence.entity.User;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public class UserRepository {
private UserCrudRepository userCrudRepository;
private ProfileCrudRepository profileCrudRepository;
/**
* Gets all users information
* @return User
*/
public List<User> getAll() {
return (List<User>) userCrudRepository.findAll();
}
/**
* Gets an specific user
* @param id
* @return User
*/
public Optional<User> getUser(int id) {
return userCrudRepository.findById(id);
}
/**
* Save new user
* @param user
* @return User
*/
public User save(User user) {
return userCrudRepository.save(user);
}
}
```
User.java
```package com.dgonzalez.apirest.persistence.entity;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String username;
private String password;
@Column(name = "created_at")
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
}
```
ProfileCrudRepository.java
```package com.dgonzalez.apirest.persistence.crud;
import com.dgonzalez.apirest.persistence.entity.Profile;
import org.springframework.data.repository.CrudRepository;
public class ProfileCrudRepository extends CrudRepository<Profile, Integer> {
}
```
Profile.java
```package com.dgonzalez.apirest.domain;
import javax.persistence.Column;
import java.time.LocalDateTime;
public class Profile {
private int profileId;
private String name;
private String lastName;
private String email;
private int age;
private double height;
private double weight;
private double imc;
private double geb;
private double eta;
private User user;
public int getProfileId() {
return profileId;
}
public void setProfileId(int profileId) {
this.profileId = profileId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getImc() {
return imc;
}
public void setImc(double imc) {
this.imc = imc;
}
public double getGeb() {
return geb;
}
public void setGeb(double geb) {
this.geb = geb;
}
public double getEta() {
return eta;
}
public void setEta(double eta) {
this.eta = eta;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
```
UserMapper.java
```package com.dgonzalez.apirest.persistence.mapper;
import com.dgonzalez.apirest.persistence.entity.User;
import org.mapstruct.Mapper;
@Mapper(componentModel = "spring")
public interface UserMapper {
}
```
|
91diego/registro-encuesta
|
91diego/registro-encuesta
OperacionesDb.php
```<?php
require_once "conexion/Conexion.php";
function c() {
return Conexion::conectar();
}
/**
* INSERTA LOS DATOS DE LA NEGOCIACION EN LA TABLA
*
* @param array $data -> informacion de la negociacion
* @param string $table
*/
function InsertDeal($data, $table) {
$insertDeal = "INSERT INTO $table (id_negociacion, cliente, desarrollo, responsable, puesto_responsable, departamento_responsable, gerente_responsable, origen, canal_ventas) VALUES (:id_negociacion, :cliente, :desarrollo, :responsable, :puesto_responsable, :departamento_responsable, :gerente_responsable, :origen, :canal_ventas)";
$stmt = Conexion::conectar()->prepare($insertDeal);
$stmt->bindParam(":id_negociacion", $data[0]['id_negociacion'], PDO::PARAM_STR);
$stmt->bindParam(":cliente", $data[0]['negociacion'], PDO::PARAM_STR);
$stmt->bindParam(":desarrollo", $data[0]['desarrollo'], PDO::PARAM_STR);
$stmt->bindParam(":responsable", $data[0]['responsable'], PDO::PARAM_STR);
$stmt->bindParam(":puesto_responsable", $data[0]['puesto'], PDO::PARAM_STR);
$stmt->bindParam(":departamento_responsable", $data[0]['departamento'], PDO::PARAM_STR);
$stmt->bindParam(":gerente_responsable", $data[0]['gerente_responsable'], PDO::PARAM_STR);
$stmt->bindParam(":origen", $data[0]['origen'], PDO::PARAM_STR);
$stmt->bindParam(":canal_ventas", $data[0]['canal_ventas'], PDO::PARAM_STR);
if ($stmt->execute()) {
return "ok";
} else {
return "error";
}
$stmt->close();
$stmt = null;
}
/**
* BUSCA EL REGISTRO EN LA BASE DE DATOS
*
* @param int $id -> id de la negociacion
* @param string $table
*/
function FindDeal($table, $id) {
$stmt = Conexion::conectar()->prepare("SELECT * FROM $table WHERE id_negociacion = :id");
$stmt->bindParam(":id", $id, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetch();
$stmt -> close();
$stmt = null;
}
/**
* REGRESA EL ID DE LA ENCUESTA
*
* @param string $name -> nombre de la encuesta
* @param int $phase -> id de la fase
* @param string $table -> nombre de la tabla
*/
function SurveyData($table, $name, $phase) {
$stmt = Conexion::conectar()->prepare("SELECT id FROM $table WHERE nombre = :encuesta
AND fase_id = :phase");
$stmt->bindParam(":encuesta", $name, PDO::PARAM_STR);
$stmt->bindParam(":phase", $phase, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetch();
$stmt -> close();
$stmt = null;
}
/**
* BUSCA SI YA SE REALIZO EL ENVIO DE LA ENCUESTA
*
* @param int $id -> id de la negociacion
* @param int $surveyId -> id de la encuesta
* @param string $table
*/
function FindSurveyShipping($table, $id, $surveyId) {
$stmt = Conexion::conectar()->prepare("SELECT * FROM $table WHERE negociacion_id = :id
AND encuesta_id = :surveyId");
$stmt->bindParam(":id", $id, PDO::PARAM_STR);
$stmt->bindParam(":surveyId", $surveyId, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetch();
$stmt -> close();
$stmt = null;
}
/**
* INSERTA EL ENVIO EN LA BASE DE DATOS
*
* @param int $id -> id de la negociacion
* @param int $surveyId -> id de la encuesta
* @param string $surveyShippingDate -> fecha de envio
* @param string $table
*/
function ShippingDate($table, $id, $surveyId, $surveyShippingDate) {
$shippingStatus = "ENVIADO";
$responseStatus = "PENDIENTE";
$responseDate = "SIN RESPUESTA";
$numberShipments = 1;
$insertDeal = "INSERT INTO $table (encuesta_id, negociacion_id, estatus_envio, fecha_envio, numero_envios, estatus_respuesta, fecha_respuesta) VALUES (:encuesta_id, :negociacion_id, :estatus_envio, :fecha_envio, :numero_envios, :estatus_respuesta, :fecha_respuesta)";
$stmt = Conexion::conectar()->prepare($insertDeal);
$stmt->bindParam(":encuesta_id", $surveyId, PDO::PARAM_STR);
$stmt->bindParam(":negociacion_id", $id, PDO::PARAM_STR);
$stmt->bindParam(":estatus_envio", $shippingStatus, PDO::PARAM_STR);
$stmt->bindParam(":fecha_envio", $surveyShippingDate, PDO::PARAM_STR);
$stmt->bindParam(":numero_envios", $numberShipments, PDO::PARAM_STR);
$stmt->bindParam(":estatus_respuesta", $responseStatus, PDO::PARAM_STR);
$stmt->bindParam(":fecha_respuesta", $responseDate, PDO::PARAM_STR);
if ($stmt->execute()) {
return "ok";
} else {
return "error";
}
$stmt->close();
$stmt = null;
}
/* function obtenerRegistros($desarrollo, $tabla) {
//print_r($desarrollo); exit;
$sqlConsulta = "SELECT nombre, cantidad AS 'cantidad stock' FROM $tabla WHERE desarrollo = :DESARROLLO";
$stmt = Conexion::conectar()->prepare($sqlConsulta);
$stmt->bindParam(":DESARROLLO",$desarrollo, PDO::PARAM_STR);
$stmt->execute();
return $stmt -> fetchAll();
$stmt -> close();
$stmt = null;
}*/
?>```
index.php
```<?php
header('Access-Control-Allow-Origin: *');
include 'funciones/Log.php';
include 'funciones/DatosNegociacion.php';
include 'funciones/OperacionesDb.php';
/**
* SE REGISTRA LA NEGOCIACION Y EL ENVIO
* EN LA BASE DE DATOS DE ENCUESTAS
* @param string $name -> nombre de le encuesta
* @param int $fase -> id de la fase asociada a la encuesta
* @param int id -> id de la negociacion asociada a la encuesta
*/
/* ESCRIBE HISTORIAL DE PETICIONES A LA APP EN UN LOG */
writeToLog($_REQUEST, 'incoming');
// SE ESTABLECE LA ZONA HORARIA
date_default_timezone_set('America/Mexico_City');
// ALMACENA LOS DATOS QUE SE PASARAN A LA VISTA
$data = [];
// SE ASIGNA LA FECHA ACTUAL
$currentDate = date('Y m d h:i:s A');
/* INFORMACION DEL DEAL */
// OBTIENE LA INFORMACION DE LA NEGOCIACION
$detailsDeal = 'https://intranet.idex.cc/rest/117/w0qdwl5fbr0hpuf1/crm.deal.get?ID='.$_REQUEST["id"];
// OBTIENE LA RESPUESTA DE LA API REST BITRIX
$responseAPI = file_get_contents($detailsDeal);
// CAMPOS DE LA RESPUESTA
$deal = json_decode($responseAPI, true);
/* FIN INFORMACION DEAL */
// CONTIENE LOS DATOS DEL RESPONSABLE
$user = users($deal["result"]["ASSIGNED_BY_ID"]);
// CONTIENE LOS DETALLES DEL DEPARTAMENTO
$departament = departament($user[0]["UF_DEPARTMENT"][0]);
// CONTIENE LOS DATOS DEL GERENTE
$manager = users($departament[0]["UF_HEAD"]);
// CONTIENE EL CANAL DE VENTAS
$purchase = purchase($deal["result"]["UF_CRM_5D03F07FB6F84"]);
// CONTIENE EL ORIGEN DE LA VENTA
$source = source($deal["result"]["SOURCE_ID"]);
// CONTIENE EL NOMBRE DEL DESARROLLO
$place = place($deal["result"]["UF_CRM_5D12A1A9D28ED"]);
$negociacion = explode(": ", $deal["result"]["TITLE"]);
array_push($data, [
"id_negociacion" => $_REQUEST["id"],
"negociacion" => strtoupper($negociacion[1]),
"desarrollo" => strtoupper($place),
"responsable" => strtoupper($user[0]["NAME"]." ".$user[0]["LAST_NAME"]),
"puesto" => strtoupper($user[0]["WORK_POSITION"]),
"departamento" => strtoupper($departament[0]["NAME"]),
"gerente_responsable" => strtoupper($manager[0]["NAME"]." ".$manager[0]["LAST_NAME"]),
"origen" => strtoupper($source[0]["NAME"]),
"canal_ventas" => strtoupper($purchase["NAME"]),
]);
writeToLog($data, ' DATA CRM ');
// BUSCAMOS LA NEGOCIACION EN LA BASE DE DATOS
$findDeal = findDeal("negociaciones", $_REQUEST["id"]);
// SI LA NEGOCIACION NO EXISTE, SE AGREGA EL REGISTRO
if (empty($findDeal)) {
$insertInfoDeal = InsertDeal($data, "negociaciones");
echo "Negociacion agregada";
} else {
echo 'Ya existe un registro';
}
// OBTENEMOS EL ID DE LA ENCUESTA
$surveyId = SurveyData("encuestas", $_REQUEST["name"], $_REQUEST["fase"]);
// BUSCAMOS EL ENVIO DE LA ENCUESTA
$surveyShipping = FindSurveyShipping("envio_encuestas", $_REQUEST["id"], $surveyId["id"]);
// writeToLog($insertInfoDeal, 'FIND SURVEY ID ');
print_r($surveyId["id"]);
// VALIDAMOS QUE EXISTA O NO ENVIO DE LA ENCUESTA
if (empty($surveyShipping)) {
$shippingDate = ShippingDate("envio_encuestas", $_REQUEST["id"], $surveyId["id"], $currentDate);
echo "Envio registrado";
} else {
echo "La encuesta ya fue enviada";
}
?>```
DatosNegociacion.php
```<?php
/**
* OBTIENE LOS DATOS DEL DEPARTAMENTO
*
* @param int $id
* @return \Illuminate\Http\Response
*/
function departament($id) {
// INFORMACION DEL DEPARTAMENTO
$detailsDepartament = 'https://intranet.idex.cc/rest/117/w0qdwl5fbr0hpuf1/department.get?ID='.$id;
// OBTIENE LA RESPUESTA DE LA API REST BITRIX
$responseAPI = file_get_contents($detailsDepartament);
// CAMPOS DE LA RESPUESTA
$departament = json_decode($responseAPI, true);
return $departament["result"];
// FIN INFORMACION DEPARTAMENTO
}
/**
* OBTIENE LOS DATOS DEL RESPONSABLE
*
* @param int $id
* @return \Illuminate\Http\Response
*/
function users($id) {
// INFORMACION RESPONSABLE
$detailsResponsable = 'https://intranet.idex.cc/rest/117/w0qdwl5fbr0hpuf1/user.get?ID='.$id;
// OBTIENE LA RESPUESTA DE LA API REST BITRIX
$responseAPI = file_get_contents($detailsResponsable);
// CAMPOS DE LA RESPUESTA
$responsable = json_decode($responseAPI, true);
// FIN INFORMACION RESPOSABLE
return $responsable["result"];
}
/**
* OBTIENE EL ORIGEN DE LA NEGOCIACION
*
* @param string $name
* @return \Illuminate\Http\Response
*/
function source($name) {
// INFORMACION RESPONSABLE
$detailsResponsable = 'https://intranet.idex.cc/rest/117/w0qdwl5fbr0hpuf1/crm.status.list?FILTER[STATUS_ID]='.$name;
// OBTIENE LA RESPUESTA DE LA API REST BITRIX
$responseAPI = file_get_contents($detailsResponsable);
// CAMPOS DE LA RESPUESTA
$responsable = json_decode($responseAPI, true);
// FIN INFORMACION RESPOSABLE
return $responsable["result"];
}
/**
* OBTIENE EL CANAL DE VENTAS
*
* @param int $id
* @return \Illuminate\Http\Response
*/
function purchase($id) {
// INFORMACION RESPONSABLE
$detailPurchase = 'https://intranet.idex.cc/rest/117/w0qdwl5fbr0hpuf1/crm.status.get?ID='.$id;
// OBTIENE LA RESPUESTA DE LA API REST BITRIX
$responseAPI = file_get_contents($detailPurchase);
// CAMPOS DE LA RESPUESTA
$purchase = json_decode($responseAPI, true);
// FIN INFORMACION RESPOSABLE
return $purchase["result"];
}
/**
* Obtiene el nombre del desarrollo del CRM
* @param int $id
* @return string $nombreDeesarrollo
*/
function place($id) {
$fieldsDeals = 'https://intranet.idex.cc/rest/117/w0qdwl5fbr0hpuf1/crm.deal.fields';
// OBTIENE LA RESPUESTA DE LA API REST BITRIX
$responseAPI = file_get_contents($fieldsDeals);
// CAMPOS DE LA RESPUESTA
$fields = json_decode($responseAPI, true);
// NUMERO DE CAMPOS EN LA POSICION DEL ARRAY
$numberItems = count($fields['result']['UF_CRM_5D12A1A9D28ED']['items']);
// ARRAY DE ITEMS
$items = [];
for ($i=0; $i < $numberItems; $i++) {
array_push($items, [
"id" => $fields['result']['UF_CRM_5D12A1A9D28ED']['items'][$i]["ID"],
"nombre" => $fields['result']['UF_CRM_5D12A1A9D28ED']['items'][$i]["VALUE"]
]);
}
for ($i=0; $i < count($items); $i++) {
if ($items[$i]["id"] == $id) {
$nombreDesarrollo = $items[$i]["nombre"];
return $nombreDesarrollo;
}
}
return $nombreDesarrollo;
}
?>```
Conexion.php
```<?php
class Conexion{
static public function conectar(){
try {
$link = new PDO("mysql:host=localhost;dbname=encuestas",
"idexcc12",
"qu6YecVrjc8o8PZ",
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
);
return $link;
} catch (PDOException $e) {
echo 'Falló la conexión: ' . $e->getMessage();
}
}
}
?>
```
|
91tlowell/PE4_part2_tic-tac-toe
|
91tlowell/PE4_part2_tic-tac-toe
tic-tac-toe.cpp
```#include <vector>
#include <iostream>
#include <fstream>
#include <string>
char player_turn = 'X';
void CreateBoard();
void DisplayBoard();
char GetPlayerChoice();
void PlaceMarker();
int main(){
// CreateBoard(); // not needed since we have the function placeMarker reading txt file to get board.
// DisplayBoard();
int count = 0;
while(count < 9){
PlaceMarker();
count++;
}
return 0;
}
void CreateBoard(){
std::ofstream myfile;
myfile.open ("board.txt");
std::vector<std::vector<char>> board {
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'}
};
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
myfile << board[i][j];
}
myfile << std::endl;
}
myfile.close();
}
void DisplayBoard(){
std::string line = "";
std::ifstream my_file_in("board.txt");
if(my_file_in.is_open()){
while(getline (my_file_in,line)){
std::cout << line << '\n';
}
my_file_in.close();
}
else{
std::cout << "Unable to open file. Please check file name for any mismatch." << std::endl;
}
}
char GetPlayerChoice() {
DisplayBoard();
char playersChoice;
std::cout << "Where on the board would you like to place your marker? :" << std::endl;
std::cin >> playersChoice;
if(playersChoice == 'X' || playersChoice == 'O') {
std::cout << "Invalid placement, please try again." << std::endl;
GetPlayerChoice();
}
return playersChoice;
}
void PlaceMarker(){
char player_choice = GetPlayerChoice();
std::vector<std::vector<char>> board {
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'}
};
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(board[i][j] == player_choice){
board[i][j] = player_turn;
}
}
}
std::ofstream my_file_out;
my_file_out.open ("board.txt");
for(int m = 0; m < board.size(); m++){
for(int n = 0; n < board.size(); n++){
my_file_out << board[m][n];
}
my_file_out << std::endl;
}
my_file_out.close();
}```
README.md
```# PE4_part2_tic-tac-toe
Tristan Lowell
Clay Fricke
```
|
934048645/934048645.github.io
|
934048645/934048645.github.io
README.md
```# 934048645.github.io```
|
939598604/docsify
|
939598604/docsify
_navbar.md
```- [主页](/)
- [百度](http://www.baidu.com)
- [百度](http://www.baidu.com)
- [百度](http://www.baidu.com)
- [百度](http://www.baidu.com)
- [百度](http://www.baidu.com)
- [百度](http://www.baidu.com)
- [百度](http://www.baidu.com)
- [百度](http://www.baidu.com)
- [百度](http://www.baidu.com)```
ali_domain.md
```> An awesome project guide 1.
```
README.md
```# docsify服务搭建
## 项目初始化
### 装脚手架工具
```
npm i docsify-cli -g
```
### 生成项目
进入Clone下来的项目目录,初始化文档工程
如果想在项目的 ./docs 目录里写文档,直接通过 init 初始化项目。
```
docsify init ./docs
```
### 开始写文档
初始化成功后,可以看到 `./docs` 目录下创建的几个文件

`index.html` 入口文件
`README.md` 会做为主页内容渲染
`.nojekyll` 用于阻止 GitHub Pages 会忽略掉下划线开头的文件
直接编辑 `docs/README.md` 就能更新网站内容,当然也可以写多个页面。
### 本地预览网站
运行一个本地服务器通过 `docsify serve` 可以方便的预览效果,而且提供 LiveReload 功能,可以让实时的预览。默认访问 [http://localhost:3000](http://localhost:3000/) 。
```
modify_github_domain.md
```> An awesome project guide 1.
```
_sidebar.md
```- [docsify服务搭建](/)
- github主页搭建
- [github仓库搭建](new_rep.md)
- [阿里云域名申请](ali_domain.md)
- [自定义github域名](modify_github_domain.md)```
new_rep.md
```# githup仓库搭建
### 初始化githup仓库
1.登录githup网站,点击有上角的加号新建仓库

2.填写仓库信息

3.复制仓库的地址用git工具同步到本地

4.将docsify生成的docs文件夹下的所有文件复制到仓库目录下,并提交到github

```
|
94-Istanbul-Front-End-Bootcamp/odev-2-milyastayan
|
94-Istanbul-Front-End-Bootcamp/odev-2-milyastayan
index.js
```let data = [];
const fetchData = () => {
//verinin çekildiği yer
fetch("data.json")
.then(response => {
return response.json();
})
.then(responseData => {
//json'dan okunan verinin data array'ine atanması
data = responseData;
//veri geldikten sonra filtreleme butonu görünür olsun
let filterButton = document.querySelector("#filterButton");
filterButton.setAttribute("style", "");
let activeList = document.querySelector(".hideActiveList");
activeList.setAttribute("style", "");
let adultList = document.querySelector(".hideAdultList");
adultList.setAttribute("style", "");
let fLetterList = document.querySelector(".hidefirstLetter");
fLetterList.setAttribute("style", "");
//verinin html içerisinde listelendiği fonksiyon
listData(responseData);
})
.catch(err => {
//hata yönetimi
console.log(err)
})
}
//verinin table tag'i içerisinde listelenmesini sağlayan fonksiyon
const listData = (data) => {
let table = document.querySelector("#people");
table.innerHTML =
`<tr>
<th>Name</th>
<th>Email</th>
<th>Age</th>
<th>Active</th>
</tr>`
+ data.map(element => {
return `
<tr>
<td>${element.name}</td>
<td>${element.email}</td>
<td>${element.age}</td>
<td>${element.isActive}</td>
</tr>
`;
})
}
const activePeopleCheck = document.querySelector('#ActiveList');
const adultPeopleCheck = document.querySelector('#AdultList');
const firstLetterFetch = document.querySelector('#firstLetter');
//verinin filtrelenmesini sağlayan fonksiyon
const filterData = () => {
try {
if (activePeopleCheck.checked && adultPeopleCheck.checked && firstLetterFetch.value) {
let filteredData = data.filter(element => element.isActive === true && element.age >= 18 && element.name[0].toLowerCase() === firstLetterFetch.value.toLowerCase());
listData(filteredData);
}
else if (activePeopleCheck.checked && firstLetterFetch.value) {
let filteredData = data.filter(element => element.isActive === true && element.name[0].toLowerCase() === firstLetterFetch.value.toLowerCase());
listData(filteredData);
}
else if (firstLetterFetch.value && adultPeopleCheck.checked) {
let filteredData = data.filter(element => element.name[0].toLowerCase() === firstLetterFetch.value.toLowerCase() && element.age >= 18);
listData(filteredData);
}
else if (activePeopleCheck.checked && adultPeopleCheck.checked) {
let filteredData = data.filter(element => element.isActive === true && element.age >= 18);
listData(filteredData);
}
else if (activePeopleCheck.checked) {
let filteredData = data.filter(element => element.isActive === true);
listData(filteredData);
}
else if (adultPeopleCheck.checked) {
let filteredData = data.filter(element => element.age >= 18);
listData(filteredData);
}
else if (firstLetterFetch.value) {
let filteredData = data.filter(element => element.name[0].toLowerCase() === firstLetterFetch.value.toLowerCase());
listData(filteredData);
}
}
catch (err) {
alert('Bir hata oluştu!');
}
}```
|
9527-ol/Web-scraping-challenge
|
9527-ol/Web-scraping-challenge
scrape_mars.py
```from splinter import Browser
from bs4 import BeautifulSoup as bs
import time
import pandas as pd
def init_browser():
# @NOTE: Replace the path with your actual path to the chromedriver
executable_path = {"executable_path": "/usr/local/bin/chromedriver"}
return Browser("chrome", **executable_path, headless=False)
def scrape_url(url):
browser = init_browser()
browser.visit(url)
time.sleep(3)
html = browser.html
soup = bs(html, 'html.parser')
browser.quit()
return soup
def scrape():
mars_data = {}
news_url = "https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest"
news_soup = scrape_url(url_news)
latest_title = news_soup.find('div', class_='content_title').find('a').text
latest_text = news_soup.find('div', class_='rollover_description_inner').text
mars_data['latest_title'] = latest_title
mars_data['latest_text'] = latest_text
img_url = 'https://www.jpl.nasa.gov/spaceimages/images/largesize/PIA23852_hires.jpg'
img_soup = scrape_url(img_url)
image_url = img_soup.find('div',class_='img').find('img')['src']
featured_image_url = f'https://www.jpl.nasa.gov{img_url}'
mars_data['featured_image_url'] = featured_image_url
weather_url = 'https://twitter.com/marswxreport?lang=en'
weather_soup = scrape_url(weather_url)
mars_weather = soup.find('div', class_='js-tweet-text-container').text
mars_data['mars_weather'] = mars_weather
table_url = 'https://space-facts.com/mars/'
table_soup = scrape_url(table_url)
table_soup = scrape_url(url_table)
mars_table = str(table_soup.find('tbody'))
mars_data['mars_facts'] = mars_table
hemisphere_url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'
hemisphere_soup = scrape_url(hemisphere_url)
items = hemisphere_soup.find_all('div', class_='item')
hemisphere_image_urls = []
main_url = 'https://astrogeology.usgs.gov'
for item in items:
title = item.find('h3').text
sm_img_url = item.find('a', class_='itemLink product-item')['href']
browser.visit(main_url + sm_img_url)
img_html = browser.html
soup = BeautifulSoup(img_html, 'html.parser')
image_url = main_url + soup.find('img', class_='wide-image')['src']
hemisphere_image_urls.append({"title" : title, "img_url" : image_url})
return mars_data
```
|
95424736/SPYDER
|
95424736/SPYDER
拉钩网登陆.py
```import time
from selenium import webdriver
# 创建浏览器对象
driver = webdriver.Chrome()
driver.get('https://passport.lagou.com/login/login.html?')
# # 查找节点
ID = driver.find_element_by_xpath("//input[@type='text']")
password = driver.find_element_by_xpath("//input[@type='password']")
time.sleep(2)
#输入用户名
ID.send_keys('用户名')
time.sleep(2)
#输入密码
password.send_keys('密码')
login = driver.find_element_by_xpath("//input[@type='submit']")
#登录
login.click()
```
README.md
```# SPYDER
AN EASY SPTDER
HI
```
非小号虚拟货币数据.py
```from selenium import webdriver
from lxml import etree
from multiprocessing import Queue
from threading import Thread
import csv
import time
#创建类对象
class FeiXiaohaospider(object):
def __init__(self):
#初始url
self.baseurl ="https://www.feixiaohao.com/list_"
#数据队列
self.msgQueue = Queue()
#url队列
self.urlQueue = Queue()
#html队列
self.htmlQueue = Queue()
#记录请求线程的数量,设定最大量为10
self.alive = 10
#记录爬取的数据数量
self.n = 0
#储存函数,存入csv文件
def savemsg(self):
#创建csv文件,编码gb18030,
with open('非小号虚拟货币数据.csv','a',newline='',encoding='gb18030') as f:
writer = csv.writer(f)
#设置列表表头
writer.writerow(['币种','流通市值','全球指数','24H成交额','流通数量','24H涨幅'])
#循环存入数据
while True:
#当数据msg队列不为空时,开始存入
if not self.msgQueue.empty():
getmsg = self.msgQueue.get()
writer.writerow(getmsg)
self.n += 1
#记录存入的数据数量
print('存入%d条数据' % self.n)
#当三个队列都为空时候,且get线程不在运行时,数据抓取完毕,退出解析线程
else:
time.sleep(5)
if (not self.alive) and self.urlQueue.empty() and self.htmlQueue.empty() and self.msgQueue.empty() :
print('存储线程退出')
break
#解析线程,从html队列取出html源码进行解析
def parseHtml(self):
while True:
#当html队列不为空时,开始进行网页解析
if not self.htmlQueue.empty():
getHtml = self.htmlQueue.get()
p = etree.HTML(getHtml)
baseList = p.xpath('//tr[@class="ivu-table-row"]')
for base in baseList:
L = []
L.append(base.xpath('./td/div/a/span/text()')[0]) #币种
msg = base.xpath("./td[@class='ivu-table-column-right'][1]//text()")[5]
L.append(msg) if msg else L.append(' ')
msg = base.xpath("./td[@class='ivu-table-column-right'][2]//text()")[5]
L.append(msg) if msg else L.append(' ')
msg = base.xpath("./td[@class='ivu-table-column-right'][3]//text()")[5]
L.append(msg) if msg else L.append(' ')
msg = base.xpath('./td/div/span/span/text()')[0]
L.append(msg) if msg else L.append(' ')
msg = base.xpath("./td/div/span[contains(@class,'text')]/text()")
L.append(msg[0]) if msg else L.append(' ')
#将解析后得到的数据存入msg队列
self.msgQueue.put(L)
else:
time.sleep(5)
print(self.alive)
#当url队列和html队列都为空时候,数据解析完毕,退出解析线程
if self.urlQueue.empty() and (not self.alive) and self.htmlQueue.empty():
break
#请求线程,用于模仿浏览器行为,获得html页面
def gethtml(self):
while True:
if not self.urlQueue.empty():
# 设置chrome为无头浏览器
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=chrome_options)
geturl = self.urlQueue.get()
driver.get(geturl)
html = driver.page_source
self.htmlQueue.put(html)
else:
#当url队列为空时候,无要继续创建的页面,退出线程
print('请求线程退出')
break
#主函数
def main(self):
#创建24个url
for i in range(1,25):
url = self.baseurl+str(i)+'.html'
self.urlQueue.put(url)
#创建储存线程的列表,用于统一回收
L1 = []
#分别创建10个请求线程和10个解析线程
for i in range(10):
t1 = Thread(target=self.gethtml)
t1.start()
L1.append(t1)
L2 = []
for i in range(10):
t2 = Thread(target=self.parseHtml)
t2.start()
L2.append(t2)
#创建一个储存线程
t3 = Thread(target=self.savemsg)
t3.start()
L2.append(t3)
print('线程创建完毕,开始爬取.......')
#回收线程
for i in L1:
i.join()
# 请求线程数量减1
self.alive -= 1
for i in L2:
i.join()
print('爬取完毕,线程关闭')
if __name__ == "__main__":
bt = time.time()
myspider = FeiXiaohaospider()
myspider.main()
print('爬取完毕,共用时',time.time()-bt,'秒,共爬取数据',myspider.n,'条')
```
链家杭州二手房信息爬取.py
```import requests
from lxml import etree
from multiprocessing import Queue
from threading import Thread
import csv
import random
import time
#创建user-agent列表
USERAGENT = ['Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60 ',
'Opera/8.0 (Windows NT 5.1; U; en)',
'Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50 ',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50',
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0 ',
'Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2 ',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 ',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11 ',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36 ',
'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER',
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)',
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)',
'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0 ',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0)',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.4.3.4000 Chrome/30.0.1599.101 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 UBrowser/4.0.3214.0 Safari/537.36']
#随机生成headers信息的user-agent
headers = {"User-Agent":random.choice(USERAGENT)}
#创建class类
class lianjiaSpider(object):
#初始化
def __init__(self):
#基础url
self.baseurl = "https://hz.lianjia.com/ershoufang/"
#价格区间列表,p1-p6代表二手房不同的价格区间,用作拼接url
self.priceList = ['p1','p2','p2','p4','p5','p6']
#创建url队列,html源码队列、二手房信息队列
self.urlQueue = Queue()
self.htmlQueue = Queue()
self.msgQueue = Queue()
#获取数据的数量
self.n = 0
#储存函数,将二手房信息存入csv表
def saveMsg(self):
time.sleep(2)
with open('链家二手房价格信息表.csv', 'a', newline='', encoding='gb18030') as f:
writer = csv.writer(f)
while True:
#当msgQueue队列不为空时,开始存入信息
if not self.msgQueue.empty():
#阻塞2S,若未从队列中获取信息,则线程退出
try:
getmsg = self.msgQueue.get(timeout=2)
writer.writerow(getmsg)
self.n += 1
except:
break
#当msgQueue队列持续5秒仍旧为空,则线程退出
else:
time.sleep(5)
if self.msgQueue.empty():
break
#解析函数,解析得到的html页面
def parseHtml(self):
while True:
# 当htmlQueue队列不为空时,开始存入信息
if not self.htmlQueue.empty():
# 阻塞2S,若未从队列中获取信息,则线程退出
try:
gethtml = self.htmlQueue.get(timeout=1)
p = etree.HTML(gethtml)
p = p.xpath("//li[@class='clear LOGCLICKDATA']")
#当页面匹配的信息不为空时,进行页面进一步解析
if p:
for i in p:
#二手房地址信息
msg = i.xpath(".//div/div[@class='address']/div//text()")
#二手房价格信息
price = i.xpath(".//div/div[@class='priceInfo']/div//text()")
#二手房其他信息
other = i.xpath(".//div/div[@class='followInfo']//text()")
L = [''.join(price[0:2]), price[2], msg[1], msg[0], other[0]]
#将二手房信息以列表形式存入msgQueue队列
self.msgQueue.put(L)
except:
print('**************有一个parsehtml线程退出*******************')
break
# 当htmlQueue队列持续5秒仍旧为空,判断为没有新的html加入,线程退出
else:
time.sleep(5)
if self.htmlQueue.empty():
break
#获取页面函数,用于获取页面的源码
def getHtml(self):
while True:
#urlQueue队列不为空时进行页面获取,为空时退出线程
if not self.urlQueue.empty():
#开始获取页面
try:
geturl = self.urlQueue.get(timeout=0.5)
p = requests.get(geturl,headers=headers)
p.encoding = 'utf-8'
html = p.text
#将页面html信息存入htmlQueue队列
self.htmlQueue.put(html)
except:
break
else:
break
#主函数,开始执行程序
def main(self):
for price in self.priceList:
for i in range(101):
url = self.baseurl + 'pg' + str(i) + price
self.urlQueue.put(url)
print('*****url存储完毕******')
tList = []
for i in range(15):
t1 = Thread(target=self.getHtml)
t2 = Thread(target=self.parseHtml)
tList.append(t1)
tList.append(t2)
t1.start()
t2.start()
t3 = Thread(target=self.saveMsg)
t3.start()
tList.append(t3)
print('******线程创建完毕*******')
print('抓取中..........')
for i in tList:
i.join()
print('******线程回收完毕*******')
if __name__ == "__main__":
a = time.time()
mySpider = lianjiaSpider()
mySpider.main()
print('抓取完毕,用时:',time.time()-a,'秒,',' 爬取信息',mySpider.n,'条')
```
百度贴吧类.py
```# -*- coding: utf-8 -*-
"""
Created on Wed Mar 27 18:23:23 2019
@author: Python
"""
import urllib.request
import urllib.parse
class BaiduSpider(object):
def __init__(self):
self.baseurl='http://tieba.baidu.com/f?'
self.headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0'}
#获取页面
def getPage(self,url):
req = urllib.request.Request(url, headers=self.headers)
res = urllib.request.urlopen(req)
html = res.read().decode('utf-8')
return html
def writePage(self,filename,html):
with open(filename,'w',encoding='utf-8') as f:
f.write(html)
def workOn(self):
name = input('请输入贴吧名称:')
begin = int(input('请输入起始页:'))
end = int(input('请输入终止页:'))
#拼接贴吧主页的url地址
kw = urllib.parse.urlencode({'kw':name})
for page in range(begin, end+1):
pn = (page - 1)*50
url = self.baseurl + kw+ '&pn=' + str(pn)
html = self.getPage(url)
filename = '第'+str(page)+'页.html'
self.writePage(filename,html)
print('第%d页爬取成功'%page)
if __name__ == '__main__':
spider = BaiduSpider()
spider.workOn()```
|
95rolancia/cats-gallery-javascript
|
95rolancia/cats-gallery-javascript
api.js
```const API_END_POINT = "public/data";
const delay = (ms = 500) => new Promise((r) => setTimeout(r, ms));
export default class Api {
async request(nodeId) {
try {
await delay();
const res = await fetch(`${API_END_POINT}/${nodeId ? nodeId : "content"}.json`);
if (!res.ok) {
throw new Error("서버의 상태가 이상합니다!", res);
}
return await res.json();
} catch (err) {
throw new Error("무언가가 잘못되었습니다!", err);
}
}
}
```
README.md
```# 고양이 사진첩!
## 간단한 설명
OS의 파일 탐색기를 웹 브라우저에서 구현
## 데모 👀
https://95rolancia.github.io/cats-gallery-javascript
## 구조
├── public
├── src
│ ├── api
│ │ └── api.js
│ ├── components
│ │ ├── app.js
│ │ ├── breadcrumb.js
│ │ ├── imageview.js
│ │ └── nodes.js
│ ├── styles
│ │ ├── auth_service.js
│ │ ├── card_repository.js
│ │ ├── firebase.js
│ │ └── image_uploader.js
│ └── utils
│ └── loading.js
├── index.js
├── index.html
└── README.md
## 기술 스택
- HTML
- CSS
- JavaScript
## 기능
- 폴더 클릭 시 폴더로 들어가기
- 파일 클릭 시 파일 보여주기
- 로딩
- 주소창 클릭 시에도 이동
## 소감
이 문제는 프로그래머스 과제관에 있는 고양이 사진첩 문제입니다.
프로젝트를 진행하면서 명령적 프로그래밍, 선언적 프로그래밍에 대해 곱씹게 되었으며 component 단위로 구현함으로써 React와 같은 라이브러리를 사용하는 이유도 조금이나마 알게되었습니다.
```
index.js
```import App from "./src/components/app.js";
import Api from "./src/service/api.js";
const api = new Api();
new App({ $app: document.querySelector("#app"), api: api });
```
breadcrumb.js
```export default class BreadCrumb {
constructor({ $app, initialState, onNavClick }) {
this.state = initialState;
this.onNavClick = onNavClick;
this.$target = document.createElement("nav");
this.$target.className = "Breadcrumb";
$app.appendChild(this.$target);
this.render();
this.$target.addEventListener("click", (e) => {
const $navItem = e.target.closest(".nav-item");
if ($navItem) {
const { index } = $navItem.dataset;
this.onNavClick(index ? index : null);
}
});
}
setState(nextState) {
this.state = nextState;
this.render();
}
render() {
this.$target.innerHTML = `<div class="nav-item">root</div>${this.state
.map((node, index) => `<div class="nav-item" data-index="${index}">${node.name}</div>`)
.join("")}`;
}
}
```
app.js
```import BreadCrumb from "./breadcrumb.js";
import Nodes from "./nodes.js";
import Loading from "../utils/loading.js";
import ImageView from "./imageview.js";
const cache = {};
export default class App {
constructor({ $app, api }) {
this.api = api;
this.state = {
isRoot: true,
nodes: [],
depth: [],
selectedFilePath: null,
isLoading: false,
};
this.breadCrumb = new BreadCrumb({
$app,
initialState: this.state.depth,
onNavClick: (index) => this.onNavClick(index),
});
this.nodes = new Nodes({
$app,
initialState: { ...this.state },
// () => onClick() 이런 식으로 해줘야 app에 있는 this를 사용할 수 있다!
onClick: (node) => this.onClick(node),
onBackClick: () => this.onBackClick(),
Loading,
});
this.imageView = new ImageView({
$app,
initialState: this.state.selectedFilePath,
onCloseClick: () => this.onCloseClick(),
});
this.loading = new Loading({ $app, initialState: this.state.isLoading });
this.init();
}
setState(nextState) {
this.state = nextState;
this.breadCrumb.setState(this.state.depth);
this.nodes.setState({
isRoot: this.state.isRoot,
nodes: this.state.nodes,
});
this.imageView.setState(this.state.selectedFilePath);
this.loading.setState(this.state.isLoading);
}
async onClick(node) {
this.setState({
...this.state,
isLoading: true,
});
try {
if (node.type === "DIRECTORY") {
const nextNodes = cache[node.id] ? cache[node.id] : await this.api.request(node.id);
this.setState({
...this.state,
depth: [...this.state.depth, node],
isRoot: false,
nodes: nextNodes,
});
cache[node.id] = nextNodes;
} else if (node.type === "FILE") {
this.setState({
...this.state,
selectedFilePath: node.filePath,
});
}
} catch (err) {
console.error(err);
} finally {
this.setState({
...this.state,
isLoading: false,
});
}
}
async onBackClick() {
this.setState({
...this.state,
isLoading: true,
});
try {
const nextState = { ...this.state };
nextState.depth.pop();
const prevNodeId =
nextState.depth.length === 0 ? null : nextState.depth[nextState.depth.length - 1].id;
if (prevNodeId === null) {
const rootNodes = cache.root ? cache.root : await this.api.request();
this.setState({
...nextState,
isRoot: true,
nodes: rootNodes,
});
} else {
const prevNodes = cache[prevNodeId]
? cache[prevNodeId]
: await this.api.request(prevNodeId);
this.setState({
...nextState,
isRoot: false,
nodes: prevNodes,
});
}
} catch (e) {
console.error(e);
} finally {
this.setState({
...this.state,
isLoading: false,
});
}
}
onCloseClick() {
this.setState({
...this.state,
selectedFilePath: null,
});
}
onNavClick(index) {
if (index === null) {
this.setState({
...this.state,
depth: [],
isRoot: true,
nodes: cache.root,
});
return;
}
if (index === this.state.depth.length - 1) {
return;
}
const nextState = { ...this.state };
const nextDepth = this.state.depth.slice(0, index + 1);
this.setState({
...nextState,
depth: nextDepth,
nodes: cache[nextDepth[nextDepth.length - 1].id],
});
}
async init() {
this.setState({
...this.state,
isLoading: true,
});
try {
const rootNodes = await this.api.request();
this.setState({
...this.state,
isRoot: true,
nodes: rootNodes,
});
cache.root = rootNodes;
console.log("first init\n", this.state);
} catch (err) {
console.error(err);
} finally {
this.setState({
...this.state,
isLoading: false,
});
}
}
}
```
|
963666666/golang
|
963666666/golang
micro.md
```
## 拆分流程
- 代码拆分:
- 公共技术组件拆分
- 先拆分公共技术组件为独立的包
- 确保拆分后包引用准确,编译没问题
- 启动运行没有问题,
- 所有的自动化测试执行没有问题
- 资金账户子系统拆分
- 复制红包业务代码到独立的资金账户项目
- 在资金账户包中移除和资金账户无关的代码
- 确保拆分后包引用准确,编译没问题
- 确保资金账户子系统启动运行没有问题
- 运行资金账户包所有的自动化测试执行没有问题
- UI子系统拆分
- 复制红包业务代码到独立的UI 项目
- 在资金账户包中移除和UI无关的代码
- 确保拆分后包引用准确,编译没问题
- 确保UI子系统启动运行没有问题
- 运行UI页面,测试执行没有问题
- 红包子系统拆分,红包系统作为红包子系统
- 在红包子系统中移除和红包无关的代码
- 红包子系统中引用资金账户子系统代码的地方,全部定义interface,修改为引用interface
- 先确保拆分后包引用准确,编译没问题
- 编写引用资金账户业务的interface实现为http调用方式。
- 确保红包子系统启动运行没有问题
- 运行红包所有的自动化测试执行没有问题
- 修改UI页面部分,从直接代码调用改为为调用HTTP接口
```
README.md
```# infra
Go红包微服务拆分公共基础设施组件```
README.md
```# resk
#### 介绍
慕课网3小时极简春节抢红包之Go的实战源代码
课程地址:https://www.imooc.com/learn/1101
resk: red envelope seckill(second kill)
红包秒杀系统
```
red-sql.md
```
## red_envelope_goods
| 字段 | 字段名称 | 数据类型 | 说明 |
| --------------- | -------------- | ------------------------ | ------------------------------------------------- |
| id | 自增ID | bigint(20) | 自增ID |
| envelope_no | 红包编号 | varchar(32) | 红包编号,红包唯一标识 |
| envelope_type | 红包类型 | tinyint(2) | 红包类型:普通红包,碰运气红包,过期红包 |
| username | 用户名称 | varchar(64) | 用户名称 |
| user_id | 用户编号 | varchar(40) | 用户编号, 红包所属用户 |
| blessing | 祝福语 | varchar(64) | 祝福语 |
| amount | 红包总金额 | decimal(30,6) unsigned | 红包总金额 |
| amount_one | 单个红包金额 | decimal(30,6) unsigned | 单个红包金额,碰运气红包无效 |
| quantity | 红包总数量 | int(10) unsigned | 红包总数量 |
| remain_amount | 红包剩余金额额 | decimal(30,6) unsigned | 红包剩余金额额 |
| remain_quantity | 红包剩余数量 | int(10) unsigned | 红包剩余数量 |
| expired_at | 过期时间 | datetime(3) | 过期时间 |
| status | 红包/订单状态 | tinyint(2) | 红包/订单状态:0 创建、1 发布启用、2过期、3失效 |
| order_type | 订单类型 | tinyint(2) | 订单类型:发布单、退款单 |
| pay_status | 支付状态 | tinyint(2) | 支付状态:未支付,支付中,已支付,支付失败 |
| created_at | 创建时间 | datetime(3) | 创建时间 |
| updated_at | 更新时间 | datetime(3) | 更新时间 |
## red_envelope_item
| 字段 | 字段名称 | 数据类型 | 说明 |
| ------------- | ------------------ | ------------------------ | ------------------------------------------ |
| id | 自增ID | bigint(20) | 自增ID |
| item_no | 红包订单详情编号 | bigint(20) | 红包订单详情编号 |
| envelope_no | 红包编号 | varchar(32) | 红包编号,红包唯一标识 |
| recv_username | 红包接收者用户名称 | varchar(64) | 红包接收者用户名称 |
| recv_user_id | 红包接收者用户编号 | varchar(40) | 红包接收者用户编号 |
| amount | 收到金额 | decimal(30,6) unsigned | 收到金额 |
| quantity | 收到数量 | int(10) unsigned | 收到数量:对于收红包来说是1 |
| remain_amount | 收到后红包剩余金额 | decimal(30,6) unsigned | 收到后红包剩余金额 |
| account_no | 红包接收者账户ID | varchar(32) | 红包接收者账户ID |
| pay_status | 支付状态 | tinyint(2) | 支付状态:未支付,支付中,已支付,支付失败 |
| created_at | 创建时间 | datetime(3) | 创建时间 |
| updated_at | 更新时间 | datetime(3) | 更新时间 |```
double-average.go
```package main
import (
"fmt"
"git.imooc.com/wendell1000/infra/algo"
)
func main() {
count, amount := int64(10), int64(10000)
remain := amount
sum := int64(0)
for i := int64(0); i < 100; i++ {
x := algo.DoubleAverage(count-i, remain)
remain -= x
sum += x
fmt.Print(i+1, "=", float64(x)/float64(100), ", ")
}
fmt.Println()
fmt.Println("总和", sum)
}
```
README.md
```# resk
#### 介绍
####
慕课网《3小时极简春节抢红包之Go的实战源代码》《GO从0到1实战微服务版抢红包系统》
课程地址1《3小时极简春节抢红包之Go的实战》:https://www.imooc.com/learn/1101
课程地址2《GO从0到1实战微服务版抢红包系统》:https://coding.imooc.com/class/345.html
resk: red envelope seckill(second kill) 红包秒杀系统
分支说明,分支名称由“v+章号+节号1_节号N""组成,比如:
- v3-4 表示第三章第四节
- v4-10_12 表示第四章第10节至第12节
| 章编号 | 节编号 | 课程标题 | 分支 |
| ------ | ------ | ------------------------------------------------ | -------- |
| 3 | 4 | 初始源代码: 3-4 Go module模块化管理代码依赖 | v3-4 |
| 4 | 1 | 在Golang中如何设计枚举? | v4-1 |
| 4 | 2 | 在Golang中如何使用Json序列化:从标准库和jsoniter | v4-2 |
| 4 | 3~4 | 基础资源-配置设计-配置starter编码实践 | v4-3_4 |
| 4 | 5 | 基础资源-配置设计-启动管理器编码实践 | v4-5 |
| 4 | 6~7 | 基础设施资源-mysql starter编码实践 | v4-6_7 |
| 4 | 8~9 | 基础设施资源-log starter编码实践 | v4-8_9 |
| 4 | 10~12 | 基础设施资源-验证器 starter编码实践 | v4-10_12 |
| 4 | 13~15 | 基础设施资源-web框架 starter编码实践 | v4-13_15 |
| 5 | 0 | 在第4章的基础上重构了代码,以便更好的运行 | v5-0 |
| 5 | 3 | 资金账户模块服务接口设计和定义 | v5-3 |
| 5 | 4~8 | 资金账户模块-数据库访问层的定义和编码实践 | v5-4_8 |
| 5 | 9~13 | 资金账户-业务领域层的定义和编码实践 | v5-9_13 |
| 5 | 14-17 | 资金账户模块-应用服务层实现编码实践 | v5-14_21 |
| 5 | 18-21 | 资金账户模块-Web接口的定义和编码实践 | v5-14_21 |
| 6 | 4 | 红包模块-服务接口设计和定义编码实践 | v6-4 |
| 6 | 5~7 | 红包模块-数据访问层的定义和编码实践 | v6-5_7 |
| 6 | 8~10 | 发红包业务领域层的编码实践 | v6-8_10 |
| 6 | 11~15 | 红包模块-发红包web和goRpc用户接口层编码实践 | v6-11_15 |
| 6 | 17~21 | 红包模块-抢红包业务领域层和应用服务层编码实践 | v6-17_21 |
| 6 | 22 | 红包模块-抢红包web和GoRPC用户接口的轻松适配和编码实践 | v6-22 |
| 6 | 23~28 | 红包模块-过期红包 | v6-23_28 |
| 6 | 29~31 | 红包模块-mobile H5 UI | v6.29_31 |
|7|1~6|集成测试来保证代码健壮和稳定运行|v7|
|8|1~6|Golang项目打包运维部署|v8|
|9|1~7|红包微服务化架构概述和实践|v9-1_7|
|9|8~10|红包微服务化服务拆分实践:拆分后包含所有微服务代码的分支|v9-8_10|
|9|10|红包微服务化服务拆分实践:拆分后清理只包含resk微服务代码的分支,其他微服务查看account/infra/resk-ui仓库的v9-10分支|v9-10|
|10|1~9|微服务http服务发现客户端实践|v10-1_9|
|10|10|基于服务发现负载均衡的goRpc客户端编码实践:备注resk/infra|v10-10|
|11|-|微服务下分布式配置管理实践|v11|
|12|-|微服务部署管理实践|v12|
|13|-|红包系统性能分析实战演示|v13|
## 备注:
- 红包微服务化服务拆分实践后提交了2个分支,分别是:
- 分支:v9-8_10,拆分后包含所有微服务代码的分支
- 分支v9-10:拆分后清理只包含resk微服务代码的分支,其他微服务查看account/infra/resk-ui仓库的v9-10分支
- infra公共基础组件仓库地址: https://git.imooc.com/coding-345/infra.git
- account资金账户仓库地址:https://git.imooc.com/coding-345/account.git
- resk-ui红包mobile ui仓库地址:https://git.imooc.com/coding-345/resk-ui.git```
put.go
```package eureka
import (
"strings"
log "github.com/sirupsen/logrus"
)
func (c *Client) SendHeartbeat(appId, instanceId string) error {
values := []string{"apps", appId, instanceId}
path := strings.Join(values, "/")
res, err := c.Put(path, nil)
if res != nil {
log.WithFields(log.Fields{
"path": path,
"status": res.StatusCode,
}).Info("SendHeartbeat ")
}
return err
}
func (c *Client) UpdateMetadata(appId, instanceId string, metaData map[string]string) error {
values := []string{"apps", appId, instanceId, "metadata"}
path := strings.Join(values, "/") + "?"
for k, v := range metaData {
path = path + k + "=" + v + "&"
}
res, err := c.Put(path, nil)
if res != nil {
log.WithFields(log.Fields{
"path": path,
"status": res.StatusCode,
}).Info("UpdateMetadata ")
}
return err
}
//PUT /eureka/v2/apps/appID/instanceID/status?value=OUT_OF_SERVICE
func (c *Client) UpdateStatus(appId, instanceId string, status string) error {
values := []string{"apps", appId, instanceId, "status"}
path := strings.Join(values, "/") + "?value=" + status
res, err := c.Put(path, nil)
if res != nil {
log.WithFields(log.Fields{
"path": path,
"status": res.StatusCode,
}).Info("UpdateStatus ")
}
return err
}
```
sql.md
```
### Account
| 字段 | 字段名称 | 数据类型 | 说明 |
| ------------- | ------------------------------------------------------------ | ---------------------- | ------------------------------------------------------------ |
| id | 账户自增ID | bigint(20) | 自增ID,无业务含义 |
| account_no | 账户编号 | varchar(32) | 账户编号,账户唯一标识 |
| account_name | 账户名称 | varchar(64) | 账户名称,用来说明账户的简短描述,账户对应的名称或者命名,比如xxx积分、xxx零钱 |
| account_type | 账户类型 | tinyint(2) | 账户类型,用来区分不同类型的账户:积分账户、会员卡账户、钱包账户、红包账户 |
| currency_code | 货币类型编码 | char(3) | 货币类型编码:CNY人民币,EUR欧元,USD美元 。。。 |
| user_id | 用户编号 | varchar(40) | 用户编号, 账户所属用户 |
| username | 用户名称 | varchar(64) | 用户名称 |
| balance | 账户可用余额 | decimal(30,6) unsigned | 账户可用余额 |
| status | 账户状态 | tinyint(2) | 账户状态,账户状态:0账户初始化,1启用,2停用 |
| created_at | 创建时间 | datetime(3) | 创建时间 |
| updated_at | 更新时间 | datetime(3) | 更新时间 |
### Account_log
| 字段 | 字段名称 | 数据类型 | 说明 |
| ------------- | ------------------------------------------------------------ | ---------------------- | ------------------------------------------------------------ |
| id | 自增ID | bigint(20) | 自增ID,无业务含义 |
| trade_no | 交易单号 | varchar(32) | 交易单号 全局不重复字符或数字,唯一性标识 |
| log_no | 流水编号 | varchar(32) | 流水编号 全局不重复字符或数字,唯一性标识 |
| account_no | 账户编号 | varchar(32) | 账户编号 账户ID |
| user_id | 用户编号 | varchar(40) | 用户编号 |
| username | 用户名称 | varchar(64) | 用户名称 |
| target_account_no | 账户编号 | varchar(32) | 账户编号 账户ID |
| target_user_id | 目标用户编号 | varchar(40) | 目标用户编号 |
| target_username | 目标用户名称 | varchar(64) | 目标用户名称 |
| amount | 交易金额 | decimal(30,6) | 交易金额,该交易涉及的金额 |
| balance | 交易后余额 | decimal(30,6) unsigned | 交易后余额,该交易后的余额 |```
discovery.go
```package eureka
import (
"encoding/xml"
"io/ioutil"
"net/http"
"time"
"sync/atomic"
"github.com/tietang/go-utils/errs"
"strings"
log "github.com/sirupsen/logrus"
"net/url"
)
type Discovery struct {
apps *Applications
AppNames map[string]string
eurekaUrl []string
callbacks []func(*Applications)
ct uint64
}
func NewDiscovery(eurekaUrl []string) *Discovery {
return &Discovery{eurekaUrl: eurekaUrl, callbacks: make([]func(*Applications), 0)}
}
func (d *Discovery) AddCallback(callback func(*Applications)) {
d.callbacks = append(d.callbacks, callback)
}
func (d *Discovery) execCallbacks(apps *Applications) {
if len(d.callbacks) > 0 {
for _, c := range d.callbacks {
go c(apps)
}
}
}
func (d *Discovery) ScheduleAtFixedRate(second time.Duration) {
d.run()
go d.runTask(second)
}
func (d *Discovery) runTask(second time.Duration) {
timer := time.NewTicker(second)
for {
select {
case <-timer.C:
go d.run()
}
}
}
func (d *Discovery) run() {
apps, err := d.GetApplications()
if err == nil || apps != nil {
d.apps = apps
d.execCallbacks(apps)
} else {
log.Error(err)
}
}
func (c *Discovery) GetApps() *Applications {
if c.apps == nil {
apps, err := c.GetApplications()
if err == nil {
return apps
}
}
return c.apps
}
func (c *Discovery) GetApp(name string) *Application {
if c.apps == nil {
log.Info("Applications is nil")
return nil
}
for _, app := range c.apps.Applications {
if strings.ToLower(app.Name) == strings.ToLower(name) {
return &app
}
}
return nil
}
func (c *Discovery) GetInstances(name string) (*Application, error) {
//url := c.eurekaUrl + "/apps"
url := c.getEurekaServerUrl() + "/apps/" + name
// req, err := http.NewRequest("GET", url, nil)
// req.Header.Add("Accept", "application/json")
// res, err := c.client.Do(req)
// http.Client.Do(req)
res, err := http.Get(url)
if err != nil {
log.Error(err)
return nil, err
}
// log.Info(res.StatusCode)
respBody, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Error(err)
return nil, err
}
if res.StatusCode != http.StatusOK {
log.Error(err)
return nil, err
}
app := new(Application)
err = xml.Unmarshal(respBody, app)
// log.Info(string(respBody))
// log.Info(err, applications)
return app, err
}
func (c *Discovery) GetApplications() (*Applications, error) {
//url := c.eurekaUrl + "/apps"
url := c.getEurekaServerUrl() + "/apps"
// req, err := http.NewRequest("GET", url, nil)
// req.Header.Add("Accept", "application/json")
// res, err := c.client.Do(req)
// http.Client.Do(req)
res, err := http.Get(url)
if err != nil {
log.Error(err)
return nil, err
}
// log.Info(res.StatusCode)
respBody, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Error(err)
return nil, err
}
if res.StatusCode != http.StatusOK {
log.Error(err)
return nil, err
}
var applications *Applications = new(Applications)
err = xml.Unmarshal(respBody, applications)
// log.Info(string(respBody))
// log.Info(err, applications)
return applications, err
}
func (c *Discovery) getEurekaServerUrl() string {
ct := atomic.AddUint64(&c.ct, 1)
size := len(c.eurekaUrl)
if size == 0 {
panic(errs.NilPointError("eureka url is empty"))
}
index := int(ct) % size
url := c.eurekaUrl[index]
//if strings.LastIndex(url,"/")>-1{
url = strings.TrimSuffix(url, "/")
//}
return url
}
func (d *Discovery) Health() (bool, string) {
ok, desc := true, "ok"
i := 0
for _, u := range d.eurekaUrl {
url, err := url.Parse(u)
if err != nil {
i++
ok, desc = false, err.Error()
continue
}
healthUrl := url.Scheme + "://" + url.Host + "/health"
res, err := http.Get(healthUrl)
if err != nil {
i++
ok, desc = false, err.Error()
continue
}
if res == nil || res.StatusCode != http.StatusOK {
i++
ok, desc = true, res.Status
continue
}
}
return ok, desc
}
```
domain_receive.go
```package envelopes
import (
"context"
"database/sql"
"errors"
"github.com/shopspring/decimal"
log "github.com/sirupsen/logrus"
"github.com/tietang/dbx"
"imooc.com/resk/core/accounts"
"imooc.com/resk/infra/algo"
"imooc.com/resk/infra/base"
"imooc.com/resk/services"
)
var multiple = decimal.NewFromFloat(100.0)
//收红包业务逻辑代码
func (d *goodsDomain) Receive(
ctx context.Context,
dto services.RedEnvelopeReceiveDTO) (item *services.RedEnvelopeItemDTO, err error) {
//1.创建收红包的订单明细 preCreatItem
d.preCreateItem(dto)
//2.查询出当前红包的剩余数量和剩余金额信息
goods := d.Get(dto.EnvelopeNo)
//3. 效验剩余红包和剩余金额:
//- 如果没有剩余,直接返回无可用红包金额
if goods.RemainQuantity <= 0 || goods.RemainAmount.Cmp(decimal.NewFromFloat(0)) <= 0 {
log.Errorf("没有足够的红包和金额了: %+v", goods)
return nil, errors.New("没有足够的红包和金额了")
}
//4. 使用红包算法计算红包金额
nextAmount := d.nextAmount(goods)
err = base.Tx(func(runner *dbx.TxRunner) error {
//5. 使用乐观锁更新语句,尝试更新剩余数量和剩余金额:
dao := RedEnvelopeGoodsDao{runner: runner}
rows, err := dao.UpdateBalance(goods.EnvelopeNo, nextAmount)
// - 如果更新失败,也就是返回0,表示无可用红包数量和金额,抢红包失败
if rows <= 0 || err != nil {
return errors.New("没有足够的红包和金额了")
}
// - 如果更新成功,也就是返回1,表示抢到红包
//6. 保存订单明细数据
d.item.Quantity = 1
d.item.PayStatus = int(services.Paying)
d.item.AccountNo = dto.AccountNo
d.item.RemainAmount = goods.RemainAmount.Sub(nextAmount)
d.item.Amount = nextAmount
desc := goods.Username.String + "的" + services.EnvelopeTypes[services.EnvelopeType(goods.EnvelopeType)]
d.item.Desc = desc
txCtx := base.WithValueContext(ctx, runner)
_, err = d.item.Save(txCtx)
//insert into `red_envelope_item`(`item_no`,`envelope_no`,`amount`,`quantity`,`remain_amount`,`account_no`,`recv_username`,`recv_user_id`,`pay_status`)
// values(?,?,?,?,?,?,?,?,?)
// 1LlS0fIHk4UxdnqC8wNGww5V7cJ
//1LlU0eDA6WNt16ZbLKp3RwpFWcp
if err != nil {
log.Error(err)
return err
}
//7. 将抢到的红包金额从系统红包中间账户转入当前用户的资金账户
// transfer
status, err := d.transfer(txCtx, dto)
if status == services.TransferedStatusSuccess {
return nil
} else {
return err
}
return err
})
if err != nil {
return nil, err
}
return d.item.ToDTO(), err
}
func (d *goodsDomain) transfer(
ctx context.Context,
dto services.RedEnvelopeReceiveDTO) (status services.TransferedStatus, err error) {
systemAccount := base.GetSystemAccount()
body := services.TradeParticipator{
AccountNo: systemAccount.AccountNo,
UserId: systemAccount.UserId,
Username: systemAccount.Username,
}
target := services.TradeParticipator{
AccountNo: dto.AccountNo,
UserId: dto.RecvUserId,
Username: dto.RecvUsername,
}
adomain := accounts.NewAccountDomain()
//从系统红包资金账户扣减
transfer := services.AccountTransferDTO{
TradeBody: body,
TradeTarget: target,
TradeNo: dto.EnvelopeNo,
Amount: d.item.Amount,
ChangeType: services.EnvelopeOutgoing,
ChangeFlag: services.FlagTransferOut,
Decs: "红包扣减:" + dto.EnvelopeNo,
}
status, err = adomain.TransferWithContextTx(ctx, transfer)
if err != nil || status != services.TransferedStatusSuccess {
return status, err
}
//从系统红包资金账户转入当前用户
transfer = services.AccountTransferDTO{
TradeBody: target,
TradeTarget: body,
TradeNo: dto.EnvelopeNo,
Amount: d.item.Amount,
ChangeType: services.EnvelopeIncoming,
ChangeFlag: services.FlagTransferIn,
Decs: "红包收入:" + dto.EnvelopeNo,
}
return adomain.TransferWithContextTx(ctx, transfer)
}
//预创建收红包订单明细
func (d *goodsDomain) preCreateItem(dto services.RedEnvelopeReceiveDTO) {
d.item.AccountNo = dto.AccountNo
d.item.EnvelopeNo = dto.EnvelopeNo
d.item.RecvUsername = sql.NullString{String: dto.RecvUsername, Valid: true}
d.item.RecvUserId = dto.RecvUserId
d.item.createItemNo()
}
//计算红包金额
func (d *goodsDomain) nextAmount(goods *RedEnvelopeGoods) (amount decimal.Decimal) {
if goods.RemainQuantity == 1 {
return goods.RemainAmount
}
if goods.EnvelopeType == services.GeneralEnvelopeType {
return goods.AmountOne
} else if goods.EnvelopeType == services.LuckyEnvelopeType {
cent := goods.RemainAmount.Mul(multiple).IntPart()
next := algo.DoubleAverage(int64(goods.RemainQuantity), cent)
amount = decimal.NewFromFloat(float64(next)).Div(multiple)
} else {
log.Error("不支持的红包类型")
}
return amount
}
```
install.sh
```#!/usr/bin/env bash
EXTRACT_DIR="./.resk"
EXEC="./run.sh"
function main() {
NUM=`awk '/^__SHELL_END__/ {print NR+1;exit 0}' $0`
rm -fr ${EXTRACT_DIR} && mkdir ${EXTRACT_DIR}
echo ${EXTRACT_DIR} ${NUM}
tail -n+${NUM} $0 | tar -xz -C ${EXTRACT_DIR}
cd ${EXTRACT_DIR}
chmod +x ${EXEC}
${EXEC} $*
return 0
}
main $@
exit $?
#shell结束的标识,
# 注意最后一行,必须是有且只有一个换行,而且没有任何字符
__SHELL_END__
```
pool.go
```package rabbitmq_delay
import (
"github.com/streadway/amqp"
"sync"
)
func NewPools(addr string, maxconn int) *MQPool {
return &MQPool{
MaxConnect: maxconn,
Addr: addr,
mutex: sync.Mutex{},
connects: make([]*amqp.Connection, maxconn),
index: 0,
}
}
type MQPool struct {
MaxConnect int
Addr string
connects []*amqp.Connection
index int // 链接游标, 目的是并发使用connects
mutex sync.Mutex
}
func (mp *MQPool) Init() {
}
func (mp *MQPool) Connect() (conn *amqp.Connection, err error) {
mp.mutex.Lock()
defer mp.mutex.Unlock()
mp.index += 1
index := mp.index % mp.MaxConnect
conn = mp.connects[index]
if conn == nil || conn.IsClosed() {
conn, err = amqp.Dial(mp.Addr)
if err != nil {
panic(err)
}
mp.connects[index] = conn
}
return
}
func (mp *MQPool) Channel() (*amqp.Channel, error) {
conn, err := mp.Connect()
if err != nil {
return nil, err
}
return conn.Channel()
}```
main.go
```package main
import (
"git.imooc.com/wendell1000/infra"
"git.imooc.com/wendell1000/infra/base"
_ "git.imooc.com/wendell1000/resk"
_ "github.com/go-sql-driver/mysql"
log "github.com/sirupsen/logrus"
"github.com/tietang/props/consul"
"github.com/tietang/props/ini"
"github.com/tietang/props/kvs"
)
func main() {
//获取程序运行文件所在的路径
file := kvs.GetCurrentFilePath("boot.ini", 1)
log.Info(file)
//加载和解析配置文件
conf := ini.NewIniFileCompositeConfigSource(file)
conf.Set("profile", "dev")
addr := conf.GetDefault("consul.address", "127.0.0.1:8500")
contexts := conf.KeyValue("consul.contexts").Strings()
log.Info("consul address:", addr)
log.Info("consul contexts:", contexts)
consulConf := consul.NewCompositeConsulConfigSourceByType(contexts, addr, kvs.ContentIni)
consulConf.Add(conf)
//
base.InitLog(consulConf)
app := infra.New(consulConf)
app.Start()
}
```
build.sh
```#!/bin/bash
###################################################
# set
redisAddr="147.139.1.191:6379"
mysqlAddr="mrpoker:c07XCLzBMp82DUe_9foWgr@tcp(147.139.1.191:3306)\/mrpoker?charset=utf8mb4"
mqAddr="amqp:\/\/guest:guest@147.139.1.191:5672"
influxdbAddr="http:\/\/147.139.1.191:8086"
output=output
###################################################
cd "$(dirname "$0")"
pwd
###################################################
# update config
redis=`cat server.conf|awk -F"[redis_addr]" '/redis_addr/{print $x}'`
mysql=`cat server.conf|awk -F"[mysql_addr]" '/mysql_addr/{print $x}'`
mq=`cat server.conf|awk -F"[mq_addr]" '/mq_addr/{print $x}'`
influxdb=`cat server.conf|awk -F"[influxdb_addr]" '/influxdb_addr/{print $x}'`
#redis
if [ ! -n "$redis" ]; then
sed -i "/{/a\"redis_addr\":\"$redisAddr\"," server.conf
else
sed -i "s/\"redis_addr\":.*$/\"redis_addr\":\"$redisAddr\",/" server.conf
fi
#mysql
if [ ! -n "$mysql" ]; then
sed -i "/{/a\"mysql_addr\":\"$mysqlAddr\"," server.conf
else
sed -i "s/\"mysql_addr\":.*$/\"mysql_addr\":\"$mysqlAddr\",/" server.conf
fi
#mq
if [ ! -n "$mq" ]; then
sed -i "/{/a\"mq_addr\":\"$mqAddr\"," server.conf
else
sed -i "s/\"mq_addr\":.*$/\"mq_addr\":\"$mqAddr\",/" server.conf
fi
#influxdb
if [ ! -n "$influxdb" ]; then
sed -i "/{/a\"influxdb_addr\":\"$influxdbAddr\"," server.conf
else
sed -i "s/\"influxdb_addr\":.*$/\"influxdb_addr\":\"$influxdbAddr\",/" server.conf
fi
###################################################
rm -rf $output
mkdir $output
go build -a -o $output/server server.go && \
cp server.conf $output && \
cp -rf LuaPoker $output
```
runtimers_test.go
```package main
import (
"testing"
)
func BenchmarkRunTimers(b *testing.B) {
for _, count := range []int{1000, 2000, 5000, 10000, 20000, 50000, 100000, 500000} {
RunTimers(count)
}
//for i := 0; i < b.N; i ++ {
// RunTimers(i)
//}
}
```
client.go
```package accounts
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"git.imooc.com/wendell1000/infra"
"git.imooc.com/wendell1000/infra/base"
"git.imooc.com/wendell1000/infra/httpclient"
"git.imooc.com/wendell1000/infra/lb"
"git.imooc.com/wendell1000/resk/services"
log "github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"sync"
"time"
)
var _ services.AccountService = new(AccountClientService)
var once sync.Once
type AccountClientStarter struct {
infra.BaseStarter
}
func (s *AccountClientStarter) Start(ctx infra.StarterContext) {
once.Do(func() {
services.IAccountService = NewAccountClientService()
})
}
const (
TRANSFER_ENDPOINT = "http://%s/v1/account/transfer"
CREATE_ENDPOINT = "http://%s/v1/account/create"
GET_EU_ENDPOINT = "http://%s/v1/account/envelope/get?userId=%s"
AccountServiceId = "account"
)
type AccountClientService struct {
Client *httpclient.HttpClient
}
func NewAccountClientService() *AccountClientService {
ac := &AccountClientService{}
//创建一个apps实例
apps := &lb.Apps{Client: base.EurekaClient()}
ac.Client = httpclient.NewHttpClient(apps, &httpclient.Option{
Timeout: 20 * time.Second,
})
return ac
}
//剩下的接口呢使用同样的方法来编写,
//这里把剩余的接口作为作业留给同学们来编写
//如果在编写过程中遇到问题,可以一起讨论
func (a *AccountClientService) CreateAccount(dto services.AccountCreatedDTO) (*services.AccountDTO, error) {
data, err := json.Marshal(&dto)
if err != nil {
return nil, err
}
body := bytes.NewBuffer(data)
header := http.Header{}
header.Add("Content-Type", "application/json")
r, err := a.Client.NewRequest(http.MethodPost,
fmt.Sprintf(CREATE_ENDPOINT, AccountServiceId),
body,
header,
)
if err != nil {
log.Error(err)
return nil, err
}
res, err := a.Client.Do(r)
if err != nil {
log.Error(err)
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, err
}
d, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Error(err)
return nil, err
}
rr := &base.Res{
Data: &services.AccountDTO{},
}
err = json.Unmarshal(d, rr)
if err != nil {
log.Error(err)
return nil, err
}
if rr.Code == base.ResCodeOk {
return rr.Data.(*services.AccountDTO), err
} else {
return nil, err
}
}
func (a *AccountClientService) GetEnvelopeAccountByUserId(userId string) *services.AccountDTO {
header := http.Header{}
header.Add("Content-Type", "application/json")
r, err := a.Client.NewRequest(http.MethodGet,
fmt.Sprintf(GET_EU_ENDPOINT, AccountServiceId, userId),
nil,
header,
)
if err != nil {
log.Error(err)
return nil
}
res, err := a.Client.Do(r)
if err != nil {
log.Error(err)
return nil
}
if res.StatusCode != http.StatusOK {
return nil
}
d, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Error(err)
return nil
}
rr := &base.Res{
Data: &services.AccountDTO{},
}
err = json.Unmarshal(d, rr)
if err != nil {
log.Error(err)
return nil
}
if rr.Code == base.ResCodeOk {
return rr.Data.(*services.AccountDTO)
} else {
return nil
}
}
func (a *AccountClientService) Transfer(dto services.AccountTransferDTO) (services.TransferedStatus, error) {
data, err := json.Marshal(&dto)
if err != nil {
return services.TransferedStatusFailure, err
}
body := bytes.NewBuffer(data)
header := http.Header{}
header.Add("Content-Type", "application/json")
r, err := a.Client.NewRequest(http.MethodPost,
fmt.Sprintf(TRANSFER_ENDPOINT, AccountServiceId),
body,
header,
)
if err != nil {
return services.TransferedStatusFailure, err
}
res, err := a.Client.Do(r)
if err != nil {
return services.TransferedStatusFailure, err
}
if res.StatusCode != http.StatusOK {
return services.TransferedStatusFailure, errors.New("状态不为200")
}
d, err := ioutil.ReadAll(res.Body)
if err != nil {
return services.TransferedStatusFailure, err
}
rr := &base.Res{}
err = json.Unmarshal(d, rr)
if err != nil {
return services.TransferedStatusFailure, err
}
if rr.Code == base.ResCodeOk {
return services.TransferedStatusSuccess, err
} else {
return services.TransferedStatusFailure, err
}
}
```
init.sql
```# --初始化系统红包账户
INSERT INTO `account`(`id`, `account_no`, `account_name`, `account_type`, `currency_code`, `user_id`, `username`, `balance`, `status`, `created_at`, `updated_at`) VALUES (32937, '10000020190101010000000000000001', '系统红包账户', 2, 'CNY', '100001', '系统红包账户', 0.000000, 1, '2019-05-01 08:41:10.346', '2019-05-12 09:37:55.462');
INSERT INTO `account_log`(`id`, `trade_no`, `log_no`, `account_no`, `user_id`, `username`, `target_account_no`, `target_user_id`, `target_username`, `amount`, `balance`, `change_type`, `change_flag`, `status`, `decs`, `created_at`) VALUES (43208, '20190501084054283000000002110000', '20190501084054283000000002110000', '10000020190101010000000000000001', '100001', '系统红包账户', '10000020190101010000000000000001', '100001', '系统红包账户', 0.000000, 0.000000, 0, 0, 0, '开户', '2019-05-01 08:41:10.371');
```
lb.go
```package lb
//负载均衡器接口
type Balancer interface {
Next(key string, hosts []*ServerInstance) *ServerInstance
}
```
dao_account_log_test.go
```package accounts
import (
"git.imooc.com/wendell1000/account/services"
"git.imooc.com/wendell1000/infra/base"
"github.com/segmentio/ksuid"
"github.com/shopspring/decimal"
"github.com/sirupsen/logrus"
. "github.com/smartystreets/goconvey/convey"
"github.com/tietang/dbx"
"testing"
)
func TestAccountLogDao(t *testing.T) {
err := base.Tx(func(runner *dbx.TxRunner) error {
dao := &AccountLogDao{
runner: runner,
}
Convey("通过Log编号查询账户流水数据", t, func() {
a := &AccountLog{
LogNo: ksuid.New().Next().String(),
TradeNo: ksuid.New().Next().String(),
Status: 1,
AccountNo: ksuid.New().Next().String(),
UserId: ksuid.New().Next().String(),
Username: "测试用户",
Amount: decimal.NewFromFloat(1),
Balance: decimal.NewFromFloat(100),
ChangeFlag: services.FlagAccountCreated,
ChangeType: services.AccountCreated,
}
//通过log no来查询
Convey("通过log no来查询", func() {
id, err := dao.Insert(a)
So(err, ShouldBeNil)
So(id, ShouldBeGreaterThan, 0)
na := dao.GetOne(a.LogNo)
So(na, ShouldNotBeNil)
So(na.Balance.String(), ShouldEqual, a.Balance.String())
So(na.Amount.String(), ShouldEqual, a.Amount.String())
So(na.CreatedAt, ShouldNotBeNil)
})
//通过trade no来查询
Convey("通过trade no来查询", func() {
id, err := dao.Insert(a)
So(err, ShouldBeNil)
So(id, ShouldBeGreaterThan, 0)
na := dao.GetByTradeNo(a.TradeNo)
So(na, ShouldNotBeNil)
So(na.Balance.String(), ShouldEqual, a.Balance.String())
So(na.Amount.String(), ShouldEqual, a.Amount.String())
So(na.CreatedAt, ShouldNotBeNil)
})
})
return nil
})
if err != nil {
logrus.Error(err)
}
}
```
update.sql
```ALTER TABLE `red_envelope_goods`
ADD COLUMN `origin_envelope_no` varchar(32) NULL DEFAULT '' COMMENT '原订单号' AFTER `updated_at`;```
dbx.go
```package base
import (
"resk-5/infra"
"resk-5/infra/logrus"
_ "github.com/go-sql-driver/mysql"
log "github.com/sirupsen/logrus"
"github.com/tietang/dbx"
"github.com/tietang/props/kvs"
)
//dbx 数据库实例
var database *dbx.Database
func DbxDatabase() *dbx.Database {
Check(database)
return database
}
//dbx数据库starter,并且设置为全局
type DbxDatabaseStarter struct {
infra.BaseStarter
}
func (s *DbxDatabaseStarter) Setup(ctx infra.StarterContext) {
conf := ctx.Props()
//数据库配置
settings := dbx.Settings{}
err := kvs.Unmarshal(conf, &settings, "mysql")
if err != nil {
panic(err)
}
log.Info("mysql.conn url:", settings.ShortDataSourceName())
db, err := dbx.Open(settings)
if err != nil {
panic(err)
}
log.Info(db.Ping())
db.SetLogger(logrus.NewUpperLogrusLogger())
database = db
}
```
delay_timer.go
```package rabbitmq_delay
import (
"fmt"
"github.com/streadway/amqp"
"log"
"strings"
"time"
_ "github.com/go-sql-driver/mysql" // mysql
"github.com/jmoiron/sqlx"
)
var (
MysqlDB *sqlx.DB
rabbitmqConnect *amqp.Connection
DelayQueue amqp.Queue
RecvQueue amqp.Queue
DelayChannel *amqp.Channel
)
func InitMysqlDB(addr string) error {
var err error
MysqlDB, err = sqlx.Connect("mysql", addr)
if err != nil {
fmt.Printf("sqlx.Connect err: %s\n", err.Error())
return err
}
return nil
}
func InitRabbitmqChannel(addr string) error {
var err error
rabbitmqConnect, err = amqp.Dial(addr)
if err != nil {
log.Fatalf("amqp.Dial err: %s\n", err)
return err
}
DelayChannel, err = rabbitmqConnect.Channel()
if err != nil {
log.Fatalf("rabbitmqConnect.Channel err: %s\n", err)
return err
}
return nil
}
// 消费者
func NewConsume(pool *MQPool, consumerId string) {
DelayChannel, err := pool.Channel()
if err != nil {
log.Fatalf("abbitmqConnect.Channel err: %s\n", err)
return
}
// 声明一个主要使用的 exchange
err = DelayChannel.ExchangeDeclare(
"test.timer", // name
"direct", // type
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
nil, // arguments
)
if err != nil {
fmt.Printf("ch.ExchangeDeclare err: %s\n", err.Error())
return
}
// 声明一个x-delayed-message 类型的exchange
err = DelayChannel.ExchangeDeclare(
"test.delayed.timer", // name
"x-delayed-message", // type
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
amqp.Table{
"x-delayed-type": "direct",
}, // arguments
)
if err != nil {
fmt.Printf("ch.ExchangeDeclare x-delayed-message err: %s\n", err.Error())
return
}
// 声明一个常规的队列
q, err := DelayChannel.QueueDeclare(
"test.delayed.timer.queue", // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
fmt.Printf("DelayChannel.QueueDeclare test.delayed.timer.queue err: %s\n", err.Error())
return
}
err = DelayChannel.QueueBind(
q.Name, // queue name, 这里指的是 test_logs
"test.delayed.timer.key", // routing key
"test.delayed.timer", // exchange
false,
nil)
if err != nil {
fmt.Printf("DelayChannel.QueueBind test.delayed.timer.queue err: %s\n", err.Error())
return
}
// 这里监听的是 test_logs
msgs, err := DelayChannel.Consume(
q.Name, // queue name, 这里指的是 test_logs
"", // consumer
false, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
fmt.Printf("DelayChannel.Consume err: %s\n", err.Error())
return
}
// 延时队列消费
for {
fmt.Println("start listenning to consume")
select {
case d, ok := <-msgs:
if !ok {
return
}
// 判断定时器是否被取消
go HandleMsg(string(d.Body), consumerId)
d.Ack(true)
}
}
}
// 生产者
func PublishDelayMsg(mqPool *MQPool, msg string, msgId int, delay int64) error {
// 记录创建时的时间戳
createTimestamp := time.Now().UnixNano()
msg = fmt.Sprintf("%d-%d-%s-%d", msgId, createTimestamp, msg, delay)
ch, err := mqPool.Channel()
if err != nil {
return err
}
defer ch.Close()
headers := make(amqp.Table)
if delay != 0 {
headers["x-delay"] = delay
}
err = ch.Publish(
"test.delayed.timer", // exchange 这里为空则不选择 exchange
"test.delayed.timer.key", // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
DeliveryMode: amqp.Persistent,
Timestamp: time.Now(),
ContentType: "application/json",
Body: []byte(msg),
Headers: headers,
})
if err != nil {
return err
}
return nil
}
// 消费者消费消息
func HandleMsg(msg string, consumeId string) error {
consumeTimestamp := time.Now().UnixNano()
msgSlice := strings.Split(msg, "-")
msgId := msgSlice[0]
createTime := msgSlice[1]
msgC := msgSlice[2]
delayed := msgSlice[3]
result, err := MysqlDB.Exec("insert into user (`msgId`, `createTime`, `msg`, `consumeTime`, `delayed`, `consumeId`) value (?, ?, ?, ?, ?, ?)", msgId, createTime, msgC, consumeTimestamp, delayed, consumeId)
if err != nil {
fmt.Printf("mysqlDb.exec err: %s\n", err.Error())
return err
}
id, err := result.LastInsertId()
if err != nil {
fmt.Printf("result.LastInsertId err: %s\n", err.Error())
return err
}
fmt.Println("mysqlDb.exec result is", id)
return nil
}
```
rpc_test.go
```package test
import (
"git.imooc.com/wendell1000/infra/gorpc"
"git.imooc.com/wendell1000/infra/lb"
"git.imooc.com/wendell1000/resk/services"
"github.com/shopspring/decimal"
"github.com/sirupsen/logrus"
. "github.com/smartystreets/goconvey/convey"
"github.com/tietang/go-eureka-client/eureka"
"github.com/tietang/props/ini"
"testing"
)
func TestGoRpcClient_Call(t *testing.T) {
//创建一个eureka client
conf := ini.NewIniFileConfigSource("ec_test.ini")
client := eureka.NewClient(conf)
client.Start()
client.Applications, _ = client.GetApplications()
//创建一个apps实例
apps := &lb.Apps{Client: client}
g := gorpc.GoRpcClient{Apps: apps}
Convey("goRpc测试", t, func() {
in := services.RedEnvelopeSendingDTO{
Amount: decimal.NewFromFloat(1),
UserId: "1MD35g7HA9aukHZN5VEg2kTNYYx",
Username: "测试用户",
EnvelopeType: services.LuckyEnvelopeType,
Quantity: 2,
Blessing: "",
}
out := &services.RedEnvelopeActivity{}
err := g.Call("resk", "EnvelopeRpc.SendOut", in, &out)
So(err, ShouldBeNil)
So(out.EnvelopeNo, ShouldNotBeNil)
So(out.Amount.String(), ShouldEqual, in.Amount.String())
if err != nil {
logrus.Error(err)
}
logrus.Infof("%+v", out)
})
}
```
dbx_logrus.go
```package logrus
import (
log "github.com/sirupsen/logrus"
"github.com/tietang/dbx"
)
type DbxLogrusLogger struct {
log *log.Logger
}
func NewUpperLogrusLogger() *DbxLogrusLogger {
l := &DbxLogrusLogger{
log: log.New(),
}
std := log.StandardLogger()
l.log.Level = std.Level
l.log.Hooks = std.Hooks
l.log.Formatter = std.Formatter
l.log.Out = std.Out
return l
}
func (u *DbxLogrusLogger) Log(q *dbx.QueryStatus) {
if q.Err == nil {
u.log.Debug("\n" + q.String())
} else {
u.log.Error("\n" + q.String())
}
//u.log.WithFields(log.Fields{
// "SessID": q.SessID,
// "TxID": q.TxID,
// "LastInsertID": q.LastInsertID,
// "Start": q.Start,
// "End": q.End,
// "Err": q.Err,
// "RowsAffected": q.RowsAffected,
// "SQL": q.Query,
// "Args": q.Args,
//}).Info()
}
```
init.go
```package testx
import (
"git.imooc.com/wendell1000/infra"
"git.imooc.com/wendell1000/infra/base"
"git.imooc.com/wendell1000/resk/apis/gorpc"
"git.imooc.com/wendell1000/resk/core/accounts"
"github.com/tietang/props/ini"
"github.com/tietang/props/kvs"
)
func init() {
//获取程序运行文件所在的路径
file := kvs.GetCurrentFilePath("../brun/config.ini", 1)
//加载和解析配置文件
conf := ini.NewIniFileCompositeConfigSource(file)
base.InitLog(conf)
conf.Set("testing", "true")
//
infra.Register(&base.PropsStarter{})
infra.Register(&base.DbxDatabaseStarter{})
infra.Register(&base.ValidatorStarter{})
infra.Register(&base.EurekaStarter{})
infra.Register(&base.GoRPCStarter{})
infra.Register(&gorpc.GoRpcApiStarter{})
infra.Register(&base.IrisServerStarter{})
infra.Register(&infra.WebApiStarter{})
infra.Register(&accounts.AccountClientStarter{})
infra.Register(&base.HookStarter{})
app := infra.New(conf)
app.Start()
//time.Sleep(time.Second * 3)
}
```
app.go
```package resk
import (
_ "git.imooc.com/wendell1000/account/core/accounts"
"git.imooc.com/wendell1000/infra"
"git.imooc.com/wendell1000/infra/base"
"git.imooc.com/wendell1000/resk/apis/gorpc"
_ "git.imooc.com/wendell1000/resk/apis/gorpc"
_ "git.imooc.com/wendell1000/resk/apis/web"
_ "git.imooc.com/wendell1000/resk/core/envelopes"
"git.imooc.com/wendell1000/resk/jobs"
)
func init() {
infra.Register(&base.PropsStarter{})
infra.Register(&base.DbxDatabaseStarter{})
infra.Register(&base.ValidatorStarter{})
infra.Register(&base.GoRPCStarter{})
infra.Register(&gorpc.GoRpcApiStarter{})
infra.Register(&jobs.RefundExpiredJobStarter{})
infra.Register(&base.IrisServerStarter{})
infra.Register(&infra.WebApiStarter{})
infra.Register(&base.EurekaStarter{})
infra.Register(&base.HookStarter{})
}
```
main.go
```package main
//锁的状态不是互斥的,最低三位分别表示mutexLocked, mutexWoken和mutexStarving,剩下的位置都用来表示当前有多少个goroutine等待互斥锁被释放
type Mutex struct {
state int32
sema uint32
}
//互斥锁被创建出来是,所有的状态都是0,当互斥锁被锁定时mutexLocked就会被置成1,当户持所在正常状态下被唤醒时mutexWoken就会被置成1,
//mutexStarving用于表示当前的互斥锁进入了状态
//互斥锁可以同时处于两种不同的模式,也就是正常模式和饥饿模式,在正常模式下,所有锁的等待者都会按照先进先出的顺序获取锁,但是如果一个
//刚刚被唤起的 Goroutine 遇到了新的 Goroutine 进程也调用了 Lock 方法时,大概率会获取不到锁,为了减少这种情况的出现,防止 Goroutine
// 被『饿死』,一旦 Goroutine 超过 1ms 没有获取到锁,它就会将当前互斥锁切换饥饿模式。
func main() {
}
```
ec.go
```package main
import (
"github.com/tietang/go-eureka-client/eureka"
"time"
)
func main() {
cfg := eureka.Config{
DialTimeout: time.Second * 10,
}
client := eureka.NewClientByConfig([]string{
"http://127.0.0.1:8761/eureka",
}, cfg)
appName := "Go-Example"
instance := eureka.NewInstanceInfo(
"test.com", appName,
"127.0.0.2",
8080, 30,
false)
client.RegisterInstance(appName, instance)
client.Start()
c := make(chan int, 1)
<-c
}
```
redis_test.go
```package main
import "testing"
func BenchmarkInitRedis(b *testing.B) {
for i := 0; i < b.N; i ++{
initRedis()
}
}
func TestInitRedis(t *testing.T) {
initRedis()
for i := 0; i < 1000000; i ++ {
main()
}
}```
ec2.go
```package main
import (
"github.com/tietang/go-eureka-client/eureka"
"github.com/tietang/props/ini"
)
func main() {
conf := ini.NewIniFileConfigSource("ec.ini")
client := eureka.NewClient(conf)
client.Start()
c := make(chan int, 1)
<-c
}
```
main.go
```package main
import "unsafe"
type HelloChan struct {
qcount uint
dataqsiz uint
buf unsafe.Pointer
elemsize uint16
closed uint32
elemtype *_type
sendx uint
recvx uint
recvq waitq
sendq waitq
lock mutex
}
type waitq struct {
first *sudog
last *sudog
}
func main() {
}
```
dao_item.go
```package envelopes
import (
"github.com/sirupsen/logrus"
"github.com/tietang/dbx"
)
type RedEnvelopeItemDao struct {
runner *dbx.TxRunner
}
//查询 GetOne
func (dao *RedEnvelopeItemDao) GetOne(itemNo string) *RedEnvelopeItem {
form := &RedEnvelopeItem{ItemNo: itemNo}
ok, err := dao.runner.GetOne(form)
if err != nil {
return nil
}
if !ok {
return nil
}
return form
}
//红包订单详情数据的写入 Insert
func (dao *RedEnvelopeItemDao) Insert(form *RedEnvelopeItem) (int64, error) {
rs, err := dao.runner.Insert(form)
if err != nil {
return 0, err
}
return rs.LastInsertId()
}
func (dao *RedEnvelopeItemDao) FindItems(envelopeNo string) []*RedEnvelopeItem {
items := make([]*RedEnvelopeItem, 0)
sql := "select * from red_envelope_item where envelope_no=?"
err := dao.runner.Find(&items, sql, envelopeNo)
if err != nil {
logrus.Error(err)
return items
}
return items
}
func (dao *RedEnvelopeItemDao) GetByUser(envelopeNo, userId string) *RedEnvelopeItem {
item := RedEnvelopeItem{}
sql := "select * from red_envelope_item where envelope_no=? and recv_user_id=?"
ok, err := dao.runner.Get(&item, sql, envelopeNo, userId)
if !ok {
return nil
}
if err != nil {
logrus.Error(err)
return nil
}
return &item
}
func (dao *RedEnvelopeItemDao) ListReceivedItems(userId string, page, size int) []*RedEnvelopeItem {
items := make([]*RedEnvelopeItem, 0)
sql := "select * from red_envelope_item where recv_user_id=? order by created_at desc limit ?,?"
err := dao.runner.Find(&items, sql, userId, page, size)
if err != nil {
logrus.Error(err)
return items
}
return items
}
```
redis.go
```package main
import (
"fmt"
"github.com/gomodule/redigo/redis"
"time"
)
const (
redisHost = "127.0.0.1:6379"
redisDb = 1
//password = "rmt2019!"
)
var redisClient *redis.Pool
func initRedis() {
redisClient = &redis.Pool{
MaxActive: 100, // 最大连接数,即最多的tcp连接数,一般建议往大的配置,但不要超过操作系统文件句柄个数(centos下可以ulimit -n查看)
MaxIdle: 100, // 最大空闲连接数,即会有这么多个连接提前等待着,但过了超时时间也会关闭。
IdleTimeout: time.Duration(100) * time.Second, // 空闲连接超时时间,但应该设置比redis服务器超时时间短。否则服务端超时了,客户端保持着连接也没用
Wait: true, // 当超过最大连接数 是报错还是等待, true 等待 false 报错
Dial: func() (redis.Conn, error) {
conn, err := redis.Dial("tcp", redisHost, redis.DialDatabase(redisDb), /*redis.DialPassword(password)*/)
if err != nil {
return nil, err
}
return conn, nil
},
}
}
func main() {
initRedis()
redisConn := redisClient.Get()
defer redisConn.Close()
rs, err := redisConn.Do("set", "test", "world")
if err != nil {
fmt.Println(err)
}
fmt.Printf("type is %T, value is %v\n", rs, rs)
}```
init.go
```package testx
import (
"github.com/tietang/props/ini"
"github.com/tietang/props/kvs"
"imooc.com/resk/infra"
"imooc.com/resk/infra/base"
)
func init() {
//获取程序运行文件所在的路径
file := kvs.GetCurrentFilePath("../brun/config.ini", 1)
//加载和解析配置文件
conf := ini.NewIniFileCompositeConfigSource(file)
base.InitLog(conf)
//
infra.Register(&base.PropsStarter{})
infra.Register(&base.DbxDatabaseStarter{})
infra.Register(&base.ValidatorStarter{})
app := infra.New(conf)
app.Start()
}
```
lb_hash.go
```package lb
import (
"hash/crc32"
)
//基于Hash算法的负载均衡器
var _ Balancer = new(HashBalancer)
type HashBalancer struct {
}
func (h *HashBalancer) Next(key string, hosts []*ServerInstance) *ServerInstance {
if len(hosts) == 0 {
return nil
}
//hash
count := crc32.ChecksumIEEE([]byte(key))
//取模计算索引
index := int(count) % len(hosts)
//按照索引取出实例
instance := hosts[index]
return instance
}
```
factory.go
```package eureka
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strconv"
"time"
"gopkg.in/yaml.v2"
"github.com/tietang/go-eureka-client/eureka/config"
"github.com/tietang/go-utils"
"github.com/tietang/props/kvs"
)
const (
DataCenterNameNetflix = "Netflix"
DataCenterNameAmazon = "Amazon"
DataCenterNameMyOwn = "MyOwn"
//
DataCenterNameMyOwnClass = "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo"
//
StatusUp = "UP" //Ready to receive traffic
StatusDown = "DOWN" // Do not send traffic- healthcheck callback failed
StatusStarting = "STARTING" //Just about starting- initializations to be done - do not send traffic
StatusOutOfService = "OUT_OF_SERVICE" // Intentionally shutdown for traffic
StatusUnknown = "UNKNOWN"
//
DEFAULT_LEASE_RENEWAL_INTERVAL = 30
DEFAULT_LEASE_DURATION = 90
)
func CreateDataCenterInfo(dataCenterInfo *DataCenterInfo) *DataCenterInfo {
if dataCenterInfo == nil {
dataCenterInfo = &DataCenterInfo{}
}
if dataCenterInfo.Name == "" {
dataCenterInfo.Name = DataCenterNameMyOwn
}
if dataCenterInfo.Class == "" {
dataCenterInfo.Class = DataCenterNameMyOwnClass
}
return dataCenterInfo
}
func CreateInstanceInfo(config *config.EurekaConfig) *InstanceInfo {
instanceConfig := config.Eureka.Instance
appConfig := config.Application
ins := createInstanceInfo(instanceConfig, appConfig)
return ins
}
func defaultFileName() string {
file, _ := exec.LookPath(os.Args[0])
path, _ := filepath.Abs(file)
fileName := filepath.Base(path)
return fileName
}
func createInstanceInfo(config config.EurekaInstanceConfig, appConfig config.ApplicationConfig) *InstanceInfo {
dataCenterInfo := CreateDataCenterInfo(&DataCenterInfo{})
leaseInfo := NewLeaseInfo(config.LeaseRenewalIntervalInSeconds)
leaseInfo.DurationInSecs = config.LeaseExpirationDurationInSeconds
ips, _ := utils.GetExternalIPs()
hostName := ips[0]
appName := defaultFileName()
if appConfig.Name != "" {
appName = appConfig.Name
}
instanceInfo := &InstanceInfo{
HostName: hostName,
App: appName,
AppName: appName,
AppGroupName: config.AppGroupName,
IpAddr: ips[0],
Status: StatusStarting,
DataCenterInfo: dataCenterInfo,
LeaseInfo: leaseInfo,
Metadata: nil,
}
scheme := "http"
portj := &Port{
Port: appConfig.Port,
Enabled: true,
}
if appConfig.Secured || config.SecurePortEnabled {
instanceInfo.SecurePort = portj
instanceInfo.SecureVipAddress = instanceInfo.AppName
scheme = "https"
} else {
instanceInfo.VipAddress = instanceInfo.AppName
instanceInfo.Port = portj
}
stringPort := ":" + strconv.Itoa(portj.Port)
instanceInfo.StatusPageUrl = scheme + "://" + hostName + stringPort + "/info"
instanceInfo.HealthCheckUrl = scheme + "://" + hostName + stringPort + "/health"
instanceInfo.HomePageUrl = scheme + "://" + hostName + stringPort + "/"
instanceInfo.Metadata = &MetaData{
Map: make(map[string]string),
}
kv := config.MetadataMap
for k, v := range kv {
instanceInfo.Metadata.Map[k] = v
}
// instanceInfo.Metadata.Map["foo"] = "bar" //add metadata for example
instanceId := fmt.Sprintf("%s:%s:%d", instanceInfo.HostName, instanceInfo.AppName, instanceInfo.Port.Port)
instanceInfo.Metadata.Map["instanceId"] = instanceId
instanceInfo.InstanceId = instanceId
return instanceInfo
}
func CreateEurekaClient(eurekaConfig config.EurekaClientConfig) *Client {
zones := eurekaConfig.GetAvailabilityZones(eurekaConfig.Region)
machines := make([]string, 0)
for _, zone := range zones {
machinesForZone := eurekaConfig.GetEurekaServerServiceUrls(zone)
if len(machinesForZone) > 0 {
machines = append(machines, machinesForZone...)
}
}
c := Config{
// default timeout is one second
DialTimeout: time.Second,
}
client := NewClientByConfig(machines, c)
client.ClientConfig = &eurekaConfig
return client
}
// 检查文件或目录是否存在
// 如果由 filename 指定的文件或目录存在则返回 true,否则返回 false
func exists(filename string) bool {
_, err := os.Stat(filename)
return err == nil || os.IsExist(err)
}
func CreateEurekaClientByYaml(fileName string) *Client {
file, _ := os.Getwd()
fmt.Println("current path:", file)
if fileName == "" {
fileName = "application.yml"
}
cfg := file + "/" + fileName //"/application.yml"
c := &config.EurekaConfig{
Eureka: config.Eureka{
Client: config.NewEurekaClientConfig(),
Instance: config.NewEurekaInstanceConfig(),
},
}
if exists(cfg) {
data, err := ReadFile(cfg)
err = yaml.Unmarshal([]byte(data), c)
if err != nil {
fmt.Println("error: %v", err)
}
} else {
fmt.Println("error: file %s not exists.", cfg)
}
client := newClientbyConfig(c)
return client
}
func newClientbyConfig(c *config.EurekaConfig) *Client {
ins := CreateInstanceInfo(c)
client := CreateEurekaClient(c.Eureka.Client)
client.InstanceInfo = ins
client.ClientConfig = &c.Eureka.Client
client.InstanceConfig = &c.Eureka.Instance
client.InstanceConfig.Appname = c.Application.Name
return client
}
// NewClient create a basic client that is configured to be used
// with the given machine list.
func NewClient(conf kvs.ConfigSource) *Client {
c := &config.EurekaConfig{
Eureka: config.Eureka{
Client: config.NewEurekaClientConfig(),
Instance: config.NewEurekaInstanceConfig(),
},
}
err := conf.Unmarshal(c)
if err != nil {
panic(err)
}
//machines := []string{}
//config := Config{
// // default timeout is one second
// DialTimeout: time.Second,
//}
//
//client := &Client{
// Cluster: NewCluster(machines),
// Config: config,
//}
//
//client.initHTTPClient()
//
client := newClientbyConfig(c)
return client
}
func NewClientByConfig(machines []string, config Config) *Client {
client := &Client{
Cluster: NewCluster(machines),
Config: config,
}
logger.Debugf("%+v", client.Cluster)
client.initHTTPClient()
return client
}
func NewClientDefault(machines []string) *Client {
config := Config{
// default timeout is one second
DialTimeout: time.Second,
}
client := &Client{
Cluster: NewCluster(machines),
Config: config,
}
logger.Debugf("%+v", client.Cluster)
client.initHTTPClient()
return client
}
// NewTLSClient create a basic client with TLS configuration
func NewTLSClient(machines []string, cert string, key string, caCerts []string) (*Client, error) {
// overwrite the default machine to use https
if len(machines) == 0 {
machines = []string{"https://127.0.0.1:8761"}
}
config := Config{
// default timeout is one second
DialTimeout: time.Second,
CertFile: cert,
KeyFile: key,
CaCertFile: make([]string, 0),
}
client := &Client{
Cluster: NewCluster(machines),
Config: config,
}
err := client.initHTTPSClient(cert, key)
if err != nil {
return nil, err
}
for _, caCert := range caCerts {
if err := client.AddRootCA(caCert); err != nil {
return nil, err
}
}
return client, nil
}
// NewClientFromFile creates a client from a given file path.
// The given file is expected to use the JSON format.
func NewClientFromFile(fpath string) (*Client, error) {
fi, err := os.Open(fpath)
if err != nil {
return nil, err
}
defer func() {
if err := fi.Close(); err != nil {
panic(err)
}
}()
return NewClientFromReader(fi)
}
// NewClientFromReader creates a Client configured from a given reader.
// The configuration is expected to use the JSON format.
func NewClientFromReader(reader io.Reader) (*Client, error) {
c := new(Client)
b, err := ioutil.ReadAll(reader)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, c)
if err != nil {
return nil, err
}
if c.Config.CertFile == "" {
c.initHTTPClient()
} else {
err = c.initHTTPSClient(c.Config.CertFile, c.Config.KeyFile)
}
if err != nil {
return nil, err
}
for _, caCert := range c.Config.CaCertFile {
if err := c.AddRootCA(caCert); err != nil {
return nil, err
}
}
return c, nil
}
func ReadFile(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
src, err := ioutil.ReadAll(f)
return src, err
}
```
post.go
```package eureka
import (
"encoding/json"
"net/http"
"strings"
log "github.com/sirupsen/logrus"
"github.com/tietang/go-utils/errs"
)
func (c *Client) RegisterInstance(appName string, instanceInfo *InstanceInfo) error {
values := []string{"apps", appName}
path := strings.Join(values, "/")
instance := &Instance{
Instance: instanceInfo,
}
body, err := json.Marshal(instance)
if err != nil {
return err
}
res, err := c.Post(path, body)
if err != nil {
return err
}
if res != nil {
log.WithFields(log.Fields{
"path": path,
"status": res.StatusCode,
"body": string(body),
}).Info("RegisterInstance ")
}
if res.StatusCode != http.StatusNoContent {
return errs.NewError("unRegisterInstance", res.StatusCode)
}
return err
}
```
dao_goods.go
```package envelopes
import (
"github.com/shopspring/decimal"
log "github.com/sirupsen/logrus"
"github.com/tietang/dbx"
"imooc.com/resk/services"
"time"
)
type RedEnvelopeGoodsDao struct {
runner *dbx.TxRunner
}
//插入
func (dao *RedEnvelopeGoodsDao) Insert(
po *RedEnvelopeGoods) (int64, error) {
rs, err := dao.runner.Insert(po)
if err != nil {
return 0, err
}
return rs.LastInsertId()
}
//查询,根据红包编号来
func (dao *RedEnvelopeGoodsDao) GetOne(envelopeNo string) *RedEnvelopeGoods {
po := &RedEnvelopeGoods{EnvelopeNo: envelopeNo}
ok, err := dao.runner.GetOne(po)
if err != nil || !ok {
log.Error(err)
return nil
}
return po
}
//更新红包余额和数量
//不再使用事务行锁来更新红包余额和数量
//使用乐观锁来保证更新红包余额和数量的安全,避免负库存问题
//通过在where子句中判断红包剩余金额和数量来解决2个问题:
//1. 负库存问题,避免红包剩余金额和数量不够时进行扣减更新
//2. 减少实际的数据更新,也就是过滤掉部分无效的更新,提高总体性能
func (dao *RedEnvelopeGoodsDao) UpdateBalance(
envelopeNo string, amount decimal.Decimal) (int64, error) {
sql := "update red_envelope_goods " +
" set remain_amount=remain_amount-CAST(? AS DECIMAL(30,6)), " +
" remain_quantity=remain_quantity-1 " +
" where envelope_no=? " +
//最重要的,乐观锁的关键
" and remain_quantity>0" +
" and remain_amount >= CAST(? AS DECIMAL(30,6)) "
rs, err := dao.runner.Exec(sql, amount.String(), envelopeNo, amount.String())
if err != nil {
return 0, err
}
return rs.RowsAffected()
}
//更新订单状态
func (dao *RedEnvelopeGoodsDao) UpdateOrderStatus(
envelopeNo string, status services.OrderStatus) (int64, error) {
sql := " update red_envelope_goods" +
" set status=? " +
" where envelope_no=?"
rs, err := dao.runner.Exec(sql, status, envelopeNo)
if err != nil {
return 0, err
}
return rs.RowsAffected()
}
//过期,把过期的所有红包都查询出来,分页,limit,offset size
func (dao *RedEnvelopeGoodsDao) FindExpired(
offset, size int) []RedEnvelopeGoods {
var goods []RedEnvelopeGoods
now := time.Now()
sql := " select * from red_envelope_goods " +
" where remain_quantity>0 and expired_at>? and status<>4 " +
" limit ?,?"
err := dao.runner.Find(&goods, sql, now, offset, size)
if err != nil {
log.Error(err)
}
return goods
}
//
func (dao *RedEnvelopeGoodsDao) Find(po *RedEnvelopeGoods, offset, limit int) []RedEnvelopeGoods {
var redEnvelopeGoodss []RedEnvelopeGoods
err := dao.runner.FindExample(po, &redEnvelopeGoodss)
if err != nil {
log.Error(err)
}
return redEnvelopeGoodss
}
func (dao *RedEnvelopeGoodsDao) FindByUser(userId string, offset, limit int) []RedEnvelopeGoods {
var goods []RedEnvelopeGoods
sql := " select * from red_envelope_goods " +
" where user_id=? order by created_at desc limit ?,?"
err := dao.runner.Find(&goods, sql, userId, offset, limit)
if err != nil {
log.Error(err)
}
return goods
}
func (dao *RedEnvelopeGoodsDao) ListReceivable(offset, size int) []RedEnvelopeGoods {
var goods []RedEnvelopeGoods
now := time.Now()
sql := " select * from red_envelope_goods " +
" where remain_quantity>0 and expired_at>? order by created_at desc limit ?,?"
err := dao.runner.Find(&goods, sql, now, offset, size)
if err != nil {
log.Error(err)
}
return goods
}
```
app.go
```package lb
import (
"fmt"
"github.com/tietang/go-eureka-client/eureka"
"strings"
)
type Apps struct {
Client *eureka.Client
}
func (a *Apps) Get(appName string) *App {
var app *eureka.Application
for _, a := range a.Client.Applications.Applications {
if a.Name == strings.ToUpper(appName) {
app = &a
break
}
}
if app == nil {
return nil
}
na := &App{
Name: app.Name,
Instances: make([]*ServerInstance, 0),
lb: &RoundRobinBalancer{},
}
for _, ins := range app.Instances {
var port int
if ins.SecurePort.Enabled {
port = ins.SecurePort.Port
} else {
port = ins.Port.Port
}
si := &ServerInstance{
InstanceId: ins.InstanceId,
AppName: appName,
Status: Status(ins.Status),
Address: fmt.Sprintf("%s:%d", ins.IpAddr, port),
Metadata: make(map[string]string),
}
si.Metadata["rpcAddr"] = fmt.Sprintf("%s:%s", ins.IpAddr, ins.Metadata.Map["rpcPort"])
na.Instances = append(na.Instances, si)
}
return na
}
type App struct {
Name string
Instances []*ServerInstance
lb Balancer
}
func (a *App) Get(key string) *ServerInstance {
ins := a.lb.Next(key, a.Instances)
return ins
}
//服务实例的状态
type Status string
const (
StatusEnabled Status = "enabled"
StatusDisabled Status = "disabled"
)
//服务实例
type ServerInstance struct {
InstanceId string
AppName string
Address string
Status Status
Metadata map[string]string
}
```
websocket.go
```package websocket_example
import (
"bufio"
"net/http"
"time"
)
//用于描述连接握手时候发生的错误
type HandshakeError struct {
message string
}
type Upgrader struct {
// 握手完成的时间
HandshakeTimeout time.Duration
// 以字节为单位指定I/O缓冲区大小,如果缓冲区的大小为零,则使用http服务分配缓冲区
// I/O缓冲区大小不限制发送和接受消息的大小
ReadBufferSize, WriteBufferSize int
// WriteBufferPool是用于写操作的缓冲池。如果该值未设置,则将写缓冲区分配给连接的连接的生存期。
//
// 当应用程序具有适度的写量时,池是最有用的通过大量的连接。
//
// 应用程序应该为每个惟一值使用一个池WriteBufferSize。
WriteBufferPool BufferPool
// Subprotocols specifies the server's supported protocols in order of
// preference. If this field is not nil, then the Upgrade method negotiates a
// subprotocol by selecting the first match in this list with a protocol
// requested by the client. If there's no match, then no protocol is
// negotiated (the Sec-Websocket-Protocol header is not included in the
// handshake response).
Subprotocols []string
// Error specifies the function for generating HTTP error responses. If Error
// is nil, then http.Error is used to generate the HTTP response.
Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
// CheckOrigin returns true if the request Origin header is acceptable. If
// CheckOrigin is nil, then a safe default is used: return false if the
// Origin request header is present and the origin host is not equal to
// request Host header.
//
// A CheckOrigin function should carefully validate the request origin to
// prevent cross-site request forgery.
CheckOrigin func(r *http.Request) bool
// EnableCompression specify if the server should attempt to negotiate per
// message compression (RFC 7692). Setting this value to true does not
// guarantee that compression will be supported. Currently only "no context
// takeover" modes are supported.
EnableCompression bool
}
func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
const badHandshake = "websocket: the client is not using the websocket protocol: "
if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'upgrade' token not found in 'Connection' header")
}
if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'websocket' token not found in 'Upgrade' header")
}
if r.Method != "GET" {
return u.returnError(w, r, http.StatusMethodNotAllowed, badHandshake+"request method is not GET")
}
if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") {
return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header")
}
if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok {
return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-WebSocket-Extensions' headers are unsupported")
}
checkOrigin := u.CheckOrigin
if checkOrigin == nil {
checkOrigin = checkSameOrigin
}
if !checkOrigin(r) {
return u.returnError(w, r, http.StatusForbidden, "websocket: request origin not allowed by Upgrader.CheckOrigin")
}
challengeKey := r.Header.Get("Sec-Websocket-Key")
if challengeKey == "" {
return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'Sec-WebSocket-Key' header is missing or blank")
}
subprotocol := u.selectSubprotocol(r, responseHeader)
// Negotiate PMCE
var compress bool
if u.EnableCompression {
for _, ext := range parseExtensions(r.Header) {
if ext[""] != "permessage-deflate" {
continue
}
compress = true
break
}
}
h, ok := w.(http.Hijacker)
if !ok {
return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker")
}
var brw *bufio.ReadWriter
netConn, brw, err := h.Hijack()
if err != nil {
return u.returnError(w, r, http.StatusInternalServerError, err.Error())
}
if brw.Reader.Buffered() > 0 {
netConn.Close()
return nil, errors.New("websocket: client sent data before handshake is complete")
}
var br *bufio.Reader
if u.ReadBufferSize == 0 && bufioReaderSize(netConn, brw.Reader) > 256 {
// Reuse hijacked buffered reader as connection reader.
br = brw.Reader
}
buf := bufioWriterBuffer(netConn, brw.Writer)
var writeBuf []byte
if u.WriteBufferPool == nil && u.WriteBufferSize == 0 && len(buf) >= maxFrameHeaderSize+256 {
// Reuse hijacked write buffer as connection buffer.
writeBuf = buf
}
c := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize, u.WriteBufferPool, br, writeBuf)
c.subprotocol = subprotocol
if compress {
c.newCompressionWriter = compressNoContextTakeover
c.newDecompressionReader = decompressNoContextTakeover
}
// Use larger of hijacked buffer and connection write buffer for header.
p := buf
if len(c.writeBuf) > len(p) {
p = c.writeBuf
}
p = p[:0]
p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
p = append(p, computeAcceptKey(challengeKey)...)
p = append(p, "\r\n"...)
if c.subprotocol != "" {
p = append(p, "Sec-WebSocket-Protocol: "...)
p = append(p, c.subprotocol...)
p = append(p, "\r\n"...)
}
if compress {
p = append(p, "Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...)
}
for k, vs := range responseHeader {
if k == "Sec-Websocket-Protocol" {
continue
}
for _, v := range vs {
p = append(p, k...)
p = append(p, ": "...)
for i := 0; i < len(v); i++ {
b := v[i]
if b <= 31 {
// prevent response splitting.
b = ' '
}
p = append(p, b)
}
p = append(p, "\r\n"...)
}
}
p = append(p, "\r\n"...)
// Clear deadlines set by HTTP server.
netConn.SetDeadline(time.Time{})
if u.HandshakeTimeout > 0 {
netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout))
}
if _, err = netConn.Write(p); err != nil {
netConn.Close()
return nil, err
}
if u.HandshakeTimeout > 0 {
netConn.SetWriteDeadline(time.Time{})
}
return c, nil
}
```
config.go
```package config
import (
"strings"
)
const (
EurekaAcceptFull = "full"
EurekaAcceptCompact = "compact"
DEFAULT_EUREKA_URL = "http://localhost:8761/eureka/"
DEFAULT_EUREKA_ZONE = "defaultZone"
UP = "UP"
DOWN = "DOWN"
STARTING = "STARTING"
)
type ApplicationConfig struct {
Name string `yam:"name" json:"name" xml:"name"`
Port int `yam:"port" json:"port" xml:"port"`
Secured bool `yam:"secured" json:"secured" xml:"secured"`
}
type EurekaConfig struct {
_prefix string `prefix:""`
Eureka Eureka `yam:"eureka" json:"eureka" xml:"eureka"`
Application ApplicationConfig `yam:"application" json:"application" xml:"application"`
}
type Eureka struct {
//_prefix string `prefix:"eureka"`
Client EurekaClientConfig `yam:"client" json:"client" xml:"client"`
Instance EurekaInstanceConfig `yam:"instance" json:"instance" xml:"instance"`
}
type EurekaTransportConfig struct {
SessionedClientReconnectIntervalSeconds int `yam:"sessionedClientReconnectIntervalSeconds" json:"sessionedClientReconnectIntervalSeconds" xml:"sessionedClientReconnectIntervalSeconds"`
RetryableClientQuarantineRefreshPercentage float64 `yam:"retryableClientQuarantineRefreshPercentage" json:"retryableClientQuarantineRefreshPercentage" xml:"retryableClientQuarantineRefreshPercentage"`
BootstrapResolverRefreshIntervalSeconds int `yam:"bootstrapResolverRefreshIntervalSeconds" json:"bootstrapResolverRefreshIntervalSeconds" xml:"bootstrapResolverRefreshIntervalSeconds"`
ApplicationsResolverDataStalenessThresholdSeconds int `yam:"applicationsResolverDataStalenessThresholdSeconds" json:"applicationsResolverDataStalenessThresholdSeconds" xml:"applicationsResolverDataStalenessThresholdSeconds"`
AsyncResolverRefreshIntervalMs int `yam:"asyncResolverRefreshIntervalMs" json:"asyncResolverRefreshIntervalMs" xml:"asyncResolverRefreshIntervalMs"`
AsyncResolverWarmUpTimeoutMs int `yam:"asyncResolverWarmUpTimeoutMs" json:"asyncResolverWarmUpTimeoutMs" xml:"asyncResolverWarmUpTimeoutMs"`
AsyncExecutorThreadPoolSize int `yam:"asyncExecutorThreadPoolSize" json:"asyncExecutorThreadPoolSize" xml:"asyncExecutorThreadPoolSize"`
ReadClusterVip string `yam:"readClusterVip" json:"readClusterVip" xml:"readClusterVip"`
BootstrapResolverForQuery bool `yam:"bootstrapResolverForQuery" json:"bootstrapResolverForQuery" xml:"bootstrapResolverForQuery"`
}
func NewEurekaTransportConfig() EurekaTransportConfig {
return EurekaTransportConfig{
SessionedClientReconnectIntervalSeconds: 1200,
RetryableClientQuarantineRefreshPercentage: 0.66,
BootstrapResolverRefreshIntervalSeconds: 300,
ApplicationsResolverDataStalenessThresholdSeconds: 300,
AsyncResolverRefreshIntervalMs: 300000,
AsyncResolverWarmUpTimeoutMs: 5000,
AsyncExecutorThreadPoolSize: 5,
BootstrapResolverForQuery: true,
}
}
type EurekaInstanceConfig struct {
Appname string `yam:"appname" json:"appname" xml:"appname"`
AppGroupName string `yam:"appGroupName" json:"appGroupName" xml:"appGroupName"`
InstanceEnabledOnit bool `yam:"instanceEnabledOnit" json:"instanceEnabledOnit" xml:"instanceEnabledOnit"`
NonSecurePort int `yam:"nonSecurePort" json:"nonSecurePort" xml:"nonSecurePort"`
SecurePort int `yam:"securePort" json:"securePort" xml:"securePort"`
NonSecurePortEnabled bool `yam:"nonSecurePortEnabled" json:"nonSecurePortEnabled" xml:"nonSecurePortEnabled"`
SecurePortEnabled bool `yam:"securePortEnabled" json:"securePortEnabled" xml:"securePortEnabled"`
LeaseRenewalIntervalInSeconds uint `yam:"leaseRenewalIntervalInSeconds" json:"leaseRenewalIntervalInSeconds" xml:"leaseRenewalIntervalInSeconds"`
LeaseExpirationDurationInSeconds int `yam:"leaseExpirationDurationInSeconds" json:"leaseExpirationDurationInSeconds" xml:"leaseExpirationDurationInSeconds"`
VirtualHostName string `yam:"virtualHostName" json:"virtualHostName" xml:"virtualHostName"`
InstanceId string `yam:"instanceId" json:"instanceId" xml:"instanceId"`
SecureVirtualHostName string `yam:"secureVirtualHostName" json:"secureVirtualHostName" xml:"secureVirtualHostName"`
ASGName string `yam:"aSGName" json:"aSGName" xml:"aSGName"`
// DataCenterInfo DataCenterInfoConfig `yam:"dataCenterInfo" json:"dataCenterInfo" xml:"dataCenterInfo"`
IpAddress string `yam:"ipAddress" json:"ipAddress" xml:"ipAddress"`
StatusPageUrlPath string `yam:"statusPageUrlPath" json:"statusPageUrlPath" xml:"statusPageUrlPath"`
StatusPageUrl string `yam:"statusPageUrl" json:"statusPageUrl" xml:"statusPageUrl"`
HomePageUrlPath string `yam:"homePageUrlPath" json:"homePageUrlPath" xml:"homePageUrlPath"`
HomePageUrl string `yam:"homePageUrl" json:"homePageUrl" xml:"homePageUrl"`
HealthCheckUrlPath string `yam:"healthCheckUrlPath" json:"healthCheckUrlPath" xml:"healthCheckUrlPath"`
HealthCheckUrl string `yam:"healthCheckUrl" json:"healthCheckUrl" xml:"healthCheckUrl"`
SecureHealthCheckUrl string `yam:"secureHealthCheckUrl" json:"secureHealthCheckUrl" xml:"secureHealthCheckUrl"`
Namespace string `yam:"namespace" json:"namespace" xml:"namespace"`
Hostname string `yam:"hostname" json:"hostname" xml:"hostname"`
PreferIpAddress bool `yam:"preferIpAddress" json:"preferIpAddress" xml:"preferIpAddress"`
InitialStatus string `yam:"initialStatus" json:"initialStatus" xml:"initialStatus"`
MetadataMap map[string]string `yam:"metadataMap" json:"metadataMap" xml:"metadataMap"`
}
func NewEurekaInstanceConfig() EurekaInstanceConfig {
ins := EurekaInstanceConfig{
Appname: "unknow",
NonSecurePort: 8080,
SecurePort: 443,
NonSecurePortEnabled: true,
LeaseRenewalIntervalInSeconds: 30,
LeaseExpirationDurationInSeconds: 90,
StatusPageUrlPath: "/info",
HomePageUrlPath: "/",
HealthCheckUrlPath: "/health",
Namespace: "eureka",
PreferIpAddress: true,
InitialStatus: UP,
}
ins.VirtualHostName = ins.Appname
return ins
}
type EurekaClientConfig struct {
Transport EurekaTransportConfig `yam:"transport" json:"transport" xml:"transport"`
RegistryFetchIntervalSeconds int `yam:"registryFetchIntervalSeconds" json:"registryFetchIntervalSeconds" xml:"registryFetchIntervalSeconds"`
InstanceInfoReplicationIntervalSeconds int `yam:"instanceInfoReplicationIntervalSeconds" json:"instanceInfoReplicationIntervalSeconds" xml:"instanceInfoReplicationIntervalSeconds"`
InitialInstanceInfoReplicationIntervalSeconds int `yam:"initialInstanceInfoReplicationIntervalSeconds" json:"initialInstanceInfoReplicationIntervalSeconds" xml:"initialInstanceInfoReplicationIntervalSeconds"`
EurekaServiceUrlPollIntervalSeconds int `yam:"eurekaServiceUrlPollIntervalSeconds" json:"eurekaServiceUrlPollIntervalSeconds" xml:"eurekaServiceUrlPollIntervalSeconds"`
EurekaServerReadTimeoutSeconds int `yam:"eurekaServerReadTimeoutSeconds" json:"eurekaServerReadTimeoutSeconds" xml:"eurekaServerReadTimeoutSeconds"`
EurekaServerConnectTimeoutSeconds int `yam:"eurekaServerConnectTimeoutSeconds" json:"eurekaServerConnectTimeoutSeconds" xml:"eurekaServerConnectTimeoutSeconds"`
BackupRegistryImpl string `yam:"backupRegistryImpl" json:"backupRegistryImpl" xml:"backupRegistryImpl"`
EurekaServerTotalConnections int `yam:"eurekaServerTotalConnections" json:"eurekaServerTotalConnections" xml:"eurekaServerTotalConnections"`
EurekaServerTotalConnectionsPerHost int `yam:"eurekaServerTotalConnectionsPerHost" json:"eurekaServerTotalConnectionsPerHost" xml:"eurekaServerTotalConnectionsPerHost"`
EurekaServerURLContext string `yam:"eurekaServerURLContext" json:"eurekaServerURLContext" xml:"eurekaServerURLContext"`
EurekaServerPort string `yam:"eurekaServerPort" json:"eurekaServerPort" xml:"eurekaServerPort"`
EurekaServerDNSName string `yam:"eurekaServerDNSName" json:"eurekaServerDNSName" xml:"eurekaServerDNSName"`
Region string `yam:"region" json:"region" xml:"region"`
EurekaConnectionIdleTimeoutSeconds int `yam:"eurekaConnectionIdleTimeoutSeconds" json:"eurekaConnectionIdleTimeoutSeconds" xml:"eurekaConnectionIdleTimeoutSeconds"`
RegistryRefreshSingleVipAddress string `yam:"registryRefreshSingleVipAddress" json:"registryRefreshSingleVipAddress" xml:"registryRefreshSingleVipAddress"`
HeartbeatExecutorThreadPoolSize int `yam:"heartbeatExecutorThreadPoolSize" json:"heartbeatExecutorThreadPoolSize" xml:"heartbeatExecutorThreadPoolSize"`
HeartbeatExecutorExponentialBackOffBound int `yam:"heartbeatExecutorExponentialBackOffBound" json:"heartbeatExecutorExponentialBackOffBound" xml:"heartbeatExecutorExponentialBackOffBound"`
CacheRefreshExecutorThreadPoolSize int `yam:"cacheRefreshExecutorThreadPoolSize" json:"cacheRefreshExecutorThreadPoolSize" xml:"cacheRefreshExecutorThreadPoolSize"`
CacheRefreshExecutorExponentialBackOffBound int `yam:"cacheRefreshExecutorExponentialBackOffBound" json:"cacheRefreshExecutorExponentialBackOffBound" xml:"cacheRefreshExecutorExponentialBackOffBound"`
GZipContent bool `yam:"gZipContent" json:"gZipContent" xml:"gZipContent"`
UseDnsForFetchingServiceUrls bool `yam:"useDnsForFetchingServiceUrls" json:"useDnsForFetchingServiceUrls" xml:"useDnsForFetchingServiceUrls"`
RegisterWithEureka bool `yam:"registerWithEureka" json:"registerWithEureka" xml:"registerWithEureka"`
PreferSameZoneEureka bool `yam:"preferSameZoneEureka" json:"preferSameZoneEureka" xml:"preferSameZoneEureka"`
LogDeltaDiff bool `yam:"logDeltaDiff" json:"logDeltaDiff" xml:"logDeltaDiff"`
DisableDelta bool `yam:"disableDelta" json:"disableDelta" xml:"disableDelta"`
FetchRemoteRegionsRegistry string `yam:"fetchRemoteRegionsRegistry" json:"fetchRemoteRegionsRegistry" xml:"fetchRemoteRegionsRegistry"`
FilterOnlyUpInstances bool `yam:"filterOnlyUpInstances" json:"filterOnlyUpInstances" xml:"filterOnlyUpInstances"`
FetchRegistry bool `yam:"fetchRegistry" json:"fetchRegistry" xml:"fetchRegistry"`
DollarReplacement string `yam:"dollarReplacement" json:"dollarReplacement" xml:"dollarReplacement"`
EscapeCharReplacement string `yam:"escapeCharReplacement" json:"escapeCharReplacement" xml:"escapeCharReplacement"`
AllowRedirects bool `yam:"allowRedirects" json:"allowRedirects" xml:"allowRedirects"`
OnDemandUpdateStatusChange bool `yam:"onDemandUpdateStatusChange" json:"onDemandUpdateStatusChange" xml:"onDemandUpdateStatusChange"`
EncoderName string `yam:"encoderName" json:"encoderName" xml:"encoderName"`
DecoderName string `yam:"decoderName" json:"decoderName" xml:"decoderName"`
ClientDataAccept string `yam:"clientDataAccept" json:"clientDataAccept" xml:"clientDataAccept"`
AvailabilityZones map[string]string `yam:"availabilityZones" json:"availabilityZones" xml:"availabilityZones"`
ServiceUrl map[string]string `yam:"serviceUrl" json:"serviceUrl" xml:"serviceUrl"`
}
func NewEurekaClientConfig() EurekaClientConfig {
return EurekaClientConfig{
Transport: NewEurekaTransportConfig(),
RegistryFetchIntervalSeconds: 30,
InstanceInfoReplicationIntervalSeconds: 30,
InitialInstanceInfoReplicationIntervalSeconds: 40,
EurekaServiceUrlPollIntervalSeconds: 300,
EurekaServerReadTimeoutSeconds: 8,
EurekaServerConnectTimeoutSeconds: 5,
EurekaServerTotalConnections: 200,
EurekaServerTotalConnectionsPerHost: 50,
Region: "cn-east-1",
EurekaConnectionIdleTimeoutSeconds: 30,
HeartbeatExecutorThreadPoolSize: 2,
HeartbeatExecutorExponentialBackOffBound: 10,
CacheRefreshExecutorThreadPoolSize: 2,
CacheRefreshExecutorExponentialBackOffBound: 10,
ServiceUrl: map[string]string{DEFAULT_EUREKA_ZONE: DEFAULT_EUREKA_URL},
GZipContent: true,
UseDnsForFetchingServiceUrls: false,
RegisterWithEureka: true,
PreferSameZoneEureka: true,
AvailabilityZones: make(map[string]string),
FilterOnlyUpInstances: true,
FetchRegistry: true,
DollarReplacement: "_-",
EscapeCharReplacement: "__",
AllowRedirects: false,
OnDemandUpdateStatusChange: true,
ClientDataAccept: EurekaAcceptFull,
}
}
func (e *EurekaClientConfig) GetAvailabilityZones(region string) []string {
value, ok := e.AvailabilityZones[region]
if !ok {
value = DEFAULT_EUREKA_ZONE
}
return strings.Split(value, ",")
}
func (e *EurekaClientConfig) GetEurekaServerServiceUrls(myZone string) []string {
serviceUrls, ok := e.ServiceUrl[myZone]
if !ok {
serviceUrls = e.ServiceUrl[DEFAULT_EUREKA_ZONE]
}
if serviceUrls == "" {
return []string{"https://127.0.0.1:8761"}
}
return strings.Split(serviceUrls, ",")
}
```
rpc.go
```package gorpc
import (
"git.imooc.com/wendell1000/infra"
"git.imooc.com/wendell1000/infra/base"
)
type GoRpcApiStarter struct {
infra.BaseStarter
}
func (g *GoRpcApiStarter) Init(ctx infra.StarterContext) {
base.RpcRegister(new(EnvelopeRpc))
}
```
over.go
```package test
import (
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/shopspring/decimal"
"github.com/tietang/dbx"
"net/http"
_ "net/http/pprof"
"time"
)
var db *dbx.Database
func init() {
settings := dbx.Settings{
DriverName: "mysql",
User: "root",
Password: "111111",
//Password: "123456",
//Host: "192.168.232.175:3306",
Host: "172.16.1.248:3306",
Database: "po0",
MaxOpenConns: 10,
MaxIdleConns: 5,
ConnMaxLifetime: time.Minute * 30,
LoggingEnabled: false,
Options: map[string]string{
"charset": "utf8",
"parseTime": "true",
"autocommit": "true",
"allowNativePasswords": "true",
},
}
var err error
db, err = dbx.Open(settings)
if err != nil {
fmt.Println(err)
}
db.SetLogging(false)
db.RegisterTable(&GoodsSigned{}, "goods")
db.RegisterTable(&GoodsSigned2{}, "red_envelope_goods3")
db.RegisterTable(&GoodsUnsigned{}, "goods_unsigned")
pprof()
}
//运行pprof分析器
func pprof() {
go func() {
fmt.Println(http.ListenAndServe(":16060", nil))
}()
}
//事务锁方案
var query = "select * from goods where envelope_no=? for update"
var update = "update goods set remain_amount=?,remain_quantity=? where envelope_no=? "
func UpdateForLock(g *Goods) {
//通过db.tx函数构建事务锁代码块
err := db.Tx(func(runner *dbx.TxRunner) error {
//第一步:锁定需要修改的资源,也就是需要修改的数据行
//编写事务锁查询语句,使用for update子句来锁定资源
out := &GoodsSigned{}
_, err := runner.Get(out, query, g.EnvelopeNo)
if err != nil {
return err
}
//第二部:计算剩余金额和剩余数量
subAmount := decimal.NewFromFloat(0.01)
remainAmount := out.RemainAmount.Sub(subAmount)
remainQuantity := out.RemainQuantity - 1
//第三步:执行更新
_, row, err := runner.Execute(update, remainAmount, remainQuantity, g.EnvelopeNo)
if err != nil {
return err
}
if row < 1 {
return errors.New("库存扣减失败")
}
return nil
})
//BenchmarkConcurrentUpdateForLock-4 1000 51071139 ns/op
//BenchmarkConcurrentUpdateForLock-4 1000 45212671 ns/op
if err != nil {
fmt.Println(err)
}
}
//数据库无符号类型+直接更新方案
func UpdateForUnsigned(g *Goods) {
update := "update goods_unsigned " +
"set remain_amount=remain_amount-?, " +
"remain_quantity=remain_quantity-? " +
"where envelope_no=?"
_, row, err := db.Execute(update, 0.01, 1, g.EnvelopeNo)
//db.Execute(update, 0.01, 1, g.EnvelopeNo)
//BenchmarkConcurrentUpdateForUnsigned-4 500000 140751 ns/op
if err != nil {
fmt.Println(err)
}
if row < 1 {
fmt.Println("扣减失败")
}
}
//乐观锁方案
func UpdateForOptimistic(g *Goods) {
update := "update goods " +
"set remain_amount=remain_amount-?, " +
" remain_quantity=remain_quantity-? " +
" where envelope_no=? " +
" and remain_amount>=? " +
" and remain_quantity>=? "
_, row, err := db.Execute(update, 0.01, 1, g.EnvelopeNo, 0.01, 1)
if err != nil {
fmt.Println(err)
}
if row < 1 {
fmt.Println("扣减失败")
}
}
//乐观锁+无符号字段双保险方案
func UpdateForOptimisticAndUnsigned(g *Goods) {
update := "update goods_unsigned " +
"set remain_amount=remain_amount-?, " +
" remain_quantity=remain_quantity-? " +
" where envelope_no=? " +
" and remain_amount>=? " +
" and remain_quantity>=? "
_, row, err := db.Execute(update, 0.01, 1, g.EnvelopeNo, 0.01, 1)
if err != nil {
fmt.Println(err)
}
if row < 1 {
fmt.Println("扣减失败")
}
}
```
app.go
```package resk
import (
_ "resk-5/apis/web"
_ "resk-5/core/accounts"
"resk-5/infra"
"resk-5/infra/base"
)
func init() {
infra.Register(&base.PropsStarter{})
infra.Register(&base.DbxDatabaseStarter{})
infra.Register(&base.ValidatorStarter{})
infra.Register(&base.IrisServerStarter{})
infra.Register(&infra.WebApiStarter{})
}```
heapsort.go
```package heapsort
var arr []interface{}
func heapSort(arr []int64) []int64 {
arrLen := len(arr)
buildMaxHeap(arr)
for i := arrLen -1; i >=0; i -- {
swap(arr, 0, i)
arrLen -= 1
heapify(arr, 0, arrLen)
}
return []int64{}
}
func buildMaxHeap(arr []int64) []int64 {
arrLen := len(arr)
for i := arrLen / 2; i >= 0; i -- {
heapify(arr, i, arrLen)
}
return []int64{}
}
func heapify(arr []int64, i, arrLen int) {
left := 2*i + 1
right := 2*i + 2
largest := i
if left < arrLen && arr[left] > arr[largest] {
largest = left
}
if right < arrLen && arr[right] > arr[largest] {
largest = right
}
if largest != i {
swap(arr, i, largest)
heapify(arr, i, largest)
}
}
func swap(arr []int64, i, j int) {
arr[i], arr[j] = arr[j], arr[i]
}
```
debug.go
```package eureka
import (
log "github.com/sirupsen/logrus"
)
var logger *log.Logger
func GetLogger() *log.Logger {
return log.StandardLogger()
}
//
//func SetLogger(loggerLog *log.Logger) {
// logger.SetLogger(loggerLog)
//}
//
func init() {
// Default logger uses the go default log.
//logger = gominlog.NewClassicMinLogWithPackageName("eureka")
//logger.SetLevel(gominlog.Linfo)
logger = GetLogger()
}
```
httpserver.go
```package main
import "net/http"
func main() {
http.HandleFunc("/hello",
func(writer http.ResponseWriter, r *http.Request) {
s := r.URL.RawQuery
writer.Write([]byte("hello,world." + s))
})
http.ListenAndServe(":8082", nil)
}
```
logrus.go
```package main
import (
"time"
"github.com/sirupsen/logrus"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
)
func init() {
path := "./testlog/go.log"
/* 日志轮转相关函数
`WithLinkName` 为最新的日志建立软连接
`WithRotationTime` 设置日志分割的时间,隔多久分割一次
WithMaxAge 和 WithRotationCount二者只能设置一个
`WithMaxAge` 设置文件清理前的最长保存时间
`WithRotationCount` 设置文件清理前最多保存的个数
*/
// 下面配置日志每隔 1 分钟轮转一个新文件,保留最近 3 分钟的日志文件,多余的自动清理掉。
writer, _ := rotatelogs.New(
path+".%Y%m%d%H%M",
rotatelogs.WithLinkName(path),
rotatelogs.WithMaxAge(time.Duration(180)*time.Second),
rotatelogs.WithRotationTime(time.Duration(60)*time.Second),
)
logrus.SetOutput(writer)
//log.SetFormatter(&log.JSONFormatter{})
}
func main() {
for {
logrus.Info("hello, world!")
time.Sleep(time.Duration(2) * time.Second)
}
}```
rpctestnet.go
```package bitcoin
const RPC_USERNAME = "admin1"
const RPC_PASSWORD = "123"
const RPC_HOST = "127.0.0.1"
const RPC_PORT = "19001" // 测试使用的钱包地址
const TEST_ADDRESS = "mkiytxYA6kxUC8iTnzLPgMfCphnz91zRfZ" // 测试用的钱包地址,注意与比特币正式地址的区别
const TEST_PRIVATE_KEY = "cTAUfueRoL1HUXasWdnETANA7uRq33BUp3Sw88vKZpo9Hs8xWP82" // 测试用的钱包私钥
const TEST_WALLET_NAME = "TestWallet1" // 测试的钱包名称
const MIN_DUST_AMOUNT = 10000 // 最小有效交易金额,单位为satoshi,即0.00000001 BTC
const MIN_TRANSACTION_FEE = 10000 // 矿工费用的最小金额,单位为satoshi
```
q.go
```package main
import (
"encoding/json"
"fmt"
"imooc.com/resk/services"
)
func main() {
data, _ := json.Marshal(&services.RedEnvelopeSendingDTO{})
fmt.Println(string(data))
}
```
http_client_test.go
```package httpclient
import (
. "github.com/smartystreets/goconvey/convey"
"github.com/tietang/go-eureka-client/eureka"
"github.com/tietang/props/ini"
"imooc.com/resk/infra/lb"
"io/ioutil"
"net/http"
"testing"
)
func TestHttpClient_Do(t *testing.T) {
//创建一个eureka client
conf := ini.NewIniFileConfigSource("ec_test.ini")
client := eureka.NewClient(conf)
client.Start()
client.Applications, _ = client.GetApplications()
//创建一个apps实例
apps := &lb.Apps{Client: client}
c := NewHttpClient(apps, &Option{
Timeout: defaultHttpTimeout,
})
Convey("http客户端", t, func() {
for i := 0; i < 10; i++ {
req, err := c.NewRequest(http.MethodGet,
"http://resk/",
nil, nil)
So(err, ShouldBeNil)
So(req, ShouldNotBeNil)
res, err := c.Do(req)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
So(res.StatusCode, ShouldEqual, http.StatusOK)
defer res.Body.Close()
d, err := ioutil.ReadAll(res.Body)
So(err, ShouldBeNil)
So(d, ShouldNotBeNil)
}
})
}
//作为作业留给同学们:
// 使用简单轮询算法,运行测试用例试一下,看看效果,并且能发现什么问题呢?
//想一想问题是什么?
// 造成这个问题的原因是什么?
// 那么如何来解决这个问题?
//那么在问答区或者QQ群里我们展开讨论
```
newConn.go
```package main
import (
"context"
"golang/connectpool/pool"
)
func main() {
ctx := context.Background()
config := &pool.Config{
MaxConn: 1,
MaxIdle: 1,
}
conn := pool.Prepare(ctx, config)
if _, err := conn.New(ctx); err != nil {
return
}
if _, err := conn.New(ctx); err != nil {
return
}
if _, err := conn.New(ctx); err != nil {
return
}
if _, err := conn.New(ctx); err != nil {
return
}
if _, err := conn.New(ctx); err != nil {
return
}
}
```
after-shuffle.go
```package main
import (
"fmt"
"git.imooc.com/wendell1000/infra/algo"
)
func main() {
fmt.Println(algo.AfterShuffle(int64(10), int64(10000)))
}
```
rpc.go
```package gorpc
import (
"errors"
"resk-5/infra/lb"
"github.com/sirupsen/logrus"
"net/rpc"
)
type GoRpcClient struct {
Apps *lb.Apps
}
func (g *GoRpcClient) Call(serviceId, serviceMethod string, in interface{}, out interface{}) error {
//通过微服务名称从本地服务注册表中查询应用和应用实例列表
app := g.Apps.Get(serviceId)
if app == nil {
return errors.New("没有可用的微服务应用,应用名称:" + serviceId + ",请求:" + serviceMethod)
}
//通过负载均衡算法从应用实例列表中选择一个实例
ins := app.Get(serviceMethod)
if ins == nil {
return errors.New("没有可用的应用实例,应用名称:" + serviceId + ",请求:" + serviceMethod)
}
//选择的实例IP和端口
addr := ins.Metadata["rpcAddr"]
c, err := rpc.Dial("tcp", addr)
if err != nil {
logrus.Error(err)
return err
}
defer c.Close()
err = c.Call(serviceMethod, in, out)
if err != nil {
logrus.Error(err)
}
return err
}
```
main.go
```package main
import (
"golua_timer/rabbitmq_delay"
"math/rand"
"time"
)
var (
addr = "root:123456@tcp(192.168.99.100:3306)/hello"
rabbitmqAddr = "amqp://guest:guest@192.168.0.239:5672"
)
func main() {
rabbitmq_delay.InitMysqlDB(addr)
//rabbitmq_delay.InitRabbitmq(rabbitmqAddr)
mqPool := rabbitmq_delay.NewPools(rabbitmqAddr, 10)
rabbitmq_delay.InitRabbitmqChannel(rabbitmqAddr)
rand.Seed(time.Now().UnixNano())
go rabbitmq_delay.NewConsume(mqPool, "1")
go rabbitmq_delay.NewConsume(mqPool, "2")
for i := 0; i < 1000; i++ {
n := rand.Int63n(10)
rabbitmq_delay.PublishDelayMsg(mqPool, "helloworld", i, n*1000)
}
for {
}
}
```
rpc.go
```package base
import (
"git.imooc.com/wendell1000/infra"
log "github.com/sirupsen/logrus"
"net"
"net/rpc"
"reflect"
)
var rpcServer *rpc.Server
func RpcServer() *rpc.Server {
Check(rpcServer)
return rpcServer
}
func RpcRegister(ri interface{}) {
typ := reflect.TypeOf(ri)
log.Infof("goRPC Register: %s", typ.String())
RpcServer().Register(ri)
}
type GoRPCStarter struct {
infra.BaseStarter
server *rpc.Server
}
func (s *GoRPCStarter) Init(ctx infra.StarterContext) {
s.server = rpc.NewServer()
rpcServer = s.server
}
func (s *GoRPCStarter) Start(ctx infra.StarterContext) {
port := ctx.Props().GetDefault("app.rpc.port", "8082")
//监听网络端口
listener, err := net.Listen("tcp", ":"+port)
if err != nil {
log.Panic(err)
}
log.Info("tcp port listened for rpc:", port)
//处理网络连接和请求
go s.server.Accept(listener)
}
```
runner.go
```package dbx
import (
"database/sql"
"database/sql/driver"
"github.com/tietang/dbx/mapping"
)
type Mapper func(model interface{}, rows *sql.Rows) (interface{}, error)
type RowsMapper func(rows *sql.Rows) (interface{}, error)
type RowMapper func(row *sql.Row) (interface{}, error)
type TxRunner struct {
*Runner
driver.Tx
}
type Runner struct {
sqlExecutor
mapperExecutor
mapping.EntityMapper
ILogger
LoggerSettings
}
func NewTxRunner(tx *sql.Tx) *TxRunner {
r := &TxRunner{}
r.Runner = &Runner{}
r.sqlExecutor = tx
r.Tx = tx
return r
}
func NewRunner(se sqlExecutor, em mapping.EntityMapper) *Runner {
r := &Runner{}
r.sqlExecutor = se
r.EntityMapper = em
return r
}
```
main.go
```package main
import (
"encoding/json"
"fmt"
"git.imooc.com/wendell1000/resk/services"
)
func main() {
d, e := json.Marshal(&services.AccountTransferDTO{})
fmt.Println(e)
fmt.Println(string(d))
}
```
main.go
```package main
import (
"fmt"
"sort"
)
type uints []uint
func NewUints() *uints {
return &uints{500, 130, 160, 30, 560, 910, 1, 3, 9, 7, 6}
}
func (ui uints) Len() int {
return len(ui)
}
func (ui uints) Less(i, j int) bool {
return ui[i] < ui[j]
}
func (ui uints) Swap(i, j int) {
ui[i], ui[j] = ui[j], ui[i]
}
func (ui uints) search(key uint) int {
//查找算法
f := func(x int) bool {
return ui[x] > key
}
i := sort.Search(len(ui), f)
return i
}
func main() {
ui := NewUints()
sort.Sort(ui)
fmt.Printf("ui type is %v\n", ui)
rs := ui.search(1)
fmt.Printf("sort result is %v\n", rs)
}
```
main.go
```package main
import (
"fmt"
"sort"
"sync"
"time"
)
/*type timer struct {
tb *timersBucket
i int
when int64
period int64
f func(interface{}, uintptr)
arg interface{}
seq uintptr
}
type Timer struct {
C <-chan Time
r runTimeTimer
}
type timersBucket struct {
lock mutex
gp *g
created bool
sleeping bool
recheduling bool
sleepUntil int64
waitnote note
t []*timer
}*/
func main() {
for true {
select {
case hello := <-time.NewTicker(time.Duration(10 * time.Second)).C:
fmt.Println(hello)
}
}
}
func RunTimers(count int) {
durationCh := make(chan time.Duration, count)
wg := sync.WaitGroup{}
wg.Add(count)
for i := 0; i < count; i++ {
go func() {
startedAt := time.Now()
time.AfterFunc(10*time.Millisecond, func() {
defer wg.Done()
durationCh <- time.Since(startedAt)
})
}()
}
wg.Wait()
close(durationCh)
durations := []time.Duration{}
totalDuration := 0 * time.Millisecond
for duration := range durationCh {
durations = append(durations, duration)
totalDuration += duration
}
averageDuration := totalDuration / time.Duration(count)
sort.Slice(durations, func(i, j int) bool {
return durations[i] < durations[j]
})
fmt.Printf("run %v timers with average=%v, pct50=%v, pct99=%v\n", count, averageDuration, durations[count/2], durations[int(float64(count)*0.99)])
}
```
domain_sending.go
```package envelopes
import (
"context"
"github.com/tietang/dbx"
"imooc.com/resk/core/accounts"
"imooc.com/resk/infra/base"
"imooc.com/resk/services"
"path"
)
//发红包业务领域代码
func (d *goodsDomain) SendOut(
goods services.RedEnvelopeGoodsDTO) (activity *services.RedEnvelopeActivity, err error) {
//创建红包商品
d.Create(goods)
//创建活动
activity = new(services.RedEnvelopeActivity)
//红包链接,格式:http://域名/v1/envelope/{id}/link/
link := base.GetEnvelopeActivityLink()
domain := base.GetEnvelopeDomain()
activity.Link = path.Join(domain, link, d.EnvelopeNo)
accountDomain := accounts.NewAccountDomain()
err = base.Tx(func(runner *dbx.TxRunner) (err error) {
ctx := base.WithValueContext(context.Background(), runner)
//事务逻辑问题:
//保存红包商品和红包金额的支付必须要保证全部成功或者全部失败
//保存红包商品
id, err := d.Save(ctx)
if id <= 0 || err != nil {
return err
}
//红包金额支付
//1. 需要红包中间商的红包资金账户,定义在配置文件中,事先初始化到资金账户表中
//2. 从红包发送人的资金账户中扣减红包金额 ,把红包金额从红包发送人的资金账户里扣除
body := services.TradeParticipator{
AccountNo: goods.AccountNo,
UserId: goods.UserId,
Username: goods.Username,
}
systemAccount := base.GetSystemAccount()
target := services.TradeParticipator{
AccountNo: systemAccount.AccountNo,
Username: systemAccount.Username,
UserId: systemAccount.UserId,
}
transfer := services.AccountTransferDTO{
TradeBody: body,
TradeTarget: target,
TradeNo: d.EnvelopeNo,
Amount: d.Amount,
ChangeType: services.EnvelopeOutgoing,
ChangeFlag: services.FlagTransferOut,
Decs: "红包金额支付",
}
status, err := accountDomain.TransferWithContextTx(ctx, transfer)
if status == services.TransferedStatusSuccess {
return nil
}
//3. 将扣减的红包总金额转入红包中间商的红包资金账户
//入账
transfer = services.AccountTransferDTO{
TradeBody: target,
TradeTarget: body,
TradeNo: d.EnvelopeNo,
Amount: d.Amount,
ChangeType: services.EnvelopeIncoming,
ChangeFlag: services.FlagTransferIn,
Decs: "红包金额转入",
}
status, err = accountDomain.TransferWithContextTx(ctx, transfer)
if status == services.TransferedStatusSuccess {
return nil
}
return err
})
if err != nil {
return nil, err
}
//扣减金额没有问题,返回活动
activity.RedEnvelopeGoodsDTO = *d.RedEnvelopeGoods.ToDTO()
return activity, err
}
```
forms.go
```package views
import "github.com/shopspring/decimal"
type UserForm struct {
UserId string `form:"user_id"`
Mobile string `form:"mobile"`
Username string `form:"username"`
}
type RedEnvelopeSendingForm struct {
EnvelopeType int `form:"envelopeType"` //红包类型:普通红包,碰运气红包
Blessing string `form:"blessing"` //祝福语
Amount decimal.Decimal `form:"amount"` //红包金额:普通红包指单个红包金额,碰运气红包指总金额
Quantity int `form:"quantity"` //红包总数量
}
```
banner.go
```package infra
import "fmt"
const (
banner = `
▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄
▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌
▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌
▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌▐░▌
▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌░▌
▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░▌
▐░█▀▀▀▀█░█▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀█░▌▐░▌░▌
▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌▐░▌
▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄█░▌▐░▌ ▐░▌
▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌
`
)
//http://patorjk.com/software/taag/#p=testall&h=0&v=0&f=Graceful&t=Resk
func init() {
fmt.Println(banner)
}
```
domain_goods.go
```package envelopes
import (
"context"
"github.com/segmentio/ksuid"
"github.com/shopspring/decimal"
"github.com/sirupsen/logrus"
"github.com/tietang/dbx"
"imooc.com/resk/infra/base"
"imooc.com/resk/services"
"time"
)
type goodsDomain struct {
RedEnvelopeGoods
item itemDomain
}
//生成一个红包编号
func (d *goodsDomain) createEnvelopeNo() {
d.EnvelopeNo = ksuid.New().Next().String()
}
//创建一个红包商品对象
func (d *goodsDomain) Create(
goods services.RedEnvelopeGoodsDTO) {
d.RedEnvelopeGoods.FromDTO(&goods)
d.RemainQuantity = goods.Quantity
d.Username.Valid = true
d.Blessing.Valid = true
if d.EnvelopeType == services.GeneralEnvelopeType {
d.Amount = goods.AmountOne.Mul(
decimal.NewFromFloat(float64(goods.Quantity)))
}
if d.EnvelopeType == services.LuckyEnvelopeType {
d.AmountOne = decimal.NewFromFloat(0)
}
d.RemainAmount = d.Amount
//过期时间
d.ExpiredAt = time.Now().Add(24 * time.Hour)
d.Status = services.OrderCreate
d.OrderType = services.OrderTypeSending
d.PayStatus = services.Paying
d.createEnvelopeNo()
}
//保存到红包商品表
func (d *goodsDomain) Save(ctx context.Context) (id int64, err error) {
err = base.ExecuteContext(ctx, func(runner *dbx.TxRunner) error {
dao := RedEnvelopeGoodsDao{runner: runner}
id, err = dao.Insert(&d.RedEnvelopeGoods)
return err
})
return id, err
}
//创建并保存红包商品
func (d *goodsDomain) CreateAndSave(ctx context.Context, goods services.RedEnvelopeGoodsDTO) (id int64, err error) {
//创建红包商品
d.Create(goods)
//保存红包商品
return d.Save(ctx)
}
//查询红包商品信息
func (d *goodsDomain) Get(envelopeNo string) (goods *RedEnvelopeGoods) {
err := base.Tx(func(runner *dbx.TxRunner) error {
dao := RedEnvelopeGoodsDao{runner: runner}
goods = dao.GetOne(envelopeNo)
return nil
})
if err != nil {
logrus.Error(err)
}
return goods
}
func (d *goodsDomain) UpdateOrderStatus(envelopeNo string,
status services.OrderStatus) (rows int64, err error) {
err = base.Tx(func(runner *dbx.TxRunner) error {
dao := RedEnvelopeGoodsDao{runner: runner}
rows, err = dao.UpdateOrderStatus(envelopeNo, status)
return nil
})
if err != nil {
logrus.Error(err)
}
return
}
func (d *goodsDomain) UpdatePayStatus(envelopeNo string,
status services.PayStatus) (rows int64, err error) {
err = base.Tx(func(runner *dbx.TxRunner) error {
dao := RedEnvelopeGoodsDao{runner: runner}
rows, err = dao.UpdatePayStatus(envelopeNo, status)
return nil
})
if err != nil {
logrus.Error(err)
}
return
}
```
q.go
```package main
import (
"fmt"
"git.imooc.com/wendell1000/resk/core/envelopes"
)
func main() {
goods := envelopes.RedEnvelopeGoods{
EnvelopeNo: "111",
}
r := goods
r.EnvelopeNo = "222"
fmt.Println(goods.EnvelopeNo)
fmt.Println(r.EnvelopeNo)
func() {
fmt.Println(goods.EnvelopeNo)
fmt.Println(r.EnvelopeNo)
}()
}
```
service_recieve_test.go
```package envelopes
import (
"github.com/segmentio/ksuid"
"github.com/shopspring/decimal"
"github.com/sirupsen/logrus"
. "github.com/smartystreets/goconvey/convey"
"imooc.com/resk/services"
"strconv"
"sync"
"testing"
)
func TestRedEnvelopeService_Receive(t *testing.T) {
//1. 准备几个红包资金账户,用于发红包和收红包
accountService := services.GetAccountService()
Convey("收红包测试用例", t, func() {
accounts := make([]*services.AccountDTO, 0)
size := 10
for i := 0; i < size; i++ {
account := services.AccountCreatedDTO{
UserId: ksuid.New().Next().String(),
Username: "测试用户" + strconv.Itoa(i+1),
Amount: "2000",
AccountName: "测试账户" + strconv.Itoa(i+1),
AccountType: int(services.EnvelopeAccountType),
CurrencyCode: "CNY",
}
//账户创建
acDto, err := accountService.CreateAccount(account)
So(err, ShouldBeNil)
So(acDto, ShouldNotBeNil)
accounts = append(accounts, acDto)
}
acDto := accounts[0]
So(len(accounts), ShouldEqual, size)
//2. 使用其中一个用户发送一个红包
re := services.GetRedEnvelopeService()
//发送普通红包
goods := services.RedEnvelopeSendingDTO{
UserId: acDto.UserId,
Username: acDto.Username,
EnvelopeType: services.GeneralEnvelopeType,
Amount: decimal.NewFromFloat(1.88),
Quantity: size,
Blessing: services.DefaultBlessing,
}
at, err := re.SendOut(goods)
So(err, ShouldBeNil)
So(at, ShouldNotBeNil)
So(at.Link, ShouldNotBeEmpty)
So(at.RedEnvelopeGoodsDTO, ShouldNotBeNil)
//验证每一个属性
dto := at.RedEnvelopeGoodsDTO
So(dto.Username, ShouldEqual, goods.Username)
So(dto.UserId, ShouldEqual, goods.UserId)
So(dto.Quantity, ShouldEqual, goods.Quantity)
q := decimal.NewFromFloat(float64(dto.Quantity))
So(dto.Amount.String(), ShouldEqual, goods.Amount.Mul(q).String())
remainAmount := at.Amount
//3. 使用发送红包数量的人收红包
Convey("收普通红包", func() {
for i, account := range accounts {
rcv := services.RedEnvelopeReceiveDTO{
EnvelopeNo: at.EnvelopeNo,
RecvUserId: account.UserId,
RecvUsername: account.Username,
AccountNo: account.AccountNo,
}
item, err := re.Receive(rcv)
logrus.Info(i)
logrus.Infof("%+v", item)
So(err, ShouldBeNil)
So(item, ShouldNotBeNil)
So(item.Amount, ShouldEqual, at.AmountOne)
remainAmount = remainAmount.Sub(at.AmountOne)
So(item.RemainAmount.String(), ShouldEqual, remainAmount.String())
}
})
//收碰运气红包,作为作业留给同学们来实现
goods.EnvelopeType = services.LuckyEnvelopeType
goods.Amount = decimal.NewFromFloat(18.8)
at, err = re.SendOut(goods)
So(err, ShouldBeNil)
So(at, ShouldNotBeNil)
So(at.Link, ShouldNotBeEmpty)
So(at.RedEnvelopeGoodsDTO, ShouldNotBeNil)
//验证每一个属性
dto = at.RedEnvelopeGoodsDTO
So(dto.Username, ShouldEqual, goods.Username)
So(dto.UserId, ShouldEqual, goods.UserId)
So(dto.Quantity, ShouldEqual, goods.Quantity)
So(dto.Amount.String(), ShouldEqual, goods.Amount.String())
remainAmount = at.Amount
re = services.GetRedEnvelopeService()
Convey("收碰运气红包", func() {
So(len(accounts), ShouldEqual, size)
total := decimal.NewFromFloat(0)
for i, account := range accounts {
if i > 10 {
break
}
rcv := services.RedEnvelopeReceiveDTO{
EnvelopeNo: at.EnvelopeNo,
RecvUserId: account.UserId,
RecvUsername: account.Username,
AccountNo: account.AccountNo,
}
item, err := re.Receive(rcv)
if item != nil {
total = total.Add(item.Amount)
}
logrus.Info(i+1, " ", total.String(), " ", item.Amount.String())
So(err, ShouldBeNil)
So(item, ShouldNotBeNil)
remainAmount = remainAmount.Sub(item.Amount)
So(item.RemainAmount.String(), ShouldEqual, remainAmount.String())
}
So(total.String(), ShouldEqual, goods.Amount.String())
})
})
}
func TestRedEnvelopeService_Receive_Failure(t *testing.T) {
//1. 准备几个红包资金账户,用于发红包和收红包
accountService := services.GetAccountService()
Convey("收红包测试用例", t, func() {
accounts := make([]*services.AccountDTO, 0)
size := 5
for i := 0; i < size; i++ {
account := services.AccountCreatedDTO{
UserId: ksuid.New().Next().String(),
Username: "测试用户" + strconv.Itoa(i+1),
Amount: "100",
AccountName: "测试账户" + strconv.Itoa(i+1),
AccountType: int(services.EnvelopeAccountType),
CurrencyCode: "CNY",
}
//账户创建
acDto, err := accountService.CreateAccount(account)
So(err, ShouldBeNil)
So(acDto, ShouldNotBeNil)
accounts = append(accounts, acDto)
}
//2. 使用其中一个用户发送一个红包
acDto := accounts[0]
So(len(accounts), ShouldEqual, size)
re := services.GetRedEnvelopeService()
//发送普通红包
goods := services.RedEnvelopeSendingDTO{
UserId: acDto.UserId,
Username: acDto.Username,
EnvelopeType: services.LuckyEnvelopeType,
Amount: decimal.NewFromFloat(10),
Quantity: 3,
Blessing: services.DefaultBlessing,
}
at, err := re.SendOut(goods)
So(err, ShouldBeNil)
So(at, ShouldNotBeNil)
So(at.Link, ShouldNotBeEmpty)
So(at.RedEnvelopeGoodsDTO, ShouldNotBeNil)
//验证每一个属性
dto := at.RedEnvelopeGoodsDTO
So(dto.Username, ShouldEqual, goods.Username)
So(dto.UserId, ShouldEqual, goods.UserId)
So(dto.Quantity, ShouldEqual, goods.Quantity)
So(dto.Amount.String(), ShouldEqual, goods.Amount.String())
//
re = services.GetRedEnvelopeService()
Convey("收碰运气红包", func() {
So(len(accounts), ShouldEqual, size)
total := decimal.NewFromFloat(0)
remainAmount := goods.Amount
sendingAmount := decimal.NewFromFloat(0)
for i, account := range accounts {
rcv := services.RedEnvelopeReceiveDTO{
EnvelopeNo: at.EnvelopeNo,
RecvUserId: account.UserId,
RecvUsername: account.Username,
AccountNo: account.AccountNo,
}
if i <= 2 {
item, err := re.Receive(rcv)
if item != nil {
total = total.Add(item.Amount)
}
logrus.Info(i+1, " ", total.String(), " ", item.Amount.String())
So(err, ShouldBeNil)
So(item, ShouldNotBeNil)
remainAmount = remainAmount.Sub(item.Amount)
So(item.RemainAmount.String(), ShouldEqual, remainAmount.String())
a := accountService.GetEnvelopeAccountByUserId(rcv.RecvUserId)
So(a, ShouldNotBeNil)
if item.RecvUserId == goods.UserId {
b := decimal.NewFromFloat(100)
b = b.Sub(decimal.NewFromFloat(10))
b = b.Add(item.Amount)
So(a.Balance.String(), ShouldEqual, b.String())
sendingAmount = item.Amount
} else {
So(a.Balance.String(), ShouldEqual, item.Amount.Add(decimal.NewFromFloat(100)).String())
}
} else {
item, err := re.Receive(rcv)
So(err, ShouldNotBeNil)
So(item, ShouldBeNil)
}
}
So(total.String(), ShouldEqual, goods.Amount.String())
order := re.Get(at.EnvelopeNo)
So(order, ShouldNotBeNil)
So(order.RemainAmount.String(), ShouldEqual, "0")
So(order.RemainQuantity, ShouldEqual, 0)
a := accountService.GetEnvelopeAccountByUserId(order.UserId)
So(a, ShouldNotBeNil)
So(a.Balance.String(), ShouldEqual, sendingAmount.Add(decimal.NewFromFloat(90)).String())
})
})
}
func TestRedEnvelopeService_Receive_C(t *testing.T) {
//1. 准备几个红包资金账户,用于发红包和收红包
accountService := services.GetAccountService()
Convey("收红包测试用例", t, func() {
accounts := make([]*services.AccountDTO, 0)
size := 100
for i := 0; i < size; i++ {
account := services.AccountCreatedDTO{
UserId: ksuid.New().Next().String(),
Username: "测试用户" + strconv.Itoa(i+1),
Amount: "2000",
AccountName: "测试账户" + strconv.Itoa(i+1),
AccountType: int(services.EnvelopeAccountType),
CurrencyCode: "CNY",
}
//账户创建
acDto, err := accountService.CreateAccount(account)
So(err, ShouldBeNil)
So(acDto, ShouldNotBeNil)
accounts = append(accounts, acDto)
}
acDto := accounts[0]
So(len(accounts), ShouldEqual, size)
//2. 使用其中一个用户发送一个红包
re := services.GetRedEnvelopeService()
//发送普通红包
goods := services.RedEnvelopeSendingDTO{
UserId: acDto.UserId,
Username: acDto.Username,
EnvelopeType: services.LuckyEnvelopeType,
Amount: decimal.NewFromFloat(20),
Quantity: 10,
Blessing: services.DefaultBlessing,
}
at, err := re.SendOut(goods)
So(err, ShouldBeNil)
So(at, ShouldNotBeNil)
So(at.Link, ShouldNotBeEmpty)
So(at.RedEnvelopeGoodsDTO, ShouldNotBeNil)
//验证每一个属性
dto := at.RedEnvelopeGoodsDTO
So(dto.Username, ShouldEqual, goods.Username)
So(dto.UserId, ShouldEqual, goods.UserId)
So(dto.Quantity, ShouldEqual, goods.Quantity)
So(dto.Amount.String(), ShouldEqual, goods.Amount.String())
at, err = re.SendOut(goods)
So(err, ShouldBeNil)
So(at, ShouldNotBeNil)
So(at.Link, ShouldNotBeEmpty)
So(at.RedEnvelopeGoodsDTO, ShouldNotBeNil)
//验证每一个属性
dto = at.RedEnvelopeGoodsDTO
So(dto.Username, ShouldEqual, goods.Username)
So(dto.UserId, ShouldEqual, goods.UserId)
So(dto.Quantity, ShouldEqual, goods.Quantity)
So(dto.Amount.String(), ShouldEqual, goods.Amount.String())
re = services.GetRedEnvelopeService()
Convey("收碰运气红包", func() {
So(len(accounts), ShouldEqual, size)
var wg sync.WaitGroup
for _, account := range accounts {
wg.Add(1)
go func() {
rcv := services.RedEnvelopeReceiveDTO{
EnvelopeNo: at.EnvelopeNo,
RecvUserId: account.UserId,
RecvUsername: account.Username,
AccountNo: account.AccountNo,
}
re.Receive(rcv)
wg.Done()
}()
}
wg.Wait()
items := re.ListItems(at.EnvelopeNo)
So(len(items), ShouldEqual, 10)
total := decimal.NewFromFloat(0)
for _, item := range items {
total = total.Add(item.Amount)
}
So(total.String(), ShouldEqual, at.Amount.String())
//这里就测试出来一个并发下面的临界问题:
//当库存还大于1的时候,假如剩余的金额为2元
// 那么在计算红包序列的时候是不会取最后剩余的所有金额的
//仍然是以数量大于1的情况下计算的,
// 比如有2个用户同时抢,分别计算得到0.8元和1.1元
//这时1.1元的用户获得红包,同时还剩余0.9元,并且库存是1
// 这个时候0.8元的用户也去抢,符合乐观锁的逻辑,也抢到0.8元,
// 然后库存剩余为0,但剩余金额为0.1元,之后由于库存为0了,
// 剩余金额就不能被抢走了,那么这个问题呢通过乐观锁是不能解决的,
// 我这里把这个问题留给同学们思考一下,查阅一下资料看如何来解决?
// 在问答区我们进行讨论,看看有多少方法可以解决这个问题?
//
})
})
}
```
dao_goods_test.go
```package envelopes
//作业: 编写红包商品表自动化测试用例
// 1. 红包商品数据写入
// 2. 更新红包剩余金额和数量
```
app.go
```package resk
import (
_ "git.imooc.com/wendell1000/account/apis/web"
_ "git.imooc.com/wendell1000/account/core/accounts"
"git.imooc.com/wendell1000/infra"
"git.imooc.com/wendell1000/infra/base"
)
func init() {
infra.Register(&base.PropsStarter{})
infra.Register(&base.DbxDatabaseStarter{})
infra.Register(&base.ValidatorStarter{})
infra.Register(&base.IrisServerStarter{})
infra.Register(&infra.WebApiStarter{})
infra.Register(&base.EurekaStarter{})
infra.Register(&base.HookStarter{})
}
```
lb_rr.go
```package lb
import (
"math/rand"
"sync/atomic"
)
var _ Balancer = new(RoundRobinBalancer)
//简单轮询负载均衡算法
type RoundRobinBalancer struct {
ct uint32 //计数器
}
func (r *RoundRobinBalancer) Next(key string, hosts []*ServerInstance) *ServerInstance {
if len(hosts) == 0 {
return nil
}
//自增
count := atomic.AddUint32(&r.ct, 1)
//取模计算索引
index := int(count) % len(hosts)
//按照索引取出实例
instance := hosts[index]
return instance
}
var _ Balancer = new(RandomBalancer)
//随机负载均衡算法
type RandomBalancer struct {
}
func (r *RandomBalancer) Next(key string, hosts []*ServerInstance) *ServerInstance {
if len(hosts) == 0 {
return nil
}
//随机数
count := rand.Int31()
//取模计算索引
index := int(count) % len(hosts)
//按照索引取出实例
instance := hosts[index]
return instance
}
```
domain_account.go
```package accounts
import (
"context"
"git.imooc.com/wendell1000/account/services"
"git.imooc.com/wendell1000/infra/base"
"github.com/kataras/iris/core/errors"
"github.com/segmentio/ksuid"
"github.com/shopspring/decimal"
"github.com/sirupsen/logrus"
"github.com/tietang/dbx"
)
//有状态的,每次使用时都要实例化
type accountDomain struct {
account Account
accountLog AccountLog
}
func NewAccountDomain() *accountDomain {
return new(accountDomain)
}
//创建logNo 的逻辑
func (domain *accountDomain) createAccountLogNo() {
//暂时采用ksuid的ID生成策略来创建No
//后期会优化成可读性比较好的,分布式ID
//全局唯一的ID
domain.accountLog.LogNo = ksuid.New().Next().String()
}
//生成accountNo的逻辑
func (domain *accountDomain) createAccountNo() {
domain.account.AccountNo = ksuid.New().Next().String()
}
//创建流水的记录
func (domain *accountDomain) createAccountLog() {
//通过account来创建流水,创建账户逻辑在前
domain.accountLog = AccountLog{}
domain.createAccountLogNo()
domain.accountLog.TradeNo = domain.accountLog.LogNo
//流水中的交易主体信息
domain.accountLog.AccountNo = domain.account.AccountNo
domain.accountLog.UserId = domain.account.UserId
domain.accountLog.Username = domain.account.Username.String
//交易对象信息
domain.accountLog.TargetAccountNo = domain.account.AccountNo
domain.accountLog.TargetUserId = domain.account.UserId
domain.accountLog.TargetUsername = domain.account.Username.String
//交易金额
domain.accountLog.Amount = domain.account.Balance
domain.accountLog.Balance = domain.account.Balance
//交易变化属性
domain.accountLog.Decs = "账户创建"
domain.accountLog.ChangeType = services.AccountCreated
domain.accountLog.ChangeFlag = services.FlagAccountCreated
}
//账户创建的业务逻辑
func (domain *accountDomain) Create(
dto services.AccountDTO) (*services.AccountDTO, error) {
//创建账户持久化对象
domain.account = Account{}
domain.account.FromDTO(&dto)
domain.createAccountNo()
domain.account.Username.Valid = true
//创建账户流水持久化对象
domain.createAccountLog()
accountDao := AccountDao{}
accountLogDao := AccountLogDao{}
var rdto *services.AccountDTO
err := base.Tx(func(runner *dbx.TxRunner) error {
accountDao.runner = runner
accountLogDao.runner = runner
//插入账户数据
id, err := accountDao.Insert(&domain.account)
if err != nil {
return err
}
if id <= 0 {
return errors.New("创建账户失败")
}
//如果插入成功,就插入流水数据
id, err = accountLogDao.Insert(&domain.accountLog)
if err != nil {
return err
}
if id <= 0 {
return errors.New("创建账户流水失败")
}
domain.account = *accountDao.GetOne(domain.account.AccountNo)
return nil
})
rdto = domain.account.ToDTO()
return rdto, err
}
func (a *accountDomain) Transfer(dto services.AccountTransferDTO) (status services.TransferedStatus, err error) {
err = base.Tx(func(runner *dbx.TxRunner) error {
ctx := base.WithValueContext(context.Background(), runner)
status, err = a.TransferWithContextTx(ctx, dto)
return err
})
return status, err
}
//必须在base.TX事务块里面运行,不能单独运行
func (a *accountDomain) TransferWithContextTx(ctx context.Context, dto services.AccountTransferDTO) (status services.TransferedStatus, err error) {
//如果交易变化是支出,修正amount
amount := dto.Amount
if dto.ChangeFlag == services.FlagTransferOut {
amount = amount.Mul(decimal.NewFromFloat(-1))
}
//创建账户流水记录
a.accountLog = AccountLog{}
a.accountLog.FromTransferDTO(&dto)
a.createAccountLogNo()
//检查余额是否足够和更新余额:通过乐观锁来验证,更新余额的同时来验证余额是否足够
//更新成功后,写入流水记录
err = base.ExecuteContext(ctx, func(runner *dbx.TxRunner) error {
accountDao := AccountDao{runner: runner}
accountLogDao := AccountLogDao{runner: runner}
rows, err := accountDao.UpdateBalance(dto.TradeBody.AccountNo, amount)
if err != nil {
status = services.TransferedStatusFailure
return err
}
if rows <= 0 && dto.ChangeFlag == services.FlagTransferOut {
status = services.TransferedStatusSufficientFunds
return errors.New("余额不足")
}
account := accountDao.GetOne(dto.TradeBody.AccountNo)
if account == nil {
return errors.New("红包账户不存在")
}
a.account = *account
a.accountLog.Balance = a.account.Balance
id, err := accountLogDao.Insert(&a.accountLog)
if err != nil || id <= 0 {
status = services.TransferedStatusFailure
return errors.New("账户流水创建失败")
}
return nil
})
if err != nil {
logrus.Error(err)
} else {
status = services.TransferedStatusSuccess
}
return status, err
}
//根据账户编号来查询账户信息
func (a *accountDomain) GetAccount(accountNo string) *services.AccountDTO {
accountDao := AccountDao{}
var account *Account
err := base.Tx(func(runner *dbx.TxRunner) error {
accountDao.runner = runner
account = accountDao.GetOne(accountNo)
return nil
})
if err != nil {
return nil
}
if account == nil {
return nil
}
return account.ToDTO()
}
//根据用户ID来查询红包账户信息
func (a *accountDomain) GetEnvelopeAccountByUserId(userId string) *services.AccountDTO {
accountDao := AccountDao{}
var account *Account
err := base.Tx(func(runner *dbx.TxRunner) error {
accountDao.runner = runner
account = accountDao.GetByUserId(userId, int(services.EnvelopeAccountType))
return nil
})
if err != nil {
return nil
}
if account == nil {
return nil
}
return account.ToDTO()
}
//根据用户ID和账户类型来查询账户信息
func (a *accountDomain) GetAccountByUserIdAndType(userId string, accountType services.AccountType) *services.AccountDTO {
accountDao := AccountDao{}
var account *Account
err := base.Tx(func(runner *dbx.TxRunner) error {
accountDao.runner = runner
account = accountDao.GetByUserId(userId, int(accountType))
return nil
})
if err != nil {
return nil
}
if account == nil {
return nil
}
return account.ToDTO()
}
//根据流水ID来查询账户流水
func (a *accountDomain) GetAccountLog(logNo string) *services.AccountLogDTO {
dao := AccountLogDao{}
var log *AccountLog
err := base.Tx(func(runner *dbx.TxRunner) error {
dao.runner = runner
log = dao.GetOne(logNo)
return nil
})
if err != nil {
logrus.Error(err)
return nil
}
if log == nil {
return nil
}
return log.ToDTO()
}
//根据交易编号来查询账户流水
func (a *accountDomain) GetAccountLogByTradeNo(tradeNo string) *services.AccountLogDTO {
dao := AccountLogDao{}
var log *AccountLog
err := base.Tx(func(runner *dbx.TxRunner) error {
dao.runner = runner
log = dao.GetByTradeNo(tradeNo)
return nil
})
if err != nil {
logrus.Error(err)
return nil
}
if log == nil {
return nil
}
return log.ToDTO()
}
```
connectPool.go
```package pool
import (
"context"
"golang.org/x/tools/go/ssa/interp/testdata/src/fmt"
"iris/core/errors"
"sync"
"time"
)
type Conn struct {
maxConn int // 最大连接数
maxIdle int // 最大可用连接数
freeConn int // 线程池空闲连接数
connPool []int // 连接池
openCount int // 已经打开的连接数
waitConn map[int]chan Permission // 排队等待的连接队列
waitCount int // 等待个数
lock sync.Mutex // 锁
nextConnIndex NextConnIndex // 下一个连接的ID标识(用于区分每个ID)
freeConns map[int]Permission // 连接池的连接
}
type Permission struct {
NextConnIndex // 对应Conn中的NextConnIndex
Content string // 通行证的具体内容,比如"PASSED"表示成功获取
CreatedAt time.Time // 创建时间,即连接的创建时间
MaxLifeTime time.Duration // 连接的存活时间,本次没有用到这个属性,保留
}
type NextConnIndex struct {
Index int
}
type Config struct {
MaxConn int
MaxIdle int
}
//初始化连接池参数
func Prepare(ctx context.Context, config *Config) (conn *Conn) {
/*go func() {
for {
conn.expiredCh = make(chan string, len(conn.freeConns))
for _, value := range conn.freeConns {
if value.CreatedAt.Add(value.MaxLifeTime).Before(nowFunc()) {
conn.expiredCh <- "CLOSE"
}
}
}
}()*/
return &Conn{
maxConn: config.MaxConn,
maxIdle: config.MaxIdle,
openCount: 0,
connPool: []int{},
waitConn: make(map[int]chan Permission),
waitCount: 0,
freeConns: make(map[int]Permission),
}
}
//创将连接
func (conn *Conn) New(ctx context.Context) (permission Permission, err error) {
conn.lock.Lock()
select {
default:
case <-ctx.Done():
conn.lock.Unlock() // context取消或超时,则退出
return Permission{}, errors.New("new conn failed, context cancelled!")
}
//连接池不为空,从连接池获取连接
if len(conn.freeConns) > 0 {
var (
popPermission Permission
popReqKey int
)
//获取其中的一个连接
for popReqKey, popPermission = range conn.freeConns {
break
}
//从连接池中删除
delete(conn.freeConns, popReqKey)
fmt.Println("log", "use free conn!!!!!", "openCount: ", conn.openCount, " freeConns: ", conn.freeConns)
conn.lock.Unlock()
return popPermission, nil
}
if conn.openCount > conn.maxConn { // 当前连接数大于上限,则加入等待队列
nextConnIndex := getNextConnIndex(conn)
req := make(chan Permission, 1)
conn.waitConn[nextConnIndex] = req
conn.waitCount ++
conn.lock.Unlock()
select {
case <-time.After(time.Second * time.Duration(3)):
fmt.Println("超时,通知主线程推出")
return
case ret, ok := <-req:
if !ok {
return Permission{}, errors.New("new conn failed, no available conn release")
}
fmt.Println("log", "received released conn!!!!!", "openCount: ", conn.openCount, " freeConns: ", conn.freeConns)
return ret, nil
}
}
//新建连接
conn.openCount ++
nextConnIndex := getNextConnIndex(conn)
permission = Permission{
NextConnIndex: NextConnIndex{nextConnIndex},
Content: "PASSED",
CreatedAt: time.Now(),
MaxLifeTime: time.Second * 5,
}
conn.lock.Unlock()
fmt.Println("log", "create conn!!!!!", "openCount: ", conn.openCount, " freeConns: ", conn.freeConns)
return permission, nil
}
func getNextConnIndex(conn *Conn) int {
currentIndex := conn.nextConnIndex.Index
conn.nextConnIndex.Index = currentIndex + 1
return conn.nextConnIndex.Index
}
//释放连接
func (conn *Conn) Release(ctx context.Context) (result bool, err error) {
conn.lock.Lock()
// 如果等待队列有等待任务,则通知正在阻塞等待获取连接的进程(即New方法中"<-req"逻辑)
// 这里没有做指定连接的释放,只是保证释放的连接会被利用起来
if len(conn.waitConn) > 0 {
var req chan Permission
var reqKey int
for reqKey, req = range conn.waitConn {
break
}
//假定释放的连接就是下面新建的连接
permission := Permission{
NextConnIndex: NextConnIndex{reqKey},
Content: "PASSED", CreatedAt: time.Now(), MaxLifeTime: time.Second * 5,
}
req <- permission
conn.waitCount --
delete(conn.waitConn, reqKey)
conn.lock.Unlock()
} else {
if conn.openCount > 0 {
conn.openCount --
if len(conn.freeConns) > conn.maxIdle { // 确保连接池大小不会超过maxIdle
nextConnIndex := getNextConnIndex(conn)
permission := Permission{
NextConnIndex: NextConnIndex{nextConnIndex},
Content: "PASSED", CreatedAt: time.Now(), MaxLifeTime: time.Second * 5}
conn.freeConns[nextConnIndex] = permission
}
}
conn.lock.Unlock()
}
return
}
```
account.go
```package web
import (
"github.com/kataras/iris"
"github.com/sirupsen/logrus"
"resk-5/infra"
"resk-5/infra/base"
"resk-5/services"
)
//定义web api的时候,对每一个子业务,定义统一的前缀
//资金账户的根路径定义为:/account
//版本号:/v1/account
func init() {
infra.RegisterApi(new(AccountApi))
}
type AccountApi struct {
}
func (a *AccountApi) Init() {
groupRouter := base.Iris().Party("/v1/account")
groupRouter.Post("/create", createHandler)
groupRouter.Post("/transfer", transferHandler)
groupRouter.Get("/envelope/get", getEnvelopeAccountHandler)
groupRouter.Get("/get", getAccountHandler)
}
//账户创建的接口: /v1/account/create
//POST body json
/*
{
"UserId": "w123456",
"Username": "测试用户1",
"AccountName": "测试账户1",
"AccountType": 0,
"CurrencyCode": "CNY",
"Amount": "100.11"
}
{
"code": 1000,
"message": "",
"data": {
"AccountNo": "1K1hrG0sQw7lDuF6KOQbMBe2o3n",
"AccountName": "测试账户1",
"AccountType": 0,
"CurrencyCode": "CNY",
"UserId": "w123456",
"Username": "测试用户1",
"Balance": "100.11",
"Status": 1,
"CreatedAt": "2019-04-18T13:26:51.895+08:00",
"UpdatedAt": "2019-04-18T13:26:51.895+08:00"
}
}
*/
func createHandler(ctx iris.Context) {
//获取请求参数,
account := services.AccountCreatedDTO{}
err := ctx.ReadJSON(&account)
r := base.Res{
Code: base.ResCodeOk,
}
if err != nil {
r.Code = base.ResCodeRequestParamsError
r.Message = err.Error()
ctx.JSON(&r)
logrus.Error(err)
return
}
//执行创建账户的代码
service := services.GetAccountService()
dto, err := service.CreateAccount(account)
if err != nil {
r.Code = base.ResCodeInnerServerError
r.Message = err.Error()
logrus.Error(err)
}
r.Data = dto
ctx.JSON(&r)
}
//转账的接口 :/v1/account/transfer
/**
{
"UserId": "w123456-1",
"Username": "测试用户1",
"AccountName": "测试账户1",
"AccountType": 0,
"CurrencyCode": "CNY",
"Amount": "100.11"
}
{
"UserId": "w123456-2",
"Username": "测试用户2",
"AccountName": "测试账户2",
"AccountType": 0,
"CurrencyCode": "CNY",
"Amount": "100.11"
}
{
"TradeNo": "trade123456",
"TradeBody": {
"AccountNo": "1K5YdR5Cng5FsBaF95fkcRJE08v",
"UserId": "w123456-2",
"Username": "测试用户2"
},
"TradeTarget": {
"AccountNo": "1K5iy4IzhyywntWMeVlxKdxVn4G",
"UserId": "w123456-1",
"Username": "测试用户1"
},
"AmountStr": "1",
"ChangeType": -1,
"ChangeFlag": -1,
"Decs": "转出"
}
*/
func transferHandler(ctx iris.Context) {
//获取请求参数,
account := services.AccountTransferDTO{}
err := ctx.ReadJSON(&account)
r := base.Res{
Code: base.ResCodeOk,
}
if err != nil {
r.Code = base.ResCodeRequestParamsError
r.Message = err.Error()
ctx.JSON(&r)
logrus.Error(err)
return
}
//执行转账逻辑
service := services.GetAccountService()
status, err := service.Transfer(account)
if err != nil {
r.Code = base.ResCodeInnerServerError
r.Message = err.Error()
logrus.Error(err)
}
if status != services.TransferedStatusSuccess {
r.Code = base.ResCodeBizError
r.Message = err.Error()
}
r.Data = status
ctx.JSON(&r)
}
//查询红包账户的web接口: /v1/account/envelope/get
func getEnvelopeAccountHandler(ctx iris.Context) {
userId := ctx.URLParam("userId")
r := base.Res{
Code: base.ResCodeOk,
}
if userId == "" {
r.Code = base.ResCodeRequestParamsError
r.Message = "用户ID不能为空"
ctx.JSON(&r)
return
}
service := services.GetAccountService()
account := service.GetEnvelopeAccountByUserId(userId)
r.Data = account
ctx.JSON(&r)
}
//查询账户信息的web接口:/v1/account/get
func getAccountHandler(ctx iris.Context) {
accountNo := ctx.URLParam("accountNo")
r := base.Res{
Code: base.ResCodeOk,
}
if accountNo == "" {
r.Code = base.ResCodeRequestParamsError
r.Message = "账户编号不能为空"
ctx.JSON(&r)
return
}
service := services.GetAccountService()
account := service.GetAccount(accountNo)
r.Data = account
ctx.JSON(&r)
}
```
mysql.go
```package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"time"
)
func main() {
dsName := "po:111111@tcp(192.168.232.175:3306)/po?charset=utf8&parseTime=true&loc=Local"
db, err := sql.Open("mysql", dsName)
if err != nil {
fmt.Println(err)
}
db.SetMaxIdleConns(2)
db.SetMaxOpenConns(3)
db.SetConnMaxLifetime(7 * time.Hour)
fmt.Println(db.Query("select now() "))
defer db.Close()
}
```
main.go
```package main
import flag "github.com/spf13/pflag"
import (
"fmt"
"strings"
)
// 定义命令行参数对应的变量
var cliName = flag.StringP("name", "n", "nick", "Input Your Name")
var cliAge = flag.IntP("age", "a",22, "Input Your Age")
var cliGender = flag.StringP("gender", "g","male", "Input Your Gender")
var cliOK = flag.BoolP("ok", "o", false, "Input Are You OK")
var cliDes = flag.StringP("des-detail", "d", "", "Input Description")
var cliOldFlag = flag.StringP("badflag", "b", "just for test", "Input badflag")
func wordSepNormalizeFunc(f *flag.FlagSet, name string) flag.NormalizedName {
from := []string{"-", "_"}
to := "."
for _, sep := range from {
name = strings.Replace(name, sep, to, -1)
}
return flag.NormalizedName(name)
}
func main() {
// 设置标准化参数名称的函数
flag.CommandLine.SetNormalizeFunc(wordSepNormalizeFunc)
// 为 age 参数设置 NoOptDefVal
flag.Lookup("age").NoOptDefVal = "25"
// 把 badflag 参数标记为即将废弃的,请用户使用 des-detail 参数
flag.CommandLine.MarkDeprecated("badflag", "please use --des-detail instead")
// 把 badflag 参数的 shorthand 标记为即将废弃的,请用户使用 des-detail 的 shorthand 参数
flag.CommandLine.MarkShorthandDeprecated("badflag", "please use -d instead")
// 在帮助文档中隐藏参数 gender
flag.CommandLine.MarkHidden("badflag")
// 把用户传递的命令行参数解析为对应变量的值
flag.Parse()
fmt.Println("name=", *cliName)
fmt.Println("age=", *cliAge)
fmt.Println("gender=", *cliGender)
fmt.Println("ok=", *cliOK)
fmt.Println("des=", *cliDes)
}
```
http_client.go
```package httpclient
import (
"bytes"
"errors"
"resk-5/infra/lb"
"io"
"io/ioutil"
"net/http"
"net/url"
"time"
)
const (
defaultHttpTimeout = 30 * time.Second
)
var parseUrl = url.Parse
type Option struct {
Timeout time.Duration
}
type HttpClient struct {
client *http.Client
Option Option
apps *lb.Apps
}
func NewHttpClient(apps *lb.Apps, opt *Option) *HttpClient {
c := &HttpClient{
apps: apps,
}
if opt == nil {
c.Option = Option{
Timeout: defaultHttpTimeout,
}
} else {
c.Option = *opt
}
c.client = &http.Client{
Timeout: c.Option.Timeout,
}
return c
}
func (c *HttpClient) NewRequest(
method, url string,
body io.Reader,
headers http.Header) (*http.Request, error) {
if method == "" {
method = http.MethodGet
}
//解析URL
u, err := parseUrl(url)
if err != nil {
return nil, err
}
//从解析后的URL中提取微服务名称
name := u.Host
//通过微服务名称从本地服务注册表中查询应用和应用实例列表
app := c.apps.Get(name)
if app == nil {
return nil, errors.New("没有可用的微服务应用,应用名称:" + name + ",请求:" + url)
}
//通过负载均衡算法从应用实例列表中选择一个实例
ins := app.Get(url)
if ins == nil {
return nil, errors.New("没有可用的应用实例,应用名称:" + name + ",请求:" + url)
}
//将原来URL中的域名部分替换成选择的实例IP和端口
u.Host = ins.Address
//使用新构造URL创建一个Request
//fmt.Println("修改前", url)
url = u.String()
//fmt.Println("修改后", url)
r, err := http.NewRequest(method, url, body)
if len(headers) > 0 {
for key, value := range headers {
for _, val := range value {
r.Header.Add(key, val)
}
}
}
return r, err
}
func (c *HttpClient) Do(r *http.Request) (*http.Response, error) {
res, err := c.client.Do(r)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
res.Body = ioutil.NopCloser(bytes.NewBuffer(body))
return res, err
}
```
q.go
```package main
import (
"fmt"
"path"
)
func main() {
p := "/Users/tietang/my/gitcode/resk-projects/src/resk-5/infra/base/dbx.go"
d, f := path.Split(p)
fmt.Println(d)
fmt.Println(f)
fmt.Println(path.Base(d))
fmt.Println(path.Base(p))
}
```
delete.go
```package eureka
import "strings"
import log "github.com/sirupsen/logrus"
func (c *Client) UnregisterInstance(appId, instanceId string) error {
values := []string{"apps", appId, instanceId}
path := strings.Join(values, "/")
_, err := c.Delete(path)
return err
}
func (c *Client) DeleteStatusOverride(appId, instanceId string, status string) error {
values := []string{"apps", appId, instanceId, "status"}
path := strings.Join(values, "/") + "?value=" + status
res, err := c.Delete(path)
if res != nil {
log.WithFields(log.Fields{
"path": path,
"status": res.StatusCode,
}).Info("DeleteStatusOverride ")
}
return err
}
```
instance.go
```package eureka
import (
"os"
"os/signal"
"syscall"
"time"
log "github.com/sirupsen/logrus"
"github.com/tietang/go-utils"
)
func (c *Client) SetCurrentInstanceInfo(ins *InstanceInfo) {
c.InstanceInfo = ins
}
func (c *Client) Start() {
go c.run()
go c.hook()
}
func (c *Client) run() {
ins := c.InstanceInfo
if ins == nil {
log.Error("no instance info")
return
}
timer := time.NewTicker(10 * time.Second)
isInit := false
lastFailBeatSeconds := 0
lastFailBeatTimes := 0
for {
select {
case <-timer.C:
go func() {
applications, errForGet := c.GetApplications() // Retrieves all applications from eureka server(s)
if errForGet == nil {
c.Applications = applications
}
if !isInit {
errForReg := c.RegisterInstance(ins.AppName, ins) // Register new instance in your eureka(s)
if errForReg == nil {
isInit = true
}
err := c.UpdateStatus(ins.AppName, ins.InstanceId, StatusUp)
if err == nil {
isInit = true
}
} else {
errForBeat := c.SendHeartbeat(ins.App, ins.InstanceId) // say to eureka that your app is alive (here you must send heartbeat before 30 sec)
if errForBeat != nil {
lastFailBeatTimes++
nowSeconds := time.Now().Second()
if lastFailBeatSeconds == 0 {
lastFailBeatSeconds = nowSeconds
}
if nowSeconds-lastFailBeatSeconds >= 30 || lastFailBeatTimes >= 3 {
isInit = false
}
}
}
}()
}
}
}
func (client *Client) hook() {
hook := utils.NewHook()
handler := func(s os.Signal, arg interface{}) {
log.WithFields(log.Fields{
"signal": s,
}).Info("handle signal: ")
client.UnregisterInstance(client.InstanceInfo.AppName, client.InstanceInfo.InstanceId)
os.Exit(1)
}
//Interrupt Signal = syscall.SIGINT interrupt
//Kill Signal = syscall.SIGKILL killed
//syscall.SIGTERM terminated
hook.Register(os.Interrupt, handler)
hook.Register(os.Kill, handler)
hook.Register(syscall.SIGTERM, handler)
for {
c := make(chan os.Signal)
signal.Notify(c)
sig := <-c
err := hook.Handle(sig, nil)
if err != nil {
log.WithFields(log.Fields{
"signal": sig,
}).Info("unknown signal received: : ")
// os.Exit(1)
}
}
}
```
domain_item.go
```package envelopes
import (
"context"
"github.com/segmentio/ksuid"
"github.com/tietang/dbx"
"imooc.com/resk/infra/base"
"imooc.com/resk/services"
)
type itemDomain struct {
RedEnvelopeItem
}
//生成itemNo
func (d *itemDomain) createItemNo() {
d.ItemNo = ksuid.New().Next().String()
}
//创建Item
func (d *itemDomain) Create(item services.RedEnvelopeItemDTO) {
d.RedEnvelopeItem.FromDTO(&item)
d.RecvUsername.Valid = true
d.createItemNo()
}
//保存item数据
func (d *itemDomain) Save(ctx context.Context) (id int64, err error) {
err = base.ExecuteContext(ctx, func(runner *dbx.TxRunner) error {
dao := RedEnvelopeItemDao{runner: runner}
id, err = dao.Insert(&d.RedEnvelopeItem)
return err
})
return id, err
}
//通过itemNo查询抢红包明细数据
func (d *itemDomain) GetOne(
ctx context.Context, itemNo string) (dto *services.RedEnvelopeItemDTO) {
err := base.ExecuteContext(ctx, func(runner *dbx.TxRunner) error {
dao := RedEnvelopeItemDao{runner: runner}
po := dao.GetOne(itemNo)
if po != nil {
dto = po.ToDTO()
}
return nil
})
if err != nil {
return nil
}
return dto
}
func (d *itemDomain) GetByUser(userId, envelopeNo string) (dto *services.RedEnvelopeItemDTO) {
err := base.Tx(func(runner *dbx.TxRunner) error {
dao := RedEnvelopeItemDao{runner: runner}
po := dao.GetByUser(envelopeNo, userId)
if po != nil {
dto = po.ToDTO()
}
return nil
})
if err != nil {
return nil
}
return dto
}
//通过envelopeNo查询已抢到红包列表
func (d *itemDomain) FindItems(envelopeNo string) (itemDtos []*services.RedEnvelopeItemDTO) {
var items []*RedEnvelopeItem
err := base.Tx(func(runner *dbx.TxRunner) error {
dao := RedEnvelopeItemDao{runner: runner}
items = dao.FindItems(envelopeNo)
return nil
})
if err != nil {
return itemDtos
}
itemDtos = make([]*services.RedEnvelopeItemDTO, 0)
var luckItem *services.RedEnvelopeItemDTO
for i, po := range items {
item := po.ToDTO()
if i == 0 {
luckItem = item
} else {
if luckItem.Amount.Cmp(po.Amount) < 0 {
luckItem = item
}
}
itemDtos = append(itemDtos, item)
}
luckItem.IsLuckiest = true
return itemDtos
}
```
service.go
```package accounts
import (
"fmt"
"git.imooc.com/wendell1000/account/services"
"git.imooc.com/wendell1000/infra/base"
"github.com/kataras/iris/core/errors"
"github.com/shopspring/decimal"
"sync"
)
var _ services.AccountService = new(accountService)
var once sync.Once
func init() {
once.Do(func() {
services.IAccountService = new(accountService)
})
}
type accountService struct {
}
func (a *accountService) CreateAccount(dto services.AccountCreatedDTO) (*services.AccountDTO, error) {
domain := accountDomain{}
//验证输入参数
if err := base.ValidateStruct(&dto); err != nil {
return nil, err
}
//验证账户是否存在和幂等性
acc := domain.GetAccountByUserIdAndType(dto.UserId, services.AccountType(dto.AccountType))
if acc != nil {
return acc, errors.New(
fmt.Sprintf("用户的该类型账户已经存在:username=%s[%s],账户类型=%d",
dto.Username, dto.UserId, dto.AccountType))
}
//执行账户创建的业务逻辑
amount, err := decimal.NewFromString(dto.Amount)
if err != nil {
return nil, err
}
account := services.AccountDTO{
UserId: dto.UserId,
Username: dto.Username,
AccountType: dto.AccountType,
AccountName: dto.AccountName,
CurrencyCode: dto.CurrencyCode,
Status: 1,
Balance: amount,
}
rdto, err := domain.Create(account)
return rdto, err
}
func (a *accountService) Transfer(dto services.AccountTransferDTO) (services.TransferedStatus, error) {
//验证参数
domain := accountDomain{}
//验证输入参数
if err := base.ValidateStruct(&dto); err != nil {
return services.TransferedStatusFailure, err
}
//执行转账逻辑
amount, err := decimal.NewFromString(dto.AmountStr)
if err != nil {
return services.TransferedStatusFailure, err
}
dto.Amount = amount
if dto.ChangeFlag == services.FlagTransferOut {
if dto.ChangeType > 0 {
return services.TransferedStatusFailure,
errors.New("如果changeFlag为支出,那么changeType必须小于0")
}
} else {
if dto.ChangeType < 0 {
return services.TransferedStatusFailure,
errors.New("如果changeFlag为收入,那么changeType必须大于0")
}
}
status, err := domain.Transfer(dto)
//转账成功,并且交易主体和交易目标不是同一个人,而且交易类型不是储值,则进行反向操作
if status == services.TransferedStatusSuccess && dto.TradeBody.AccountNo != dto.TradeTarget.AccountNo && dto.ChangeType != services.AccountStoreValue {
backwardDto := dto
backwardDto.TradeBody = dto.TradeTarget
backwardDto.TradeTarget = dto.TradeBody
backwardDto.ChangeType = -dto.ChangeType
backwardDto.ChangeFlag = -dto.ChangeFlag
status, err := domain.Transfer(backwardDto)
return status, err
}
return status, err
}
func (a *accountService) StoreValue(dto services.AccountTransferDTO) (services.TransferedStatus, error) {
dto.TradeTarget = dto.TradeBody
dto.ChangeFlag = services.FlagTransferIn
dto.ChangeType = services.AccountStoreValue
return a.Transfer(dto)
}
func (a *accountService) GetEnvelopeAccountByUserId(userId string) *services.AccountDTO {
domain := accountDomain{}
account := domain.GetEnvelopeAccountByUserId(userId)
return account
}
func (a *accountService) GetAccount(accountNo string) *services.AccountDTO {
domain := accountDomain{}
return domain.GetAccount(accountNo)
}
```
envelope.go
```package gorpc
import (
"imooc.com/resk/services"
)
type EnvelopeRpc struct {
}
//Go内置的RPC接口有一些规范:
//1. 入参和出参都要作为方法参数
//2. 方法必须有2个参数,并且是可导出类型
//3. 第二个参数(返回值)必须是指针类型
//4. 方法返回值要返回error类型
//5. 方法必须是可导出的
func (e *EnvelopeRpc) SendOut(
in services.RedEnvelopeSendingDTO,
out *services.RedEnvelopeActivity) error {
s := services.GetRedEnvelopeService()
a, err := s.SendOut(in)
a.CopyTo(out)
return err
}
func (e *EnvelopeRpc) Receive(
in services.RedEnvelopeReceiveDTO,
out *services.RedEnvelopeItemDTO) error {
s := services.GetRedEnvelopeService()
a, err := s.Receive(in)
a.CopeTo(out)
return err
}
//感兴趣的同学,可以尝试使用thrift来适配用户接口
```
service.go
```package envelopes
import (
"context"
"errors"
acservices "git.imooc.com/wendell1000/account/services"
"git.imooc.com/wendell1000/infra/base"
"git.imooc.com/wendell1000/resk/services"
"github.com/shopspring/decimal"
log "github.com/sirupsen/logrus"
"sync"
)
var once sync.Once
func init() {
once.Do(func() {
services.IRedEnvelopeService = new(redEnvelopeService)
})
}
type redEnvelopeService struct {
}
//发红包
func (r *redEnvelopeService) SendOut(
dto services.RedEnvelopeSendingDTO) (activity *services.RedEnvelopeActivity, err error) {
//验证
if err = base.ValidateStruct(&dto); err != nil {
return activity, err
}
//获取红包发送人的资金账户信息
account := acservices.GetAccountService().GetEnvelopeAccountByUserId(dto.UserId)
if account == nil {
return nil, errors.New("用户账户不存在:" + dto.UserId)
}
goods := dto.ToGoods()
goods.AccountNo = account.AccountNo
if goods.Blessing == "" {
goods.Blessing = services.DefaultBlessing
}
if goods.EnvelopeType == services.GeneralEnvelopeType {
goods.AmountOne = goods.Amount
goods.Amount = decimal.Decimal{}
}
//执行发送红包的逻辑
domain := new(goodsDomain)
activity, err = domain.SendOut(*goods)
if err != nil {
log.Error(err)
}
return activity, err
}
//收红包
func (r *redEnvelopeService) Receive(dto services.RedEnvelopeReceiveDTO) (item *services.RedEnvelopeItemDTO, err error) {
//参数效验
if err = base.ValidateStruct(&dto); err != nil {
return nil, err
}
//获取当前收红包用户的账户信息
account := acservices.GetAccountService().GetEnvelopeAccountByUserId(dto.RecvUserId)
if account == nil {
return nil, errors.New("红包资金账户不存在:user_id=" + dto.RecvUserId)
}
dto.AccountNo = account.AccountNo
//进行尝试收红包
domain := goodsDomain{}
itemDomain := itemDomain{}
item = itemDomain.GetByUser(dto.RecvUserId, dto.EnvelopeNo)
if item != nil {
return item, nil
}
item, err = domain.Receive(context.Background(), dto)
return item, err
}
func (r *redEnvelopeService) Refund(envelopeNo string) (order *services.RedEnvelopeGoodsDTO) {
panic("implement me")
}
func (r *redEnvelopeService) Get(envelopeNo string) (order *services.RedEnvelopeGoodsDTO) {
domain := goodsDomain{}
po := domain.GetOne(envelopeNo)
if po == nil {
return order
}
return po.ToDTO()
}
func (r *redEnvelopeService) ListSent(userId string, page, size int) (orders []*services.RedEnvelopeGoodsDTO) {
domain := new(goodsDomain)
pos := domain.FindByUser(userId, page, size)
orders = make([]*services.RedEnvelopeGoodsDTO, 0, len(pos))
for _, p := range pos {
orders = append(orders, p.ToDTO())
}
return
}
func (r *redEnvelopeService) ListReceivable(page, size int) (orders []*services.RedEnvelopeGoodsDTO) {
domain := new(goodsDomain)
pos := domain.ListReceivable(page, size)
orders = make([]*services.RedEnvelopeGoodsDTO, 0, len(pos))
for _, p := range pos {
if p.RemainQuantity > 0 {
orders = append(orders, p.ToDTO())
}
}
return
}
func (r *redEnvelopeService) ListReceived(userId string, page, size int) (items []*services.RedEnvelopeItemDTO) {
domain := new(goodsDomain)
pos := domain.ListReceived(userId, page, size)
items = make([]*services.RedEnvelopeItemDTO, 0, len(pos))
if len(pos) == 0 {
return items
}
for _, p := range pos {
items = append(items, p.ToDTO())
}
return
}
func (r *redEnvelopeService) ListItems(envelopeNo string) (items []*services.RedEnvelopeItemDTO) {
domain := itemDomain{}
return domain.FindItems(envelopeNo)
}
```
rpc_client.go
```package main
import (
"github.com/shopspring/decimal"
"github.com/sirupsen/logrus"
"imooc.com/resk/services"
"net/rpc"
)
func main() {
c, err := rpc.Dial("tcp", ":18082")
if err != nil {
logrus.Panic(err)
}
sendout(c)
receive(c)
}
func receive(c *rpc.Client) {
in := services.RedEnvelopeReceiveDTO{
EnvelopeNo: "",
RecvUserId: "",
RecvUsername: "",
AccountNo: "",
}
out := &services.RedEnvelopeItemDTO{}
err := c.Call("Envelope.Receive", in, out)
if err != nil {
logrus.Panic(err)
}
logrus.Infof("%+v", out)
}
func sendout(c *rpc.Client) {
in := services.RedEnvelopeSendingDTO{
Amount: decimal.NewFromFloat(1),
UserId: "47692588035919872",
Username: "测试用户",
EnvelopeType: services.GeneralEnvelopeType,
Quantity: 2,
Blessing: "",
}
out := &services.RedEnvelopeActivity{}
err := c.Call("EnvelopeRpc.SendOut", in, &out)
if err != nil {
logrus.Panic(err)
}
logrus.Infof("%+v", out)
}
```
rpc_client.go
```package main
import (
"errors"
"github.com/shopspring/decimal"
"github.com/sirupsen/logrus"
"git.imooc.com/wendell1000/infra/lb"
"git.imooc.com/wendell1000/resk/services"
"net/rpc"
"strings"
)
func main() {
//conf := ini.NewIniFileConfigSource("ec_test.ini")
//client := eureka.NewClient(conf)
//client.Start()
//client.Applications, _ = client.GetApplications()
//apps := &lb.Apps{Client: client}
//c := &GoRpcClient{apps: apps}
//cs := &EnvelopeClientService{client: c, serviceId: "resk"}
//
//in := services.RedEnvelopeSendingDTO{
// Amount: decimal.NewFromFloat(1),
// UserId: "47692588035919872",
// Username: "测试用户",
// EnvelopeType: services.GeneralEnvelopeType,
// Quantity: 2,
// Blessing: "",
//}
//out, err := cs.SendOut(in)
//if err != nil {
// logrus.Panic(err)
//}
//logrus.Infof("%+v", out)
c, err := rpc.Dial("tcp", ":18082")
if err != nil {
logrus.Panic(err)
}
sendout(c)
//receive(c)
}
func receive(c *rpc.Client) {
in := services.RedEnvelopeReceiveDTO{
EnvelopeNo: "",
RecvUserId: "",
RecvUsername: "",
AccountNo: "",
}
out := &services.RedEnvelopeItemDTO{}
err := c.Call("Envelope.Receive", in, out)
if err != nil {
logrus.Panic(err)
}
logrus.Infof("%+v", out)
}
func sendout(c *rpc.Client) {
in := services.RedEnvelopeSendingDTO{
Amount: decimal.NewFromFloat(1),
UserId: "1MD35g7HA9aukHZN5VEg2kTNYYx",
Username: "测试用户",
EnvelopeType: services.GeneralEnvelopeType,
Quantity: 2,
Blessing: "",
}
out := &services.RedEnvelopeActivity{}
err := c.Call("EnvelopeRpc.SendOut", in, &out)
if err != nil {
logrus.Error(err)
}
logrus.Infof("%+v", out)
}
type GoRpcClient struct {
apps *lb.Apps
}
func (g *GoRpcClient) Call(serviceId, serviceMethod string, in interface{}, out interface{}) error {
//通过微服务名称从本地服务注册表中查询应用和应用实例列表
app := g.apps.Get(strings.ToUpper(serviceId))
if app == nil {
return errors.New("没有可用的微服务应用,应用名称:" + serviceId + ",请求:" + serviceMethod)
}
//通过负载均衡算法从应用实例列表中选择一个实例
ins := app.Get(serviceMethod)
if ins == nil {
return errors.New("没有可用的应用实例,应用名称:" + serviceId + ",请求:" + serviceMethod)
}
//选择的实例IP和端口
address := ins.Address
c, err := rpc.Dial("tcp", address)
if err != nil {
logrus.Error(err)
}
err = c.Call(serviceId, in, &out)
if err != nil {
logrus.Error(err)
}
defer c.Close()
return err
}
type EnvelopeClientService struct {
client *GoRpcClient
serviceId string
}
func (e *EnvelopeClientService) SendOut(dto services.RedEnvelopeSendingDTO) (activity *services.RedEnvelopeActivity, err error) {
activity = &services.RedEnvelopeActivity{}
err = e.client.Call(e.serviceId, "EnvelopeRpc.SendOut", dto, activity)
return
}
func (e *EnvelopeClientService) Receive(dto services.RedEnvelopeReceiveDTO) (item *services.RedEnvelopeItemDTO, err error) {
item = &services.RedEnvelopeItemDTO{}
err = e.client.Call(e.serviceId, "EnvelopeRpc.Receive", dto, item)
return
}
```
rpc.go
```package gorpc
import (
"imooc.com/resk/infra"
"imooc.com/resk/infra/base"
)
type GoRpcApiStarter struct {
infra.BaseStarter
}
func (g *GoRpcApiStarter) Init(ctx infra.StarterContext) {
base.RpcRegister(new(EnvelopeRpc))
}
```
|
969858096/lspdemo
|
969858096/lspdemo
README.md
```# lspdemo
测试创建远程项目
```
LspdemoApplication.java
```package com.lsp.lspdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LspdemoApplication {
public static void main(String[] args) {
SpringApplication.run(LspdemoApplication.class, args);
}
}
```
|
96boards-projects/zephyr_multithread_blinky
|
96boards-projects/zephyr_multithread_blinky
README.md
```# 96Boards Carbon Basic Multi Thread Example
This example demonstrates spawning of multiple threads using K_THREAD_DEFINE.
# Table of Contents
- [1) Hardware requirements](#1-hardware-requirements)
- [2) Software](#2-software)
- [2.1) Build Environment Setup](#21-build-environment-setup)
- [3) Overview](#3-overview)
- [4) Building and Running](#4-building-and-running)
- [5) Conclusion](#4-conclusion)
# 1. Hardware requirements:
1. [96Boards Carbon IE](https://www.96boards.org/product/carbon/)
# 2. Software
## 2.1 Build Environment Setup
- Follow the official Zephyr documentation to setup build environment
- [Linux](http://docs.zephyrproject.org/getting_started/installation_linux.html)
- [macOS](http://docs.zephyrproject.org/getting_started/installation_mac.html)
- [Windows](http://docs.zephyrproject.org/getting_started/installation_mac.html)
# 3. Overview
The example works by spawning three threads. The first two threads control a
separate LED. Both of these LEDs (USR1 and USR2) have their individual loop
control and timing logic defined by separate functions.
The third thread, uart_out(), sends out messages on the UART using printk().
- blink1() controls the USR1 LED that has a 100ms sleep cycle
- blink2() controls the USR2 LED that has a 1000ms sleep cycle
Each thread is then defined at compile time using K_THREAD_DEFINE.
This example is available in the upstream Zephyr Source: https://github.com/zephyrproject-rtos/zephyr/tree/master/samples/basic/threads
# 4. Building and Running
- **Compile**
```shell
$ cd zephyr_base
$ source zephyr-env.sh
$ cd samples/basic/threads
$ mkdir build
$ cd build
$ cmake -DBOARD=96b_carbon ..
$ make
```
- **Flashing via OTG**
- Connect the micro-USB cable to the USB OTG Carbon port and to your computer. The board should power ON. Force the board into DFU mode by keeping the BOOT0 switch pressed while pressing and releasing the RST switch
- You should see following confirmation on your Linux host:
```shell
$ dmesg
usb 1-2.1: new full-speed USB device number 14 using xhci_hcd
usb 1-2.1: New USB device found, idVendor=0483, idProduct=df11
usb 1-2.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
usb 1-2.1: Product: STM32 BOOTLOADER
usb 1-2.1: Manufacturer: STMicroelectronics
usb 1-2.1: SerialNumber: 3574364C3034
```
- Flash
```shell
$ sudo make flash
```
- **Running**
- Push the RST button
- You will be able to see USR1 and USR2 LEDs Flashing
- To see the UART output
- Connect the micro-USB cable to the USB UART (FTDI) port and to your computer. Run your favorite terminal program to listen for output.
```shell
minicom -D <tty_device> -b 115200
```
- Replace <tty_device> with the port where the board 96Boards Carbon can be found. For example, under Linux, /dev/ttyUSB0. The -b option sets baud rate. Press the Reset button and you should see the the following message in your terminal
# 5. Conclusion
K_THREAD_DEFINE function provides a simple way to do multi-threaded programming on an MCU on the Zephyr RTOS. However, K_THREAD_DEFINE also provides extreme combustibility and control as described in the official documentation for Kernel Threads API: http://docs.zephyrproject.org/api/kernel_api.html#threads
```
main.c
```#include <zephyr.h>
#include <device.h>
#include <gpio.h>
#include <misc/printk.h>
#include <board.h>
/* size of stack area used by each thread */
#define STACKSIZE 1024
/* scheduling priority used by each thread */
#define PRIORITY 7
/* Change this if you have an LED connected to a custom port */
#define PORT0 LED0_GPIO_PORT
#define PORT1 LED1_GPIO_PORT
/* Change this if you have an LED connected to a custom pin */
#define LED0 LED0_GPIO_PIN
#define LED1 LED1_GPIO_PIN
void blink1(void)
{
int cnt = 0;
struct device *gpioa;
gpioa = device_get_binding(PORT0);
gpio_pin_configure(gpioa, LED0, GPIO_DIR_OUT);
while (1) {
gpio_pin_write(gpioa, LED0, (cnt + 1) % 2);
k_sleep(100);
cnt++;
}
}
void blink2(void)
{
int cnt = 0;
struct device *gpiod;
gpiod = device_get_binding(PORT1);
gpio_pin_configure(gpiod, LED1, GPIO_DIR_OUT);
while (1) {
gpio_pin_write(gpiod, LED1, cnt % 2);
k_sleep(1000);
cnt++;
}
}
void uart_out(void)
{
int cnt = 1;
while (1) {
printk("Toggle USR1 LED: Counter = %d\n", cnt);
if (cnt >= 10) {
printk("Toggle USR2 LED: Counter = %d\n", cnt);
cnt = 0;
}
k_sleep(100);
cnt++;
}
}
K_THREAD_DEFINE(blink1_id, STACKSIZE, blink1, NULL, NULL, NULL,
PRIORITY, 0, K_NO_WAIT);
K_THREAD_DEFINE(blink2_id, STACKSIZE, blink2, NULL, NULL, NULL,
PRIORITY, 0, K_NO_WAIT);
K_THREAD_DEFINE(uart_out_id, STACKSIZE, uart_out, NULL, NULL, NULL,
PRIORITY, 0, K_NO_WAIT);
```
|
9728627/kongkong
|
9728627/kongkong
PostViewActivity.java
```package eduhollcs184assignments.ucsb.cs.httpwww.kongkong;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.Toolbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import static eduhollcs184assignments.ucsb.cs.httpwww.kongkong.MainActivity.Category.ALL;
import static eduhollcs184assignments.ucsb.cs.httpwww.kongkong.MainActivity.Category.SELF;
/**
* Created by scottzhu on 2017/12/3.
* Activity for all Posts.
*/
public class PostViewActivity extends AppCompatActivity {
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference rootRef = db.getReference();
DatabaseReference postRef = rootRef.child("Posts");
FloatingActionButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
setContentView(R.layout.activity_post_view);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
final List<PostViewAdapter.Post> posts;
posts = new ArrayList<>();
final RecyclerView rv = findViewById(R.id.recyclerView);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setReverseLayout(true);
llm.setStackFromEnd(true);
rv.setLayoutManager(llm);
PostViewAdapter adapter = new PostViewAdapter(posts);
rv.setAdapter(adapter);
fab = (FloatingActionButton) findViewById(R.id.fab2);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(user != null){
Intent myIntent = new Intent(PostViewActivity.this, PostActivity.class);
startActivity(myIntent);
}
else{
Toast.makeText(PostViewActivity.this, "Please sign in to unlock more features...",
Toast.LENGTH_SHORT).show();
}
}
});
postRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
HashMap<String, Object> tmp = (HashMap<String, Object>) dataSnapshot.getValue();
int likeNumber = ((ArrayList<String>) tmp.get("Like List")).size();
PostViewAdapter.Post newPost =
new PostViewAdapter.Post((String) tmp.get("Email"),
(String) tmp.get("Location"),
(String) tmp.get("Title"),
(String) tmp.get("Description"),
MainActivity.Category.toCategory((String) tmp.get("Topic")),
dataSnapshot.getKey(),
likeNumber);
Log.d("db","Email: "+tmp.get("Email"));
if(newPost.category == MainActivity.category)posts.add(newPost);
else if(MainActivity.category == ALL)posts.add(newPost);
else {
FirebaseUser nowUser = FirebaseAuth.getInstance().getCurrentUser();
if(nowUser == null) Log.d("pva", "No Account");
if(nowUser != null && MainActivity.category == SELF && newPost.email.equals(nowUser.getEmail()))posts.add(newPost);
}
PostViewAdapter adapter = new PostViewAdapter(posts);
rv.setAdapter(adapter);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private FirebaseAuth mAuth;
FirebaseUser user;
private Menu menu2;
private MenuItem loginMenu;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
this.menu2 = menu;
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
if (user == null){
loginMenu = menu2.findItem(R.id.action_logout);
MenuItem profileMenu = menu2.findItem(R.id.action_profile);
profileMenu.setEnabled(false);
loginMenu.setTitle("Login");
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if (id == R.id.action_logout) {
Intent myIntent = new Intent(PostViewActivity.this, LoginActivity.class);
startActivity(myIntent);
FirebaseAuth.getInstance().signOut();
finish();
return true;
}
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
return super.onOptionsItemSelected(item);
}
}
```
README.md
```# SpaceRenter (KongKong)
### cs184 - final project
### Group Members:
Xiao Sun, Zizhuo Lin, Zeyu Zhu, James Wang
### Product idea
* An android app that allow its user to share unused space with others.
### Who is your audience?
* We hope our first group of audience can be UCSB students and nearby residents, or… could simply be anyone.
### What problem do you solve?
* Luggage storage
* Parking lot sharing
* Pets fosterage
* Short-term lease
* Short-term Bike/Car rental
And so on …
### MORE FEATURES WILL BE ADDED
### Think about how people currently do things like you propose to be done with your app, and how your solution will improve things for your audience.
* At the end of each of quarter, students have to move out their belongings. It is hard to find a space to place their luggages and other belongings. SpaceRenter could allow people who is in demand to find someone else who is willing to rent their room in a short term.
* Some apartments in IV only provide one parking for lot for each unit, but there are more than one tenant have a car, and they need to find more parking space. SpaceRenter could allow people rent out their extra parking space to someone in demand.
* When you and your family are planning for a vacation, but worrying about no one could take care of your pets, SpaceRenter could allow its user to find someone who is responsible to take good care of your pets.
* Residence halls and some off-campus apartments would be closed during summer. SpaceRenter could help students find someone who is looking to sublease their apartment.
* If you are visiting UCSB or you want to use bike/car for a short term, you can see who is renting a bike/car. Usually, most of students will leave their bikes in apartments iv. Anyone in demand can rent them in our app.
```
PostViewAdapter.java
```package eduhollcs184assignments.ucsb.cs.httpwww.kongkong;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import static android.support.v4.content.ContextCompat.startActivity;
/**
* Created by scottzhu on 2017/12/3.
* Adapter for RecyclerView.
*/
public class PostViewAdapter extends RecyclerView.Adapter<PostViewAdapter.PostViewHolder> {
static class Post {
String email;
String location;
String title;
String desc;
String ID;
int like_number;
MainActivity.Category category;
public Post(String email, String location, String title, String desc, MainActivity.Category category, String ID, int like_number) {
this.email = email;
this.location = location;
this.title = title;
this.desc = desc;
this.category = category;
this.ID = ID;
this.like_number = like_number;
}
}
List<Post> postList;
Context context;
PostViewAdapter(List<Post> list){
postList = list;
Log.d("pva", "Created Adapter.");
}
@Override
public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_viewcard, parent, false);
context = view.getContext();
PostViewHolder holder = new PostViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(PostViewHolder holder, int position) {
final int pos = position;
holder.postEmail.setText(postList.get(position).email);
holder.postLocation.setText(postList.get(position).location);
holder.postTitle.setText(postList.get(position).title);
holder.postCategory.setText(MainActivity.Category.toString(postList.get(position).category));
String num = postList.get(position).like_number-1+"";
holder.postLike.setText(num);
holder.cv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String ID = postList.get(pos).ID;
Intent intent;
intent = new Intent(context, PostShowActivity.class);
intent.putExtra("ID", ID);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return postList.size();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView postCategory;
TextView postEmail;
TextView postLocation;
TextView postTitle;
TextView postLike;
public PostViewHolder(View itemView) {
super(itemView);
cv = itemView.findViewById(R.id.cv);
postCategory = itemView.findViewById(R.id.post_category);
postEmail = itemView.findViewById(R.id.post_email);
postLocation = itemView.findViewById(R.id.post_location);
postTitle = itemView.findViewById(R.id.post_title);
postLike = itemView.findViewById(R.id.card_like_num);
}
}
}
```
RegisterActivity.java
```package eduhollcs184assignments.ucsb.cs.httpwww.kongkong;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import static android.content.ContentValues.TAG;
public class RegisterActivity extends Activity {
private FirebaseAuth mAuth;
private EditText password;
private EditText email;
private ImageView button;
private String myEmail;
public static Toast myToast;
private FirebaseAuth.AuthStateListener mAuthListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
//this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//set content view AFTER ABOVE sequence (to avoid crash)
this.setContentView(R.layout.activity_register);
mAuth = FirebaseAuth.getInstance();
password = (EditText) findViewById(R.id.password);
email = (EditText) findViewById(R.id.email);
button = (ImageView) findViewById(R.id.registerButton);
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
// NOTE: this Activity should get onpen only when the user is not signed in, otherwise
// the user will receive another verification email.
sendVerification();
} else {
// User is signed out
}
// ...
}
};
}
public void createAccount(View view) {
final Animation myAnim = AnimationUtils.loadAnimation(RegisterActivity.this, R.anim.bounce);
// Use bounce interpolator with amplitude 0.2 and frequency 20
MyBounceInterpolator interpolator = new MyBounceInterpolator(0.2, 20);
myAnim.setInterpolator(interpolator);
button.startAnimation(myAnim);
myEmail = email.getText().toString();
final String myPass = password.getText().toString();
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(myEmail) && !isPasswordValid(myPass)) {
Toast.makeText(RegisterActivity.this, "Password must contain at least 6 characters",
Toast.LENGTH_SHORT).show();
}
// Check for a valid email address.
else if (TextUtils.isEmpty(myEmail)) {
Toast.makeText(RegisterActivity.this, "Cannot be empty",
Toast.LENGTH_SHORT).show();
}
/*else if (!isEmailValid(myEmail)) {
Toast.makeText(RegisterActivity.this, "Invalid email address",
Toast.LENGTH_SHORT).show();
}*/
else {
button.setEnabled(false);
mAuth.createUserWithEmailAndPassword(myEmail, myPass)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//Toast.makeText(RegisterActivity.this, "Success",Toast.LENGTH_SHORT).show();
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "createUserWithEmail:success");
//FirebaseUser user = mAuth.getCurrentUser();
//updateUI(user);
mAuth.addAuthStateListener(mAuthListener);
} else {
button.setEnabled(true);
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(RegisterActivity.this, "Failed to create user:" + task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
public void sendVerification() {
final FirebaseUser user = mAuth.getCurrentUser();
user.sendEmailVerification()
.addOnCompleteListener(this, new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(RegisterActivity.this,
"Verification email sent to " + user.getEmail(),
myToast.LENGTH_SHORT).show();
System.out.println(user.getEmail());
Intent myIntent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(myIntent);
finish();
//prevent the onAuthState in registerActivity will go over again and send another email
mAuth.removeAuthStateListener(mAuthListener);
} else {
Log.e(TAG, "sendEmailVerification", task.getException());
Toast.makeText(RegisterActivity.this,
"Failed to send verification email.",
myToast.LENGTH_SHORT).show();
}
}
});
}
private boolean isPasswordValid(String password) {
return password.length() > 5;
}
@Override
public void onStart() {
super.onStart();
}
public void changeAct(View view) {
Intent myIntent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(myIntent);
finish();
}
//anonymous login
public void anonymousLogin(View view) {
FirebaseAuth.getInstance().signOut();
Intent myIntent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(myIntent);
//finish();
}
//reset password
public void reset(View view){
Intent myIntent = new Intent(RegisterActivity.this, ResetPassActivity.class);
startActivity(myIntent);
}
}
```
PostActivity.java
```package eduhollcs184assignments.ucsb.cs.httpwww.kongkong;
import android.*;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import org.w3c.dom.Text;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
public class PostActivity extends AppCompatActivity {
int DATE_PICKER = 999;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference rootRef = db.getReference();
DatabaseReference postRef = rootRef.child("Posts");
FirebaseAuth myAuth = FirebaseAuth.getInstance();
String email = myAuth.getCurrentUser().getEmail();
TextView dateView;
int year, month, day;
private Calendar calendar;
EditText Title, Location, Email, Description;
ImageView button;
ImageView post;
String pic_uri;
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference mStorage = storage.getReference();
private static final int GALLERY = 4;
//spinner for different topics
//Spinner spinner;
//ArrayAdapter<CharSequence> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
if (ContextCompat.checkSelfPermission(PostActivity.this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(PostActivity.this, new String[] { android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.choices, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
Title = (EditText) findViewById(R.id.titleeditText);
Location = (EditText) findViewById(R.id.locationeditText3);
//Email = (EditText) findViewById(R.id.emaileditText4);
Description = (EditText) findViewById(R.id.deseditText5);
button = (ImageView) findViewById(R.id.postbutton);
post = (ImageView) findViewById(R.id.button3);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
post.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,GALLERY);
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Animation myAnim = AnimationUtils.loadAnimation(PostActivity.this, R.anim.bounce);
// Use bounce interpolator with amplitude 0.2 and frequency 20
MyBounceInterpolator interpolator = new MyBounceInterpolator(0.2, 20);
myAnim.setInterpolator(interpolator);
button.startAnimation(myAnim);
String t = Title.getText().toString();
String l = Location.getText().toString();
String d = Description.getText().toString();
String s = spinner.getSelectedItem().toString();
//get start and end date
dateView = (TextView) findViewById(R.id.startDate);
String sdate = dateView.getText().toString();
dateView = (TextView) findViewById(R.id.endDate);
String edate = dateView.getText().toString();
//check any missing field
if(TextUtils.isEmpty(t) || TextUtils.isEmpty(l)||TextUtils.isEmpty(d) ||
sdate.equals("Please Select") || edate.equals("Please Select") || s.equals("Please select a topic..."))
{
Toast.makeText(getApplicationContext(), "Missing information",
Toast.LENGTH_LONG).show();
return;
}
//check date
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = new Date();
Date endDate = new Date();
try {
startDate = df.parse(sdate);
endDate = df.parse(edate);
} catch (ParseException e) {
e.printStackTrace();
}
if(startDate.after(endDate)){
Toast.makeText(getApplicationContext(), "Start date is after end date",
Toast.LENGTH_LONG).show();
return;
}
String p = pic_uri;
ArrayList<String> like_list = new ArrayList<String>();
like_list.add("initial");
HashMap<String,Object> posts_map = new HashMap<>();
posts_map.put("Title", t);
posts_map.put("Location", l);
posts_map.put("Email", email);
posts_map.put("Description", d);
posts_map.put("Topic", s);
posts_map.put("PictureUri", p);
posts_map.put("Start Date", sdate);
posts_map.put("End Date", edate);
posts_map.put("Like List", like_list);
postRef.push().setValue(posts_map);
Intent myIntent = new Intent(PostActivity.this, MainActivity.class);
startActivity(myIntent);
}
});
}
@SuppressWarnings("deprecation")
public void setDate(View view){
dateView = (TextView) view;
showDialog(DATE_PICKER);
}
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == DATE_PICKER) {
return new DatePickerDialog(this,
myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new
DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0,
int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
private void showDate(int year, int month, int day) {
StringBuilder date = new StringBuilder();
if (month < 10){
date.append("0");
}
date.append(month).append("/");
if (day < 10){
date.append("0");
}
date.append(day).append("/");
date.append(year);
dateView.setText(date);
}
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY) {
Uri uri;
if (data != null) {
uri = data.getData();
//Log.i("uriiiiii",String.valueOf(uri.getLastPathSegment()));
pic_uri = String.valueOf(uri.getLastPathSegment() + ".jpg");
post.setImageURI(uri);
//StorageReference fileName = mStorage.child("Photos/" + uri.getLastPathSegment() + ".png");
StorageReference fileName = mStorage.child("images/" + uri.getLastPathSegment() + ".jpg");
UploadTask up = fileName.putFile(uri);
up.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
}
});
}
else
return;
}
}
}
```
SplashScreen.java
```package eduhollcs184assignments.ucsb.cs.httpwww.kongkong;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class SplashScreen extends AppCompatActivity {
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash_screen);
}
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
//updateUI(currentUser);
if (currentUser != null && currentUser.isEmailVerified()){
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent myIntent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(myIntent);
finish();
Toast.makeText(SplashScreen.this, "Already In", Toast.LENGTH_SHORT).show();
}
},3000); // 3000 = 3seconds
}
else{
//Toast.makeText(this, "Register Page", Toast.LENGTH_SHORT).show();
//Wait for 2 seconds and start Activity Main
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
SplashScreen.this.startActivity(new Intent(SplashScreen.this,RegisterActivity.class));
SplashScreen.this.finish();
}
},3000); // 3000 = 3seconds
}
}
}
```
LoginActivity.java
```package eduhollcs184assignments.ucsb.cs.httpwww.kongkong;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import static android.content.ContentValues.TAG;
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText password;
private EditText email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification
//this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
password = (EditText) findViewById(R.id.editTextPassword);
email = (EditText) findViewById(R.id.editTextEmail);
//check the email and password is not empty
}
public void signIn(View view) {
ImageView login = (ImageView) findViewById(R.id.buttonSignin);
final Animation myAnim = AnimationUtils.loadAnimation(LoginActivity.this, R.anim.bounce);
// Use bounce interpolator with amplitude 0.2 and frequency 20
MyBounceInterpolator interpolator = new MyBounceInterpolator(0.2, 20);
myAnim.setInterpolator(interpolator);
login.startAnimation(myAnim);
final String myEmail = email.getText().toString();
final String myPass = password.getText().toString();
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(myEmail) && !isPasswordValid(myPass)) {
Toast.makeText(LoginActivity.this, "Password must contain at least 6 characters",
Toast.LENGTH_SHORT).show();
}
// Check for a valid email address.
else if (TextUtils.isEmpty(myEmail)) {
Toast.makeText(LoginActivity.this, "Cannot be empty",
Toast.LENGTH_SHORT).show();
}
else if (!isEmailValid(myEmail)) {
Toast.makeText(LoginActivity.this, "Invalid email address",
Toast.LENGTH_SHORT).show();
}
else {
mAuth.signInWithEmailAndPassword(myEmail, myPass)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
// Sign in success, update UI with the signed-in user's information
if (user!=null && user.isEmailVerified()){
Log.d(TAG, "signInWithEmail:success");
//FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
Toast.makeText(LoginActivity.this, "Success",
Toast.LENGTH_SHORT).show();
Log.i("User", "User" + user);
Log.i("UserID", "UserID" + userID);
Intent myIntent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(myIntent);
finish();
}else{
Toast.makeText(LoginActivity.this, "Email not verified",
Toast.LENGTH_SHORT).show();
}
}
else{
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
Toast.makeText(LoginActivity.this, "Invalid email address or password",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
}
private boolean isEmailValid(String email) {
return (email.contains("@"));
}
private boolean isPasswordValid(String password) {
return password.length() > 5;
}
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
//if (RegisterActivity.myToast == null) {
//RegisterActivity.myToast.makeText(this, "Login Page", Toast.LENGTH_SHORT).show();
//}
}
public void changeAct(View view){
Intent myIntent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(myIntent);
finish();
}
//anonymous login
public void anonymousLogin(View view){
FirebaseAuth.getInstance().signOut();
Intent myIntent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(myIntent);
//finish();
}
//reset password
public void reset(View view){
Intent myIntent = new Intent(LoginActivity.this, ResetPassActivity.class);
startActivity(myIntent);
}
}
```
ResetPassActivity.java
```package eduhollcs184assignments.ucsb.cs.httpwww.kongkong;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
public class ResetPassActivity extends AppCompatActivity {
private EditText email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
//this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
setContentView(R.layout.activity_reset_pass);
email = (EditText) findViewById(R.id.editTextEmail2);
}
public void resetPassword(View view){
final String myEmail = email.getText().toString();
// Check for a valid email address.
if (TextUtils.isEmpty(myEmail)) {
Toast.makeText(ResetPassActivity.this, "Cannot be empty",
Toast.LENGTH_SHORT).show();
}
else if (!isEmailValid(myEmail)) {
Toast.makeText(ResetPassActivity.this, "Invalid email address",
Toast.LENGTH_SHORT).show();
}
else {
FirebaseAuth auth = FirebaseAuth.getInstance();
auth.sendPasswordResetEmail(myEmail)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
// do something when mail was sent successfully.
Toast.makeText(ResetPassActivity.this,
"Reset password email sent",
Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(ResetPassActivity.this, LoginActivity.class);
startActivity(myIntent);
finish();
} else {
Toast.makeText(ResetPassActivity.this, "Failed to send:" + task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
// ...
}
}
});
}
}
private boolean isEmailValid(String email) {
return (email.contains("@"));
}
//anonymous login
public void anonymousLogin(View view){
FirebaseAuth.getInstance().signOut();
Intent myIntent = new Intent(ResetPassActivity.this, MainActivity.class);
startActivity(myIntent);
//finish();
}
//change to sign in page
public void changeAct(View view) {
Intent myIntent = new Intent(ResetPassActivity.this, LoginActivity.class);
startActivity(myIntent);
finish();
}
}
```
PostShowActivity.java
```package eduhollcs184assignments.ucsb.cs.httpwww.kongkong;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageException;
import com.google.firebase.storage.StorageReference;
import org.w3c.dom.Text;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class PostShowActivity extends AppCompatActivity {
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference rootRef = db.getReference();
DatabaseReference postRef = rootRef.child("Posts");
FirebaseAuth mAuth = FirebaseAuth.getInstance();
TextView title;
TextView author;
TextView location;
TextView content;
TextView time;
ImageButton email;
ImageButton like;
ImageView picshow;
ArrayList<String> like_list;
TextView like_number;
Bitmap pic;
String p;
Button delete;
final String[] author_email = new String [1];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
setContentView(R.layout.activity_post_show);
title = (TextView) findViewById(R.id.postview_title);
author = (TextView) findViewById(R.id.postview_author);
location = (TextView) findViewById(R.id.postview_location);
content = (TextView) findViewById(R.id.postview_content);
time = (TextView) findViewById(R.id.available_time);
email = (ImageButton) findViewById(R.id.email_button);
picshow =(ImageView) findViewById(R.id.picshow);
delete = (Button) findViewById(R.id.delete_button);
like= (ImageButton) findViewById(R.id.like_button);
like_number = (TextView) findViewById(R.id.likeNumber);
final String[] userEmail = new String[1];
if(mAuth.getCurrentUser() != null){
userEmail[0]=mAuth.getCurrentUser().getEmail();
}
else{
userEmail[0]="";
Toast.makeText(getApplicationContext(), "You need to login to see pictures", Toast.LENGTH_LONG).show();
}
Intent intent = getIntent();
final String post_id = intent.getStringExtra("ID");
postRef.orderByKey().equalTo(post_id).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
HashMap<String,Object> tmp = (HashMap<String,Object>) ds.getValue();
title.setText((String) tmp.get("Title"));
author.setText((String)tmp.get("Email"));
author_email[0] = (String) tmp.get("Email");
location.setText((String) tmp.get("Location"));
content.setText((String) tmp.get("Description"));
String ava_time = tmp.get("Start Date") + " to " + tmp.get("End Date");
time.setText(ava_time);
like_list = (ArrayList<String>) tmp.get("Like List");
String like_num = like_list.size()-1 + "";
like_number.setText(like_num);
p = (String) tmp.get("PictureUri");
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference mStorage = storage.getReference();
StorageReference islandRef = mStorage.child("images/" + p);
/*
try {
final File localFile = File.createTempFile("Images", "bmp");
islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
// Local temp file has been created
pic = BitmapFactory.decodeFile(localFile.getAbsolutePath());
picshow.setImageBitmap(pic);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
}
});
}
catch (IOException e) {
e.printStackTrace();
}
*/
final long ONE_MEGABYTE = 2048 * 2048;
islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
@Override
public void onSuccess(byte[] bytes) {
// Data for "images/island.jpg" is returns, use this as needed
System.out.println("picture loaded");
pic = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
picshow.setImageBitmap(pic);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
}
});
if (userEmail[0].equals(author_email[0]) == false){
delete.setVisibility(View.INVISIBLE);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
email.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent emailIntent = new Intent(Intent.ACTION_SEND);
System.out.println(author_email[0]);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{author_email[0]});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Message From Kong");
emailIntent.putExtra(Intent.EXTRA_TEXT, "I am interested in your post ...");
emailIntent.setType("message/rfc882");
startActivity(Intent.createChooser(emailIntent, "Choose email client..."));
}
});
final Context context = getApplicationContext();
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = (String) delete.getText();
if(text.equals("Delete")){
delete.setText("Confirm");
}
else if(text.equals("Confirm")){
DatabaseReference delete_node = postRef.child(post_id);
delete_node.removeValue();
Toast.makeText(context, "Post deleted", Toast.LENGTH_SHORT).show();
Intent backIntent =new Intent(context, MainActivity.class);
context.startActivity(backIntent);
}
}
});
if (mAuth.getCurrentUser() == null){
like.setEnabled(false);
}
like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatabaseReference likeRef = postRef.child(post_id).child("Like List");
if(like_list.contains(userEmail[0])){
like_list.remove(userEmail[0]);
}
else like_list.add(userEmail[0]);
likeRef.setValue(like_list);
String like_num = like_list.size()-1 + "";
like_number.setText(like_num);
}
});
}
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), PostViewActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
}
```
|
9759176595/DATA-Structure
|
9759176595/DATA-Structure
bubblesort.c
```#include<stdio.h>
int main()
{
int n,temp;
printf("Enter the no of array elements:\n");
scanf("%d",&n);
int arr[n];
printf("Enter the elements:\n");
for (int i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}
for (int i = 0; i < n-1; i++)
{
for (int j = 0; j < n-1; j++)
{
if(arr[j]>arr[j+1])
{temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf("Sorted elements are:\n");
for (int i = 0; i < n; i++)
{
printf("%d\n",arr[i] );
}
}```
leafcount.c
```#include<stdio.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
int getleafCount(struct node *node)
{
if(node==NULL)
{
return 0;
}
if(node->left==NULL && node->right==NULL)
return 1;
else
return getleafCount(node->left)+getleafCount(node->right);
}
struct node *newnode(int data)
{
struct node *node=(struct node*)malloc(sizeof(struct node));
node->data=data;
node->left=NULL;
node->right=NULL;
return(node);
}
int main()
{
struct node *root=newnode(1);
root->left=newnode(2);
root->right=newnode(5);
root->left->left=newnode(7);
root->left->right=newnode(9);
printf("leaf count of tree is %d\n",getleafCount(root) );
return 0;
}```
tree1.c
```#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *left, *right;
};
struct node *create()
{
int x;
struct node *newnode;
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter data or -1 for no data\n");
scanf("%d",&x);
if(x==-1)
{
return 0;
}
else
{
newnode->data=x;
printf("Enter left child of %d\n",x );
newnode->left=create();
printf("Enter right child of %d\n",x );
newnode->right=create();
return newnode;
}
}
void main()
{
struct node *root;
root=0;
root=create();
}```
mergesort.c
```#include<stdio.h>
void mergeSort(int [],int ,int );
void merge(int[],int ,int ,int);
void main()
{
int a[10]={10,9,7,101,23,44,12,78,34,23};
int i;
mergeSort(a,0,9);
printf("The sorted elements are:\n");
for (int i = 0; i < 10; i++)
{
printf("%d\n",a[i] );
}
}
void mergeSort(int a[],int beg,int end)
{
int mid;
if(beg<end)
{
mid=(beg+end)/2;
mergeSort(a,beg,mid);
mergeSort(a,mid+1,end);
merge(a,beg,mid,end);
}
}
void merge(int a[],int beg,int mid,int end)
{
int i=beg,j=mid+1,k,index=beg;
int temp[10];
while(i<=mid && j<=end)
{
if(a[i]<a[j])
{
temp[index]=a[i];
i=i+1;
}
else
{
temp[index]=a[j];
j=j+1;
}
index++;
}
if(i>mid)
{
while(j<=end)
{
temp[index]=a[i];
index++;
i++;
}
}
k=beg;
while(k<index)
{
a[k]=temp[k];
k++;
}
}```
quicksort.c
```#include<stdio.h>
int partition(int a[],int beg,int end);
void quickSort(int a[],int beg,int end);
void main()
{
int arr[10]={90,23,101,45,65,23,67,89,34,23};
quickSort(arr,0,9);
printf("the sorted array is :");
for (int i = 0; i < 10; i++)
{
printf("%d\n",arr[i] );
}
}
int partition(int a[],int beg,int end)
{
int left,right,temp,loc,flag;
loc=left=beg;
right=end;
flag=0;
while(flag!=1)
{
while((a[loc]<=a[right])&&(loc!=right))
right--;
if(loc==right)
flag=1;
else if(a[loc]>a[right])
{
temp=a[loc];
a[loc]=a[right];
a[right]=temp;
loc=right;
}
if(flag!=1)
{
while((a[loc]>=a[left])&&(loc!=left))
left++;
if(loc==left)
flag=1;
else if(a[loc]<a[left])
{
temp=a[loc];
a[loc]=a[left];
a[left]=temp;
loc=left;
}
}
}
return loc;
}
void quickSort(int a[],int beg,int end)
{
int loc;
if(beg<end)
{
loc=partition(a,beg,end);
quickSort(a,beg,loc-1);
quickSort(a,loc+1,end);
}
}```
treetraversal.c
```#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *left;
struct node *right;
}node;
struct node *create()
{
int x;
struct node *newnode;
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter data or -1 for no data\n");
scanf("%d",&x);
if(x==-1)
{
return 0;
}
else
{
newnode->data=x;
printf("Enter left child of %d\n",x );
newnode->left=create();
printf("Enter right child of %d\n",x );
newnode->right=create();
return newnode;
}
}
void traverse(node *t)
{
if(!t==NULL)
{
printf("left child data is %d\n",t->data );
traverse(t->left);
t=t->right;
}
if(!t==NULL)
{
printf("right child data is %d\n",t->data );
traverse(t->right);
}
}
// void inorder(node *t)
// {
// if(t)
// {
// inorder(t->left);
// printf("%d\n",t->data );
// inorder(t->right);
// }
// }
// void preorder(node *t)
// {
// if(t)
// {
// printf("%d\n",t->data );
// preorder(t->left);
// preorder(t->right);
// }
// }
void postorder(node *t)
{
if(t)
{
postorder(t->left);
postorder(t->right);
printf("%d\n",t->data );
}
}
int main()
{
node *root=create();
node *t=root;
printf("root child is %d\n",t->data );
traverse(t);
//inorder(t);
//preorder(t);
postorder(t);
printf("is the order traversal\n");
return 0;
}```
insertionsort.c
```#include<stdio.h>
#include<stdlib.h>
int main()
{
int arr[4]={5,4,6,2};
int i,key;
for (int j = 2; j < 4; j++)
{
key=arr[j];
i=j-1;
while(i>0&& arr[i]>key)
{
arr[i+1]=arr[i];
i=i-1;
}
arr[i+1]=key;
//printf("the key element is %d\n",arr[i+1] );
}
for (int i = 0; i < 4; i++)
{
printf("%d\n",arr[i] );
}
}
```
heightoftree.c
```#include<stdio.h>
typedef struct node
{
int data;
struct node *left;
struct node *right;
}Node;
Node *create()
{
int x;
Node *newnode=(Node *)malloc(sizeof(Node));
printf("Enter data for node(-1 for no data)\n");
scanf("%d",&x);
if(x==-1)
{
return 0;
}
newnode->data=x;
printf("Enter the left child of node rooted at %d\n", newnode->data);
newnode->left=create();
printf("Enter the right child of node rooted at %d\n", newnode->data);
newnode->right=create();
return(newnode);
}
void traverse(Node *t)
{
if(!t==NULL)
{
printf("left child data is %d\n",t->data );
traverse(t->left);
t=t->right;
}
if(!t==NULL)
{
printf("right child data is %d\n",t->data );
traverse(t->right);
}
}
int H(Node *t)
{
int I,r,max;
if(!t)
{
return 0;
}
else if(!(t->left)&& !(t->right))
{
return 0;
}
else
I=H(t->left);
r=H(t->right);
int p=I>r?I:r;
printf("the height is %d\n",p );
return(1+p);
}
int main()
{
int height;
Node *root=create();
printf("root child is %d\n",root->data );
traverse(root);
height=H(root);
printf("the height is %d\n",height );
return 0;
}```
|
97hajerahmeda97/RC4
|
97hajerahmeda97/RC4
main.cpp
```#define MAX 65534
#include <string>
#include<stdio.h>
#include<time.h>
#include <ctype.h>
#include <iostream>
#include <string.h>
using namespace std;
char cryptotext[MAX];
char plaintext[MAX];
int keystream[MAX];
int main()
{ char text[256],t[256];
int s[256];
cout<<"enter plain text:";
cin.getline(text,255);
int textlength = strlen(text);
for(int i = 0; i < 256; i++){
s[i] = i;
}
int n,ss,u=0;
char key[256];
cout<<endl;
cout<<"enter key:";
cin.getline(key,255);
n= strlen(key);
ss=n;
if(ss<256)
{
for(int i=0;i<256;i++)
{
if(u<ss)
{
t[i]=key[u];
u++;
}
else{u=0;
i--;
}
}
}
int temp,j=0;
for(int i = 0; i < 256; i++){
j = (j + s[i] + t[i]) % 256;
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
int z=textlength;
int a=0,b=0,c, tt,index = 0;
while(z>0){
a= (a+1)%256;
b = (b + s[a]) % 256;
c = s[a];
s[a] = s[b];
s[b] = c;
tt = (s[a] + s[b]) % 256;
keystream[index] = s[tt];
index ++;
z--;
}
for(int i = 0; i < textlength; i++){
cryptotext[i] = char(keystream[i] ^ int(text[i])); // تشفير
}
cout<<endl;
cout<<"keys XOR ciphertext"<<endl;
for(int i = 0; i < textlength; i++){
cout<<keystream[i]<<" "<<(keystream[i] ^ int(text[i]))<<" "<<cryptotext[i]<<endl;
}
cout<<endl;
cout<<"--------------plain text:-------------------------";
for(int i = 0; i < textlength; i++){
plaintext[i] = char(keystream[i] ^ cryptotext[i]); // فك تشفير
}
for(int i = 0; i < textlength; i++){
cout<<plaintext[i];
}
// ============ اكتمال فك التشفير ============
return 0;}
```
|
99002592/GenesisSubmission
|
99002592/GenesisSubmission
Requirements.md
```Requirement Analysis:
High level requirements:
|ID|Description|
|---|-----------|
|001|Should perform accurate calculations|
|002|Easy user-interface|
|003|Result should be instantly displayed|
|004|Should perform all basic arithmetic calculations|
|005|Should have ability to perform certain scientific calculations|
Low level requirements:
|ID| Description|
|---|---|
|001| Calculator should have multi-step input capability|
|002| Ability to store the last 5 results|
|003| Scientific calculations should enable only certain inputs|
|004| Can perform logical (bitwise) operations|
|005| Effective stack operation|
```
README.md
```# GenesisSubmission
[](https://app.codacy.com/manual/99002592/GenesisSubmission?utm_source=github.com&utm_medium=referral&utm_content=99002592/GenesisSubmission&utm_campaign=Badge_Grade_Dashboard)



```
TestPlan.md
```Test Plan:
|ID| Description| Pre-condition| Expected input| Expected output| Actual output|
|---|---|---|---|---|---|
|001| Arithmetic operation between two large numbers| Numbers are fed as input| Two large numbers| Result exceeded maximum size|
|002 |Division by zero |Two numbers are divided |Divisor is always zero |Display error message|
|003| Order of precedence of arithmetic operations| Arithmetic operation is performed| Two arithmetic operations with brackets| Expression within brackets is evaluated first|
|004 |Subtraction resulting in negative number |Subtraction to be performed |Subtract a larger number from a smaller number| Negative number should be displayed |
|005| Displaying float values| Enter float numbers| Number like 1.8 is entered | Number is not rounded off to 2 and 1.8 is displayed|
```
|
99003513/task-2c
|
99003513/task-2c
README.md
```# task-2c
phani documents for calculator
1.what is Calculator?
• A Calculator is a simple electronic hardware device or a software capable of performing the simple calculations such as addition,multiplications,subtraction,division,finding square roots,percentages and conversions etc.
• In 1957,the Casio computer company developed the first electronic calculator.
• A simple numeric keypad is present to enter the numbers into the calculator.
• Calculators can also built into most operating systems on computers,smart phones and also tablets.
2.Where we use Scientific Calculator?
• Examination halls
• Colleges
• Computers
• Labs
3.When we use calculators?
Calculators are useful during examinations for getting complex calculations in very less time. For finding trigonometric values, hyperbolic functions, inverses. While calculating bills in malls and restaurants, these calculators are very useful. Engineering students will use this type of calculator to do complex operations on power values, exponentials etc.
4.Why we use calculators?
• Complex calculations are very tough to calculate in less time.So this scientific calculator is useful for all operations.
• To get the results very accurately.
• To save our valuable time.
• Saves human power.
How to make the Scientific calculator?
Input will be given by the user from the keyboard and the result will be displayed to the screen i,e output will be on the screen.
1. Write the code for all the requirements.
2. Use one programming language for coding the required functions.
3. Use ‘C’ programming language for the purpose of coding to make this scientific calculators.
4. Use github and visual studio for making and building file for required specifications.
5. Use electronic hardware to embedded code into the processor.
6. Check correctly of all functionalities.
```
|
99050823/Week-3---pizza-calculator
|
99050823/Week-3---pizza-calculator
README.md
```# Week 3 - pizza calculator
JS opdracht
```
|
999946/px2rpx-loader
|
999946/px2rpx-loader
px2rpx-loader.js
```var loaderUtils = require('loader-utils')
var Px2rpx = require('px2rpx')
module.exports = function (source, target) {
var options = loaderUtils.getOptions(this);
var px2rpxOptions = options;
for(var index in options.patterns) {
const pattern = options.patterns[index];
if(target.file && new RegExp(pattern.test).test(target.file)) {
px2rpxOptions = pattern.options;
break;
}
}
var px2rpxIns = new Px2rpx(px2rpxOptions);
return px2rpxIns.generaterpx(source);
}
```
|
9Hua/ife_layout_assignment_D7-BC-18_8_9
|
9Hua/ife_layout_assignment_D7-BC-18_8_9
label_action.js
```var labels = document.querySelectorAll('#banner li a');
var imgs = document.querySelectorAll('#banner img');
var navs = document.querySelectorAll('nav li a');
{
for (i = 0; i < labels.length; i++) {
var label = labels[i];
setLabelHandler(label, i);
}
function setLabelHandler(label, labelPos) {
label.onclick = function () {
for (i = 0; i < labels.length; i++) {
if (labels[i].getAttribute('class')) {
labels[i].removeAttribute('class');
}
}
label.setAttribute('class', 'active');
for (i = 0; i < imgs.length; i++) {
if (imgs[i].getAttribute('class')) {
imgs[i].removeAttribute('class');
}
}
imgs[labelPos].setAttribute('class', 'active-picture');
}
}
}
{
for (i = 0; i < navs.length; i++) {
var nav = navs[i];
setLabelHandler(nav, i);
}
function setLabelHandler(nav, navPos) {
nav.onclick = function () {
for (i = 0; i < navs.length; i++) {
if (navs[i].getAttribute('class')) {
navs[i].removeAttribute('class');
}
}
nav.setAttribute('class', 'active');
}
}
}```
|
9Mert/first-step
|
9Mert/first-step
README.md
```# first-step
A simply demo repository to known basics!
```
|
9oh9/9oh9-blog
|
9oh9/9oh9-blog
app.js
```var ghost = require('ghost'),
path = require('path');
var app = ghost({
config: path.join(__dirname, 'config.js')
});
if(require.main === module){
app.then(function (ghostServer) {
ghostServer.start();
});
}
else {
module.exports = app;
}
```
www
```#!/usr/bin/env nodejs
var app = require('../app');
app.then(function (ghostServer){
ghostServer.start();
});
```
README.md
```# 9oh9-blog
Blog for all things 9oh9.
```
|
A-Alaa/rails-task-panel-wbsockets
|
A-Alaa/rails-task-panel-wbsockets
routes.rb
```Rails.application.routes.draw do
resources 'algorithms'
root 'algorithms#index'
mount ActionCable.server => 'cable'
end
```
README.md
```# README
This is an example application for using WebSockets instead of half-duplex HTTP polling.
### Prerequisites
* Ruby language
* Gem bundler
* Rails v5.2
### Usage
```bash
git clone https://github.com/A-Alaa/rails-task-panel-wbsockets.git
cd rails-task-panel-wbsockets
bundle install
rails db:reset && rails s
```
Open the application at [http://localhost:3000/](http://localhost:3000/)
```
algorithm.rb
```class Algorithm < ApplicationRecord
before_save :default_values
after_create_commit { RunAlgorithmJob.perform_later self }
after_update {StatusUpdateJob.perform_later self}
def default_values
self.input ||= "Chr#{ rand(1..46) }"
self.duration ||= rand(1..6)
self.status ||= 'pending'
end
end
```
run_algorithm_job.rb
```class RunAlgorithmJob < ApplicationJob
queue_as :default
def perform(algorithm)
# Heavy task
sleep algorithm.duration.to_i
algorithm.status = "ready"
algorithm.save!
end
end
```
status_update_job.rb
```class StatusUpdateJob < ApplicationJob
queue_as :default
def perform(algorithm)
ActionCable.server.broadcast 'status_channel', updated_algorithm: algorithm
end
end
```
algorithms_controller.rb
```class AlgorithmsController < ApplicationController
def index
puts Algorithm.all
@algorithms = Algorithm.all
end
def new
@algorithm = Algorithm.new
end
def create
@algorithm = Algorithm.create!
redirect_to algorithms_path
end
end
```
algorithms_controller_test.rb
```require 'test_helper'
class AlgorithmsControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get algorithms_index_url
assert_response :success
end
test "should get create" do
get algorithms_create_url
assert_response :success
end
test "should get new" do
get algorithms_new_url
assert_response :success
end
end
```
|
A-Crofoot/ECE351_Code
|
A-Crofoot/ECE351_Code
Lab_0.py
```
################################################################
# #
# Austin W. Crofoot #
# ECE 351-53 #
# Due 1/26/2021 #
# #
################################################################
import numpy
import matplotlib.pyplot
import scipy
import control
import pandas```
README.md
```# ECE351_Code
Python Code for all ECE351 Labs.
```
|
A-Mehdi/Intro-To-AI-Team-Project
|
A-Mehdi/Intro-To-AI-Team-Project
Test.py
```import os
import cv2
from models.Test_Config import Face2Cartoon
if __name__ == '__main__':
Input_path = './test_images/'
Save_path = './save_images/'
filename_list = os.listdir(Input_path)
for i in filename_list:
save_name = i.split('.')[0] + '.png'
img = cv2.cvtColor(cv2.imread(f'./test_images/{i}'), cv2.COLOR_BGR2RGB)
c2p = Face2Cartoon()
cartoon = c2p.inference(img)
if cartoon is not None:
cv2.imwrite(Save_path + save_name, cartoon)```
__init__.py
```from .CycleGanConfig import ResnetGenerator
from .Config import GanConfig
from .Test_Config import Face2Cartoon
from .Notebook_Config import Notebook_GanConfig
```
README.md
```Intro-To-AI-TeamProject
=========================
How to Test
---------------------------------------------------------------------------
1. Put input images into test_images folder
2. Use Test.py for test
Or use train_notebook.ipynb and run test cell for test
3. Test result images will be saved in save_images folder.
---------------------------------------------------------------------------
Models
---------------------------------------------------------------------------------------------
* Our final trained model is saved in train_model folder named "face2cartoon_params_latest.pt".
* Other models are saved for comparison.
---------------------------------------------------------------------------------------------
Results
-------------------------------------------------------------------------------------------
1. FID score: 140.7905003784768 for 30000 epoch from scratch without additional male pictures.
2. FID score: 90.23898659001463 pretrained+60000 epoch with additional male pictures.
3. FID score: 78.01624949505901 pretrained model without any modification.
-------------------------------------------------------------------------------------------
```
Data_load.py
```import torch.utils.data as data
from PIL import Image
import os
import os.path
def has_file_allowed_extension(filename, extensions):
file_lower = filename.lower()
return any(file_lower.endswith(ext) for ext in extensions)
def find_classes(dir):
classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
classes.sort()
classes_to_id_ = {classes[i]: i for i in range(len(classes))}
return classes, classes_to_id_
def make_dataset(dir, extensions):
imgs = []
for root, _, filenames in sorted(os.walk(dir)):
for fname in sorted(filenames):
if has_file_allowed_extension(fname, extensions):
path = os.path.join(root, fname)
item = (path, 0)
imgs.append(item)
return imgs
class DatasetFolder(data.Dataset):
def __init__(self, root, loader, extensions, transform=None, target_transform=None):
samples = make_dataset(root, extensions)
if len(samples) == 0:
raise(RuntimeError("Found 0 files in subfolders of: " + root + "\n"
"Supported extensions are: " + ",".join(extensions)))
self.root = root
self.loader = loader
self.extensions = extensions
self.samples = samples
self.transform = transform
self.target_transform = target_transform
def __getitem__(self, index):
path, targets = self.samples[index]
sample = self.loader(path)
if self.transform is not None:
sample = self.transform(sample)
if self.target_transform is not None:
targets = self.target_transform(targets)
return sample, targets
def __len__(self):
return len(self.samples)
def __repr__(self):
format_str = 'Dataset ' + self.__class__.__name__ + '\n'
format_str += ' Number of datapoints: {}\n'.format(self.__len__())
format_str += ' Root Location: {}\n'.format(self.root)
tmp = ' Transforms (if any): '
format_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
tmp = ' Target Transforms (if any): '
format_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
return format_str
IMG_FORMAT = ['.jpg', '.jpeg', '.png']
def data_loader(path):
with open(path, 'rb') as f:
img = Image.open(f)
return img.convert('RGB')
def dft_loader(path):
return data_loader(path)
class ImgFolder(DatasetFolder):
def __init__(self, root, transform=None, target_transform=None,
loader=dft_loader):
super(ImgFolder, self).__init__(root, loader, IMG_FORMAT,
transform=transform,
target_transform=target_transform)
self.imgs = self.samples
```
|
A-Talbot/Election_Analysis
|
A-Talbot/Election_Analysis
README.md
```# Election Audit
*Prepared for Seth and Tom - 2021 JAN 17*
## Overview of Election Audit
### Purpose
The main purpose of this audit is to analyse the election results and submit the data findings to the election commission. This audit will inlcude the following data:
* Total number of votes cast
* Voter turnout and percentage of votes from each county, including the county with the highest turnout
* A complete list of candidates who received votes
* Total number of votes and the percentage of votes each candidate received and won, respectively
* The winner of the election (based on popular vote)
### Resources
* Data source: election_results.csv
* Software: Python 3.8.5, Visual Studio Code, 1.52.1
## Election Audit Results
* The total number of votes casted in this congressional election were **369,711**
* The number of votes and percentage of total votes for each county in the precinct is as follows:

* As confirmed in the above image, Denver was the county with the largest number of votes
* The following depicts a breakdown of the number of votes and precentage of total votes each candidate receieved:

* **Diana DeGette** was the winner of this election, and the following image presents the total number of votes won as well as the overall percentage of votes recieved, thus securing the popular vote

## Election Audit Summary
As presented in this README file, it is clear that the script was able to carry out all functions and data analysis requests, and as such, the script can be easily modified as necessary for use in any election, for example, in a federal election:
* The functions containing **county** can be swapped for **state** *(please see image below)*

* Additional columns within the list functions could be used to define political party *(please see image below)*

```
|
A-bahaa/A-bahaa-Analyze_ab_test_results
|
A-bahaa/A-bahaa-Analyze_ab_test_results
README.md
```# A-bahaa-Analyze_ab_test_results
Third project of the Udacity-Data-Analyst nanodegree
# Analyze A/B Test Results
A/B tests are very commonly performed by data analysts and data scientists.
For this project, I was working on understanding the results of an A/B test run by an e-commerce website. The company has developed a new web page in order to try and increase the number of users who "convert," meaning the number of users who decide to pay for the company's product. Through this notebook the goal was to help the company understand if they should implement this new page, keep the old page, or perhaps run the experiment longer to make their decision.
```
|
A-for-Anders/WeeklyUpdate_GithubTestLab
|
A-for-Anders/WeeklyUpdate_GithubTestLab
index.js
```
var button = document.getElementById("button-key-1");
button.addEventListener("click", function() {
document.location.href = "https://a-for-anders.github.io/WeeklyUpdate_GithubTestLab/PROJECTS/CLOCK/clock.html";
// document.location.href = "/PROJECTS/CLOCK/clock.html";
});
// https://a-for-anders.github.io/WeeklyUpdate_GithubTestLab/PROJECTS/CLOCK/clock.html
```
index.js
```
var testClearH, testClearM, testClearS = 0;
function checkTime(i) {
if (i < 10) {i = "0" + i};
return i;
}
function startTime_hour() {
if (testClearH == 0) {
var rightNow = new Date();
var h = rightNow.getHours();
document.querySelector("#hour").innerHTML = h;
var htime = setTimeout(startTime_hour, 100);
} else {
testClearH = 1;
}
}
function startTime_minute() {
if (testClearM == 0) {
var rightNow = new Date();
var m = rightNow.getMinutes();
m = checkTime(m);
document.querySelector("#minute").innerHTML = m;
var ttime = setTimeout(startTime_minute, 100);
} else {
testClearM = 1;
}
}
function startTime_second() {
if(testClearS == 0) {
var rightNow = new Date();
var s = rightNow.getSeconds();
s = checkTime(s);
document.querySelector("#second").innerHTML = s;
var tminute = setTimeout(startTime_second, 100);
} else {
testClearS = 1;
}
}
document.querySelector("#hour").addEventListener("click", function() {
var hourText = "hour";
if(document.querySelector("#hour").innerHTML == hourText) {
testClearH = 0;
document.querySelector("#hour").style.backgroundColor = "#4CAF50";
startTime_hour();
} else {
testClearH = 1;
document.querySelector("#hour").style.backgroundColor = "#FC3C3C";
document.querySelector("#hour").style.backgroundColor = "-webkit-transition-duration: 0.4s"; /* Safari */
document.querySelector("#hour").style.backgroundColor = "transition-duration: 0.4s";
document.querySelector("#hour").innerHTML = hourText;}
});
document.querySelector("#minute").addEventListener("click", function () {
var minuteText = "minute";
if(document.querySelector("#minute").innerHTML == minuteText) {
testClearM = 0;
document.querySelector("#minute").style.backgroundColor = "#4CAF50";
startTime_minute();
} else {
testClearM = 1;
document.querySelector("#minute").style.backgroundColor = "#FC3C3C";
document.querySelector("#minute").style.backgroundColor = "-webkit-transition-duration: 0.4s"; /* Safari */
document.querySelector("#minute").style.backgroundColor = "transition-duration: 0.4s";
document.querySelector("#minute").innerHTML = minuteText;}
});
document.querySelector("#second").addEventListener("click", function () {
var secondText = "second";
if(document.querySelector("#second").innerHTML == secondText) {
testClearS = 0;
document.querySelector("#second").style.backgroundColor = "#4CAF50";
startTime_second();
} else {
testClearS = 1;
document.querySelector("#second").style.backgroundColor = "#FC3C3C";
document.querySelector("#second").style.backgroundColor = "-webkit-transition-duration: 0.4s"; /* Safari */
document.querySelector("#second").style.backgroundColor = "transition-duration: 0.4s";
document.querySelector("#second").innerHTML = secondText;
}
});
var goBackToMain = document.getElementById("go-back");
goBackToMain.addEventListener("click", function () {
document.location.href = "https://a-for-anders.github.io/WeeklyUpdate_GithubTestLab/";
});
```
|
A-serena/weather-forecast
|
A-serena/weather-forecast
README.md
```# weather-forecast
Kivy を使用したマルチプラットフォームの天気予報アプリ
```
keisan.py
```import schedule
import time
class job:
pass```
test.py
```import japanize_kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
class Mainscreen(BoxLayout):
pass
class GraphicApp(App):
def build(self):
self.title = 'てんきよほう'
return Mainscreen()
GraphicApp().run()```
main.py
```#! python3.7
# -*- coding: utf-8 -*-
"""
メイン画面の設置、INI ファイルを参照しての API 呼び出し ~ JSON ファイルへの書き込み、
何時に処理を回すかの設定(動作未チェック)(2020/09/04時点)
"""
import configparser
import json
import requests
import schedule
from kivy.app import App
from kivy.config import Config
from kivy.core.text import DEFAULT_FONT, LabelBase
from kivy.resources import resource_add_path
# from kivy.uix.widget import Widget
# from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
Config.set('graphics', 'fullscreen', 0)
Config.set('graphics', 'width', 320)
Config.set('graphics', 'height', 568)
Config.set('graphics', 'resizable', 0)
resource_add_path(r'.\fonts')
LabelBase.register(DEFAULT_FONT, r'fonts\mplus-2c-regular.ttf')
config_ini = configparser.ConfigParser()
config_ini.read("config.ini", encoding="utf-8")
API_KEY = config_ini["Key"]["APIKEY"]
ZIP = config_ini["Zip"]["ZIP"]
API_URL = "http://api.openweathermap.org/data/2.5/forecast?zip={0},jp&units=metric&APPID={1}"
url = API_URL.format(ZIP, API_KEY)
def get_weatherworecast():
"""
天気情報を取得するやつ
"""
response = requests.get(url)
# forecastData = json.loads(response.text)
data = response.json()
# json の書き込み
with open("tenkidata.json", "w") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
with open("tenkidata.json", "r") as f:
jsn = json.load(f)
print(jsn)
print("URLです。" + url)
schedule.every().day.at("21:14").do(get_weatherworecast)
def select_word():
"""
ここに言葉を選ぶためのチャートプログラムを入れるか、
別ファイルに書いたものをimport して入れるか
"""
class Mainscreen(BoxLayout):
str_src = StringProperty('')
def __init__(self, **kwargs):
super(Mainscreen, self).__init__(**kwargs)
with open("tenkidata.json", "r") as f:
jsn = json.load(f)
self.str_src = str(jsn["list"][0]["weather"][0]["description"])
"""class Message(Label):
def __init__(self, **kwargs):
super(Message, self).__init__(**kwargs)
with open("tenkidata.json", "r") as f:
jsn = json.load(f)
self.text = str(jsn["list"][0]["weather"][0]["description"])
"""
class GraphicApp(App):
def __init__(self, **kwargs):
super(GraphicApp, self).__init__(**kwargs)
self.title = 'てんきよほう'
def build(self):
return Mainscreen()
if __name__ == "__main__":
app = GraphicApp()
app.run()
```
test_print.py
```import json
with open("tenkidata.json", "r") as f:
jsn = json.load(f)
print("***\n" + str(jsn["list"][0]["weather"][0]["description"]) + "\n***\n")```
test_display.py
```
"""
取得~書き込みの後の、
取った情報を指定した箇所に表示できるか確かめるテスト
"""
import json
from kivy.app import App
# from kivy.config import Config
# from kivy.core.text import DEFAULT_FONT, LabelBase
# from kivy.resources import resource_add_path
# from kivy.uix.widget import Widget
# from kivy.uix.label import Label
from kivy.config import Config
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
Config.set('graphics', 'fullscreen', 0)
Config.set('graphics', 'width', 320)
Config.set('graphics', 'height', 568)
Config.set('graphics', 'resizable', 0)
class Mainscreen(BoxLayout):
str_src = StringProperty('')
def __init__(self, **kwargs):
super(Mainscreen, self).__init__(**kwargs)
with open("tenkidata.json", "r") as f:
jsn = json.load(f)
self.str_src = str(jsn["list"][0]["weather"][0]["description"])
class GraphicApp(App):
def __init__(self, **kwargs):
super(GraphicApp, self).__init__(**kwargs)
self.title = 'てんきよほう'
def build(self):
return Mainscreen()
if __name__ == "__main__":
app = GraphicApp()
app.run()```
test_api.py
```"""
INI ファイルを参照して
API 呼び出し~ JSON ファイルへの書き込みができるか確かめるテスト
"""
import configparser
import json
import requests
config_ini = configparser.ConfigParser()
config_ini.read("config.ini", encoding="utf-8")
API_KEY = config_ini["Key"]["APIKEY"]
ZIP = config_ini["Zip"]["ZIP"]
API_URL = "http://api.openweathermap.org/data/2.5/forecast?zip={0},jp&units=metric&APPID={1}"
url = API_URL.format(ZIP, API_KEY)
response = requests.get(url)
# forecastData = json.loads(response.text)
data = response.json()
# json の書き込み
with open("tenkidata.json", "w") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
with open("tenkidata.json", "r") as f:
jsn = json.load(f)
print(jsn)
print("URLです。" + url)
print("***\n" + str(jsn["list"][0]["weather"][0]["description"]) + "\n***\n")```
|
A00447210/FinalProject
|
A00447210/FinalProject
PaymentInfoesController.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
namespace PizzaKnight.Controllers
{
public class PaymentInfoesController : Controller
{
private readonly Models._5510Context _context;
public int CustomerName { get; private set; }
public PaymentInfoesController(Models._5510Context context)
{
_context = context;
}
//GET: PaymentInfoes
public async Task<IActionResult> Index()
{
var _5510Context = _context.PaymentInfo.Include(p => p.CustomerName);
return View(await _5510Context.ToListAsync());
}
//GET: PaymentInfoes/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var paymentInfo = await _context.PaymentInfo
.Include(p => p.CustomerName)
.FirstOrDefaultAsync(m => m.CustomerName.Equals(CustomerName));
if (paymentInfo == null)
{
return NotFound();
}
return View(paymentInfo);
}
//GET: PaymentInfoes/Create
public IActionResult Create()
{
return View();
}
//POST: PaymentInfoes/Create
//To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("CustomerName,CardType,CardValue,CVV,ExpiryDate")] Models.PaymentInfo paymentInfo)
{
if (ModelState.IsValid)
{
int month = Int32.Parse(paymentInfo.ExpiryDate.Substring(0, 2));
int year = Int32.Parse(paymentInfo.ExpiryDate.Substring(3, 4));
if (month < 13 && month > 0 && year >= 2016 && year <= 2031)
{
if (string.Equals(paymentInfo.CardType, "Visa"))
{
string isVisa = "^4[0-9]{12}(?:[0-9]{3})?$";
if (System.Text.RegularExpressions.Regex.IsMatch(paymentInfo.CardValue, isVisa))
{
_context.Add(paymentInfo);
await _context.SaveChangesAsync();
Response.Redirect(@"\Home\Delivery");
}
else
{
ModelState.AddModelError("", "Invalid card details");
return View(paymentInfo);
}
}
else if (string.Equals(paymentInfo.CardType, "MasterCard"))
{
string isMaster = "^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$";
if (System.Text.RegularExpressions.Regex.IsMatch(paymentInfo.CardValue, isMaster))
{
_context.Add(paymentInfo);
await _context.SaveChangesAsync();
Response.Redirect(@"\Home\Delivery");
}
else
{
ModelState.AddModelError("", "Invalid card details");
return View(paymentInfo);
}
}
else
{
string isAmerican = "^3[47][0-9]{13}$";
if (System.Text.RegularExpressions.Regex.IsMatch(paymentInfo.CardValue, isAmerican))
{
_context.Add(paymentInfo);
await _context.SaveChangesAsync();
Response.Redirect(@"\Home\Delivery");
}
}
}
else
{
ModelState.AddModelError("", "Invalid ExpiryDate");
return View(paymentInfo);
}
}
return View(paymentInfo);
}
// GET: PaymentInfoes/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var paymentInfo = await _context.PaymentInfo.FindAsync(id);
if (paymentInfo == null)
{
return NotFound();
}
//ViewData["Custid"] = new SelectList(_context.Customers, "Id", "Id", paymentInfo.CustomerName);
return View(paymentInfo);
}
// POST: PaymentInfoes/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("CustomerName,Cardtype,Cardvalue,Cvv,Expirydate")] Models.PaymentInfo paymentInfo)
{
if (!CustomerName.Equals(paymentInfo.CustomerName))
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(paymentInfo);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PaymentInfoExists(paymentInfo.CustomerName))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(paymentInfo);
}
//GET: PaymentInfoes/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var paymentInfo = await _context.PaymentInfo
.Include(p => p.CustomerName)
.FirstOrDefaultAsync(m => m.CustomerName.Equals(CustomerName));
if (paymentInfo == null)
{
return NotFound();
}
return View(paymentInfo);
}
//POST: PaymentInfoes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var paymentInfo = await _context.PaymentInfo.FindAsync(id);
_context.PaymentInfo.Remove(paymentInfo);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool PaymentInfoExists(String CustomerName)
{
return _context.PaymentInfo.Any(e => e.CustomerName.Equals(CustomerName));
}
}
}
```
Details.cshtml.g.cs
```#pragma checksum "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "1baee8536b65d64b5ef9fd2af2eed89f80ffa998"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Orders_Details), @"mvc.1.0.view", @"/Views/Orders/Details.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\_ViewImports.cshtml"
using PizzaKnight;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\_ViewImports.cshtml"
using PizzaKnight.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"1baee8536b65d64b5ef9fd2af2eed89f80ffa998", @"/Views/Orders/Details.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"3f731c40b9e07f0dadb974453cba0edeb6483b90", @"/Views/_ViewImports.cshtml")]
public class Views_Orders_Details : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<Orders>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\n");
#nullable restore
#line 3 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
var pageName = "Details";
ViewData["Title"] = pageName;
#line default
#line hidden
#nullable disable
WriteLiteral("\n<h2>");
#nullable restore
#line 8 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(pageName);
#line default
#line hidden
#nullable disable
WriteLiteral("</h2>\n\n<div>\n <h4>Order</h4>\n <hr />\n <dl class=\"dl-horizontal\">\n <dt>\n ");
#nullable restore
#line 15 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayNameFor(model => model.FirstName));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd>\n ");
#nullable restore
#line 18 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayFor(model => model.FirstName));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt>\n ");
#nullable restore
#line 21 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayNameFor(model => model.LastName));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd>\n ");
#nullable restore
#line 24 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayFor(model => model.LastName));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt>\n ");
#nullable restore
#line 27 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayNameFor(model => model.AddressLine1));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd>\n ");
#nullable restore
#line 30 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayFor(model => model.AddressLine1));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt>\n ");
#nullable restore
#line 33 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayNameFor(model => model.AddressLine2));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd>\n ");
#nullable restore
#line 36 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayFor(model => model.AddressLine2));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt>\n ");
#nullable restore
#line 39 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayNameFor(model => model.ZipCode));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd>\n ");
#nullable restore
#line 42 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayFor(model => model.ZipCode));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt>\n ");
#nullable restore
#line 45 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayNameFor(model => model.City));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd>\n ");
#nullable restore
#line 48 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayFor(model => model.City));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt>\n ");
#nullable restore
#line 51 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayNameFor(model => model.State));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd>\n ");
#nullable restore
#line 54 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayFor(model => model.State));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt>\n ");
#nullable restore
#line 57 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayNameFor(model => model.Country));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd>\n ");
#nullable restore
#line 60 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayFor(model => model.Country));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt>\n ");
#nullable restore
#line 63 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayNameFor(model => model.PhoneNumber));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd>\n ");
#nullable restore
#line 66 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayFor(model => model.PhoneNumber));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt>\n ");
#nullable restore
#line 69 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayNameFor(model => model.OrderPlaced));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd>\n ");
#nullable restore
#line 72 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayFor(model => model.OrderPlaced));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt>\n ");
#nullable restore
#line 75 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayNameFor(model => model.Email));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd>\n ");
#nullable restore
#line 78 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayFor(model => model.Email));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n \n <dt>\n <br />----- Order\n </dt>\n <dd>\n <br /><b>Details -----</b>\n </dd>\n");
#nullable restore
#line 87 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
decimal subtotal = 0M;
#line default
#line hidden
#nullable disable
#nullable restore
#line 88 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
foreach (OrderDetail orderDetail in ViewBag.OrderDetailsList)
{
#line default
#line hidden
#nullable disable
WriteLiteral(" <dt>\n ");
#nullable restore
#line 91 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayNameFor(model => orderDetail.PizzaCust));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd>\n ");
#nullable restore
#line 94 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayFor(model => orderDetail.PizzaCust.Name));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt>\n ");
#nullable restore
#line 97 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayNameFor(model => orderDetail.Amount));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd>\n ");
#nullable restore
#line 100 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayFor(model => orderDetail.Amount));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt>\n ");
#nullable restore
#line 103 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Html.DisplayNameFor(model => orderDetail.Price));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd>\n ");
#nullable restore
#line 106 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(orderDetail.Price.ToString("c"));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt>\n Sub Total\n </dt>\n <dd>\n");
#nullable restore
#line 112 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
subtotal = orderDetail.Price * orderDetail.Amount;
#line default
#line hidden
#nullable disable
WriteLiteral(" ");
#nullable restore
#line 113 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(subtotal.ToString("c"));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt>\n <br />\n </dt>\n <dd>\n <br />\n </dd>\n");
#nullable restore
#line 121 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
}
#line default
#line hidden
#nullable disable
WriteLiteral(" <dt>\n Total Price\n </dt>\n <dd>\n ");
#nullable restore
#line 126 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Details.cshtml"
Write(Model.OrderTotal.ToString("c"));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n \n </dl>\n</div>\n<div>\n");
WriteLiteral(" ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "1baee8536b65d64b5ef9fd2af2eed89f80ffa99814253", async() => {
WriteLiteral("Back to List");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n</div>\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<Orders> Html { get; private set; }
}
}
#pragma warning restore 1591
```
bck.cshtml.g.cs
```#pragma checksum "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Shared\bck.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "514f804eed36583230d9c1be1eb3a4cb99507ce2"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared_bck), @"mvc.1.0.view", @"/Views/Shared/bck.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\_ViewImports.cshtml"
using PizzaKnight;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\_ViewImports.cshtml"
using PizzaKnight.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"514f804eed36583230d9c1be1eb3a4cb99507ce2", @"/Views/Shared/bck.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"3f731c40b9e07f0dadb974453cba0edeb6483b90", @"/Views/_ViewImports.cshtml")]
public class Views_Shared_bck : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral(@" <!--Main Navigation-->
<header>
<style>
#intro {
background-image: url(""https://mdbootstrap.com/img/new/fluid/city/018.jpg"");
height: 100vh;
}
/* Height for devices larger than 576px */
media (min-width: 992px) {
#intro {
margin-top: -58.59px;
}
}
.navbar .nav-link {
color: #fff !important;
}
</style>
<!-- Navbar -->
<nav class=""navbar navbar-expand-lg navbar-dark d-none d-lg-block"" style=""z-index: 2000;"">
<div class=""container-fluid"">
<!-- Navbar brand -->
<a class=""navbar-brand nav-link"" target=""_blank"" href=""https://mdbootstrap.com/docs/standard/"">
<strong>MDB</strong>
</a>
<button class=""navbar-toggler"" type=""button"" data-mdb-toggle=""collapse"" data-mdb-target=""#navbarExample01""
aria-controls=""navbarExample01"" aria-expanded=""false"" aria-label=""Toggle navigation"">
<i class=""fas fa-bars""></i");
WriteLiteral(@">
</button>
<div class=""collapse navbar-collapse"" id=""navbarExample01"">
<ul class=""navbar-nav me-auto mb-2 mb-lg-0"">
<li class=""nav-item active"">
<a class=""nav-link"" aria-current=""page"" href=""#intro"">Home</a>
</li>
<li class=""nav-item"">
<a class=""nav-link"" href=""https://www.youtube.com/channel/UC5CF7mLQZhvx8O5GODZAhdA"" rel=""nofollow""
target=""_blank"">Learn Bootstrap 5</a>
</li>
<li class=""nav-item"">
<a class=""nav-link"" href=""https://mdbootstrap.com/docs/standard/"" target=""_blank"">Download MDB UI KIT</a>
</li>
</ul>
<ul class=""navbar-nav d-flex flex-row"">
<!-- Icons -->
<li class=""nav-item me-3 me-lg-0"">
<a class=""nav-link"" href=""https://www.youtube.com/channel/");
WriteLiteral(@"UC5CF7mLQZhvx8O5GODZAhdA"" rel=""nofollow""
target=""_blank"">
<i class=""fab fa-youtube""></i>
</a>
</li>
<li class=""nav-item me-3 me-lg-0"">
<a class=""nav-link"" href=""https://www.facebook.com/mdbootstrap"" rel=""nofollow"" target=""_blank"">
<i class=""fab fa-facebook-f""></i>
</a>
</li>
<li class=""nav-item me-3 me-lg-0"">
<a class=""nav-link"" href=""https://twitter.com/MDBootstrap"" rel=""nofollow"" target=""_blank"">
<i class=""fab fa-twitter""></i>
</a>
</li>
<li class=""nav-item me-3 me-lg-0"">
<a class=""nav-link"" href=""https://github.com/mdbootstrap/mdb-ui-kit"" rel=""nofollow"" target=""_blank"">
<i class=""fab fa-github""></i>
");
WriteLiteral(@" </a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Navbar -->
<!-- Background image -->
<div id=""intro"" class=""bg-image shadow-2-strong"">
<div class=""mask"" style=""background-color: rgba(0, 0, 0, 0.8);"">
<div class=""container d-flex align-items-center justify-content-center text-center h-100"">
<div class=""text-white"">
<h1 class=""mb-3"">Learn Bootstrap 5 with MDB</h1>
<h5 class=""mb-4"">Best & free guide of responsive web design</h5>
<a class=""btn btn-outline-light btn-lg m-2"" href=""https://www.youtube.com/watch?v=c9B4TPnak1A"" role=""button""
rel=""nofollow"" target=""_blank"">Start tutorial</a>
<a class=""btn btn-outline-light btn-lg m-2"" href=""https://mdbootstrap.com/docs/standard/"" target=""_blank""
role=""button"">Download MDB UI KIT</a>
</div>
</div>
");
WriteLiteral(@" </div>
</div>
<!-- Background image -->
</header>
<!--Main Navigation-->
<!--Main layout-->
<main class=""mt-5"">
<div class=""container"">
<!--Section: Content-->
<section>
<div class=""row"">
<div class=""col-md-6 gx-5 mb-4"">
<div class=""bg-image hover-overlay ripple shadow-2-strong"" data-mdb-ripple-color=""light"">
<img src=""https://mdbootstrap.com/img/new/slides/031.jpg"" class=""img-fluid"" />
<a href=""#!"">
<div class=""mask"" style=""background-color: rgba(251, 251, 251, 0.15);""></div>
</a>
</div>
</div>
<div class=""col-md-6 gx-5 mb-4"">
<h4><strong>Facilis consequatur eligendi</strong></h4>
<p class=""text-muted"">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis consequatur
eligendi quisquam");
WriteLiteral(@" doloremque vero ex debitis veritatis placeat unde animi laborum
sapiente illo possimus, commodi dignissimos obcaecati illum maiores corporis.
</p>
<p><strong>Doloremque vero ex debitis veritatis?</strong></p>
<p class=""text-muted"">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quod itaque voluptate
nesciunt laborum incidunt. Officia, quam consectetur. Earum eligendi aliquam illum
alias, unde optio accusantium soluta, iusto molestiae adipisci et?
</p>
</div>
</div>
</section>
<!--Section: Content-->
<hr class=""my-5"" />
<!--Section: Content-->
<section class=""text-center"">
<h4 class=""mb-5""><strong>Facilis consequatur eligendi</strong></h4>
<div class=""row"">
<div class=""col-lg-4 col-md-12 mb-4"">
<d");
WriteLiteral(@"iv class=""card"">
<div class=""bg-image hover-overlay ripple"" data-mdb-ripple-color=""light"">
<img src=""https://mdbootstrap.com/img/new/standard/nature/184.jpg"" class=""img-fluid"" />
<a href=""#!"">
<div class=""mask"" style=""background-color: rgba(251, 251, 251, 0.15);""></div>
</a>
</div>
<div class=""card-body"">
<h5 class=""card-title"">Card title</h5>
<p class=""card-text"">
Some quick example text to build on the card title and make up the bulk of the
card's content.
</p>
<a href=""#!"" class=""btn btn-primary"">Button</a>
</div>
</div>
</div>
<div class=""col-lg-4 col-md-6 mb-4"">
");
WriteLiteral(@" <div class=""card"">
<div class=""bg-image hover-overlay ripple"" data-mdb-ripple-color=""light"">
<img src=""https://mdbootstrap.com/img/new/standard/nature/023.jpg"" class=""img-fluid"" />
<a href=""#!"">
<div class=""mask"" style=""background-color: rgba(251, 251, 251, 0.15);""></div>
</a>
</div>
<div class=""card-body"">
<h5 class=""card-title"">Card title</h5>
<p class=""card-text"">
Some quick example text to build on the card title and make up the bulk of the
card's content.
</p>
<a href=""#!"" class=""btn btn-primary"">Button</a>
</div>
</div>
</div>
<div class=""col-lg-4 col-md-6 mb-");
WriteLiteral(@"4"">
<div class=""card"">
<div class=""bg-image hover-overlay ripple"" data-mdb-ripple-color=""light"">
<img src=""https://mdbootstrap.com/img/new/standard/nature/111.jpg"" class=""img-fluid"" />
<a href=""#!"">
<div class=""mask"" style=""background-color: rgba(251, 251, 251, 0.15);""></div>
</a>
</div>
<div class=""card-body"">
<h5 class=""card-title"">Card title</h5>
<p class=""card-text"">
Some quick example text to build on the card title and make up the bulk of the
card's content.
</p>
<a href=""#!"" class=""btn btn-primary"">Button</a>
</div>
</div>
</div>
</div>
</section>");
WriteLiteral(@"
<!--Section: Content-->
<hr class=""my-5"" />
<!--Section: Content-->
<section class=""mb-5"">
<h4 class=""mb-5 text-center""><strong>Facilis consequatur eligendi</strong></h4>
<div class=""row d-flex justify-content-center"">
<div class=""col-md-6"">
");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "514f804eed36583230d9c1be1eb3a4cb99507ce213322", async() => {
WriteLiteral(@"
<!-- 2 column grid layout with text inputs for the first and last names -->
<div class=""row mb-4"">
<div class=""col"">
<div class=""form-outline"">
<input type=""text"" id=""form3Example1"" class=""form-control"" />
<label class=""form-label"" for=""form3Example1"">First name</label>
</div>
</div>
<div class=""col"">
<div class=""form-outline"">
<input type=""text"" id=""form3Example2"" class=""form-control"" />
<label class=""form-label"" for=""form3Example2"">Last name</label>
</div>
</div>
</div>
<!-- Email input -->
<div class=""form-out");
WriteLiteral(@"line mb-4"">
<input type=""email"" id=""form3Example3"" class=""form-control"" />
<label class=""form-label"" for=""form3Example3"">Email address</label>
</div>
<!-- Password input -->
<div class=""form-outline mb-4"">
<input type=""password"" id=""form3Example4"" class=""form-control"" />
<label class=""form-label"" for=""form3Example4"">Password</label>
</div>
<!-- Checkbox -->
<div class=""form-check d-flex justify-content-center mb-4"">
<input class=""form-check-input me-2"" type=""checkbox""");
BeginWriteAttribute("value", " value=\"", 11342, "\"", 11350, 0);
EndWriteAttribute();
WriteLiteral(@" id=""form2Example3"" checked />
<label class=""form-check-label"" for=""form2Example3"">
Subscribe to our newsletter
</label>
</div>
<!-- Submit button -->
<button type=""submit"" class=""btn btn-primary btn-block mb-4"">
Sign up
</button>
<!-- Register buttons -->
<div class=""text-center"">
<p>or sign up with:</p>
<button type=""button"" class=""btn btn-primary btn-floating mx-1"">
<i class=""fab fa-facebook-f""></i>
</button>
<button type=""button"" class=""btn btn-primary btn-floating mx-1"">
<i class=""fab fa-google""></i>
</button>
<button");
WriteLiteral(@" type=""button"" class=""btn btn-primary btn-floating mx-1"">
<i class=""fab fa-twitter""></i>
</button>
<button type=""button"" class=""btn btn-primary btn-floating mx-1"">
<i class=""fab fa-github""></i>
</button>
</div>
");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(@"
</div>
</div>
</section>
<!--Section: Content-->
</div>
</main>
<!--Main layout-->
<!--Footer-->
<footer class=""bg-light text-lg-start"">
<div class=""py-4 text-center"">
<a role=""button"" class=""btn btn-primary btn-lg m-2""
href=""https://www.youtube.com/channel/UC5CF7mLQZhvx8O5GODZAhdA"" rel=""nofollow"" target=""_blank"">
Learn Bootstrap 5
</a>
<a role=""button"" class=""btn btn-primary btn-lg m-2"" href=""https://mdbootstrap.com/docs/standard/"" target=""_blank"">
Download MDB UI KIT
</a>
</div>
<hr class=""m-0"" />
<div class=""text-center py-4 align-items-center"">
<p>Follow MDB on social media</p>
<a href=""https://www.youtube.com/channel/UC5CF7mLQZhvx8O5GODZAhdA"" class=""btn btn-primary m-1"" role=""button""
rel=""nofollow"" target=""_blank"">
<i class=""fab fa-youtube""></i>
</a>
<a href=""https://www.facebook.com/mdbootstrap"" class=""btn btn-primary");
WriteLiteral(@" m-1"" role=""button"" rel=""nofollow""
target=""_blank"">
<i class=""fab fa-facebook-f""></i>
</a>
<a href=""https://twitter.com/MDBootstrap"" class=""btn btn-primary m-1"" role=""button"" rel=""nofollow""
target=""_blank"">
<i class=""fab fa-twitter""></i>
</a>
<a href=""https://github.com/mdbootstrap/mdb-ui-kit"" class=""btn btn-primary m-1"" role=""button"" rel=""nofollow""
target=""_blank"">
<i class=""fab fa-github""></i>
</a>
</div>
<!-- Copyright -->
<div class=""text-center p-3"" style=""background-color: rgba(0, 0, 0, 0.2);"">
© 2020 Copyright:
<a class=""text-dark"" href=""https://mdbootstrap.com/"">MDBootstrap.com</a>
</div>
<!-- Copyright -->
</footer>
<!--Footer-->");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
```
OrderList.cs
```using System;
using System.Collections.Generic;
// Code scaffolded by EF Core assumes nullable reference types (NRTs) are not used or disabled.
// If you have enabled NRTs for your project, then un-comment the following line:
// #nullable disable
namespace PizzaKnight.Models
{
public partial class OrderList
{
public OrderList()
{
OrderStatus = new HashSet<OrderStatus>();
}
public string Ordid { get; set; }
public string Custname { get; set; }
public string Address { get; set; }
public string Ordertype { get; set; }
public string Discountcode { get; set; }
public decimal Totalamount { get; set; }
public int? Custid { get; set; }
public virtual Customers Cust { get; set; }
public virtual ICollection<OrderStatus> OrderStatus { get; set; }
}
}
```
CustFeedbacksController.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
namespace PizzaKnight.Controllers
{
public class CustFeedbacksController : Controller
{
private readonly Models._5510Context _context;
public CustFeedbacksController(Models._5510Context context)
{
_context = context;
}
// GET: CustFeedbacks
public async Task<IActionResult> Index()
{
//var _5510Context = _context.CustFeedback.Include(c => c.FirstName);
return View(await _context.CustFeedback.ToListAsync());
}
// GET: CustFeedbacks/Details/5
public async Task<IActionResult> Details(string FirstName)
{
if (FirstName == null)
{
return NotFound();
}
var custFeedback = await _context.CustFeedback
.Include(c => c.FirstName)
.FirstOrDefaultAsync(m => m.FirstName.Equals(FirstName));
if (custFeedback == null)
{
return NotFound();
}
return View(custFeedback);
}
// GET: CustFeedbacks/Create
public IActionResult Create()
{
return View();
}
// POST: CustFeedbacks/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("FirstName,LastName,Feedback")] Models.CustFeedback custFeedback)
{
if (ModelState.IsValid)
{
_context.Add(custFeedback);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(custFeedback);
}
// GET: CustFeedbacks/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var custFeedback = await _context.CustFeedback.FindAsync(id);
if (custFeedback == null)
{
return NotFound();
}
return View(custFeedback);
}
// GET: CustFeedbacks/Delete/5
public async Task<IActionResult> Delete(string FirstName)
{
if (FirstName == null)
{
return NotFound();
}
var custFeedback = await _context.CustFeedback
.Include(c => c.FirstName)
.FirstOrDefaultAsync(m => m.FirstName.Equals(FirstName));
if (custFeedback == null)
{
return NotFound();
}
return View(custFeedback);
}
// POST: CustFeedbacks/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string name)
{
var custFeedback = await _context.CustFeedback.FindAsync(name);
_context.CustFeedback.Remove(custFeedback);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
}
```
Customers.cs
```using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
// Code scaffolded by EF Core assumes nullable reference types (NRTs) are not used or disabled.
// If you have enabled NRTs for your project, then un-comment the following line:
// #nullable disable
namespace PizzaKnight.Models
{
public partial class Customers
{
public Customers()
{
OrderList = new HashSet<OrderList>();
OrderStatus = new HashSet<OrderStatus>();
}
public int Id { get; set; }
[Display(Name = "Firstname")]
[Required(ErrorMessage = "Firstname is required")]
[RegularExpression("^[a-zA-Z_ ]{2,20}$", ErrorMessage = "Firstname is not Valid")]
public string FirstName { get; set; }
[Display(Name = "Lastname")]
[Required(ErrorMessage = "Lastname is required")]
[RegularExpression("^[a-zA-Z_ ]{2,20}$", ErrorMessage = "Lastname is not Valid")]
public string LastName { get; set; }
[Display(Name = "Address")]
public string Addrses1 { get; set; }
[Display(Name = "City")]
[Required(ErrorMessage = "City is required")]
[RegularExpression("^[a-zA-Z_ ]{2,20}$", ErrorMessage = "City is not Valid")]
public string City { get; set; }
[Display(Name = "Province")]
[Required(ErrorMessage = "Province is required")]
[RegularExpression("^[a-zA-Z_ ]{2,20}$", ErrorMessage = "Province is not Valid")]
public string Province { get; set; }
[Required(ErrorMessage = "Country is required")]
public string Country { get; set; }
[Display(Name = "Postal")]
[Required(ErrorMessage = "Postal is required")]
public string Postal { get; set; }
[Display(Name = "Phone")]
[Required(ErrorMessage = "Phone is required")]
public string Phone { get; set; }
[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
[RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "E-mail is not valid")]
public string Emailaddress { get; set; }
public virtual ICollection<OrderList> OrderList { get; set; }
public virtual ICollection<OrderStatus> OrderStatus { get; set; }
}
}```
Index.cshtml.g.cs
```#pragma checksum "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "31d76717b34dd7726fa9873d2dc8de92f1cc75a2"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Orders_Index), @"mvc.1.0.view", @"/Views/Orders/Index.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\_ViewImports.cshtml"
using PizzaKnight;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\_ViewImports.cshtml"
using PizzaKnight.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"31d76717b34dd7726fa9873d2dc8de92f1cc75a2", @"/Views/Orders/Index.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"3f731c40b9e07f0dadb974453cba0edeb6483b90", @"/Views/_ViewImports.cshtml")]
public class Views_Orders_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<IEnumerable<Orders>>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Details", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-info"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Delete", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\n");
#nullable restore
#line 3 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
var pageName = "Orders";
ViewData["Title"] = pageName;
#line default
#line hidden
#nullable disable
WriteLiteral("\n<h2>");
#nullable restore
#line 8 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(pageName);
#line default
#line hidden
#nullable disable
WriteLiteral("</h2>\n\n");
#nullable restore
#line 10 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
if (Model.Count() <= 0)
{
#line default
#line hidden
#nullable disable
WriteLiteral(" <h3>You haven\'t created any ");
#nullable restore
#line 12 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(pageName);
#line default
#line hidden
#nullable disable
WriteLiteral(" yet...</h3>\n");
#nullable restore
#line 13 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
}
#line default
#line hidden
#nullable disable
WriteLiteral("\n\n<table class=\"table\">\n <thead>\n <tr>\n <th>\n ");
#nullable restore
#line 20 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayNameFor(model => model.FirstName));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </th>\n <th>\n ");
#nullable restore
#line 23 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayNameFor(model => model.LastName));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </th>\n <th>\n ");
#nullable restore
#line 26 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayNameFor(model => model.AddressLine1));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </th>\n <th>\n ");
#nullable restore
#line 29 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayNameFor(model => model.ZipCode));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </th>\n <th>\n ");
#nullable restore
#line 32 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayNameFor(model => model.City));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </th>\n <th>\n ");
#nullable restore
#line 35 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayNameFor(model => model.State));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </th>\n <th>\n ");
#nullable restore
#line 38 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayNameFor(model => model.Country));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </th>\n <th>\n ");
#nullable restore
#line 41 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayNameFor(model => model.PhoneNumber));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </th>\n <th>\n ");
#nullable restore
#line 44 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayNameFor(model => model.OrderTotal));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </th>\n <th>\n ");
#nullable restore
#line 47 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayNameFor(model => model.OrderPlaced));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </th>\n \n <th></th>\n </tr>\n </thead>\n <tbody>\n");
#nullable restore
#line 54 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
foreach (var item in Model)
{
#line default
#line hidden
#nullable disable
WriteLiteral(" <tr>\n <td>\n ");
#nullable restore
#line 58 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayFor(modelItem => item.FirstName));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </td>\n <td>\n ");
#nullable restore
#line 61 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayFor(modelItem => item.LastName));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </td>\n <td>\n ");
#nullable restore
#line 64 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayFor(modelItem => item.AddressLine1));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </td>\n <td>\n ");
#nullable restore
#line 67 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayFor(modelItem => item.ZipCode));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </td>\n <td>\n ");
#nullable restore
#line 70 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayFor(modelItem => item.City));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </td>\n <td>\n ");
#nullable restore
#line 73 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayFor(modelItem => item.State));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </td>\n <td>\n ");
#nullable restore
#line 76 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayFor(modelItem => item.Country));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </td>\n <td>\n ");
#nullable restore
#line 79 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayFor(modelItem => item.PhoneNumber));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </td>\n <td>\n ");
#nullable restore
#line 82 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(item.OrderTotal.ToString("c"));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </td>\n <td>\n ");
#nullable restore
#line 85 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
Write(Html.DisplayFor(modelItem => item.OrderPlaced));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </td>\n \n \n <td>\n");
WriteLiteral(" ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31d76717b34dd7726fa9873d2dc8de92f1cc75a212041", async() => {
WriteLiteral("Details");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null)
{
throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues"));
}
BeginWriteTagHelperAttribute();
#nullable restore
#line 91 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
WriteLiteral(item.OrderId);
#line default
#line hidden
#nullable disable
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(" |\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31d76717b34dd7726fa9873d2dc8de92f1cc75a214305", async() => {
WriteLiteral("Delete");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null)
{
throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues"));
}
BeginWriteTagHelperAttribute();
#nullable restore
#line 92 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
WriteLiteral(item.OrderId);
#line default
#line hidden
#nullable disable
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n </td>\n </tr>\n");
#nullable restore
#line 95 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Orders\Index.cshtml"
}
#line default
#line hidden
#nullable disable
WriteLiteral(" </tbody>\n</table>\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<IEnumerable<Orders>> Html { get; private set; }
}
}
#pragma warning restore 1591
```
OrderDetail.cs
```using System;
using System.Collections.Generic;
// Code scaffolded by EF Core assumes nullable reference types (NRTs) are not used or disabled.
// If you have enabled NRTs for your project, then un-comment the following line:
// #nullable disable
namespace PizzaKnight.Models
{
public partial class OrderDetail
{
public int OrderDetailId { get; set; }
public int OrderId { get; set; }
public int PizzaCustId { get; set; }
public int Amount { get; set; }
public decimal Price { get; set; }
public virtual Orders Order { get; set; }
public virtual PizzaCust PizzaCust { get; set; }
}
}
```
Delivery.cshtml.g.cs
```#pragma checksum "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\Home\Delivery.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "8a4d113d0b66144eb5c4f95c8457018215aea84a"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_Delivery), @"mvc.1.0.view", @"/Views/Home/Delivery.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\_ViewImports.cshtml"
using PizzaKnight;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\_ViewImports.cshtml"
using PizzaKnight.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"8a4d113d0b66144eb5c4f95c8457018215aea84a", @"/Views/Home/Delivery.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"3f731c40b9e07f0dadb974453cba0edeb6483b90", @"/Views/_ViewImports.cshtml")]
public class Views_Home_Delivery : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("onload", new global::Microsoft.AspNetCore.Html.HtmlString("countdown();"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper;
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\n<!DOCTYPE HTML>\n<html>\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("head", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "8a4d113d0b66144eb5c4f95c8457018215aea84a3596", async() => {
WriteLiteral(@"
<style>
h1 {
text-align: center;
}
ol {
text-align: center;
}
div {
text-align: center;
}
</style>
<script>
//set minutes
var mins = 30;
//calculate the seconds
var secs = mins * 60;
//countdown function is evoked when page is loaded
function countdown() {
setTimeout('Decrement()', 60);
}
//Decrement function decrement the value.
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById(""minutes"");
seconds = document.getElementById(""seconds"");
//if less than a minute remaining
//Display only seconds value.
if (seconds < 59) {
seconds.value = secs;
}
//Display both minutes and seconds
//getminutes and getseconds is used to
");
WriteLiteral(@"//get minutes and seconds
else {
minutes.value = getminutes();
seconds.value = getseconds();
}
//when less than a minute remaining
//colour of the minutes and seconds
//changes to red
if (mins < 1) {
minutes.style.color = ""red"";
seconds.style.color = ""red"";
}
//if seconds becomes zero,
//then page alert time up
if (mins < 0) {
alert('time up');
minutes.value = 0;
seconds.value = 0;
}
//if seconds > 0 then seconds is decremented
else {
secs--;
setTimeout('Decrement()', 1000);
}
}
}
function getminutes() {
//minutes is seconds divided by 60, rounded down
mins = M");
WriteLiteral(@"ath.floor(secs / 60);
return mins;
}
function getseconds() {
//take minutes remaining (as seconds) away
//from total seconds remaining
return secs - Math.round(mins * 60);
}
</script>
");
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n<!-- onload function is evoke when page is load -->\n<!--countdown function is called when page is loaded -->\n\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("body", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "8a4d113d0b66144eb5c4f95c8457018215aea84a7059", async() => {
WriteLiteral(@"
<div>
<h1> <strong> Thanks for your order, We'll deliver your pizzas Before Timer Sets off!!</strong></h1>
<ol>
<input id=""minutes"" type=""text"" style=""width: 100px; text-align:center;
border: none; font-size: 60px;
font-weight: bold; color: black;"">
<font size=""5"">
</font>
<input id=""seconds"" type=""text"" style="" width: 100px;
text-align: center;
border: none;
font-size: 60px;
font-weight: bold;
color: black;"">
<font size=""5""> </font>
</ol>
</div>
");
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n\n</html>");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
```
Details.cshtml.g.cs
```#pragma checksum "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\CustFeedbacks\Details.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "4e1e13d2b255588227f047551f243a2d6adb882f"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_CustFeedbacks_Details), @"mvc.1.0.view", @"/Views/CustFeedbacks/Details.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\_ViewImports.cshtml"
using PizzaKnight;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\_ViewImports.cshtml"
using PizzaKnight.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"4e1e13d2b255588227f047551f243a2d6adb882f", @"/Views/CustFeedbacks/Details.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"3f731c40b9e07f0dadb974453cba0edeb6483b90", @"/Views/_ViewImports.cshtml")]
public class Views_CustFeedbacks_Details : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<PizzaKnight.Models.CustFeedback>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\n");
#nullable restore
#line 3 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\CustFeedbacks\Details.cshtml"
ViewData["Title"] = "Details";
#line default
#line hidden
#nullable disable
WriteLiteral("\n<h1>Details</h1>\n\n<div>\n <h4>CustFeedback</h4>\n <hr />\n <dl class=\"row\">\n <dt class = \"col-sm-2\">\n ");
#nullable restore
#line 14 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\CustFeedbacks\Details.cshtml"
Write(Html.DisplayNameFor(model => model.FirstName));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd class = \"col-sm-10\">\n ");
#nullable restore
#line 17 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\CustFeedbacks\Details.cshtml"
Write(Html.DisplayFor(model => model.FirstName));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt class = \"col-sm-2\">\n ");
#nullable restore
#line 20 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\CustFeedbacks\Details.cshtml"
Write(Html.DisplayNameFor(model => model.LastName));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd class = \"col-sm-10\">\n ");
#nullable restore
#line 23 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\CustFeedbacks\Details.cshtml"
Write(Html.DisplayFor(model => model.LastName));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n <dt class = \"col-sm-2\">\n ");
#nullable restore
#line 26 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\CustFeedbacks\Details.cshtml"
Write(Html.DisplayNameFor(model => model.Feedback));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dt>\n <dd class = \"col-sm-10\">\n ");
#nullable restore
#line 29 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\CustFeedbacks\Details.cshtml"
Write(Html.DisplayFor(model => model.Feedback));
#line default
#line hidden
#nullable disable
WriteLiteral("\n </dd>\n\n </dl>\n</div>\n\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<PizzaKnight.Models.CustFeedback> Html { get; private set; }
}
}
#pragma warning restore 1591
```
OrderRepository.cs
```
using PizzaKnight.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PizzaKnight.Repositories
{
public class OrderRepository : IOrderRepository
{
private readonly _5510Context _context;
private readonly ShoppingCart _shoppingCart;
public OrderRepository(_5510Context context, ShoppingCart shoppingCart)
{
_context = context;
_shoppingCart = shoppingCart;
}
public async Task CreateOrderAsync(Orders order)
{
DateTime today = DateTime.Today;
//order.OrderPlaced = today;
decimal totalPrice = 0M;
var shoppingCartItems = _shoppingCart.ShoppingCartItems;
foreach (var shoppingCartItem in shoppingCartItems)
{
var orderDetail = new OrderDetail()
{
Amount = shoppingCartItem.Amount,
PizzaCustId = shoppingCartItem.pizzaCust.Id,
Order = order,
Price = shoppingCartItem.pizzaCust.Price,
};
totalPrice += orderDetail.Price * orderDetail.Amount;
_context.OrderDetail.Add(orderDetail);
}
order.OrderTotal = totalPrice;
_context.Orders.Add(order);
await _context.SaveChangesAsync();
}
}
}
```
Index.cshtml.g.cs
```#pragma checksum "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\PizzaCust2\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "be72a9c80fca5237e785e92ad8f8738a3335536e"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_PizzaCust2_Index), @"mvc.1.0.view", @"/Views/PizzaCust2/Index.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\_ViewImports.cshtml"
using PizzaKnight;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\_ViewImports.cshtml"
using PizzaKnight.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"be72a9c80fca5237e785e92ad8f8738a3335536e", @"/Views/PizzaCust2/Index.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"3f731c40b9e07f0dadb974453cba0edeb6483b90", @"/Views/_ViewImports.cshtml")]
public class Views_PizzaCust2_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<IEnumerable<PizzaKnight.Models.PizzaCust>>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\n");
#nullable restore
#line 3 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\PizzaCust2\Index.cshtml"
ViewData["Title"] = "Pizza Menu";
#line default
#line hidden
#nullable disable
WriteLiteral("\n\n\n<h2>Pizza Menu</h2>\n<br />\n\n<h4>All Pizzas</h4>\n\n<div class=\"PizzaSummaryId\">\n");
#nullable restore
#line 15 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\PizzaCust2\Index.cshtml"
foreach (var pizza in Model)
{
#line default
#line hidden
#nullable disable
#nullable restore
#line 17 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\PizzaCust2\Index.cshtml"
Write(Html.Partial("PizzaSummary2", pizza));
#line default
#line hidden
#nullable disable
#nullable restore
#line 17 "\\Mac\Home\Downloads\penultimate\FinalProject\benro\Views\PizzaCust2\Index.cshtml"
}
#line default
#line hidden
#nullable disable
WriteLiteral(" \n</div>\n<br />\n<style>\n .PizzaSummaryId {\n display: grid;\n grid-template-columns: auto auto auto;\n height: 500px;\n padding: 10px;\n margin-bottom: 100px;\n }\n</style>");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<IEnumerable<PizzaKnight.Models.PizzaCust>> Html { get; private set; }
}
}
#pragma warning restore 1591
```
|
A01374974/Graficas2020
|
A01374974/Graficas2020
threejsInteraction.js
```let container;
let camera, scene, raycaster, renderer,root;
let life;
let mouse = new THREE.Vector2(), INTERSECTED, CLICKED;
let radius = 100, theta = 0;
let objectList=[];
let objLoader = null, jsonLoader = null;
let fract = 0;
let deltat = 1000;
let duration = 200000; // ms
let currentTime = Date.now();
let seconds=0;
let secondFinal=59;
let directionalLight = null;
let spotLight = null;
let ambientLight = null;
let pointLight = null;
let minutes=3
let timer=59
let gameOver=false;
let puntuacion=0;
let salud=50;
let now = new Date().getTime();
let objElefantlUrl = {obj:'../models/obj/elefante/elefante.obj', map:'../models/obj/elefante/Textures/elefantefull.png', normalMap:'../models/obj/elefante/Textures/elefantefull.png', specularMap: '../models/obj/elefante/Textures/elefantefull.png'};
let objModelUrl = {obj:'../models/obj/leon/12273_Lion_v1_l3.obj', map:'../models/obj/leon/12273_Lion_Diffuse.jpg',normalMap:'../models/obj/leon/12273_Lion_Diffuse.jpg', specularMap: '../models/obj/leon/12273_Lion_Diffuse.jpg'};
let floorUrl = "../images/checker_large.gif";
function promisifyLoader ( loader, onProgress )
{
function promiseLoader ( url ) {
return new Promise( ( resolve, reject ) => {
loader.load( url, resolve, onProgress, reject );
} );
}
return {
originalLoader: loader,
load: promiseLoader,
};
}
async function loadJson(url, objectList)
{
const jsonPromiseLoader = promisifyLoader(new THREE.ObjectLoader());
try {
const object = await jsonPromiseLoader.load(url);
object.castShadow = true;
object.receiveShadow = true;
object.position.y = -1;
object.position.x = 1.5;
object.name = "jsonObject";
objectList.push(object);
scene.add(object);
}
catch (err) {
return onError(err);
}
}
async function loadElefante(objModelUrl,objectList)
{
const objPromiseLoader = promisifyLoader(new THREE.OBJLoader());
try {
const object = await objPromiseLoader.load(objModelUrl.obj);
let texture = objModelUrl.hasOwnProperty('map') ? new THREE.TextureLoader().load(objModelUrl.map) : null;
let normalMap = objModelUrl.hasOwnProperty('normalMap') ? new THREE.TextureLoader().load(objModelUrl.normalMap) : null;
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.castShadow = true;
child.receiveShadow = true;
child.material.map = texture;
child.material.normalMap = normalMap;
}
});
object.scale.set(8, 8, 8);
object.position.set(20,10,-187);
scene.add(object);
}
catch (err) {
return onError(err);
}
}
const onError = ( ( err ) => { console.error( err ); } );
async function loadObj(objModelUrl, objectList)
{
const objPromiseLoader = promisifyLoader(new THREE.OBJLoader());
try {
let texture = objModelUrl.hasOwnProperty('map') ? new THREE.TextureLoader().load(objModelUrl.map) : null;
let normalMap = objModelUrl.hasOwnProperty('normalMap') ? new THREE.TextureLoader().load(objModelUrl.normalMap) : null;
for ( let i = 0; i < 6; i ++ ) {
const object = await objPromiseLoader.load(objModelUrl.obj);
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.castShadow = true;
child.receiveShadow = true;
child.material.map = texture;
child.material.normalMap = normalMap;
}
});
object.scale.set(8, 8, 8);
object.name = 'elefante';
//object.position.set(60,60,-183)
//object.position.set(Math.floor(Math.random()*(90+90))-90, Math.floor(Math.random()*(100+90))-90, -183);
object.position.set(window.innerWidth/9, Math.floor(Math.random()*(100+90))-90, -183);
console.log(object.position)
objectList.push(object);
console.log()
scene.add(object);
}
for ( let i = 0; i <5; i ++ ) {
const object = await objPromiseLoader.load(objModelUrl.obj);
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.castShadow = true;
child.receiveShadow = true;
child.material.map = texture;
child.material.normalMap = normalMap;
}
});
object.scale.set(8, 8, 8);
object.name = 'elefante';
//object.position.set(60,60,-183)
//object.position.set(Math.floor(Math.random()*(90+90))-90, Math.floor(Math.random()*(100+90))-90, -183);
object.position.set(Math.floor(Math.random()*(90+90))-90, -90, -183);
console.log(object.position)
objectList.push(object);
console.log()
scene.add(object);
}
}
catch (err) {
return onError(err);
}
}
function animate() {
let now = Date.now();
//let deltat = now - currentTime;
//currentTime = now;
let fract = deltat / duration;
let angle = Math.PI * fract;
for(object of objectList){
if(object.up){
object.position.y += 0.1;
if(object.position.y > -2.5){
object.up = false;
}
}else{
object.position.y -= 0.1;
if(object.position.y < 2){
object.up = true;
}
}
object.rotation.y += angle ;
if(object.position.x >=0){
object.position.x-=0.1;
}else if(object.position.x <0){
object.position.x+=0.1;
}else{
if(object.position.x > 0){
object.position.x-=0.1;
}else if(object.position.x <= 0){
object.position.x+=0.1;
}
}
}
for(object of objectList){
if(object.position.x>=-3&&object.position.x<=3&&object.position.y>=-3&&object.position.y<=3){
if(salud>=0.5){
salud-=0.001
$("#health").html("HEALTH: " + salud.toFixed(1) );
}else{
gameOver = true;
}
}
}
}
function run()
{
requestAnimationFrame(function() { run(); });
renderer.render( scene, camera );
animate();
}
function createScene(canvas)
{
renderer = new THREE.WebGLRenderer( { canvas: canvas, antialias: true } );
// Set the viewport size
renderer.setSize(window.innerWidth, window.innerHeight);
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
scene = new THREE.Scene();
scene.add(camera)
let textureBuild = new THREE.TextureLoader().load( '../models/obj/leon/sabana-africana-del-paisaje-puesta-sol-el-lugar-para-texto-130883255.jpg');
scene.background =textureBuild;
let light = new THREE.DirectionalLight( 0xffffff, 1 );
light.position.set( 1, 1, 1 );
scene.add( light );
// floor
let map = new THREE.TextureLoader().load(floorUrl);
map.wrapS = map.wrapT = THREE.RepeatWrapping;
map.repeat.set(8, 8);
let floorGeometry = new THREE.PlaneGeometry( 2000, 2000, 100, 100 );
let floor = new THREE.Mesh(floorGeometry, new THREE.MeshPhongMaterial({color:0xffffff, map:map, side:THREE.DoubleSide}));
floor.rotation.x = -Math.PI / 2;
scene.add( floor );
let geometry = new THREE.BoxBufferGeometry( 20, 20, 20 );
/*for ( let i = 0; i < 10; i ++ )
{
//La característica del Lamber es que no tiene reflejo
let object = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: Math.random() * 0xffffff } ) );
object.name = 'Cube' + i;
object.position.set(Math.random() * 200 - 100, Math.random() * 200 - 100, -200);
scene.add( object );
}*/
//loadElefante(objElefantlUrl,objectList)
loadObj(objElefantlUrl, objectList);
raycaster = new THREE.Raycaster();
document.addEventListener('mousemove', onDocumentMouseMove);
document.addEventListener('mousedown', onDocumentMouseDown);
window.addEventListener( 'resize', onWindowResize);
}
function onWindowResize()
{
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event )
{
event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
// find intersections
raycaster.setFromCamera( mouse, camera );
let intersects = raycaster.intersectObjects( scene.children );
if ( intersects.length > 0 )
{
let closer = intersects.length - 1;
if ( INTERSECTED != intersects[ closer ].object )
{
if ( INTERSECTED)
{
INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );
}
INTERSECTED = intersects[ closer ].object;
INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
INTERSECTED.material.emissive.setHex( 0xff0000 );
}
}
else
{
if ( INTERSECTED )
INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );
INTERSECTED = null;
}
}
function onDocumentMouseDown(event)
{
event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
// find intersections
raycaster.setFromCamera( mouse, camera );
let intersects = raycaster.intersectObjects( scene.children,true );
//console.log("intersects", intersects);
if ( intersects.length > 0 )
{
CLICKED = intersects[ intersects.length - 1 ].object;
if(!gameOver&& CLICKED.name=="mesh_0"){
//CLICKED.material.emissive.setHex( 0x00ff00 );
//console.log(CLICKED.name);
CLICKED.parent.alive=false;
CLICKED.parent.position.set(window.innerWidth/6, Math.floor(Math.random()*(100+90))-90, -183)
puntuacion+=1
$("#score").html("SCORE: " + puntuacion );}
}
else
{
if ( CLICKED )
CLICKED.material.emissive.setHex( CLICKED.currentHex );
CLICKED = null;
}
}
//Función run correcta
function run()
{
if (gameOver){
$("#reiniciar").html("<h4><A HREF='javascript:history.go(0)' style='color:BLACK'>REINICIAR</A></h4>");
}else{
requestAnimationFrame( run );
render();
animate()
setTimeout(temporizador,100)
}
}
function habilitarBoton(){
let boton1 = document.getElementById("boton1");
boton1.disabled = false;
}
function temporizador(){
if(secondFinal==0){
gameOver=true
}
/*if(minutes === 0 && timer < 0){
//gameover = true;
}else{
if(timer<0){
minutes -= 1;
timer = 59
}
timer -= 0.1;
$("#timer").html("<h1>0" + minutes +":"+
("0" + Math.floor(timer.toFixed(1))).slice(-2) + "</h1>" );
}
console.log(timer)*/
else{
seconds+=1/90
if(seconds>=1){
secondFinal-=1
seconds=0
}
$("#timer").html("<h1>0 :"+
( " "+ secondFinal) + "</h1>" );}
}
function render()
{
renderer.render( scene, camera );
}
```
threejsShadows.js
```// 1. Enable shadow mapping in the renderer.
// 2. Enable shadows and set shadow parameters for the lights that cast shadows.
// Both the THREE.DirectionalLight type and the THREE.SpotLight type support shadows.
// 3. Indicate which geometry objects cast and receive shadows.
/*let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
let renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );*/
let renderer = null,
scene = null,
camera = null,
root = null,
group = null,
objectList = [],
orbitControls = null;
transformControls = null;
let objLoader = null, jsonLoader = null;
let duration = 20000; // ms
let currentTime = Date.now();
let directionalLight = null;
let spotLight = null;
let ambientLight = null;
let pointLight = null;
let mapUrl = "../images/checker_large.gif";
let SHADOW_MAP_WIDTH = 2048, SHADOW_MAP_HEIGHT = 2048;
// let objModelUrl = {obj:'../models/obj/Penguin_obj/penguin.obj', map:'../models/obj/Penguin_obj/peng_texture.jpg'};
let objModelUrl = {obj:'../models/obj/Michael/michael.OBJ', map:'../models/obj/Michael/Michael_A.jpg', normalMap:'../models/obj/Michael/Michael_A.jpg', specularMap: '../models/obj/Michael/Michael_A.jpg'};
//let jsonModelUrl = { url:'../models/json/teapot-claraio.json' };
function promisifyLoader ( loader, onProgress )
{
function promiseLoader ( url ) {
return new Promise( ( resolve, reject ) => {
loader.load( url, resolve, onProgress, reject );
} );
}
return {
originalLoader: loader,
load: promiseLoader,
};
}
const onError = ( ( err ) => { console.error( err ); } );
async function loadJson(url, objectList)
{
const jsonPromiseLoader = promisifyLoader(new THREE.ObjectLoader());
try {
const object = await jsonPromiseLoader.load(url);
object.castShadow = true;
object.receiveShadow = true;
object.position.y = -1;
object.position.x = 1.5;
object.name = "jsonObject";
objectList.push(object);
scene.add(object);
}
catch (err) {
return onError(err);
}
}
async function loadObj(objModelUrl, objectList)
{
const objPromiseLoader = promisifyLoader(new THREE.OBJLoader());
try {
const object = await objPromiseLoader.load(objModelUrl.obj);
let texture = objModelUrl.hasOwnProperty('map') ? new THREE.TextureLoader().load(objModelUrl.map) : null;
let normalMap = objModelUrl.hasOwnProperty('normalMap') ? new THREE.TextureLoader().load(objModelUrl.normalMap) : null;
let specularMap = objModelUrl.hasOwnProperty('specularMap') ? new THREE.TextureLoader().load(objModelUrl.specularMap) : null;
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.castShadow = true;
child.receiveShadow = true;
child.material.map = texture;
child.material.normalMap = normalMap;
child.material.specularMap = specularMap;
}
});
console.log(object)
object.scale.set(0.05, 0.05, 0.05);
object.position.z = 0;
object.position.x = 0;
object.rotation.y = 5;
object.name = "objObject";
objectList.push(object);
scene.add(object);
transformControl.attach(object)
}
catch (err) {
return onError(err);
}
}
function animate()
{
let now = Date.now();
let deltat = now - currentTime;
currentTime = now;
let fract = deltat / duration;
let angle = Math.PI * 2 * fract;
for(object of objectList)
if(object)
object.rotation.y += 0.01;
}
function run()
{
requestAnimationFrame(function() { run(); });
// Render the scene
renderer.render( scene, camera );
// Spin the cube for next frame
//animate();
// Update the camera controller
orbitControls.update();
}
function setLightColor(light, r, g, b)
{
r /= 255;
g /= 255;
b /= 255;
light.color.setRGB(r, g, b);
}
function createScene(canvas)
{
// Create the Three.js renderer and attach it to our canvas
renderer = new THREE.WebGLRenderer( { canvas: canvas, antialias: true } );
// Set the viewport size
renderer.setSize(canvas.width, canvas.height);
// Turn on shadows
renderer.shadowMap.enabled = true;
// Options are THREE.BasicShadowMap, THREE.PCFShadowMap, PCFSoftShadowMap
renderer.shadowMap.type = THREE.BasicShadowMap;
// Create a new Three.js scene
scene = new THREE.Scene();
// Add a camera so we can view the scene
camera = new THREE.PerspectiveCamera( 45, canvas.width / canvas.height, 1, 4000 );
camera.position.set(15, 3, 68);
scene.add(camera);
orbitControls = new THREE.OrbitControls(camera, renderer.domElement);
orbitControls.target.y=6;
orbitControls.target.x=0;
orbitControls.target.z=0;
//Pone la cámara auna distancia específica
orbitControls.minDistance=16;
orbitControls.maxDistance=16;
orbitControls.rotateSpeed=3;
//Bloquea la cámra a una distancia específica
orbitControls.minPolarAngle = Math.PI/2;
orbitControls.maxPolarAngle = Math.PI/2;
//Bloquea la rotación de la cámara
orbitControls.enablePan=false;
orbitControls.enableRotate=false;
transformControl = new THREE.TransformControls(camera, renderer.domElement);
transformControl.setMode('rotate')
transformControl.addEventListener( 'change', renderer.render( scene, camera ));
transformControl.setSize(500);
transformControl.showX = false;
transformControl.showY = true;
transformControl.showZ = false;
transformControl.addEventListener( 'dragging-changed', ( event ) => {
orbitControls.enabled = ! event.value;
});
scene.add(transformControl);
// Create a group to hold all the objects
root = new THREE.Object3D;
// Add a directional light to show off the object
directionalLight = new THREE.DirectionalLight( 0x808080, 1);
// Create and add all the lights
directionalLight.position.set(6, 1, 1);
directionalLight.target.position.set(4,9,0);
directionalLight.castShadow = true;
root.add(directionalLight);
spotLight = new THREE.SpotLight (0X808080);
spotLight.position.set(4, 15, 0);
spotLight.target.position.set(4, 0, 0);
root.add(spotLight);
spotLight.castShadow = true;
spotLight.shadow.camera.near = 1;
spotLight.shadow. camera.far = 200;
spotLight.shadow.camera.fov = 45;
spotLight.shadow.mapSize.width = SHADOW_MAP_WIDTH;
spotLight.shadow.mapSize.height = SHADOW_MAP_HEIGHT;
ambientLight = new THREE.AmbientLight ( 0x808080 , 0.8);
root.add(ambientLight);
// Create the objects
loadObj(objModelUrl, objectList);
//loadJson(jsonModelUrl.url, objectList);
// Create a group to hold the objects
group = new THREE.Object3D;
root.add(group);
// Create a texture map
let map = new THREE.TextureLoader().load(mapUrl);
map.wrapS = map.wrapT = THREE.RepeatWrapping;
map.repeat.set(8, 8);
let color = 0xffffff;
// let asteroid = new THREE.Object3D();
// Put in a ground plane to show off the lighting
let geometry = new THREE.PlaneGeometry(200, 200, 50, 50);
let mesh = new THREE.Mesh(geometry, new THREE.MeshPhongMaterial({color:color, map:map, side:THREE.DoubleSide}));
mesh.rotation.x = -Math.PI / 2;
mesh.position.y = 0;
mesh.castShadow = false;
mesh.receiveShadow = true;
//transformControl.attach(mesh);
group.add( mesh );
scene.add( root );
}```
|
A1Kiselev/united_undeground_backend
|
A1Kiselev/united_undeground_backend
Routes.ts
```import { Router } from "express";
import ResourceModel from "../models/Resource";
const router = Router()
router.get('/', ( async (req, res) => {
const resources = await ResourceModel.find({});
res.send(resources);
}))
router.get('/calculator', ((req, res) => {
res.send('good News!!');
}))
export default router;
```
mongo.ts
```import mongoose from "mongoose";
const openDatabaseConnection = async () => {
const connectionString = 'mongodb+srv://united:1@craftman.bkmzt.mongodb.net/united_undeground?retryWrites=true&w=majority';
await mongoose.connect(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
});
};
export default openDatabaseConnection;
```
Craft.ts
```import mongoose, { Document, Schema } from 'mongoose'
import { iResource } from "./Resource";
import CraftManRoles from "../enums/CraftManRoles";
export interface iCraft extends Document {
name: string,
role: CraftManRoles,
// @ts-ignore
roadMap: Array<Record<iResource | iCraft, number>>
}
const craftSchema = new Schema({
name: {
type: Schema.Types.String,
required: true,
unique: true
},
role: {
type: Schema.Types.String,
required: true
},
roadMap: {
type: Schema.Types.Array,
required: true
}
})
const CraftModel = mongoose.model<iCraft>("Craft", craftSchema);
export default CraftModel;
```
index.ts
```import express, { Application } from 'express';
import router from "./routes/Routes";
import openDatabaseConnection from "./mongo/mongo";
const port: number = 5000;
const app: Application = express();
app.use(router);
const start = async () => {
try {
await openDatabaseConnection();
app.listen(port, () => {
console.log(`Server running on port ${port}`);
})
} catch (e) {
console.log(e);
}
}
start();
```
CraftManRoles.ts
```const enum CraftManRoles {
Runnik = 'Runnik', // Рунник
Stonemason = 'Stonemason',//Каменьщик,
Alchemist = 'Alchemist',//Алхимик,
Сarpenter = 'Carpenter',//'Столяр',
Сurrier = 'Currier',//'Кожевник',
Blacksmith = 'Blacksmith', //'Кузнец',
Armorer = 'Armorer', //'Бронник',
Jeweler = 'Jeweler',//'Ювелир',
Necromancer = 'Necromancer',//'Некромант'
}
export default CraftManRoles;
```
mongoCraftMethods.ts
```import CraftModel, { iCraft } from "../models/Craft";
import CraftManRoles from "../enums/CraftManRoles";
import { iResource } from "../models/Resource";
export const getCraftById = async (id: string) => {
return CraftModel.find({
_id: id
});
}
export const getCraftByName = async (craftName: string) => {
return CraftModel.find({
name: craftName
});
}
export const getCraftByRole = async (craftManRole: CraftManRoles) => {
return CraftModel.find({
role: craftManRole
});
}
export const getCraftByResource = async (resourceName: string) => {
return CraftModel.find({
roadMap: resourceName
});
}
export const updateCraftName = async (currentName: string, updatedName: string) => {
return CraftModel.findOneAndUpdate({
name: currentName
},
{ $set: { name: updatedName } })
}
export const updateCraftRole = async (currentName: string, craftManRole: CraftManRoles) => {
return CraftModel.findOneAndUpdate({
name: currentName
},
{ $set: { role: craftManRole } })
}
export const updateCraftListResources = async (currentName: string, listResources: Array<iResource | iCraft>) => {
return CraftModel.findOneAndUpdate({
name: currentName
},
{ $set: { roadMap: listResources } })
}
export const deleteCraftById = async (id: string) => {
return CraftModel.deleteOne({
_id: id
});
}
```
Resource.ts
```import mongoose, { Schema, Document } from "mongoose";
import ResourceTypes from "../enums/ResourceTypes";
export interface iResource extends Document {
name: string,
type: ResourceTypes,
}
const resourcesSchema = new Schema({
name: {
type: Schema.Types.String,
required: true
},
type: {
type: Schema.Types.String,
required: true
}
});
const ResourceModel = mongoose.model<iResource>("Resource", resourcesSchema);
export default ResourceModel;
```
ResourceTypes.ts
```const enum ResourceTypes {
Wood = 'Древесина',
Roks = 'Камни',
Skins = 'Шкуры',
Ore = 'Руда',
Graive = 'Могильщик'
}
export default ResourceTypes;
```
|
A26mike/Valkyrie-AutoUpdate
|
A26mike/Valkyrie-AutoUpdate
autoupdate.py
```#Valkyrie-AutoUpdate
#Written By: Caleb 'Crow' Farrell
#Date: 2020 - 10 - 15
#TODO: Create output log
#DONE: #TODO: prevent any folder W/O meta.cpp file from crashing the program
#TODO: allow for both anon and signed in use of SteamCMD
#TODO: Create a system for users to download new mods by checking a file and referencing it to the array of existing ones
import glob
import re
import os
import time
import json
#config stuffs
configFile = 'config.json'
with open(configFile, 'r') as f:
datastore = json.load(f)
steamCMDPath = datastore["steamCmdPath"]
serverPath = datastore["arma3ServerPath"]
modsRepoPath = datastore["modsRepoPath"]
#Arma 3 SteamID
appId = '107410'
#Arma3 Server SteamID
serverAppId = '233780'
#Arma 3 Workshop Mod ID
publishedId = []
#ALL Mods should have a meta.cpp file, if not at the moment this will crash the script.
#I'm to lazy to actually make this not happen and skip the files that don't. suck it up.
metaFile = "meta.cpp"
#This should reference where you store all your mods,
# AGAIN STORE THEM ALL IN A SEPERATE FOLDER
# AS SAID ABOVE FAILURE TO DO SO WILL CRASH THE SCRIPT
print(" Mods Repo Path is: " + modsRepoPath)
#Getting all mod folders
modFolders = glob.glob(modsRepoPath + "/*/")
print(modFolders)
#This is reading the meta.cpp for the publisherID and appending it to our array
for item in modFolders:
print(item)
if os.path.exists(item +'./' + metaFile):
f = open(item + metaFile)
lines = (f.readlines())
publishedId.append(lines[1])
else:
print("meta.cpp does not exist in:" + item + "If mod folder please re-download manually ")
#here we define a new array for the cleansed publisherIDs
publishedIDs = []
#Thanks to ZE JEW #9273 on Discord for the assistance on this one!
for i in publishedId:
publishedIDs.append(
int(
''.join(
re.findall(r'\d+', i)
)
)
)
print(publishedIDs)
#Running the steamCMD to update Arma server
print(steamCMDPath)
print(serverPath)
os.system(steamCMDPath+'\\'+'SteamCMD +login anonymous + force_install_dir' + serverPath + '+app_update' + serverAppId + 'validate +quit')
for item in publishedIDs:
print(item)
os.system(steamCMDPath+'\\'+'SteamCMD +login anonymous + force_install_dir' + serverPath + '+workshop_download_item' + appId + str(item) + 'validate +quit')
time.sleep(15)
```
|
A284Philipi/1165_Numero-Primo_Cpp
|
A284Philipi/1165_Numero-Primo_Cpp
main.cpp
```#include <iostream>
using namespace std;
int main()
{
int cont = 0, casos, numero, i = 2, def = 0;
cin >> casos;
while (cont < casos){
cin >> numero;
if (numero <= 3){
cout << numero << " eh primo" <<endl;
}else{
while (i < numero){
if (numero % i == 0){
def = 1;
}else{
}
i++;
}
if (def == 1){
cout << numero << " nao eh primo" <<endl;
}else{
cout << numero << " eh primo" <<endl;
}
def = 0;
i = 2;
}
cont++;
}
return 0;
}
```
|
A3ner/fluig-process_history
|
A3ner/fluig-process_history
DefProces.java
```package com.fluig.model;
public class DefProces {
private String codDefProces;
private String desDefProces;
public DefProces(String codDefProces, String desDefProces) {
this.codDefProces = codDefProces;
this.desDefProces = desDefProces;
}
public String getCodDefProces() {
return codDefProces;
}
public void setCodDefProces(String codDefProces) {
this.codDefProces = codDefProces;
}
public String getDesDefProces() {
return desDefProces;
}
public void setDesDefProces(String desDefProces) {
this.desDefProces = desDefProces;
}
}
```
ServiceApplication.java
```package com.fluig.rest.application;
/**
* @author Anderson Rodrigues Gomes <br/>
* @author Bruno Alcantara Ribeiro Marcondes <br/>
* Corporation: TOTVS LTDA <br/>
* @version 1.0<br/>
* Department: FLUIG<br/>
* */
@javax.ws.rs.ApplicationPath("/rest")
public class ServiceApplication extends javax.ws.rs.core.Application {
}```
DatabaseManagement.java
```package com.fluig.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fluig.jdbc.ConnectionFactory;
import com.fluig.model.DefProces;
public class DatabaseManagement {
private Logger log = LoggerFactory.getLogger(DatabaseManagement.class);
private Connection con = null;
private PreparedStatement statement;
private ResultSet rs;
public DatabaseManagement(){
ConnectionFactory cf = new ConnectionFactory();
this.con = cf.getConnection();
}
public List<DefProces> findDefProces(long cod_empresa){
List<DefProces> lista = new ArrayList<DefProces>();
try {
this.statement = this.con.prepareStatement("select COD_DEF_PROCES, DES_DEF_PROCES from def_proces where cod_empresa = "+cod_empresa);
if (this.statement != null) {
this.rs = this.statement.executeQuery();
while (rs.next()){
lista.add(new DefProces(rs.getString("COD_DEF_PROCES"), rs.getString("DES_DEF_PROCES")));
}
}
} catch (SQLException e){
log.error(e.getMessage());
e.printStackTrace();
} finally {
log.info("#close connections...");
this.closeConnection(this.rs, this.statement, this.con);
}
return lista;
}
private void closeConnection(ResultSet rs, PreparedStatement stmt, Connection con){
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
log.error("error on close connections: " + e.getMessage());
e.printStackTrace();
}
}
}
```
ProcessHistory.java
```package com.fluig.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fluig.dao.DatabaseManagement;
@Path("/process")
public class ProcessHistory{
private Logger log = LoggerFactory.getLogger(ProcessHistory.class);
@GET
@Path("/{cod_empresa}")
@Produces({"application/json"})
public Response getProcess(@PathParam("cod_empresa") long cod_empresa)
{
try
{
return Response.ok(new DatabaseManagement().findDefProces(cod_empresa))
.build();
} catch (Exception e) {
e.printStackTrace();
}return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("Nao foi possivel carregar os processos")
.type("application/json")
.build();
}
}
```
|
AA-Akshat/Cubelelo-
|
AA-Akshat/Cubelelo-
README.md
```# Cubelelo-
Cubelelo (Web Development Task for Team IOSD)
```
|
AA472/EE-354
|
AA472/EE-354
main.c.c
```#include "stdlib.h"
#include "stm32f446.h"
//extern void assemblyFunc();
void Led_out();
void moveSandUp();
void moveSandDown();
void moveWaterUp();
void moveWaterDown();
void resetHour();
void resetWater();
void resetPach();
unsigned char rands[250];
unsigned char rows [16];//= {0xFF,0xFF,0xFF,0xFF,0xFF,0x7E, 0x3C,0,0,0,0,0,0,0,0,0}; // used for output
unsigned char LEDS [16][8] ;
//= // this is the initial shape of the hour glass
// {
// {1,1,1,1,1,1,1,1},{1,1,1,1,1,1,1,1},{1,1,1,1,1,1,1,1},{1,1,1,1,1,1,1,1},{1,1,1,1,1,1,1,1}
// ,{2,1,1,1,1,1,1,2},{2,2,1,1,1,1,2,2},{2,2,2,0,0,2,2,2},{2,2,2,0,0,2,2,2},{2,2,0,0,0,0,2,2}
// ,{2,0,0,0,0,0,0,2},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0}
// };
int mode = 2; //decides which of the three games
int main()
{
int tmp = GPIOA_IDR & (1<<2);
int tmp2 = GPIOA_IDR & (1<<3);
int tmp3 = GPIOA_IDR & (1<<4);
if(tmp !=0)
mode = 2;
if(tmp2 !=0)
mode = 2;
for(int i=0; i<250;i++)
rands[i] = rand();
int x = 0;
//Enable Port A clock
RCC_AHB1ENR |= 1;
//Enable Port C clock
RCC_AHB1ENR |= 1<<2;
RCC_APB2ENR |= 0x100;
// A/D clock
GPIOA_MODER |= 0x3FF;
//Entire PC port is output
GPIOC_MODER |= 0x555555555;
//Set Pull up pull down off
GPIOA_PUPDR &= 0xFFFFFFFF3;
ADC1_CR2 |= 1; //A/D enable
ADC1_SQR3 = 1;
//Start conversion initial
ADC1_CR2 |= 1<<30;
if(mode == 1)
resetHour();
else if(mode==2)
resetWater();
while(1)
{
ADC1_CR2 |= 1<<30;//Start conversion
unsigned int TimeOut = 0;
while(((ADC1_SR &(1<<1))== 0) && TimeOut < 100000)
{
TimeOut++;//Timeout variable in case of error
}
//Load in A/D value
x = ADC1_DR;
if(x < 1900 ){
if(mode == 1)
moveSandUp();
else if (mode == 2)
moveWaterUp();
}
else if (x > 2200){
if(mode == 1)
moveSandDown();
else if (mode == 2)
moveWaterDown();
}
for(int i =0; i<100; i++)
Led_out();
}
}
//if the board is tilted, this will move the LEDS like an hour glass towards gravity.
void moveWaterUp(){
for( unsigned char i = 1; i != 16; i++){ // go throw all rows except the bottom because it cannot go down
if((i <16 && i > 11)||(i < 4)){
for( unsigned char j = 0; j != 8; j++){ // go throw all the columns
if(LEDS[i][j] == 1){
if(LEDS[i-1][j] == 0){
LEDS [i-1][j] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i-1] |= 1<<j;
}
else if(j >0 && LEDS[i-1][j-1] == 0){
LEDS [i-1][j-1] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i-1] |= 1<<(j-1);
}
else if(j >0 && LEDS[i][j-1] == 0){
LEDS [i][j-1] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i] |= 1<<(j-1);
}
}
}
}
else{
for( unsigned char j = 7; j != 255; j--){ // go throw all the columns
if(LEDS[i][j] == 1){
if(LEDS[i-1][j] == 0){
LEDS [i-1][j] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i-1] |= 1<<j;
}
else if(j < 7 && LEDS[i+1][j+1] == 0 && i!=5){
LEDS [i-1][j+1] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i-1] |= 1<<(j+1);
}
else if(j < 7 && LEDS[i][j+1] == 0){
LEDS [i][j+1] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i] |= 1<<(j+1);
}
}
}
}
}
}
void moveWaterDown(){
for( unsigned char i = 14; i != 255; i--){ // go throw all rows except the bottom because it cannot go down
if((i <15 && i > 10)||(i < 4)){
for( unsigned char j = 7; j != 255; j--){ // go throw all the columns
if(LEDS[i][j] == 1){
if(LEDS[i+1][j] == 0){
LEDS [i+1][j] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i+1] |= 1<<j;
}
else if(j < 7 && LEDS[i+1][j+1] == 0){
LEDS [i+1][j+1] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i+1] |= 1<<(j+1);
}
else if(j < 7 && LEDS[i][j+1] == 0 ){
LEDS [i][j+1] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i] |= 1<<(j+1);
}
}
}
}
else{
for( unsigned char j = 0; j != 8; j++){ // go throw all the columns
if(LEDS[i][j] == 1){
if(LEDS[i+1][j] == 0){
LEDS [i+1][j] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i+1] |= 1<<j;
}
else if(j >0 && LEDS[i+1][j-1] == 0 && i!=10){
LEDS [i+1][j-1] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i+1] |= 1<<(j-1);
}
else if(j >0 && LEDS[i][j-1] == 0){
LEDS [i][j-1] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i] |= 1<<(j-1);
}
}
}
}
}
}
void moveSandDown(){
for( unsigned char i = 14; i != 255; i--){ // go throw all rows except the bottom because it cannot go down
for( unsigned char j = 7; j != 255; j--){ // go throw all the columns
if(LEDS[i][j] == 1){ // if the current LED is lit up
if(LEDS[i + 1][j] == 0){ // if the LED under it is empty, move there
LEDS [i+1][j] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i+1] |= 1<<j;
}
else if(LEDS[i + 1][j + 1] == 0 && j < 7){ //otherwise check
LEDS [i+1][j+ 1] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i+1] |= 1<< (1 + j);
}
else if(LEDS[i + 1][j-1] == 0 && j >0){
LEDS [i+1][j-1] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i+1] |= 1<<(j-1);
}
}
}
}
} //if the board is tilted, this will move the LEDS like an hour glass towards gravity.
void moveSandUp(){
unsigned char temp;
for( unsigned char i = 1; i != 16; i++){
temp =0;
for( unsigned char j = 7; j != 255; j--){
if(LEDS[i][j] == 1){
if(LEDS[i - 1][j] == 0){
LEDS [i-1][j] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i-1] |= 1<<j;
}
else if(LEDS[i - 1][j + 1] == 0 && j < 7){
LEDS [i-1][j+ 1] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i-1] |= 1<<(j+1);
}
else if(LEDS[i - 1][j-1] == 0 && j >0){
LEDS [i-1][j-1] = 1;
LEDS [i][j] = 0;
rows [i] &= ~(1<<j);
rows [i-1] |= 1<<(j-1);
}
}
}
}
}
void Led_out(void){
unsigned int tmp = 0;
//Store output value in tmp
tmp = GPIOC_ODR;
//tmp |= 0x38;//PC3-5 = high, decoder row 0 off
tmp |= 1<<9;//PC6 On, Decoder 1 off
tmp &= ~(1<<8);//PC7 Off, Decoder 2 on
for ( int i = 0; i < 8; i++)
{
tmp = GPIOC_ODR;
tmp &= ~(0x1c00);//Clears decoder bits
tmp |= i<<10;//Set i into decoder pins
tmp &= ~(0xFF );//Clear driver values
tmp |= rows[i] ;//Force value of driver
tmp |= 1<<9;//PC6 On, Decoder 1 off
tmp &= ~(1<<8);//PC7 Off, Decoder 2 on
GPIOC_ODR = tmp;
for (int k = 0; k < 100; k++);
}
for (int i = 0; i < 8; i++)
{
tmp = GPIOC_ODR;
tmp &= ~(0x1c00);//Clears decoder bits
tmp |= i<<10;//Set i into decoder pins
tmp &= ~(0xFF );//Clear driver values
tmp |= rows[i+8] ;//Force value of driver
tmp &= ~(1<<9);//PC6 off, Decoder 1 on
tmp |= 1<<8;//PC7 on, Decoder 2 off
GPIOC_ODR = tmp;
for (int k = 0; k < 100; k++);
}
}
void resetHour(){
rows[0] = 0xFF;
rows[1] = 0xFF;
rows[2] = 0xFF;
rows[3] = 0xFF;
rows[4] = 0x7E;
rows[5] = 0x3C;
rows[6] = 0;
rows[7] = 0;
rows[8] = 0;
rows[9] = 0;
rows[10] = 0;
rows[11] = 0;
rows[12] = 0;
rows[13] = 0;
rows[14] = 0;
rows[15] = 0;
for(unsigned char i = 0; i < 16; i++){
for(unsigned char j = 0; j<8 ; j++){
if( i < 7)
LEDS[i][j] = 1;
else
LEDS[i][j] = 0;
}
}
LEDS[5][0] = 2; LEDS [5][7] = 2;
LEDS[6][0] = 2; LEDS [6][1] =2; LEDS[6][6] = 2; LEDS[6][7] = 2;
LEDS[7][0] = 2; LEDS [7][1] = 2; LEDS[7][2] = 2; LEDS[7][5] = 2; LEDS [7][6] = 2; LEDS[7][7] = 2;
LEDS[8][0] = 2; LEDS [8][1] = 2; LEDS[8][2] = 2; LEDS[8][5] = 2; LEDS [8][6] = 2; LEDS[8][7] = 2;
LEDS[9][0] = 2; LEDS [9][1] =2; LEDS[9][6] = 2; LEDS[9][7] = 2;
LEDS[10][0] = 2; LEDS [10][7] = 2;
}
void resetWater(){
rows[0] = 0xFF;
rows[1] = 0xFF;
rows[2] = 0xFF;
rows[3] = 0;
rows[4] = 0;
rows[5] = 0;
rows[6] = 0;
rows[7] = 0;
rows[8] = 0;
rows[9] = 0;
rows[10] = 0;
rows[11] = 0;
rows[12] = 0;
rows[13] = 0;
rows[14] = 0;
rows[15] = 0;
for(unsigned char i = 0; i < 16; i++){
for(unsigned char j = 0; j<8 ; j++){
if( i < 3)
LEDS[i][j] = 1;
else if( i==4 && j < 7)
LEDS[i][j]=2;
else if( i==11 && j >0)
LEDS[i][j]=2;
else
LEDS[i][j] = 0;
}
}
}
```
|
AAWhang/cat-dog
|
AAWhang/cat-dog
scripts.js
```$(document).ready(function() {
$("button#Cat").click(function() {
$("ul#call").prepend("<img src='img/cat.png'>");
$("ul#response").prepend("<img src='img/dog.jpg'>");
$("ul#call").children("img").first().click(function() {
$(this).remove();
});
$("ul#response").children("img").first().click(function() {
$(this).remove();
});
});
$("button#Dog").click(function() {
$("ul#call").prepend("<img src='img/dog.jpg'>");
$("ul#response").prepend("<img src='img/cat.png'>");
$("ul#call").children("img").first().click(function() {
$(this).remove();
});
$("ul#response").children("img").first().click(function() {
$(this).remove();
});
});
});
```
|
AAkira/MultiTicker
|
AAkira/MultiTicker
multiticker.go
```package multiticker
import (
"time"
)
type MultiTicker struct {
C <-chan Tick // send label and time
c chan Tick
items []tickItem
closeCh chan struct{}
}
func NewMultiTicker(intervalSecond map[string]time.Duration) *MultiTicker {
g := 1
m := 0
for _, v := range intervalSecond {
s := int(v.Seconds())
g = gcd(g, s)
m = max(m, s)
}
items := make([]tickItem, 0, len(intervalSecond))
for k, v := range intervalSecond {
items = append(items, tickItem{key: k, gcdPoint: int(v.Seconds()) / g})
}
c := make(chan Tick, 1)
t := &MultiTicker{
C: c,
c: c,
items: items,
closeCh: make(chan struct{}),
}
go t.start(g, m)
return t
}
func (m *MultiTicker) start(gcd int, max int) {
defer close(m.c)
ticker := time.NewTicker(time.Duration(gcd) * time.Second)
defer ticker.Stop()
loopCount := 1
resetCount := max / gcd
for {
select {
case <-m.closeCh:
return
case t := <-ticker.C:
for _, v := range m.items {
if loopCount%v.gcdPoint != 0 {
continue
}
// non-blocking send
select {
case m.c <- Tick{v.key, t}:
time.Sleep(1 * time.Microsecond)
default:
}
}
if loopCount == resetCount {
loopCount = 1
} else {
loopCount++
}
}
}
}
// call this function only once
func (m *MultiTicker) Stop() {
close(m.closeCh)
}
type Tick struct {
Key string
Tick time.Time
}
type tickItem struct {
key string
gcdPoint int
}
func gcd(a, b int) int {
if b == 0 {
return a
} else {
return gcd(b, a%b)
}
}
func max(a, b int) int {
if a > b {
return a
} else {
return b
}
}
```
README.md
```# Multiple ticker
This library is the efficiently multiple ticker like `time.Ticker`.
```
|-----> [A, time.Time] /2s
[A:2, B:4, C:6] Interval List => ⏱MultipleTicker => ---|-----> [B, time.Time] /4s
|-----> [C, time.TIme] /6s
```
For example, you set 2, 4 and 6.
Ticker interval is 2s(gcd).
`ticker.C` is received `string` key and `time.Time`.
## Usage
### Install
`$ go get github.com/aakira/multiticker`
### How to use
Set the map with key and time.Duration.
`map[string]time.Duration` (key: string, intervalSeconds: time.Duration)
```go
interval := map[string]time.Duration{"a": 2 * time.Second, "b": 4 * time.Second, "c": 6 * time.Second}
ticker := multiticker.NewMultiTicker(interval)
// Must call this stop function
defer ticker.Stop()
for c := range ticker.C {
switch c.Key {
case "a": // receive per 2s
fmt.Printf("receive: %s, time: %v\n", c.Key, c.Tick)
case "b": // receive per 4s
fmt.Printf("receive: %s, time: %v\n", c.Key, c.Tick)
case "c": // receive per 6s
fmt.Printf("receive: %s, time: %v\n", c.Key, c.Tick)
default:
fmt.Printf("receive: %s, time: %v\n", c.Key, c.Tick)
return
}
}
```
## License
```
Copyright (C) 2018 A.Akira
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.
```
```
main.go
```package main
import (
"time"
"fmt"
"github.com/aakira/multiticker"
)
func main() {
ticker := multiticker.NewMultiTicker(map[string]time.Duration{
"a": 4 * time.Second,
"b": 2 * time.Second,
"c": 6 * time.Second,
"d": 10 * time.Second,
})
defer ticker.Stop() // you must call stop function
for c := range ticker.C {
switch c.Key {
case "a":
fmt.Printf("receive: %s, time: %v\n", c.Key, c.Tick)
case "b":
fmt.Printf("receive: %s, time: %v\n", c.Key, c.Tick)
case "c":
fmt.Printf("receive: %s, time: %v\n", c.Key, c.Tick)
default:
fmt.Printf("receive: %s, time: %v\n", c.Key, c.Tick)
return
}
}
}
```
multiticker_test.go
```package multiticker
import (
"testing"
"time"
"context"
"fmt"
)
func TestMultiTicker(t *testing.T) {
t.Helper()
type testCase struct {
name string
list map[string]int
timeoutSecond int
}
testCases := []testCase{
{
name: "normal",
list: map[string]int{
"a": 2,
"b": 4,
"c": 6,
"d": 12,
},
timeoutSecond: 9,
},
{
name: "prime number",
list: map[string]int{
"a": 3,
"b": 7,
},
timeoutSecond: 11,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
loopCounter := make(map[string]int, len(testCase.list))
loopCountDefault := 0
intervalList := make(map[string]time.Duration, len(testCase.list))
for k, v := range testCase.list {
intervalList[k] = time.Duration(v) * time.Second
loopCounter[k] = 0
}
ticker := NewMultiTicker(intervalList)
defer ticker.Stop()
ctx, cancel := context.WithTimeout(context.Background(),
time.Duration(testCase.timeoutSecond)*time.Second)
defer cancel()
fmt.Println(loopCounter)
L:
for {
select {
case c := <-ticker.C:
if _, ok := loopCounter[c.Key]; ok {
loopCounter[c.Key]++
fmt.Printf("%s %d", c.Key, loopCounter[c.Key])
} else {
loopCountDefault++
}
case <-ctx.Done():
break L
}
}
for k, v := range loopCounter {
// check caller count
fmt.Printf("%s %d %d \n", k, v, testCase.timeoutSecond/testCase.list[k])
if v != testCase.timeoutSecond/testCase.list[k] {
t.Fail()
}
}
if loopCountDefault != 0 {
t.Fail()
}
})
}
}
func TestMultiTicker_gcd(t *testing.T) {
t.Helper()
type testCase struct {
name string
inputA int
inputB int
expected int
}
testCases := []testCase{
{
name: "1, 2",
inputA: 1,
inputB: 2,
expected: 1,
},
{
name: "1, 7",
inputA: 1,
inputB: 7,
expected: 1,
},
{
name: "2, 4",
inputA: 2,
inputB: 4,
expected: 2,
},
{
name: "prime number",
inputA: 7,
inputB: 11,
expected: 1,
},
{
name: "0, 1",
inputA: 0,
inputB: 1,
expected: 1,
},
{
name: "10, 5",
inputA: 10,
inputB: 5,
expected: 5,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
if gcd(testCase.inputA, testCase.inputB) != testCase.expected {
t.Fail()
}
})
}
}
func TestMultiTicker_max(t *testing.T) {
t.Helper()
type testCase struct {
name string
inputA int
inputB int
expected int
}
testCases := []testCase{
{
name: "1, 2",
inputA: 1,
inputB: 2,
expected: 2,
},
{
name: "0, 1",
inputA: 0,
inputB: 1,
expected: 1,
},
{
name: "10, 4",
inputA: 10,
inputB: 4,
expected: 10,
},
{
name: "11, 7",
inputA: 11,
inputB: 7,
expected: 11,
},
{
name: "10, 10",
inputA: 10,
inputB: 10,
expected: 10,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
if max(testCase.inputA, testCase.inputB) != testCase.expected {
t.Fail()
}
})
}
}
```
|
AB07AB/PRO-C101
|
AB07AB/PRO-C101
CloudStorage.py
```import dropbox
import os
from dropbox.files import WriteMode
class TransferData:
def __init__(self, access_token):
self.access_token = access_token
def upload_file(self, file_from, file_to):
dbx = dropbox.Dropbox(self.access_token)
for root,dirs,files in os.walk(file_from):
for filename in files:
local_path=os.path.join(root,filename)
relative_path = os.path.relpath(local_path, file_from)
dropbox_path = os.path.join(file_to, relative_path)
f = open(file_from, 'rb')
dbx.files_upload(f.read(),dropbox_path, mode=WriteMode('overwrite'))
def main():
access_token = 'xrABerC6IiMAAAAAAAAAAREsARBDof83GGQhubgxe9m36TGOP8s4W9y7UcrR8dW6'
transferData = TransferData(access_token)
file_from = input("Enter the file path to transfer : ")
file_to = input("Enter the full path to upload to dropbox: ")
transferData.upload_file(file_from, file_to)
print("File has been succesfully moved")
main()```
|
ABAPPLO/chatbot_learn
|
ABAPPLO/chatbot_learn
README.md
```# chatnot
聊天机器人相关
目前两个文件 一个是 中文的chart bot 别人写的
另一个人是比较全的全世界的聊天机器人框架或这完整的代码
```
|
ABAPREPO/ZTESTPROJECT
|
ABAPREPO/ZTESTPROJECT
README.md
```# ZTESTPROJECT
Sample project
```
|
ABCDEF-123456/testing
|
ABCDEF-123456/testing
README.md
```# testing
This is a markdown file
# Edureka-Internship-Assignment-1
```
|
ABCpdf-Team/PDF-OCG-Layers
|
ABCpdf-Team/PDF-OCG-Layers
Form1.cs
```// ===========================================================================
// ©2013-2021 WebSupergoo. All rights reserved.
//
// This source code is for use exclusively with the ABCpdf product under
// the terms of the license for that product. Details can be found at
//
// http://www.websupergoo.com/
//
// This copyright notice must not be deleted and must be reproduced alongside
// any sections of code extracted from this module.
// ===========================================================================
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using WebSupergoo.ABCpdf12;
using WebSupergoo.ABCpdf12.Objects;
using WebSupergoo.ABCpdf12.Operations;
using WebSupergoo.ABCpdf12.Atoms;
using OptionalContent;
namespace OCGLayers
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form {
private Button annotateButton;
private Button removeButton;
private TextBox textBox2;
private PictureBox previewPictureBox;
private CheckedListBox layersCheckedListBox;
private ComboBox pageCombo;
private Button openButton;
private Button saveButton;
private Button createButton1;
private Button createButton2;
private Button createButton3;
private TextBox textBox1;
private TextBox textBox3;
private Button openExternallyButton;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.annotateButton = new System.Windows.Forms.Button();
this.removeButton = new System.Windows.Forms.Button();
this.textBox2 = new System.Windows.Forms.TextBox();
this.previewPictureBox = new System.Windows.Forms.PictureBox();
this.layersCheckedListBox = new System.Windows.Forms.CheckedListBox();
this.pageCombo = new System.Windows.Forms.ComboBox();
this.openButton = new System.Windows.Forms.Button();
this.saveButton = new System.Windows.Forms.Button();
this.createButton1 = new System.Windows.Forms.Button();
this.createButton2 = new System.Windows.Forms.Button();
this.createButton3 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox3 = new System.Windows.Forms.TextBox();
this.openExternallyButton = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.previewPictureBox)).BeginInit();
this.SuspendLayout();
//
// annotateButton
//
this.annotateButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.annotateButton.Location = new System.Drawing.Point(599, 609);
this.annotateButton.Name = "annotateButton";
this.annotateButton.Size = new System.Drawing.Size(247, 33);
this.annotateButton.TabIndex = 2;
this.annotateButton.Text = "Annotate Layers";
this.annotateButton.Click += new System.EventHandler(this.annotateButton_Click);
//
// removeButton
//
this.removeButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.removeButton.Location = new System.Drawing.Point(599, 655);
this.removeButton.Name = "removeButton";
this.removeButton.Size = new System.Drawing.Size(247, 34);
this.removeButton.TabIndex = 3;
this.removeButton.Text = "Remove Invisible Layers";
this.removeButton.Click += new System.EventHandler(this.removeButton_Click);
//
// textBox2
//
this.textBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox2.Location = new System.Drawing.Point(25, 748);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(541, 26);
this.textBox2.TabIndex = 5;
//
// previewPictureBox
//
this.previewPictureBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.previewPictureBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.previewPictureBox.Location = new System.Drawing.Point(25, 26);
this.previewPictureBox.Name = "previewPictureBox";
this.previewPictureBox.Size = new System.Drawing.Size(541, 698);
this.previewPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.previewPictureBox.TabIndex = 6;
this.previewPictureBox.TabStop = false;
//
// layersCheckedListBox
//
this.layersCheckedListBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.layersCheckedListBox.FormattingEnabled = true;
this.layersCheckedListBox.Location = new System.Drawing.Point(599, 72);
this.layersCheckedListBox.Name = "layersCheckedListBox";
this.layersCheckedListBox.Size = new System.Drawing.Size(247, 172);
this.layersCheckedListBox.TabIndex = 7;
this.layersCheckedListBox.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.layersCheckedListBox_ItemCheck);
//
// pageCombo
//
this.pageCombo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.pageCombo.FormattingEnabled = true;
this.pageCombo.Location = new System.Drawing.Point(599, 26);
this.pageCombo.Name = "pageCombo";
this.pageCombo.Size = new System.Drawing.Size(247, 28);
this.pageCombo.TabIndex = 8;
this.pageCombo.SelectedIndexChanged += new System.EventHandler(this.pageCombo_SelectedIndexChanged);
//
// openButton
//
this.openButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.openButton.Location = new System.Drawing.Point(25, 791);
this.openButton.Name = "openButton";
this.openButton.Size = new System.Drawing.Size(165, 34);
this.openButton.TabIndex = 9;
this.openButton.Text = "Load PDF...";
this.openButton.Click += new System.EventHandler(this.openButton_Click);
//
// saveButton
//
this.saveButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.saveButton.Location = new System.Drawing.Point(360, 791);
this.saveButton.Name = "saveButton";
this.saveButton.Size = new System.Drawing.Size(165, 34);
this.saveButton.TabIndex = 10;
this.saveButton.Text = "Save PDF...";
this.saveButton.Click += new System.EventHandler(this.saveButton_Click);
//
// createButton1
//
this.createButton1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.createButton1.Location = new System.Drawing.Point(599, 369);
this.createButton1.Name = "createButton1";
this.createButton1.Size = new System.Drawing.Size(247, 34);
this.createButton1.TabIndex = 11;
this.createButton1.Text = "Create Simple Layers";
this.createButton1.Click += new System.EventHandler(this.createButton1_Click);
//
// createButton2
//
this.createButton2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.createButton2.Location = new System.Drawing.Point(599, 409);
this.createButton2.Name = "createButton2";
this.createButton2.Size = new System.Drawing.Size(247, 34);
this.createButton2.TabIndex = 12;
this.createButton2.Text = "Create Nested Layers";
this.createButton2.Click += new System.EventHandler(this.createButton2_Click);
//
// createButton3
//
this.createButton3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.createButton3.Location = new System.Drawing.Point(599, 449);
this.createButton3.Name = "createButton3";
this.createButton3.Size = new System.Drawing.Size(247, 34);
this.createButton3.TabIndex = 13;
this.createButton3.Text = "Create Membership Layers";
this.createButton3.Click += new System.EventHandler(this.createButton3_Click);
//
// textBox1
//
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textBox1.Enabled = false;
this.textBox1.Location = new System.Drawing.Point(599, 259);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(247, 104);
this.textBox1.TabIndex = 14;
this.textBox1.Text = "The buttons below allow you to create different types of layer structure. Details" +
" of the specific structures created can be found in the source code.";
//
// textBox3
//
this.textBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.textBox3.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textBox3.Enabled = false;
this.textBox3.Location = new System.Drawing.Point(599, 514);
this.textBox3.Multiline = true;
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(247, 89);
this.textBox3.TabIndex = 15;
this.textBox3.Text = "Use the buttons below to annotate items on the page with their layer details and " +
"also to delete and redact items on specific layers.";
//
// openExternallyButton
//
this.openExternallyButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.openExternallyButton.Location = new System.Drawing.Point(599, 704);
this.openExternallyButton.Name = "openExternallyButton";
this.openExternallyButton.Size = new System.Drawing.Size(247, 34);
this.openExternallyButton.TabIndex = 16;
this.openExternallyButton.Text = "Open in Acrobat";
this.openExternallyButton.UseVisualStyleBackColor = true;
this.openExternallyButton.Click += new System.EventHandler(this.openExternallyButton_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(8, 19);
this.ClientSize = new System.Drawing.Size(873, 856);
this.Controls.Add(this.openExternallyButton);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.createButton3);
this.Controls.Add(this.createButton2);
this.Controls.Add(this.createButton1);
this.Controls.Add(this.saveButton);
this.Controls.Add(this.openButton);
this.Controls.Add(this.pageCombo);
this.Controls.Add(this.layersCheckedListBox);
this.Controls.Add(this.previewPictureBox);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.removeButton);
this.Controls.Add(this.annotateButton);
this.Name = "Form1";
this.Text = "Optional Content Demo";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.previewPictureBox)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private Doc _doc;
List<Group> _groups;
private void Form1_Load(object sender, EventArgs e) {
string thePath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string[] files = Directory.GetFiles(thePath, "*.pdf");
foreach (string file in files) {
if (!file.Contains("_out")) {
try {
LoadPDF(file);
break;
}
catch {
}
}
}
}
private void annotateButton_Click(object sender, EventArgs e) {
if (_doc == null)
return;
Properties props = Properties.FromDoc(_doc, false);
foreach (Page page in _doc.ObjectSoup.Catalog.Pages.GetPageArrayAll()) {
Reader oc = Reader.FromPage(props, page);
TextOperation op = new TextOperation(_doc);
op.PageContents.AddPages();
string text = op.GetText();
IList<TextFragment> fragments = op.Select(0, text.Length);
_doc.FontSize = 12;
_doc.Width = 0.1;
foreach (TextFragment fragment in fragments) {
_doc.Rect.String = fragment.Rect.String;
List<OptionalContent.Layer> states = oc.GetLayersFromStreamAndPosition(fragment.StreamID, fragment.StreamOffset);
string[] names = new string[states.Count];
for (int i = 0; i < names.Length; i++) {
names[i] = states[i].Group != null ? states[i].Group.EntryName.Text : "Membership Dictionary";
}
if (names.Length > 0)
_doc.AddText(string.Join(" ", names));
_doc.FrameRect();
}
}
UpdatePreview();
}
private void removeButton_Click(object sender, EventArgs e) {
if (_doc == null)
return;
try {
Cursor.Current = Cursors.WaitCursor;
Properties props = Properties.FromDoc(_doc, false);
Page page = (Page)_doc.ObjectSoup[_doc.Page];
Reader reader = Reader.FromPage(props, page);
List<OptionalContent.Layer> layers = reader.GetLayers();
foreach (OptionalContent.Layer layer in layers) {
if (layer.Visible == false) {
if (reader == null)
reader = Reader.FromPage(props, page);
Reader.Redact(ref reader, layer);
}
}
UpdateLayers();
UpdatePreview();
}
finally {
Cursor.Current = Cursors.Default;
}
}
private List<TemporaryFile> _tempFiles;
private void openExternallyButton_Click(object sender, EventArgs e) {
if (_tempFiles == null)
_tempFiles = new List<TemporaryFile>();
TemporaryFile temp = new TemporaryFile(".pdf");
// when we save we try to keep the object ids constant
_doc.SaveOptions.Linearize = false;
_doc.SaveOptions.Remap = false;
_doc.Save(temp.Path);
_tempFiles.Add(temp);
System.Diagnostics.Process.Start(temp.Path);
}
private void createButton1_Click(object sender, EventArgs e) {
Doc doc = new Doc();
Properties props = Properties.FromDoc(doc, true);
List<Group> groups = new List<Group>();
for (int i = 1; i < 4; i++)
groups.Add(props.AddGroup("Layer " + i.ToString(), null));
doc.FontSize = 36;
doc.Rect.Inset(20, 20);
for (int i = 0; i < 1; i++) {
doc.Page = doc.AddPage();
Page page = (Page)doc.ObjectSoup[doc.Page];
Writer writer = new Writer(props, page);
foreach (Group group in groups) {
OptionalContent.Layer layer = writer.AddGroup(group);
writer.StartLayer(layer);
doc.AddText(group.EntryName.Text + "\r\n");
writer.EndLayer();
doc.AddText("Always Visible\r\n");
writer.StartLayer(layer);
doc.AddText(group.EntryName.Text + "\r\n\r\n");
writer.EndLayer();
}
doc.Flatten();
}
LoadPDF(doc);
}
private void createButton2_Click(object sender, EventArgs e) {
Doc doc = new Doc();
Properties props = Properties.FromDoc(doc, true);
Group parent = null;
List<Group> groups = new List<Group>();
// The Optional Content Group parent determines the nesting in the UI.
// The presentation of the nesting is separate from the actual nesting
// of visibility. In general you will want to ensure the two correspond
// as in the code here.
for (int i = 1; i <= 10; i++) {
Group group = props.AddGroup("Layer " + i.ToString(), parent);
groups.Add(group);
parent = i == 5 ? null : group;
}
doc.Page = doc.AddPage();
doc.FontSize = 36;
doc.Rect.Inset(20, 20);
Page page = (Page)doc.ObjectSoup[doc.Page];
Writer writer = new Writer(props, page);
// This determines the nesting of actual visibility. Here we ensure that this
// corresponds to the hierarchy specified in the UI so that it works in an
// obvious way.
for (int i = 0; i < groups.Count; i++) {
Group group = groups[i];
OptionalContent.Layer layer = writer.AddGroup(group);
if (i == 5)
while (writer.Depth > 0)
writer.EndLayer();
writer.StartLayer(layer);
doc.AddText(group.EntryName.Text + "\r\n");
}
while (writer.Depth > 0)
writer.EndLayer();
doc.Flatten();
LoadPDF(doc);
}
private void createButton3_Click(object sender, EventArgs e) {
Doc doc = new Doc();
Properties props = Properties.FromDoc(doc, true);
List<Group> groups = new List<Group>();
for (int i = 1; i < 4; i++)
groups.Add(props.AddGroup("Layer " + i.ToString(), null));
// membership policies are simple to use but limited in scope
MembershipGroup alloff = props.AddMembershipGroup();
alloff.Policy = MembershipGroup.PolicyEnum.AllOff;
alloff.PolicyGroups = groups;
// membership visibility expressions are more complex but more powerful
MembershipGroup mgve = props.AddMembershipGroup();
ArrayAtom ve = mgve.MakeVisibilityExpression(MembershipGroup.LogicEnum.Or, groups);
mgve.EntryVE = mgve.MakeVisibilityExpression(MembershipGroup.LogicEnum.Not, new ArrayAtom[] { ve });
doc.FontSize = 36;
doc.Rect.Inset(20, 20);
for (int i = 0; i < 3; i++) {
doc.Page = doc.AddPage();
Page page = (Page)doc.ObjectSoup[doc.Page];
Writer writer = new Writer(props, page);
OptionalContent.Layer layer1 = writer.AddGroup(alloff);
doc.AddText("The next line uses a Policy so that it is only visible if all layers are turned off...\r\n");
writer.StartLayer(layer1);
doc.AddText("I am normally invisible\r\n\r\n");
writer.EndLayer();
OptionalContent.Layer layer2 = writer.AddGroup(mgve);
doc.AddText("The next line uses a Visibility Expression so that it is only visible if all layers are turned off...\r\n");
writer.StartLayer(layer2);
doc.AddText("I am normally invisible\r\n");
writer.EndLayer();
doc.Flatten();
}
LoadPDF(doc);
}
private void pageCombo_SelectedIndexChanged(object sender, EventArgs e) {
_doc.PageNumber = pageCombo.SelectedIndex + 1;
UpdateLayers();
UpdatePreview();
}
private void LoadPDF(string file) {
Doc doc = new Doc();
doc.Read(file);
LoadPDF(doc);
textBox2.Text = file;
}
private class ComboBoxItem {
public string Name;
public int Value;
public ComboBoxItem(string name, int value) {
Name = name; Value = value;
}
public override string ToString() {
return Name;
}
}
private void LoadPDF(Doc doc) {
_doc = doc;
_groups = null;
int n = _doc.PageCount;
pageCombo.Items.Clear();
for (int i = 1; i <= n; i++)
pageCombo.Items.Add(new ComboBoxItem("Page " + i.ToString() + " of " + n.ToString(), i));
pageCombo.SelectedIndex = 0;
UpdateLayers();
UpdatePreview();
}
private void UpdateLayers() {
_groups = null;
layersCheckedListBox.Items.Clear();
if (_doc == null)
return;
Properties oc = Properties.FromDoc(_doc, false);
if (oc == null)
return;
Configuration config = oc.GetDefault();
if (config == null)
return;
Page page = (Page)_doc.ObjectSoup[_doc.Page];
List<Group> groups = oc.GetGroups(page);
List<int> indents = new List<int>();
oc.SortGroupsForPresentation(groups, indents);
Doc doc = _doc;
try {
_doc = null;
int n = groups.Count;
for (int i = 0; i < n; i++) {
Group group = groups[i];
string indent = new string(' ', indents[i] * 3);
layersCheckedListBox.Items.Add(indent + group.EntryName.Text, group.Visible);
}
}
finally {
_doc = doc;
_groups = groups;
}
}
private void UpdatePreview() {
if (_doc == null) {
previewPictureBox.Image = null;
return;
}
_doc.Rect.String = _doc.MediaBox.String;
previewPictureBox.Image = _doc.Rendering.GetBitmap();
//if (_doc.Rendering.Log.Length > 0)
// MessageBox.Show("Render warning: " + _doc.Rendering.Log);
}
private void layersCheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e) {
if ((_doc == null) || (_groups == null) || (e.NewValue == CheckState.Indeterminate))
return;
_groups[e.Index].Visible = e.NewValue == CheckState.Checked;
UpdatePreview();
}
private void openButton_Click(object sender, EventArgs e) {
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "PDF Files (.pdf)|*.pdf|AI Files (*.ai)|*.ai";
dialog.FilterIndex = 1;
if (dialog.ShowDialog() == DialogResult.OK)
LoadPDF(dialog.FileName);
}
private void saveButton_Click(object sender, EventArgs e) {
if (_doc == null)
_doc = new Doc();
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
dialog.FilterIndex = 1;
dialog.FileName = "Untitled.pdf";
if (dialog.ShowDialog() == DialogResult.OK)
_doc.Save(dialog.FileName);
}
}
internal sealed class TemporaryFile : IDisposable {
private string mPath;
private TemporaryFile() { }
public TemporaryFile(string ext) {
mPath = GetTempFilePath(ext);
}
~TemporaryFile() {
Dispose(false);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
// sealed class cannot introduce virtual method
// warned if sealed class introduces protected member
private /*virtual*/ void Dispose(bool disposing) {
try {
DeleteFile();
}
catch {
}
}
public string Path { get { return mPath; } }
public void DeleteFile() {
if (mPath != null) {
if (File.Exists(mPath))
File.Delete(mPath);
mPath = null;
}
}
private static string GetTempFilePath(string ext) {
if (string.IsNullOrWhiteSpace(ext))
ext = ".dat";
else if (!ext.StartsWith("."))
ext = "." + ext;
return System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString() + ext);
}
}
}
```
OptionalContent.cs
```// ===========================================================================
// ©2013-2021 WebSupergoo. All rights reserved.
//
// This source code is for use exclusively with the ABCpdf product under
// the terms of the license for that product. Details can be found at
//
// http://www.websupergoo.com/
//
// This copyright notice must not be deleted and must be reproduced alongside
// any sections of code extracted from this module.
// ===========================================================================
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using System.Net;
using WebSupergoo.ABCpdf12;
using WebSupergoo.ABCpdf12.Objects;
using WebSupergoo.ABCpdf12.Operations;
using WebSupergoo.ABCpdf12.Atoms;
namespace OptionalContent {
/// <summary>
/// This class represents the Optional Content Properties Dictionary in a PDF document.
/// This is the top level container of all Optional Content Groups (OCGs)
/// in a document. OCGs are referenced at the top level in a global dictionary and their
/// visibility states are held in a global configuration dictionary. These OCGs may then
/// be referenced by one or more pages in the document.
/// Here we refer to OCGs simply as Groups.
/// </summary>
class Properties {
/// <summary>
/// Create a Properties object for the Doc.
/// </summary>
/// <param name="doc">The Doc on which to operate.</param>
/// <param name="create">Whether to create a new properties entry if one is not already present.</param>
/// <returns>The Properties object. This may be null if layers were not present in the document and the create parameter is false.</returns>
public static Properties FromDoc(Doc doc, bool create) {
Catalog catalog = doc.ObjectSoup.Catalog;
Atom atom = catalog.Resolve(Atom.GetItem(catalog.Atom, "OCProperties"));
if ((atom == null) && (create)) {
int id = doc.AddObject("<< /OCGs [] /D << /BaseState /ON >> >>");
IndirectObject io = doc.ObjectSoup[id];
Atom.SetItem(catalog.Atom, "OCProperties", new RefAtom(io));
atom = io.Atom;
}
if (atom == null)
return null;
return new Properties(catalog, atom);
}
private Catalog _catalog;
private Atom _atom;
private Properties(Catalog catalog, Atom atom) {
_catalog = catalog;
_atom = atom;
}
/// <summary>
/// The Catalog from the Doc.
/// </summary>
public Catalog Catalog { get { return _catalog; } }
/// <summary>
/// Get the Groups for the Doc.
/// </summary>
/// <returns>A list of the Groups.</returns>
public List<Group> GetGroups() {
List<Group> list = new List<Group>();
ArrayAtom array = EntryOCGs;
if (array != null) {
foreach (Atom item in array) {
IndirectObject io = _catalog.ResolveObj(item);
Group group = Group.FromIndirectObject(this, io);
if (group != null)
list.Add(group);
}
}
return list;
}
/// <summary>
/// Get the Optional Content Groups (OCGs) for the Page.
/// </summary>
/// <param name="page">The page from which OCGs should be found.</param>
/// <returns>A list of the OCGs.</returns>
public List<Group> GetGroups(Page page) {
List<Group> list = new List<Group>();
ISet<Atom> props = page.GetResourcesByType("Properties", true, true, true, true, null);
foreach (Atom item in props) {
IndirectObject io = page.ResolveObj(item);
Group ocg = Group.FromIndirectObject(this, io);
if (ocg != null) {
list.Add(ocg);
continue;
}
MembershipGroup mg = MembershipGroup.FromIndirectObject(this, io);
if (mg != null) {
foreach (var ocg2 in mg.PolicyGroups)
list.Add(ocg2);
continue;
}
}
return list;
}
/// <summary>
/// Sort Groups for presentation in a UI. Remove any Groups which should not appear in UI.
/// Construct a list of indents for those Groups that should be presented nested.
/// </summary>
/// <param name="groups">The OCGs to order.</param>
/// <param name="indents">A list of indents to indicate nestedness.</param>
public void SortGroupsForPresentation(List<Group> groups, List<int> indents) {
Dictionary<int, Group> lookup = new Dictionary<int, Group>();
foreach (Group group in groups)
lookup[group.IndirectObject.ID] = group;
groups.Clear();
indents.Clear();
Configuration config = GetDefault();
ArrayAtom order = config != null ? config.EntryOrder : null;
if (order == null)
return;
SortGroupsForPresentation(order, lookup, groups, indents, 0);
}
private void SortGroupsForPresentation(ArrayAtom order, Dictionary<int, Group> lookup, List<Group> groups, List<int> indents, int depth) {
if (depth > 100)
throw new Exception("OCG order nesting depth unfeasibly large.");
foreach (Atom atom in order) {
Atom resAtom = _catalog.Resolve(atom);
if (resAtom is ArrayAtom) { // OCG group
SortGroupsForPresentation((ArrayAtom)resAtom, lookup, groups, indents, depth + 1);
}
else if (resAtom is DictAtom) { // OCG
RefAtom refAtom = _catalog.ResolveRef(atom);
if (refAtom != null) {
Group group = null;
lookup.TryGetValue(refAtom.ID, out group);
if (group != null) {
groups.Add(group);
indents.Add(depth);
}
}
}
}
}
/// <summary>
/// Add a Group to the Doc.
/// </summary>
/// <param name="name">The name for the Group</param>
/// <param name="parent">The parent for the Group to indicate nested visibility. This may be null if nested visibility is not required.</param>
/// <returns>The newly added Group.</returns>
public Group AddGroup(string name, Group parent) {
Group ocg = Group.NewGroup(this);
ocg.EntryName = new StringAtom(name);
if (true) { // we need to list the ocg in the global database
ArrayAtom array = EntryOCGs;
if (array == null) {
array = new ArrayAtom();
EntryOCGs = array;
}
array.Add(new RefAtom(ocg.IndirectObject));
}
if (true) { // we also need to list it in the visible entries
Configuration config = GetDefault();
ArrayAtom array = config.EntryOrder;
if (array == null) {
array = new ArrayAtom();
config.EntryOrder = array;
}
if (parent != null) {
Tuple<ArrayAtom, int> entry = FindArrayEntry(parent.IndirectObject, array, 0);
if (entry == null)
throw new ArgumentException("Parent OCG not present in configuration dictionary.");
array = entry.Item1;
int index = entry.Item2;
ArrayAtom next = index < array.Count - 1 ? _catalog.Resolve(array[index + 1]) as ArrayAtom : null;
if (next == null) {
next = new ArrayAtom();
array.Insert(index + 1, next);
}
array = next;
}
array.Add(new RefAtom(ocg.IndirectObject));
}
return ocg;
}
/// <summary>
/// Add a Membership Group to the Doc.
/// </summary>
/// <returns>The newly added Membership Group.</returns>
public MembershipGroup AddMembershipGroup() {
return MembershipGroup.New(this);
}
/// <summary>
/// Get the default Configuration to indicate which layers are visible or invisible.
/// </summary>
/// <returns>The Configuration.</returns>
public Configuration GetDefault() {
Atom defaultConfig = EntryD;
return defaultConfig != null ? Configuration.FromAtom(this, defaultConfig) : null;
}
/// <summary>
/// Get the alternate Configurations that may be used to indicate which layers are visible or invisible.
/// Alternate configurations are indended for use under different circumstances - they represent alternate
/// views of the pages.
/// </summary>
/// <returns>A list of Configurations.</returns>
public List<Configuration> GetConfigs() {
List<Configuration> list = new List<Configuration>();
ArrayAtom configs = EntryConfigs;
if (configs != null) {
foreach (Atom item in configs) {
Configuration occd = Configuration.FromAtom(this, item);
list.Add(occd);
}
}
return list;
}
/// <summary>
/// The Optional Content Properties Dictionary OCG entry.
/// </summary>
public ArrayAtom EntryOCGs {
get { return _catalog.Resolve(Atom.GetItem(_atom, "OCGs")) as ArrayAtom; }
set { Atom.SetItem(_atom, "OCGs", value); }
}
/// <summary>
/// The Optional Content Properties Dictionary D entry.
/// </summary>
public DictAtom EntryD {
get { return _catalog.Resolve(Atom.GetItem(_atom, "D")) as DictAtom; }
set { Atom.SetItem(_atom, "D", value); }
}
/// <summary>
/// The Optional Content Properties Dictionary Configs entry.
/// </summary>
public ArrayAtom EntryConfigs {
get { return _catalog.Resolve(Atom.GetItem(_atom, "Configs")) as ArrayAtom; }
set { Atom.SetItem(_atom, "Configs", value); }
}
private static Tuple<ArrayAtom, int> FindArrayEntry(IndirectObject io, ArrayAtom array, int depth) {
if (depth > 100)
return null;
int n = array.Count;
for (int i = 0; i < n; i++) {
Atom atom = array[i];
ArrayAtom subArray = io.Resolve(atom) as ArrayAtom;
if (subArray != null) {
Tuple<ArrayAtom, int> result = FindArrayEntry(io, subArray, depth + 1);
if (result != null)
return result;
}
else {
RefAtom refAtom = io.ResolveRef(atom);
if ((refAtom != null) && (refAtom.ID == io.ID))
return new Tuple<ArrayAtom, int>(array, i);
}
}
return null;
}
public static RefAtom MakeResourceIndirect(Page page, IndirectObject container, string resourceType, string resourceName, Atom resourceAtom, ref Atom cache) {
RefAtom refAtom = container.ResolveRef(resourceAtom);
if (refAtom == null) {
if (cache == null)
cache = GetResourceDict(page, container, resourceType, true);
IndirectObject prop = new IndirectObject();
prop.Atom = resourceAtom;
container.Doc.ObjectSoup.Add(prop);
refAtom = (RefAtom)Atom.SetItem(cache, resourceName, new RefAtom(prop));
}
return refAtom;
}
public static DictAtom GetResourceDict(Page page, IndirectObject container, string resourceType, bool create) {
DictAtom dict = null;
Atom resAtom = null;
if (container is FormXObject) {
resAtom = container.Resolve(Atom.GetItem(container.Atom, "Resources"));
if (resAtom == null)
resAtom = Atom.SetItem(container.Atom, "Resources", new DictAtom());
}
else {
resAtom = container.Resolve(Atom.GetItem(page.Atom, "Resources"));
Debug.Assert(resAtom != null, "Page does not contain Resources.");
}
dict = container.Resolve(Atom.GetItem(resAtom, resourceType)) as DictAtom;
if ((dict == null) && (create))
dict = (DictAtom)Atom.SetItem(resAtom, resourceType, new DictAtom());
return dict;
}
}
/// <summary>
/// This class represents an Optional Content Group (OCG) in a PDF document.
/// An OCG is a layer-like object that may be visible or invisible. Items on the page
/// may belong to one or more than one OCG. Only if all OCGs that they belong to are visible
/// are the items visible. OCGs are held at the Doc level in a global dictionary
/// and then referenced at a Page level.
/// </summary>
class Group {
/// <summary>
/// Create a new Group for the document.
/// </summary>
/// <param name="oc">The Properties object for the Doc.</param>
/// <returns>The new Group.</returns>
public static Group NewGroup(Properties oc) {
IndirectObject io = IndirectObject.FromString("<< /Type /OCG /Name () >>");
oc.Catalog.Doc.ObjectSoup.Add(io);
return FromIndirectObject(oc, io);
}
/// <summary>
/// Create a list of Groups from a list of atoms that reference Optional Content Groups (OCGs) already existing in the Doc.
/// Only those atoms that reference OCGs will be included in the list. Other atoms will be ignored.
/// </summary>
/// <param name="oc">The Properties object for the Doc.</param>
/// <param name="atoms">The list of atoms.</param>
/// <returns>A list of Groups.</returns>
public static List<Group> FromAtoms(Properties oc, IEnumerable<Atom> atoms) {
List<Group> list = new List<Group>();
foreach (Atom atom in atoms) {
IndirectObject io = oc.Catalog.ResolveObj(atom);
Group ocg = Group.FromIndirectObject(oc, io);
if (ocg != null)
list.Add(ocg);
}
return list;
}
/// <summary>
/// Create a Group from an IndirectObject that already exists in the Doc.
/// If the IndirectObject is not an Optional Content Group then null will be returned.
/// </summary>
/// <param name="oc">The Properties object for the Doc.</param>
/// <param name="io">The IndirectObject.</param>
/// <returns>The Group.</returns>
public static Group FromIndirectObject(Properties oc, IndirectObject io) {
if (io == null)
return null;
Group ocg = new Group(oc, io);
return ocg.AllOk() ? ocg : null;
}
private Properties _oc;
private IndirectObject _io;
private Group(Properties oc, IndirectObject io) {
_oc = oc;
_io = io;
}
private bool AllOk() {
// check type
NameAtom type = _io.Resolve(Atom.GetItem(_io.Atom, "Type")) as NameAtom;
if ((type == null) || (type.Text != "OCG"))
return false; // malformed entry - corrupt PDF
// The optional intent can be either a name or an array of names.
// To keep things simple we always use the array form.
Atom intent = _io.Resolve(Atom.GetItem(_io.Atom, "Intent"));
if (intent is NameAtom) {
ArrayAtom array = new ArrayAtom();
array.Add(intent);
Atom.SetItem(_io.Atom, "Intent", array);
intent = array;
}
return true;
}
/// <summary>
/// The IndirectObject representing the Group.
/// </summary>
public IndirectObject IndirectObject {
get { return _io; }
}
/// <summary>
/// Indicates whether the Group is visible or not.
/// </summary>
public bool Visible {
get { return _oc.GetDefault().GetVisibility(true, this); }
set { _oc.GetDefault().SetVisibility(value, this); }
}
/// <summary>
/// Adds the Group to a page.
/// </summary>
/// <param name="page"></param>
/// <returns></returns>
public string AddToPage(Page page) {
return page.AddResource(_io, "Properties", "OC" + _io.ID.ToString());
}
/// <summary>
/// The Optional Content Group Dictionary Name entry.
/// </summary>
public StringAtom EntryName {
get { return _io.Resolve(Atom.GetItem(_io.Atom, "Name")) as StringAtom; }
set { Atom.SetItem(_io.Atom, "Name", value); }
}
/// <summary>
/// The Optional Content Group Dictionary Intent entry.
/// </summary>
public ArrayAtom EntryIntent {
get { return _io.Resolve(Atom.GetItem(_io.Atom, "Intent")) as ArrayAtom; }
set { Atom.SetItem(_io.Atom, "Intent", value); }
}
/// <summary>
/// The Optional Content Group Dictionary Usage entry.
/// </summary>
public DictAtom EntryUsage {
get { return _io.Resolve(Atom.GetItem(_io.Atom, "Usage")) as DictAtom; }
set { Atom.SetItem(_io.Atom, "Usage", value); }
}
}
/// <summary>
/// This class represents an Optional Content Membership Dictionary (OCMD) in a PDF document.
/// This is a bit of a mouthful and doesn't actually express what it is, which is a
/// kind of metagroup. It expresses visibility dependent on the visibility of a
/// set of groups rather than directly being switched on and off by itself. OCMDs are not
/// referenced at the document level - only at a page level. However of course the OCMD references
/// OCGs which are themselves referenced at a document level.
/// Membership Groups may express visibility either using a Policy or using a Visibility Expression.
/// Policies are simpler to implement but limited in scope. Visibility Expressions are more complex
/// but also more powerful.
/// OCGs always have to be IndirectObjects since they are referenced from more than one place.
/// OCMGs do not have to be IndirectObject - they can be simple Atoms - since they are only referenced from
/// the Resources of the Page. However to make things simple we convert them to IndiretObjects when we
/// find them.
/// </summary>
class MembershipGroup {
/// <summary>
/// An enumeration representing the possibilities for a Policy based Membership Group.
/// </summary>
public enum PolicyEnum { AllOn, AnyOn, AllOff, AnyOff };
/// <summary>
/// An enumeration representing the possibilities for a Logic based Membership Group.
/// </summary>
public enum LogicEnum { And, Or, Not };
/// <summary>
/// Create a new Membership Group.
/// </summary>
/// <param name="oc">The Properties object for the Doc</param>
/// <returns>The Membership Group</returns>
public static MembershipGroup New(Properties oc) {
IndirectObject io = IndirectObject.FromString("<< /Type /OCMD >>");
oc.Catalog.Doc.ObjectSoup.Add(io);
return FromIndirectObject(oc, io);
}
/// <summary>
/// Create a list of Membership Groups from a list of atoms that reference Optional Content Membership Groups (OCMGs) already existing in the Doc.
/// Only those atoms that reference OCMGs will be included in the list. Other atoms will be ignored.
/// </summary>
/// <param name="oc">The Properties object for the Doc.</param>
/// <param name="atoms">The list of atoms.</param>
/// <returns>A list of Membership Groups.</returns>
public static List<MembershipGroup> FromAtoms(Properties oc, IEnumerable<Atom> atoms) {
// Here we assume that all atoms passed in are references to an OCMG IndirectObject.
// In our code this is always the case. However if you modify the code to take Atoms
// read from another PDF then you need to tak account of the fact that OCMGs (unlike
// OCGs) need not be IndirectObjects - they can be plain DictAtoms. If this is the case
// you will need to use Properties.MakeResourceIndirect to convert these Atoms into
// IndirectObjects.
List<MembershipGroup> list = new List<MembershipGroup>();
foreach (Atom atom in atoms) {
IndirectObject io = oc.Catalog.ResolveObj(atom);
MembershipGroup ocmg = MembershipGroup.FromIndirectObject(oc, io);
if (ocmg != null)
list.Add(ocmg);
}
return list;
}
/// <summary>
/// Create a new Membership Group from an IndirectObject that already exists in the Doc.
/// If the IndirectObject is not a Membership Group then null will be returned.
/// </summary>
/// <param name="oc">The Properties object for the Doc</param>
/// <param name="io">The IndirectObject.</param>
/// <returns>The Group.</returns>
public static MembershipGroup FromIndirectObject(Properties oc, IndirectObject io) {
if (io == null)
return null;
MembershipGroup ocm = new MembershipGroup(oc, io);
return ocm.AllOk() ? ocm : null;
}
private Properties _oc;
private IndirectObject _io;
private MembershipGroup(Properties oc, IndirectObject io) {
_oc = oc;
_io = io;
}
private bool AllOk() {
// check type
NameAtom type = _io.Resolve(Atom.GetItem(_io.Atom, "Type")) as NameAtom;
if ((type == null) || (type.Text != "OCMD"))
return false; // malformed entry - corrupt PDF
// The optional OCGs can be either a dict or an array of dicts.
// To keep things simple we always use the array form.
Atom ocgs = _io.Resolve(Atom.GetItem(_io.Atom, "OCGs"));
if (ocgs is DictAtom) {
ArrayAtom array = new ArrayAtom();
array.Add(ocgs);
Atom.SetItem(_io.Atom, "OCGs", array);
ocgs = array;
}
return true;
}
/// <summary>
/// The IndirectObject representing the Membership Group.
/// </summary>
public IndirectObject IndirectObject {
get { return _io; }
}
/// <summary>
/// Indicates whether the Membership Group is visible or not.
/// </summary>
public bool Visible {
get { return EntryVE != null ? EvaluateVisibility(EntryVE, 0) : EvaluateVisibility(Policy, PolicyGroups); }
}
private bool EvaluateVisibility(Atom ve, int depth) {
if (depth > 100)
return true;
ve = _oc.Catalog.Resolve(ve);
if (ve is ArrayAtom) {
ArrayAtom array = (ArrayAtom)ve;
int n = array.Count;
string op = n > 0 ? Atom.GetName(_oc.Catalog.Resolve(Atom.GetItem(array, 0))) : "";
if (op == LogicEnum.And.ToString()) {
for(int i = 1; i < n; i++) {
IndirectObject io = _oc.Catalog.ResolveObj(array[i]);
if (io != null) {
if (!EvaluateVisibility(io))
return false;
}
else {
if (!EvaluateVisibility(array[i], depth + 1))
return false;
}
}
return true;
}
else if (op == LogicEnum.Or.ToString()) {
for(int i = 1; i < n; i++) {
IndirectObject io = _oc.Catalog.ResolveObj(array[i]);
if (io != null) {
if (EvaluateVisibility(io))
return true;
}
else {
if (EvaluateVisibility(array[i], depth + 1))
return true;
}
}
return false;
}
else if ((op == LogicEnum.Not.ToString()) && (n > 1)) {
IndirectObject io = _oc.Catalog.ResolveObj(array[1]);
if (io != null)
return !EvaluateVisibility(io);
else
return !EvaluateVisibility(array[1], depth + 1);
}
}
return true;
}
private bool EvaluateVisibility(PolicyEnum? policy, IEnumerable<Group> groups) {
bool visible = true;
if (policy == null)
policy = PolicyEnum.AnyOn;
if (groups == null)
groups = new Group[0];
if (policy == PolicyEnum.AnyOn) {
visible = false;
foreach (Group group in groups) {
if (group.Visible) {
visible = true;
break;
}
}
}
else if (policy == PolicyEnum.AnyOff) {
visible = false;
foreach (Group group in groups) {
if (!group.Visible) {
visible = true;
break;
}
}
}
else if (policy == PolicyEnum.AllOn) {
visible = true;
foreach (Group group in groups) {
if (!group.Visible) {
visible = false;
break;
}
}
}
else if (policy == PolicyEnum.AllOff) {
visible = true;
foreach (Group group in groups) {
if (group.Visible) {
visible = false;
break;
}
}
}
return visible;
}
private bool EvaluateVisibility(IndirectObject io) {
Group group = Group.FromIndirectObject(_oc, io);
return group != null ? group.Visible : true;
}
/// <summary>
/// The Policy for the Membership Group. Null indicates that there is no Policy.
/// </summary>
public PolicyEnum? Policy {
get { NameAtom a = EntryP; return a != null ? (PolicyEnum?)Enum.Parse(typeof(PolicyEnum), a.Text) : null; }
set { EntryP = value.HasValue ? new NameAtom(value.ToString()) : null; }
}
/// <summary>
/// The Groups on which the Policy will operate.
/// </summary>
public IEnumerable<Group> PolicyGroups {
get {
ArrayAtom array = EntryOCGs;
return array != null ? Group.FromAtoms(_oc, EntryOCGs) : new List<Group>();
}
set {
ArrayAtom array = new ArrayAtom();
foreach (Group item in value)
array.Add(new RefAtom(item.IndirectObject));
EntryOCGs = array;
}
}
/// <summary>
/// Create a Visibility Expression showing how the visibility of a set of Groups should be combined.
/// </summary>
/// <param name="op">The logic operator used to combine the visibility.</param>
/// <param name="groups">The set of Groups on which to operate. Visible Groups are true and invisible ones are false.</param>
/// <returns>An ArrayAtom containing the Visibility Expression.</returns>
public ArrayAtom MakeVisibilityExpression(LogicEnum op, IEnumerable<Group> groups) {
ArrayAtom array = new ArrayAtom();
array.Add(new NameAtom(op.ToString()));
foreach (var group in groups)
array.Add(new RefAtom(group.IndirectObject));
return array;
}
/// <summary>
/// Create a Visibility Expression showing how the visibility of a set of Visibility Expressions should be combined.
/// </summary>
/// <param name="op">The logic operator used to combine the visibility.</param>
/// <param name="atoms">The set of groups on which to operate.</param>
/// <returns>An ArrayAtom containing the Visibility Expression.</returns>
public ArrayAtom MakeVisibilityExpression(LogicEnum op, IEnumerable<ArrayAtom> atoms) {
ArrayAtom array = new ArrayAtom();
array.Add(new NameAtom(op.ToString()));
foreach (var atom in atoms)
array.Add(atom);
return array;
}
/// <summary>
/// All the Groups on which the Membership Group depends.
/// </summary>
public IEnumerable<Atom> GetGroupReferences() {
List<Atom> list = new List<Atom>();
GetGroupReferences(EntryVE, list, 0);
GetGroupReferences(EntryOCGs, list, 0);
return list;
}
private IEnumerable<Atom> GetGroupReferences(ArrayAtom array, List<Atom> list, int depth) {
if ((array == null) || (depth > 100))
return list;
foreach (Atom atom in array) {
Atom item = _oc.Catalog.Resolve(atom);
if (item is ArrayAtom)
GetGroupReferences((ArrayAtom)item, list, depth + 1);
else {
RefAtom refAtom =_oc.Catalog.ResolveRef(atom);
if (refAtom != null)
list.Add(refAtom);
}
}
return list;
}
/// <summary>
/// Add the Membership Group to a Page.
/// </summary>
/// <param name="page">The Page to which this should be added.</param>
/// <returns>The resource name used for this Membership Group.</returns>
public string AddToPage(Page page) {
return page.AddResource(_io, "Properties", "OC" + _io.ID.ToString());
}
/// <summary>
/// The Optional Content Membership Dictionary OCGs entry.
/// </summary>
public ArrayAtom EntryOCGs {
get { return _io.Resolve(Atom.GetItem(_io.Atom, "OCGs")) as ArrayAtom; }
set { Atom.SetItem(_io.Atom, "OCGs", value); }
}
/// <summary>
/// The Optional Content Membership Dictionary P entry.
/// </summary>
public NameAtom EntryP {
get { return _io.Resolve(Atom.GetItem(_io.Atom, "P")) as NameAtom; }
set { Atom.SetItem(_io.Atom, "P", value); }
}
/// <summary>
/// The Optional Content Membership Dictionary VE entry.
/// </summary>
public ArrayAtom EntryVE {
get { return _io.Resolve(Atom.GetItem(_io.Atom, "VE")) as ArrayAtom; }
set { Atom.SetItem(_io.Atom, "VE", value); }
}
}
/// <summary>
/// This class represents an Optional Content Configuration Dictionary (OCCD) in a PDF document.
/// An OCCD expresses the visibility of the Groups in the document and also how they should be
/// presented in a User Interface (UI).
/// </summary>
class Configuration {
/// <summary>
/// Create a Configuration from an Optional Content Configuration Dictionary (OCCD) Atom already existing in the Doc.
/// If the Atom is not an OCCD then null will be returned.
/// </summary>
/// <param name="oc">The Properties object for the Doc.</param>
/// <param name="atom">The Atom.</param>
/// <returns>The Configuration.</returns>
public static Configuration FromAtom(Properties oc, Atom atom) {
if ((atom == null) || (oc == null))
return null;
return new Configuration(oc, atom);
}
private Properties _oc;
private Atom _atom;
private Configuration(Properties oc, Atom atom) {
_oc = oc;
_atom = atom;
}
/// <summary>
/// The Atom representing the Membership Group.
/// </summary>
public Atom Atom {
get { return _atom; }
}
private enum Visibility { On, Off, Unchanged };
/// <summary>
/// Evaluate the visibility of the Group.
/// </summary>
/// <param name="isDefault">Whether this is the default configuration.</param>
/// <param name="layer">The Group for which visibility should be evaluated.</param>
/// <returns>Whether visible.</returns>
public bool GetVisibility(bool isDefault, Group layer) {
Visibility visibility = Visibility.On;
NameAtom baseState = isDefault ? null : EntryBaseState;
if (baseState != null) {
switch (baseState.Text) {
case "OFF": visibility = Visibility.Off; break;
case "Unchanged": visibility = Visibility.Unchanged; break;
}
}
if (visibility != Visibility.On) {
ArrayAtom array = EntryON;
if (array != null) {
foreach (Atom item in array) {
IndirectObject io = _oc.Catalog.ResolveObj(item);
if ((io != null) && (io.ID == layer.IndirectObject.ID)) {
visibility = Visibility.On;
break;
}
}
}
}
else if (visibility != Visibility.Off) {
ArrayAtom array = EntryOFF;
if (array != null) {
foreach (Atom item in array) {
IndirectObject io = _oc.Catalog.ResolveObj(item);
if ((io != null) && (io.ID == layer.IndirectObject.ID)) {
visibility = Visibility.Off;
break;
}
}
}
}
return visibility != Visibility.Off;
}
/// <summary>
/// Set the visibility of a Group.
/// </summary>
/// <param name="visible">Whether the Group should be visible.</param>
/// <param name="layer">The Group for which visibility should be evaluated.</param>
public void SetVisibility(bool visible, Group layer) {
RemoveEntries(EntryOFF, layer.IndirectObject.ID);
RemoveEntries(EntryON, layer.IndirectObject.ID);
if (visible) {
if (EntryON == null)
EntryON = new ArrayAtom();
EntryON.Add(new RefAtom(layer.IndirectObject));
}
else {
if (EntryOFF == null)
EntryOFF = new ArrayAtom();
EntryOFF.Add(new RefAtom(layer.IndirectObject));
}
//layer.IndirectObject.Atom = layer.IndirectObject.Atom.Clone();
}
private void RemoveEntries(ArrayAtom array, int id) {
int n = array != null ? array.Count : 0;
for (int i = 0; i < n; i++) {
IndirectObject item = _oc.Catalog.ResolveObj(array[i]);
if ((item != null) && (item.ID == id)) {
array.RemoveAt(i);
i--;
n--;
}
}
}
/// <summary>
/// The Optional Content Configuration Dictionary Name entry.
/// </summary>
public StringAtom EntryName {
get { return _oc.Catalog.Resolve(Atom.GetItem(_atom, "Name")) as StringAtom; }
set { Atom.SetItem(_atom, "Name", value); }
}
/// <summary>
/// The Optional Content Configuration Dictionary Creator entry.
/// </summary>
public StringAtom EntryCreator {
get { return _oc.Catalog.Resolve(Atom.GetItem(_atom, "Creator")) as StringAtom; }
set { Atom.SetItem(_atom, "Creator", value); }
}
/// <summary>
/// The Optional Content Configuration Dictionary BaseState entry.
/// </summary>
public NameAtom EntryBaseState {
get { return _oc.Catalog.Resolve(Atom.GetItem(_atom, "BaseState")) as NameAtom; }
set { Atom.SetItem(_atom, "BaseState", value); }
}
/// <summary>
/// The Optional Content Configuration Dictionary ON entry.
/// </summary>
public ArrayAtom EntryON {
get { return _oc.Catalog.Resolve(Atom.GetItem(_atom, "ON")) as ArrayAtom; }
set { Atom.SetItem(_atom, "ON", value); }
}
/// <summary>
/// The Optional Content Configuration Dictionary OFF entry.
/// </summary>
public ArrayAtom EntryOFF {
get { return _oc.Catalog.Resolve(Atom.GetItem(_atom, "OFF")) as ArrayAtom; }
set { Atom.SetItem(_atom, "OFF", value); }
}
/// <summary>
/// The Optional Content Configuration Dictionary Order entry.
/// </summary>
public ArrayAtom EntryOrder {
get { return _oc.Catalog.Resolve(Atom.GetItem(_atom, "Order")) as ArrayAtom; }
set { Atom.SetItem(_atom, "Order", value); }
}
}
/// <summary>
/// Class for evaluating which parts of a page are visible and which parts are members
/// of which Optional Content Groups or Membership dictionaries. Includes facilities
/// for redacting elements that are invisible.
/// </summary>
class Reader {
/// <summary>
/// Create a Reader for a particular Page.
/// </summary>
/// <param name="oc">The Properties object for the Doc.</param>
/// <param name="page">The page to operate on.</param>
/// <returns></returns>
public static Reader FromPage(Properties oc, Page page) {
Reader content = new Reader(oc, page);
return content.AllOk() ? content : null;
}
[DebuggerDisplay("\\{ Offset = {Offset} Length = {Length} Command = {Command} \\}")]
private class Op : IComparable {
public Op(int offset, int length, string command, string textWidth) {
Offset = offset;
Length = length;
Command = command;
TextWidth = textWidth;
}
public int CompareTo(Object obj) {
return this.Offset - ((Op)obj).Offset;
}
public int Offset;
public int Length;
public string Command;
public string TextWidth;
}
private Properties _oc;
private Page _page;
private Dictionary<int, List<Op>> _ops;
private Dictionary<int, Dictionary<int, Atom[]>> _states; // first int is stream ID, second is position in stream
private Dictionary<int, IDictionary<string, Atom>> _rezMap;
private Dictionary<int, List<int>> _lookups; // fast lookup list
private Reader() {
Debug.Assert(false);
}
private Reader(Properties oc, Page page) {
_oc = oc;
_page = page;
_ops = null;
_states = null;
_rezMap = null;
_lookups = null;
}
private bool AllOk() {
_page.DeInline(true);
_page.Flatten(true, false);
// Theoretically a FormXObject could have different visibilty
// at different times it is drawn. So you should really call
// _page.StampFormXObjects(true) to separate them all out. However
// this might have quite an impact on size and it seems unlikely
// so we don't currently do this.
ScanPage(_page.GetText(Page.TextType.SvgPlus2, true));
return true;
}
private void ScanPage(string svg) {
_ops = new Dictionary<int, List<Op>>();
_states = new Dictionary<int, Dictionary<int, Atom[]>>();
_rezMap = new Dictionary<int, IDictionary<string, Atom>>();
_lookups = new Dictionary<int, List<int>>();
Stack<Atom> names = new Stack<Atom>();
Stack<int> depths = new Stack<int>();
depths.Push(0);
using (StringReader reader = new StringReader(svg)) {
for (string item; (item = reader.ReadLine()) != null; ) {
if (item.StartsWith("<", StringComparison.InvariantCultureIgnoreCase)) {
// get object ID
string pdf_Op = GetAttribute(item, "pdf_Op");
string op = WebUtility.HtmlDecode(pdf_Op);
if (op == null)
continue;
int streamID = Int32.Parse(GetAttribute(item, "pdf_StreamID"));
int streamOffset = Int32.Parse(GetAttribute(item, "pdf_StreamOffset"));
int streamLength = Int32.Parse(GetAttribute(item, "pdf_StreamLength"));
string textWidth = GetAttribute(item, "pdf_w1000");
List<Op> ops = GetOpsFromStreamID(streamID);
// FormXObjects may be drawn multiple times on page. Don't need to keep
// track of all the times this happens. Once is enough.
if ((ops.Count == 0) || (ops[ops.Count - 1].Offset < streamOffset))
ops.Add(new Op(streamOffset, streamLength, op, textWidth));
bool isBDC = (op.EndsWith("BDC"));
bool isBMC = (op.EndsWith("BMC"));
bool isEMC = (op.EndsWith("EMC"));
if (isBDC || isBMC || isEMC) {
if (isBDC) {
ArrayAtom array = (ArrayAtom)Atom.FromString("[" + op + "]");
NameAtom type = array.Count > 0 ? (NameAtom)array[0] : null; // this must be a NameAtom
NameAtom name = array.Count > 1 ? array[1] as NameAtom : null; // this may be NameAtom or DictAtom but if OC, NameAtom only
if ((type != null) && (name != null) && (type.Text == "OC")) { // optional content
depths.Push(0);
IDictionary<string, Atom> map = GetResourceMapFromStreamID(streamID);
names.Push(map[name.Text]);
Dictionary<int, Atom[]> state = GetStateFromStreamID(streamID);
state.Add(streamOffset, names.Count > 0 ? names.ToArray() : new Atom[0]);
}
else { // some other kind of marked content
depths.Push(depths.Pop() + 1);
}
}
else if (isBMC) { // some other kind of marked content
depths.Push(depths.Pop() + 1);
}
else if (isEMC) {
if (depths.Peek() == 0) {
names.Pop(); // exception here indicates too many EMC without corresponding BDC
Dictionary<int, Atom[]> state = GetStateFromStreamID(streamID);
state.Add(streamOffset, names.Count > 0 ? names.ToArray() : new Atom[0]);
depths.Pop();
}
else {
depths.Push(depths.Pop() - 1);
}
}
}
}
}
}
}
/// <summary>
/// Get all the Layers referenced on the current page.
/// </summary>
/// <returns>A list of Layers.</returns>
public List<Layer> GetLayers() {
HashSet<Atom> set = new HashSet<Atom>();
foreach (KeyValuePair<int, Dictionary<int, Atom[]>> state1 in _states) {
foreach (KeyValuePair<int, Atom[]> state2 in state1.Value) {
foreach (Atom atom in state2.Value) {
set.Add(atom);
}
}
}
List<Layer> list = new List<Layer>();
foreach (Atom atom in set) {
IndirectObject io = _oc.Catalog.ResolveObj(atom);
Group group = Group.FromIndirectObject(_oc, io);
if (group != null) {
list.Add(new Layer(group, null));
continue;
}
MembershipGroup membershipGroup = MembershipGroup.FromIndirectObject(_oc, io);
if (membershipGroup != null) {
list.Add(new Layer(membershipGroup, null));
continue;
}
}
return list;
}
/// <summary>
/// Get the Groups active at a particular point in a particular content stream.
/// You can use this to establish the visibility of a PDF operator at a particular
/// point in a stream.
/// </summary>
/// <param name="streamID">The ID of the StreamObject.</param>
/// <param name="position">The offset in the stream.</param>
/// <returns>A list of Layers</returns>
public List<Layer> GetLayersFromStreamAndPosition(int streamID, int position) {
List<Layer> list = new List<Layer>();
Atom[] atoms = GetStateFromStreamAndPosition(streamID, position);
foreach (Group group in Group.FromAtoms(_oc, atoms))
list.Add(new Layer(group, null));
foreach (MembershipGroup group in MembershipGroup.FromAtoms(_oc, atoms))
list.Add(new Layer(group, null));
return list;
}
/// <summary>
/// Delete all content associated with the specified Group. After this the Reader will
/// no longer be valid and will need to be recreated if further operations are required.
/// </summary>
/// <param name="reader">The reader. This will be set to null on exit to ensure that an invalid reader is not used.</param>
/// <param name="layer">The Layer whos content should be deleted.</param>
static public void Redact(ref Reader reader, Layer layer) {
HashSet<Atom> kept = reader.Redact(layer);
reader.RemoveResources(kept);
reader = null; // invalid
}
private HashSet<Atom> Redact(Layer layer) {
HashSet<Atom> kept = new HashSet<Atom>();
foreach (KeyValuePair<int, Dictionary<int, Atom[]>> pair in _states) {
List<Op> ops = _ops[pair.Key];
Dictionary<int, Atom[]> state = GetStateFromStreamID(pair.Key);
List<int> lookup = GetLookupFromStreamID(pair.Key);
int n = lookup.Count, pos = 0;
bool keeping = true;
for (int i = 0; i < n; i++) {
bool match = false;
Atom[] ocs = state[lookup[i]]; // OCMG or OCMD
foreach (Atom atom in ocs) {
IndirectObject io = _page.ResolveObj(atom);
if (io.ID == layer.IndirectObject.ID) {
match = true;
break;
}
}
if (!match)// keep track of the ones left
foreach (Atom atom in ocs)
kept.Add(_oc.Catalog.Resolve(atom));
if (match && keeping) {
pos = lookup[i];
keeping = false;
}
else if (!match && !keeping) {
Redact(ops, pos, lookup[i]);
keeping = true;
}
}
if ((!keeping) && (ops.Count > 0)) // flush
Redact(ops, pos, ops[ops.Count - 1].Offset + 1);
StringBuilder sb = new StringBuilder();
foreach (Op op in ops)
sb.AppendLine(op.Command);
StreamObject so = (StreamObject)_page.Doc.ObjectSoup[pair.Key];
so.ClearData();
so.SetText(sb.ToString());
so.CompressFlate();
}
_states = null; // invalid
_lookups = null; // invalid
return kept;
}
private void RemoveResources(HashSet<Atom> kept) {
foreach (KeyValuePair<int, IDictionary<string, Atom>> pair1 in _rezMap) {
foreach (KeyValuePair<string, Atom> pair2 in pair1.Value) {
Atom atom = _oc.Catalog.Resolve(pair2.Value);
if (!kept.Contains(atom)) {
IndirectObject resObj = _oc.Catalog.Doc.ObjectSoup[pair1.Key];
DictAtom dict = Properties.GetResourceDict(_page, resObj, "Properties", false);
Atom.RemoveItem(dict, pair2.Key);
}
}
}
}
private void Redact(List<Op> ops, int pos1, int pos2) {
HashSet<string> cmdMakePath = new HashSet<string>(new string[] { "m", "l", "c", "v", "y", "h", "re" });
HashSet<string> cmdPaintPath = new HashSet<string>(new string[] { "S", "s", "F", "f", "f*", "B", "B*", "b", "b*" });
HashSet<string> cmdClipPath = new HashSet<string>(new string[] { "W" }); // ignore "n"
HashSet<string> cmdShow = new HashSet<string>(new string[] { "Do", "sh" });
int depth = 0;
Stack<int> depths = new Stack<int>();
List<int> paints = new List<int>();
// there should always be an exact match for the binary search
int start = ops.BinarySearch(new Op(pos1, 0, null, null));
int n = ops.Count;
for (int i = start; i < n; i++) {
Op op = ops[i];
Debug.Assert((i != start) || (op.Command.EndsWith("BDC")));
if (op.Offset > pos2)
break;
Debug.Assert(!((i == n - 1) || (ops[i + 1].Offset > pos2)) || (op.Command == "EMC"));
string cmd = op.Command.TrimEnd();
int p = cmd.Length - 1;
while (p >= 0) {
if ((char.IsWhiteSpace(cmd[p])) || (cmd[p] == ')') || (cmd[p] == ']') || (cmd[p] == '>')) {
cmd = cmd.Substring(p + 1);
break;
}
p--;
}
// here we remove any displayed content
if (cmdShow.Contains(cmd))
op.Command = "";
// here we remove any path painting but keep clipping
else if (cmdMakePath.Contains(cmd)) {
paints.Add(i);
}
else if (cmdPaintPath.Contains(cmd)) {
op.Command = "n"; // needed because of bugs in Acrobat
foreach (int j in paints)
ops[j].Command = "";
paints.Clear();
}
else if (cmdClipPath.Contains(cmd)) {
paints.Clear();
}
// here we remove the BDC / EMC entries
else if (cmd == "BMC") {
depth++;
}
else if (cmd == "BDC") {
if (op.Command.StartsWith("/OC")) {
op.Command = "";
depths.Push(depth);
}
depth++;
}
else if (cmd == "EMC") {
depth--;
if (depths.Peek() == depth) {
op.Command = "";
depths.Pop();
}
}
// here we remove the text showing commands but in a way that preserves
// the offset of the text position albeit with invisible text
else if ((cmd == "TJ") || (cmd == "Tj"))
op.Command = "[" + op.TextWidth + "] TJ";
else if (cmd == "\'")
op.Command = "T* [" + op.TextWidth + "] TJ";
else if (cmd == "\"") {
int p1 = 0, p2 = 0;
while (p1 < op.Command.Length - 1) {
if (!char.IsWhiteSpace(op.Command[p1]))
break;
p1++;
}
while (p1 < op.Command.Length - 1) {
if (char.IsWhiteSpace(op.Command[p1]))
break;
p1++;
}
p2 = p1;
while (p2 < op.Command.Length - 1) {
if (!char.IsWhiteSpace(op.Command[p2]))
break;
p2++;
}
while (p2 < op.Command.Length - 1) {
if (char.IsWhiteSpace(op.Command[p2]))
break;
p2++;
}
string tw = p1 > 0 ? op.Command.Substring(0, p1) : "0";
string tc = p2 > p1 ? op.Command.Substring(p1, p2 - p1) : "0";
op.Command = tw + " Tw " + tc + " Tc T* [" + op.TextWidth + "] TJ";
}
}
}
private Atom[] GetStateFromStreamAndPosition(int streamID, int position) {
Dictionary<int, Atom[]> state = GetStateFromStreamID(streamID);
List<int> lookup = GetLookupFromStreamID(streamID);
int pos = lookup.BinarySearch(position);
if (pos >= 0) { // exact match
return state[lookup[pos]];
}
else { // exact key not found
pos = ~pos; // Bitwise complement of the first index in the list larger than the target.
// But we want the one before that - so move back one. For that reason we shouldn't need to pin the top
if (pos == 0) // no state
return new Atom[0];
pos = pos >= 0 ? pos - 1 : pos;
return state[lookup[pos]];
}
}
private static string GetAttribute(string item, string name) {
int p1 = item.IndexOf(name);
if (p1 < 0) return null;
p1 = item.IndexOf('=', p1) + 1;
if (p1 < 0) return null;
p1 = item.IndexOf('\"', p1) + 1;
if (p1 < 0) return null;
int p2 = item.IndexOf('\"', p1);
if (p2 < 0) return null;
string attr = item.Substring(p1, p2 - p1);
return attr;
}
private List<Op> GetOpsFromStreamID(int streamID) {
List<Op> op = null;
_ops.TryGetValue(streamID, out op);
if (op == null) {
op = new List<Op>();
_ops[streamID] = op;
}
return op;
}
private Dictionary<int, Atom[]> GetStateFromStreamID(int streamID) {
Dictionary<int, Atom[]> state = null;
_states.TryGetValue(streamID, out state);
if (state == null) {
state = new Dictionary<int, Atom[]>();
_states[streamID] = state;
}
return state;
}
private IDictionary<string, Atom> GetResourceMapFromStreamID(int streamID) {
IDictionary<string, Atom> map = null;
_rezMap.TryGetValue(streamID, out map);
if (map == null) {
IndirectObject io = _page.Doc.ObjectSoup[streamID];
int id = io is FormXObject ? streamID : _page.ID;
map = _page.GetResourceMap(id, "Properties");
Atom cache = null; // Convert OCMD Atoms to IndirectObjects where necessary
List<string> keys = new List<string>(map.Keys);
foreach (string key in keys) {
Atom atom = map[key];
if (_oc.Catalog.ResolveRef(atom) == null) {
RefAtom refAtom = Properties.MakeResourceIndirect(_page, io, "Properties", key, atom, ref cache);
map[key] = refAtom;
}
}
_rezMap[streamID] = map;
}
return map;
}
private List<int> GetLookupFromStreamID(int streamID) {
List<int> lookup = null;
_lookups.TryGetValue(streamID, out lookup);
if (lookup == null) {
Dictionary<int, Atom[]> state = GetStateFromStreamID(streamID);
lookup = new List<int>(state.Keys);
lookup.Sort();
_lookups[streamID] = lookup;
}
return lookup;
}
}
/// <summary>
/// Class to represent a Layer on the page. A Layer represents a reference to a visibility
/// object from within a Page. The visibilty object may be either a Group or
/// on a Membership Group.
/// </summary>
class Layer {
private Layer() { ResourceName = ""; }
/// <summary>
/// Create a Layer object from a Group.
/// </summary>
/// <param name="group">The Group.</param>
/// <param name="name">The resource name for the Group.</param>
public Layer(Group group, string name) { Group = group; ResourceName = name; }
/// <summary>
/// Create a Layer object from a Membership Group.
/// </summary>
/// <param name="group">The Membership Group.</param>
/// <param name="name">The resource name for the Membership Group.</param>
public Layer(MembershipGroup group, string name) { MembershipGroup = group; ResourceName = name; }
/// <summary>
/// The Group. Either this or the MembershipGroup property will be null. Only one can be populated.
/// </summary>
public Group Group { get; set; }
/// <summary>
/// The Membership Group. Either this or the Group property will be null. Only one can be populated.
/// </summary>
public MembershipGroup MembershipGroup { get; set; }
/// <summary>
/// The resource name used for this object.
/// </summary>
public string ResourceName { get; set; }
/// <summary>
/// The IndirectObject for this Layer.
/// </summary>
public IndirectObject IndirectObject { get { return Group != null ? Group.IndirectObject : (MembershipGroup != null ? MembershipGroup.IndirectObject : null); } }
/// <summary>
/// Indicates whether the Group is visible or not.
/// </summary>
public bool Visible { get { return Group != null ? Group.Visible : (MembershipGroup != null ? MembershipGroup.Visible : true); } }
}
/// <summary>
/// Class for creating layers on a Page.
/// </summary>
class Writer {
private Properties _oc;
private Page _page;
private int _depth = 0;
private Writer() {
Debug.Assert(false);
}
/// <summary>
/// Create a new Writer for the Page.
/// </summary>
/// <param name="oc">The Properties object for the Doc.</param>
/// <param name="page">The Page on which to operate.</param>
public Writer(Properties oc, Page page) {
_oc = oc;
_page = page;
}
~Writer() {
Debug.Assert(_depth == 0, "Unbalanced StartLayer and EndLayer calls.");
}
/// <summary>
/// The depth of nested calls to StartLayer and EndLayer.
/// </summary>
public int Depth { get { return _depth; } }
/// <summary>
/// Add a reference to a Group for the current Page.
/// </summary>
/// <param name="group">The Group for which a reference should be added.</param>
/// <returns>The Layer.</returns>
public Layer AddGroup(Group group) {
string resource = group.AddToPage(_page);
return new Layer(group, resource);
}
/// <summary>
/// Add a reference to a Membership Group for the current Page.
/// </summary>
/// <param name="group">The Membership Group for which a reference should be added.</param>
/// <returns>The Layer.</returns>
public Layer AddGroup(MembershipGroup group) {
string resource = group.AddToPage(_page);
return new Layer(group, resource);
}
/// <summary>
/// Start writing content for a particular layer. Calls to StartLayer may be nested
/// but each call to StartLayer must be balanced by a corresponding call to EndLayer.
/// </summary>
/// <param name="layer">The Layer to start.</param>
public void StartLayer(Layer layer) {
_page.AddLayer(MakeLayerStart(_page, layer.ResourceName));
_depth++;
}
/// <summary>
/// End writing content for a particular layer. Calls to StartLayer may be nested
/// but each call to StartLayer must be balanced by a corresponding call to EndLayer.
/// </summary>
public void EndLayer() {
_page.AddLayer(MakeLayerEnd(_page));
_depth--;
}
private static StreamObject MakeLayerStart(Page page, string name) {
byte[] data = ASCIIEncoding.UTF7.GetBytes("/OC /" + name + " BDC\r\n");
return new StreamObject(page.Doc.ObjectSoup, data);
}
private static StreamObject MakeLayerEnd(Page page) {
byte[] data = ASCIIEncoding.UTF7.GetBytes("EMC\r\n");
return new StreamObject(page.Doc.ObjectSoup, data);
}
}
}
```
README.md
```<h1>PDF OGC Layers</h1>
<h2>.NET Windows Forms project demonstrating how to create and set visibility for PDF layers - Optional Content Groups - OCGs.</h2>
<p>This code sample shows how to:</p>
<ul>
<li>Create simple layers</li>
<li>Create nested layers</li>
<li>Create membership layers</li>
<li>Load a PDF containing layers</li>
<li>Annotate the layers that exist</li>
<li>Redact or delete layers that are invisible</li>
<li>Save the final PDF</li>
</ul>
<p>In the screenshot below you can see found nested layers with the layer visibility for 'Layer 4' set to off. This implicitly sets the visibility of 'Layer 5' to off because it is nested. The checkboxes on the right allow you to view the OCG structure and set OCG visibility.</p>
<p><img src="README-screenshot.png" /></p>
<p><em>The ABCpdf Team</em></p>
```
|
ABHISHEK-SIN-GH/database-project
|
ABHISHEK-SIN-GH/database-project
connect.php
```
<?php
$insert = false;
if(isset($_POST['name'])){
$server = "localhost";
$username = "root";
$password = "";
$con = mysqli_connect($server, $username, $password);
if(!$con)
{
die("conection failed due to".mysqli_connect_error());
}
// echo "successfully connected to database";
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$password = $_POST['password'];
$sql = "INSERT INTO `contactus`.`details` (`name`, `email`, `phone`, `address`, `password`, `time`)
VALUES ('$name', '$email', '$phone', '$address', '$password', current_timestamp());";
// echo $sql;
if($con->query($sql) == true)
{
$insert = true;
echo '<script type="text/javascript">';
echo ' alert("Now Please Login")'; //not showing an alert box.
echo '</script>';
}
else
{
echo "ERROR $sql <br> $con->error";
}
$con->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="description" content="Droppers Food Delivery Website in Bhilai-Durg, Chhattishgarh">
<meta name="keywords"
content="Droppers, Food-Delivery, Delivery, Delivery in Bhilai-Durg, Food, zomato, swigy, parcel, cake delivery, grocery delivery">
<meta name="author" content="Abhishek Kumar Singh">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./style.css" />
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link href="https://fonts.googleapis.com/css2?family=Caveat&family=Dancing+Script&display=swap" rel="stylesheet" />
<link
href="https://fonts.googleapis.com/css2?family=Caveat&family=Dancing+Script&family=New+Tegomin&family=Source+Code+Pro&display=swap"
rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.3/css/all.css"
integrity="sha384-SZXxX4whJ79/gErwcOYf+zWLeJdY/qpuqC4cAa9rOGUstPomtqpuNWT9wdPEn2fk" crossorigin="anonymous" />
<meta name="viewport"
content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
<link rel="stylesheet" href="./log.css">
<title>Home</title>
</head>
<body>
<div>
<div class="navbar">
<div id="logo"></div>
<div id="nav">
<a class="active" href="#">Home</a>
<div class="dropdown">
<a class="dropbtn" class="active">Services</a>
<div class="dropdown-content">
<a href="./so.html">Service Offered</a>
<a href="./pp.html">Privacy Policy</a>
<a href="./cr.html">Cancellation/Refund</a>
<a href="./t&c.html">T & C</a>
</div>
</div>
<a href="./aboutUs.html">About Us</a>
<a href="./contactUs.html">Contact Us</a>
<a style="color: rgb(236, 161, 95)" id="ps" href="#">Droppers App<br />
<p>Coming Soon On</p>
<i class="fab fa-google-play" style="font-size: 38px"></i>
</a>
</div>
</div>
<div id="toggle" style="position: absolute"></div>
<div id="navbar">
<div class="nav">
<li><a href="#">Home</a></li>
<li><a href="./so.html">Service Offered</a></li>
<li><a href="./pp.html">Privacy Policy</a></li>
<li><a href="./cr.html">Cancellation/Refund</a></li>
<li><a href="./t&c.html">T & C</a></li>
<li><a href="./aboutUs.html">About Us</a></li>
<li><a href="./contactUs.html">Contact Us</a></li>
</div>
</div>
<script>
const toggle = document.getElementById("toggle");
const navbar = document.getElementById("navbar");
toggle.onclick = function () {
toggle.classList.toggle("active");
navbar.classList.toggle("active");
};
</script>
<div id="main">
<div id="con-main">
<h4>
DROPPERS <br /><br /><i>We provide the On-demand Delivery service in the region of
<br />Bhilai-Durg.</i><br /><br />
<button id="gq" onclick="myfunc()">
<h3>
<a href="#">Get Quote</a>
</h3>
</button>
</h4>
</div>
<a style="color: rgb(236, 161, 95); text-decoration: none;" id="bg-p" href="#">
<h2>Droppers App Coming Soon On</h2>
<i class="fab fa-google-play" style="font-size: 38px"> Playstore</i>
</a>
<div id="bg-main"></div>
</div>
<div class="footer">
<div class="details">
<div>
<p>2021 © Droppers Ltd.</p>
<br />
<p>All rights reserved.</p>
</div>
<div class="cc">
<h1>Contact</h1>
<br />
<p href="mailto:droppers.service@gmail.com">
droppers.service@gmail.com
</p>
<br />
<p>7000610175</p>
</div>
</div>
<hr style="color: white; width: 90%; margin: auto" />
<br /><br />
<div class="social">
<ul>
<li>
<a href="https://www.instagram.com/droppers.service/" target="_blank"><i
class="fab fa-instagram" style="font-size: 38px"></i></a>
</li>
<li>
<i class="fab fa-twitter" style="font-size: 38px"></i>
</li>
<li>
<a href="https://www.facebook.com/droppers.service/" target="_blank"><i class="fab fa-facebook"
style="font-size: 38px"></i></a>
</li>
<li>
<a href="https://api.whatsapp.com/send?phone=+917000610175&text=Order Now!!!!!"
target="_blank"><i class="fab fa-whatsapp" style="font-size: 38px"></i></a>
</li>
</ul>
</div>
</div>
</div>
<div>
<div class="center">
<input type="checkbox" id="show">
<label for="show" class="show-btn">login</label>
<div class="container">
<label for="show" class="close-btn fas fa-times" title="close"></label>
<div class="text">
Login</div>
<form action="./connect0.php" method="POST">
<div class="data">
<label>Email or Phone</label>
<input type="text" name="email" required>
</div>
<div class="data">
<label>Password</label>
<input type="password" name="password" required>
</div>
<div class="btn">
<div class="inner">
</div>
<button type="submit">login</button>
</div>
<div class="signup-link">
Not a member? <a id="a1" href="./signup.html">Signup now</a></div>
</form>
</div>
</div>
</div>
<script>
function myfunc() {
alert("Please login to place a order!!!!");
}
</script>
<script>
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].onclick = function () {
alert("please Sign Up");
return false;
};
}
var link = document.getElementById('a1');
link.onclick = function () {
return true;
};
</script>
</body>
</html>```
|
ABHISHEKRAI12/MY-FIRST-PROJECT
|
ABHISHEKRAI12/MY-FIRST-PROJECT
README.md
```# MY-FIRST-PROJECT
First project
hello
```
|
ABI-Software/flatmapvuer
|
ABI-Software/flatmapvuer
README.md
```# FlatmapVuer
This project aims to wrap the flatmap viewer project into a vue component.
There are currently two components available. FlatmapVuer and MultiFlatmapVuer. FlatmapVuer is used for displaying a single flatmap whereas MultiFlatmapVuer takes in an array of flatmaps and provide a chooser for selecting the flatmap on display.
## Flatmapvuer on NPM
Flatmapvuer is available on npm and can be installed into your project with the following command:
```bash
npm i @abi-software/flatmapvuer
```
## How to use
Install the package "npm i @abi-software/flatmapvuer" to your vue app.
Include the package in your script.
```javascript
import {FlatmapVuer, MultiFlatmapVuer} from '@abi-software/flatmapvuer';
import '@abi-software/flatmapvuer/dist/flatmapvuer.css';
```
Local registration in vue component:
```javascript
export default {
...
components: {
FlatmapVuer,
MultiFlatmapVuer
}
...
}
```
The line above registers both the FlatmapVuer and MultiFlatmapVuer component into the global scope.
You can now use the FlatmapVuer in your vue template as followed:
```html
<FlatmapVuer entry="NCBITaxon:9606" v-on:resource-selected="FlatmapSelected" v-on:ready="FlatmapReady"/>
```
**entry** is the variable/string with the NCBI Taxonomy term. There are five available at this moment:
NCBITaxon:9606 (Human), NCBITaxon:9685 (Cat), NCBITaxon:9823 (Pig), NCBITaxon:10090 (Mouse) and NCBITaxon:10114 (Rat)
**ready** is the custom event when the map has been loaded successfully.
**resource-selected** is the custom event triggered when a part of the flatmap is selected, the returned argument **resource** provides information of the selected resource.
Markers must be added to make a label selectable and it can be done through the **addMarker** method on the mapImp member of the FlatmapVuer component.
Please see the following sample codes for details.
```javascript
methods: {
FlatmapSelected: function(resource) {
console.log(resource);
},
FlatmapReady: function(flatmapComponent) {
labels = flatmapComponent.getLabels(); //return list of labels
//The following line adds a marker on the map. UBERON:0000948
//is the UBERON id representing the heart.
flatmapComponent.mapImp.addMarker("UBERON:0000948", "simulation");
}
}
```
You can also use MultiFlatmapVuer to provide a selection of flatmaps.
```html
<MultiFlatmapVuer :availableSpecies="availableSpecies"
@resource-selected="FlatmapSelected"
@ready="FlatmapReady" :initial="initial"/>
```
**availableSpecies** is the object containing information of available species for the users. See below for an example:
```javascript
availableSpecies : {
"Human":{taxo: "NCBITaxon:9606", iconClass:"icon-mapicon_human"},
"Rat":{taxo: "NCBITaxon:10114", iconClass:"icon-mapicon_rat"},
"Mouse":{taxo: "NCBITaxon:10090", iconClass:"icon-mapicon_mouse"},
"Pig":{taxo: "NCBITaxon:9823", iconClass:"icon-mapicon_pig"},
"Cat":{taxo: "NCBITaxon:9685", iconClass:"icon-mapicon_cat"},
}
```
The keys of the codes above provide the labels on the chooser, **taxo** should be one of the available taxon id from the list and **iconClass** specifies the user provided icons to use.
**initial** specifies the start up species when the component is first mounted, it should be one of the keys on the provided available species.
## Project setup from Github
The source code is available from Github, it can be found here: https://github.com/ABI-Software/flatmapvuer .
### Clone the respositroy
```bash
git clone https://github.com/ABI-Software/flatmapvuer.git
```
### Setup
```bash
npm install
```
### Compiles and minifies for production
```bash
npm run build-bundle
```
### Run the sample application
```bash
npm run serve
```
```
flatmapQueries.js
```/* eslint-disable no-alert, no-console */
// remove duplicates by stringifying the objects
const removeDuplicates = function(arrayOfAnything){
return [...new Set(arrayOfAnything.map(e => JSON.stringify(e)))].map(e => JSON.parse(e))
}
const cachedLabels = {};
const findTaxonomyLabel = async function(flatmapAPI, taxonomy){
if (cachedLabels && cachedLabels.hasOwnProperty(taxonomy)) {
return cachedLabels[taxonomy];
}
return new Promise(resolve=>{
fetch(`${flatmapAPI}knowledge/label/${taxonomy}`, {
method: 'GET',
})
.then(response => response.json())
.then(data => {
let label = data.label;
if (label === "Mammalia") {
label = "Mammalia not otherwise specified";
}
cachedLabels[taxonomy] = label;
resolve(label);
})
.catch((error) => {
console.error('Error:', error);
cachedLabels[taxonomy] = taxonomy;
resolve(taxonomy);
})
});
}
const inArray = function(ar1, ar2){
let as1 = JSON.stringify(ar1)
let as2 = JSON.stringify(ar2)
return as1.indexOf(as2) !== -1
}
let FlatmapQueries = function(){
this.initialise = function(flatmapApi){
this.flatmapApi = flatmapApi
this.destinations = []
this.origins = []
this.components = []
this.uberons = []
this.urls = []
this.controller = undefined
this.uberons = []
this.lookUp = []
}
this.createTooltipData = async function (eventData) {
let hyperlinks = []
if (eventData.feature.hyperlinks && eventData.feature.hyperlinks.length > 0) {
hyperlinks = eventData.feature.hyperlinks
} else {
hyperlinks = this.urls.map(url=>({url: url, id: "pubmed"}))
}
let taxonomyLabel = undefined;
if (eventData.provenanceTaxonomy) {
taxonomyLabel = [];
for (let i = 0; eventData.provenanceTaxonomy.length > i; i++) {
taxonomyLabel.push(await findTaxonomyLabel(this.flatmapAPI, eventData.provenanceTaxonomy[i]))
}
}
let tooltipData = {
destinations: this.destinations,
origins: this.origins,
components: this.components,
destinationsWithDatasets: this.destinationsWithDatasets,
originsWithDatasets: this.originsWithDatasets,
componentsWithDatasets: this.componentsWithDatasets,
title: eventData.label,
featureId: eventData.resource,
hyperlinks: hyperlinks,
provenanceTaxonomy: eventData.provenanceTaxonomy,
provenanceTaxonomyLabel: taxonomyLabel
}
return tooltipData
}
this.createComponentsLabelList = function(components, lookUp){
let labelList = []
components.forEach(n=>{
labelList.push(this.createLabelFromNeuralNode(n[0]), lookUp)
if (n.length === 2){
labelList.push(this.createLabelFromNeuralNode(n[1]), lookUp)
}
})
return labelList
}
this.createLabelLookup = function(uberons) {
return new Promise(resolve=> {
let uberonMap = {}
const data = { sql: this.buildLabelSqlStatement(uberons)}
fetch(`${this.flatmapApi}knowledge/query/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(payload => {
const entity = payload.keys.indexOf("entity");
const label = payload.keys.indexOf("label");
if (entity > -1 && label > -1) {
payload.values.forEach(pair => {
uberonMap[pair[entity]] = pair[label];
});
}
resolve(uberonMap)
})
})
}
this.buildConnectivitySqlStatement = function (keastIds) {
let sql = 'select knowledge from knowledge where entity in ('
if (keastIds.length === 1) {
sql += `'${keastIds[0]}')`
} else if (keastIds.length > 1) {
for (let i in keastIds) {
sql += `'${keastIds[i]}'${i >= keastIds.length - 1 ? ')' : ','} `
}
}
return sql
}
this.buildLabelSqlStatement = function (uberons) {
let sql = 'select entity, label from labels where entity in ('
if (uberons.length === 1) {
sql += `'${uberons[0]}')`
} else if (uberons.length > 1) {
for (let i in uberons) {
sql += `'${uberons[i]}'${i >= uberons.length - 1 ? ')' : ','} `
}
}
return sql
}
this.findAllIdsFromConnectivity = function (connectivity) {
let dnodes = connectivity.connectivity.flat() // get nodes from edgelist
let nodes = [...new Set(dnodes)] // remove duplicates
let found = []
nodes.forEach(n => {
if (Array.isArray(n)) {
found.push(n.flat())
} else {
found.push(n)
}
})
this.uberons = [... new Set(found.flat())]
return this.uberons
}
this.flattenConntectivity = function (connectivity) {
let dnodes = connectivity.flat() // get nodes from edgelist
let nodes = [...new Set(dnodes)] // remove duplicates
let found = []
nodes.forEach(n => {
if (Array.isArray(n)) {
found.push(n.flat())
} else {
found.push(n)
}
})
return found.flat()
}
this.findComponents = function (connectivity) {
let dnodes = connectivity.connectivity.flat() // get nodes from edgelist
let nodes = removeDuplicates(dnodes)
let found = []
let terminal = false
nodes.forEach(node => {
terminal = false
// Check if the node is an destination or origin (note that they are labelled dendrite and axon as opposed to origin and destination)
if (inArray(connectivity.axons, node)) {
terminal = true
}
if (inArray(connectivity.dendrites, node)) {
terminal = true
}
if (!terminal) {
found.push(node)
}
})
return found
}
this.retrieveFlatmapKnowledgeForEvent = async function(eventData){
// check if there is an existing query
if (this.controller) this.controller.abort();
// set up the abort controller
this.controller = new AbortController();
const signal = this.controller.signal;
const keastIds = eventData.resource
this.destinations = []
this.origins = []
this.components = []
if (!keastIds || keastIds.length == 0) return
const data = { sql: this.buildConnectivitySqlStatement(keastIds)};
let prom1 = new Promise(resolve=>{
fetch(`${this.flatmapApi}knowledge/query/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
signal: signal
})
.then(response => response.json())
.then(data => {
if(this.connectivityExists(data)){
let connectivity = JSON.parse(data.values[0][0])
this.processConnectivity(connectivity).then(()=>{
resolve(true)
})
} else {
resolve(false)
}
})
.catch((error) => {
console.error('Error:', error);
resolve(false)
})
})
let prom2 = await this.pubmedQueryOnIds(eventData)
let results = await Promise.all([prom1, prom2])
return results
}
this.connectivityExists = function(data){
if (data.values && data.values.length > 0 && JSON.parse(data.values[0][0]).connectivity && JSON.parse(data.values[0][0]).connectivity.length > 0) {
return true
} else {
return false
}
}
this.createLabelFromNeuralNode = function(node, lookUp){
let label = lookUp[node[0]]
if (node.length === 2 && node[1].length > 0){
node[1].forEach(n=>{
if (lookUp[n] == undefined){
label += `, ${n}`
} else {
label += `, ${lookUp[n]}`
}
})
}
return label
}
this.flattenAndFindDatasets = function(components, axons, dendrites){
// process the nodes for finding datasets (Note this is not critical to the tooltip, only for the 'search on components' button)
let componentsFlat = this.flattenConntectivity(components)
let axonsFlat = this.flattenConntectivity(axons)
let dendritesFlat = this.flattenConntectivity(dendrites)
// Filter for the anatomy which is annotated on datasets
this.destinationsWithDatasets = this.uberons.filter(ub => axonsFlat.indexOf(ub.id) !== -1)
this.originsWithDatasets = this.uberons.filter(ub => dendritesFlat.indexOf(ub.id) !== -1)
this.componentsWithDatasets = this.uberons.filter(ub => componentsFlat.indexOf(ub.id) !== -1)
}
this.processConnectivity = function(connectivity){
return new Promise (resolve=>{
// Filter the origin and destinations from components
let components = this.findComponents(connectivity)
// Remove duplicates
let axons = removeDuplicates(connectivity.axons)
let dendrites = removeDuplicates(connectivity.dendrites)
// Create list of ids to get labels for
let conIds = this.findAllIdsFromConnectivity(connectivity)
// Create readable labels from the nodes. Setting this to 'this.origins' updates the display
this.createLabelLookup(conIds).then(lookUp=>{
this.destinations = axons.map(a=>this.createLabelFromNeuralNode(a,lookUp))
this.origins = dendrites.map(d=>this.createLabelFromNeuralNode(d,lookUp))
this.components = components.map(c=>this.createLabelFromNeuralNode(c, lookUp))
this.flattenAndFindDatasets(components, axons, dendrites)
resolve(true)
})
})
}
this.flattenConntectivity = function(connectivity){
let dnodes = connectivity.flat() // get nodes from edgelist
let nodes = [...new Set(dnodes)] // remove duplicates
let found = []
nodes.forEach(n=>{
if (Array.isArray(n)){
found.push(n.flat())
} else {
found.push(n)
}
})
return found.flat()
}
this.findComponents = function(connectivity){
let dnodes = connectivity.connectivity.flat() // get nodes from edgelist
let nodes = removeDuplicates(dnodes)
let found = []
let terminal = false
nodes.forEach(node=>{
terminal = false
// Check if the node is an destination or origin (note that they are labelled dendrite and axon as opposed to origin and destination)
if(inArray(connectivity.axons,node)){
terminal = true
}
if(inArray(connectivity.dendrites, node)){
terminal = true
}
if (!terminal){
found.push(node)
}
})
return found
}
this.stripPMIDPrefix = function (pubmedId){
return pubmedId.split(':')[1]
}
this.buildPubmedSqlStatement = function(keastIds) {
let sql = 'select distinct publication from publications where entity in ('
if (keastIds.length === 1) {
sql += `'${keastIds[0]}')`
} else if (keastIds.length > 1) {
for (let i in keastIds) {
sql += `'${keastIds[i]}'${i >= keastIds.length - 1 ? ')' : ','} `
}
}
return sql
}
this.buildPubmedSqlStatementForModels = function(model) {
return `select distinct publication from publications where entity = '${model}'`
}
this.flatmapQuery = function(sql){
const data = { sql: sql}
return fetch(`${this.flatmapApi}knowledge/query/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.catch((error) => {
console.error('Error:', error)
})
}
// Note that this functin WILL run to the end, as it doesn not catch the second level of promises
this.pubmedQueryOnIds = function(eventData){
return new Promise(resolve=>{
const keastIds = eventData.resource
const source = eventData.feature.source
if(!keastIds || keastIds.length === 0) return
const sql = this.buildPubmedSqlStatement(keastIds)
this.flatmapQuery(sql).then(data=>{
// Create pubmed url on paths if we have them
if (data.values.length > 0){
this.urls = [this.pubmedSearchUrl(data.values.map(id=>this.stripPMIDPrefix(id[0])))]
resolve(true)
} else { // Create pubmed url on models
this.pubmedQueryOnModels(source).then(result=>{
resolve(result)
})
}
})
})
}
this.pubmedQueryOnModels = function(source){
return this.flatmapQuery(this.buildPubmedSqlStatementForModels(source)).then(data=>{
if (Array.isArray(data.values) && data.values.length > 0){
this.urls = [this.pubmedSearchUrl(data.values.map(id=>this.stripPMIDPrefix(id[0])))]
return true
} else {
this.urls = [] // Clears the pubmed search button
}
return false
})
}
this.pubmedSearchUrl = function(ids) {
let url = 'https://pubmed.ncbi.nlm.nih.gov/?'
let params = new URLSearchParams()
params.append('term', ids)
return url + params.toString()
}
}
export {FlatmapQueries, findTaxonomyLabel}
```
CHANGELOG.md
```# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog).
## [v0.5.6](https://github.com/alan-wu/flatmapvuer/compare/v0.5.5...v0.5.6)
### Commits
- Add an accidentally removed line. [`3948001`](https://github.com/alan-wu/flatmapvuer/commit/394800196414108c4e6f8cbf271b53b022818b97)
## [v0.5.5](https://github.com/alan-wu/flatmapvuer/compare/v0.5.5-beta.1...v0.5.5) - 2023-08-07
### Merged
- Additional settings [`#114`](https://github.com/alan-wu/flatmapvuer/pull/114)
- Add hierarchical control (FC) and species information (AC) [`#113`](https://github.com/alan-wu/flatmapvuer/pull/113)
- Add label for what species provenance info comes from [`#110`](https://github.com/alan-wu/flatmapvuer/pull/110)
### Commits
- Merge in upstream changes. [`39bbcf7`](https://github.com/alan-wu/flatmapvuer/commit/39bbcf7886f22c7c5f7518e7fabcfe23c78db93f)
- Update to the latest flamtap-viewer. [`50d25c3`](https://github.com/alan-wu/flatmapvuer/commit/50d25c3e30f6bf57f60610ace38f1bd283b90cfd)
- Add hierarachical system controls. [`554f37e`](https://github.com/alan-wu/flatmapvuer/commit/554f37e15db7461f7c66537596b2f1cf694cc25d)
## [v0.5.5-beta.1](https://github.com/alan-wu/flatmapvuer/compare/v0.5.5-beta.0...v0.5.5-beta.1) - 2023-07-11
### Commits
- Open map options are now a prop. [`4a7a056`](https://github.com/alan-wu/flatmapvuer/commit/4a7a056de3a0aa2f7110d721c3dc32226fdd9a13)
## [v0.5.5-beta.0](https://github.com/alan-wu/flatmapvuer/compare/v0.5.4...v0.5.5-beta.0) - 2023-07-11
### Commits
- Add open map UI. [`11f993e`](https://github.com/alan-wu/flatmapvuer/commit/11f993e3e2882a5ba65b7361ac9a77b86c3944c7)
- Update svg icons package. [`45c39fe`](https://github.com/alan-wu/flatmapvuer/commit/45c39fea1cba3031b42cbd928f43331241181974)
## [v0.5.4](https://github.com/alan-wu/flatmapvuer/compare/v0.5.3...v0.5.4) - 2023-07-04
## [v0.5.3](https://github.com/alan-wu/flatmapvuer/compare/v0.5.2...v0.5.3) - 2023-07-04
### Merged
- Couple of pop up fixes and remove an unused argument. [`#112`](https://github.com/alan-wu/flatmapvuer/pull/112)
- Remove unused request [`#111`](https://github.com/alan-wu/flatmapvuer/pull/111)
### Commits
- Fix a couple of display issue with tooltip. [`196e1a8`](https://github.com/alan-wu/flatmapvuer/commit/196e1a89bd369d4297252e7e23edbc5ad80435f1)
- Remove unused variable. [`521828d`](https://github.com/alan-wu/flatmapvuer/commit/521828dd0ae43e23078d264793ee40f2bf9ee5a8)
- Fix uberon map for connectivity not being saved as a variable [`643690e`](https://github.com/alan-wu/flatmapvuer/commit/643690efc58934b8028bda592149179339ed7b9b)
## [v0.5.2](https://github.com/alan-wu/flatmapvuer/compare/v0.5.1...v0.5.2) - 2023-06-15
### Commits
- Fix an issue with flatmap queries not using the right name. [`eaf6167`](https://github.com/alan-wu/flatmapvuer/commit/eaf6167a1b7ff7426f313cf0231a1fc017e68752)
## [v0.5.1](https://github.com/alan-wu/flatmapvuer/compare/v0.5.1-beta.1...v0.5.1) - 2023-06-15
## [v0.5.1-beta.1](https://github.com/alan-wu/flatmapvuer/compare/v0.5.1-beta.0...v0.5.1-beta.1) - 2023-06-13
### Commits
- Revert changes in dependencies. [`3a70807`](https://github.com/alan-wu/flatmapvuer/commit/3a708074cc05a1b10e14b2bc33790cd934479469)
## [v0.5.1-beta.0](https://github.com/alan-wu/flatmapvuer/compare/v0.5.0...v0.5.1-beta.0) - 2023-06-13
### Commits
- Udpate dependencies. [`943e51f`](https://github.com/alan-wu/flatmapvuer/commit/943e51fc4f88014d6c3c9fae2b99d3ffa6465fd2)
## [v0.5.0](https://github.com/alan-wu/flatmapvuer/compare/v0.4.6...v0.5.0) - 2023-06-12
### Merged
- Update build [`#107`](https://github.com/alan-wu/flatmapvuer/pull/107)
- Fix provenance logic: [`#109`](https://github.com/alan-wu/flatmapvuer/pull/109)
### Commits
- Downgrade to vue 2.6.14 [`a81b049`](https://github.com/alan-wu/flatmapvuer/commit/a81b049813301700e3ea16dad0d7f7109433f362)
- Merge in upstream changes, [`f490c11`](https://github.com/alan-wu/flatmapvuer/commit/f490c1171d591b57987f6b6f81a3dd62feaac293)
- Update vue version to 2.7.14 [`5eeadec`](https://github.com/alan-wu/flatmapvuer/commit/5eeadecce6ea554c806d5b2c0db50fb92e9ec7a6)
## [v0.4.6](https://github.com/alan-wu/flatmapvuer/compare/0.4.6-fixes-2...v0.4.6) - 2023-06-01
## [0.4.6-fixes-2](https://github.com/alan-wu/flatmapvuer/compare/0.4.6-fixes-1...0.4.6-fixes-2) - 2023-06-05
### Commits
- Search will display the label and location of the highest score result. [`c3b2e47`](https://github.com/alan-wu/flatmapvuer/commit/c3b2e471ed3bb6eb61c078c903814f40d57ca3fa)
## [0.4.6-fixes-1](https://github.com/alan-wu/flatmapvuer/compare/v0.4.6-fixes-0...0.4.6-fixes-1) - 2023-06-02
### Commits
- Version 0.4.6-fixes-1 [`e8b60c3`](https://github.com/alan-wu/flatmapvuer/commit/e8b60c3e9bf381f4af68bd95612cdd20ea3132d0)
- Rename mapboxgl in css rules to maplibregl. [`9040cc9`](https://github.com/alan-wu/flatmapvuer/commit/9040cc96d32bb076c14c05af52f79a7137cd2651)
## [v0.4.6-fixes-0](https://github.com/alan-wu/flatmapvuer/compare/v0.4.5...v0.4.6-fixes-0) - 2023-06-01
### Commits
- Fix an issue with poppver does not dismiss. [`c26cd14`](https://github.com/alan-wu/flatmapvuer/commit/c26cd143211247c0b58dad0379ac14c69b6edc0e)
- Fix the version of flatmap-viewer at 0.2.3.2-b.4 [`d7692a2`](https://github.com/alan-wu/flatmapvuer/commit/d7692a20b855e5550c74962dd416515b9b67cdce)
- 0.4.6 release. [`d6e0e01`](https://github.com/alan-wu/flatmapvuer/commit/d6e0e014c450c7f3a2f091db4f8f70dbadbeb157)
## [v0.4.5](https://github.com/alan-wu/flatmapvuer/compare/v0.4.2...v0.4.5) - 2023-06-01
### Merged
- Update beta text. [`#108`](https://github.com/alan-wu/flatmapvuer/pull/108)
- Fix pubmed resource logic [`#106`](https://github.com/alan-wu/flatmapvuer/pull/106)
### Commits
- Update flatmap-viewer [`4dfeb29`](https://github.com/alan-wu/flatmapvuer/commit/4dfeb296889802cee878d14c1143b99a8ed8fd7d)
- Remove debug code, update package # [`4d226fa`](https://github.com/alan-wu/flatmapvuer/commit/4d226faa084b80e76ee78e9f445f47173909e113)
- Version 0.4.5 [`d28daf4`](https://github.com/alan-wu/flatmapvuer/commit/d28daf48614e67568865bd0c1ae2309d5e90cbfa)
## [v0.4.2](https://github.com/alan-wu/flatmapvuer/compare/v0.4.1...v0.4.2) - 2023-05-10
### Commits
- Fix an issue with setting state before mounted. [`73d6cc1`](https://github.com/alan-wu/flatmapvuer/commit/73d6cc11005568c6b00f3dd322ff778b12373f63)
## [v0.4.1](https://github.com/alan-wu/flatmapvuer/compare/v0.4.0...v0.4.1) - 2023-05-10
### Merged
- Update controls and tidy up [`#105`](https://github.com/alan-wu/flatmapvuer/pull/105)
- Resolve promise list with 'true/false' for whether to display tooltip [`#104`](https://github.com/alan-wu/flatmapvuer/pull/104)
- Remove services from package.json [`#103`](https://github.com/alan-wu/flatmapvuer/pull/103)
- Switch class to function as it was breaking mapintegrated build [`#102`](https://github.com/alan-wu/flatmapvuer/pull/102)
- Queries refactor [`#101`](https://github.com/alan-wu/flatmapvuer/pull/101)
- V0.4.0 [`#100`](https://github.com/alan-wu/flatmapvuer/pull/100)
### Commits
- Use new FC map [`e54bf3c`](https://github.com/alan-wu/flatmapvuer/commit/e54bf3cfa5031020f136251d3691d3d1f05a1971)
- Update version number. [`cd32fa9`](https://github.com/alan-wu/flatmapvuer/commit/cd32fa955bff0b38c29271f30cacc106f1355cb2)
- Move toolip logic to flatmapQueries.js [`9b09d0c`](https://github.com/alan-wu/flatmapvuer/commit/9b09d0c97e218e7799071aedecd7193441954a3d)
## [v0.4.0](https://github.com/alan-wu/flatmapvuer/compare/v0.3.15...v0.4.0) - 2023-04-04
### Merged
- Prov pop up feedback [`#97`](https://github.com/alan-wu/flatmapvuer/pull/97)
- Rename Change background colour to change settings. [`#96`](https://github.com/alan-wu/flatmapvuer/pull/96)
### Commits
- Create a new vue component for the selection controls. [`aed5e35`](https://github.com/alan-wu/flatmapvuer/commit/aed5e3598d4d1fc8d6dd34a0cb7541066d155751)
- Add dynamic system legends. [`9c86414`](https://github.com/alan-wu/flatmapvuer/commit/9c8641476d61830f5f5141f3fe29c1a4c04b316f)
- update flatmap-viewer to 2.2.13 [`f8e0dc8`](https://github.com/alan-wu/flatmapvuer/commit/f8e0dc8473b37935dc24b9765569ed5c9d26604d)
## [v0.3.15](https://github.com/alan-wu/flatmapvuer/compare/v0.3.12...v0.3.15) - 2023-02-27
### Merged
- Fix minimap sizing issue and make sure flatmap-viewer 2.2.9 is used [`#95`](https://github.com/alan-wu/flatmapvuer/pull/95)
- Remove call to function that does not exist [`#94`](https://github.com/alan-wu/flatmapvuer/pull/94)
- Update package # and publish [`#93`](https://github.com/alan-wu/flatmapvuer/pull/93)
- Minimap hideable [`#92`](https://github.com/alan-wu/flatmapvuer/pull/92)
- Improve initialisation and search [`#91`](https://github.com/alan-wu/flatmapvuer/pull/91)
### Commits
- Move code to flatmapvuer, fix transform origin [`a630ed8`](https://github.com/alan-wu/flatmapvuer/commit/a630ed85806cf008d6b3d36d3ee270994341b86e)
- Add an additional flag to allow label to be displayed with the searchAndShowResult function. [`5f6c57b`](https://github.com/alan-wu/flatmapvuer/commit/5f6c57b7fc4eb062c6b00b80e95f007f3bd0a95a)
- Improve state loading. [`f695883`](https://github.com/alan-wu/flatmapvuer/commit/f6958831c23fa9539463182509e1b55620eb9521)
## [v0.3.12](https://github.com/alan-wu/flatmapvuer/compare/v0.3.12-fixes-0...v0.3.12) - 2023-01-20
## [v0.3.12-fixes-0](https://github.com/alan-wu/flatmapvuer/compare/v0.3.11...v0.3.12-fixes-0) - 2023-01-20
### Merged
- Permalink update [`#90`](https://github.com/alan-wu/flatmapvuer/pull/90)
### Commits
- Flatmapvuer now uses uuid to fetch the map when saved in state. [`af447d3`](https://github.com/alan-wu/flatmapvuer/commit/af447d3e73bb8324d636b4831d7527d821704a60)
- Improve initialisation of the multi flatmap. [`c00e258`](https://github.com/alan-wu/flatmapvuer/commit/c00e2584f02e0e9d4fbb8507a5ebbabd0f2f9655)
- Fix an issue with reactivity by assigning value directly into an object. [`f87757b`](https://github.com/alan-wu/flatmapvuer/commit/f87757b32f0566eb8d6355055d60cb4ff724b597)
## [v0.3.11](https://github.com/alan-wu/flatmapvuer/compare/v0.3.10...v0.3.11) - 2022-12-16
### Merged
- Now search on model for pubmed ids [`#85`](https://github.com/alan-wu/flatmapvuer/pull/85)
### Commits
- Cut down pubmedviewer, organise tooltip proccessing [`dde4b8b`](https://github.com/alan-wu/flatmapvuer/commit/dde4b8b62808475dac4e4cc2ecbbcc72c48d1196)
- Increment version number to 0.3.11. [`a7509fd`](https://github.com/alan-wu/flatmapvuer/commit/a7509fdbd4f6914f4362f2e526362ca8248b1a5e)
- Remove older unused watch on the pubmedvuer [`a74efe6`](https://github.com/alan-wu/flatmapvuer/commit/a74efe6ea54380d36afdaeede339584697701d5b)
## [v0.3.10](https://github.com/alan-wu/flatmapvuer/compare/0.3.9...v0.3.10) - 2022-12-13
### Commits
- Update to the latest version of flatmap-viewer. [`775fd65`](https://github.com/alan-wu/flatmapvuer/commit/775fd6551877e1219fb63e675be2ce31a2eb8a36)
- Add css for other neruon type. [`a8df0c5`](https://github.com/alan-wu/flatmapvuer/commit/a8df0c5cb03448a3b3bc5ab6e709206aee54f526)
- Start storing uuid when saving the state. [`21cea3e`](https://github.com/alan-wu/flatmapvuer/commit/21cea3eb1dbd58795482f29b7c2e5ed198fb7d63)
## [0.3.9](https://github.com/alan-wu/flatmapvuer/compare/0.3.8...0.3.9) - 2022-12-08
### Merged
- Update to the latest flatmap [`#84`](https://github.com/alan-wu/flatmapvuer/pull/84)
### Commits
- Update to flatmap-viewer 2.2.7 and change the way maps are found. [`c2ae329`](https://github.com/alan-wu/flatmapvuer/commit/c2ae3297fb167e68515f8c779c4ce4222ea48211)
## [0.3.8](https://github.com/alan-wu/flatmapvuer/compare/0.3.3...0.3.8) - 2022-12-02
### Merged
- Add legends [`#83`](https://github.com/alan-wu/flatmapvuer/pull/83)
- Update node processing to display labels correctly [`#75`](https://github.com/alan-wu/flatmapvuer/pull/75)
- Switch to new colors [`#81`](https://github.com/alan-wu/flatmapvuer/pull/81)
- Run npm install and update package # [`#76`](https://github.com/alan-wu/flatmapvuer/pull/76)
- Latest changes message [`#74`](https://github.com/alan-wu/flatmapvuer/pull/74)
### Commits
- Use the latest version of flatmap-viewer and update the endpoint. [`ecc5174`](https://github.com/alan-wu/flatmapvuer/commit/ecc517468aecab36097b29fd794f4e05fd8be1db)
- Begin working on legends. [`eb225cb`](https://github.com/alan-wu/flatmapvuer/commit/eb225cbe6285ff0030a03710a0f940b79e464311)
- Fix the creation of labels from nodes [`c28653a`](https://github.com/alan-wu/flatmapvuer/commit/c28653ad3534677d51fd29f666b5b036b8939e37)
## [0.3.3](https://github.com/alan-wu/flatmapvuer/compare/v0.3.1...0.3.3) - 2022-08-19
### Merged
- Add success pop-up [`#71`](https://github.com/alan-wu/flatmapvuer/pull/71)
### Commits
- Add props to display and customis the latest changes message. [`494c3d8`](https://github.com/alan-wu/flatmapvuer/commit/494c3d8d6f86038495925704d676cbce91a665ed)
- Rename 'success' to 'latestChanges' [`6bec159`](https://github.com/alan-wu/flatmapvuer/commit/6bec15969d4fa6cfb28cfeddb89ec813c4343d6c)
- Fix tooltip boolean numbers [`76c4481`](https://github.com/alan-wu/flatmapvuer/commit/76c448124476d3a16fb9633ce1ad8e95653b5cf9)
## [v0.3.1](https://github.com/alan-wu/flatmapvuer/compare/v0.3.0...v0.3.1) - 2022-07-29
### Merged
- Add scrollbar to the pathway popups [`#70`](https://github.com/alan-wu/flatmapvuer/pull/70)
- Bump async from 2.6.3 to 2.6.4 [`#63`](https://github.com/alan-wu/flatmapvuer/pull/63)
- Bump terser from 4.8.0 to 4.8.1 [`#67`](https://github.com/alan-wu/flatmapvuer/pull/67)
- Bump minimist from 1.2.5 to 1.2.6 [`#61`](https://github.com/alan-wu/flatmapvuer/pull/61)
- Bump shell-quote from 1.7.2 to 1.7.3 [`#68`](https://github.com/alan-wu/flatmapvuer/pull/68)
- Bump eventsource from 1.1.0 to 1.1.2 [`#69`](https://github.com/alan-wu/flatmapvuer/pull/69)
### Commits
- Switch to using scrollbar for tooltips [`6467659`](https://github.com/alan-wu/flatmapvuer/commit/646765986db012aaa86985a69ab6c46571a46f66)
- Increment to version 0.3.0 [`6cdebde`](https://github.com/alan-wu/flatmapvuer/commit/6cdebde6fb62f24ed25989fedf54cae5d6380f16)
- Update package # [`9999102`](https://github.com/alan-wu/flatmapvuer/commit/9999102256526f65984534f26c174d062863e426)
## [v0.3.0](https://github.com/alan-wu/flatmapvuer/compare/v0.3.0-beta-2...v0.3.0) - 2022-07-22
### Merged
- Upstream downstream pop ups [`#64`](https://github.com/alan-wu/flatmapvuer/pull/64)
### Commits
- Refactor axon->destination dendrite->origin [`2e8ad3e`](https://github.com/alan-wu/flatmapvuer/commit/2e8ad3efeeaa22987071215922540cdacb313e9d)
- Update flatmap-viewer, no longer tooltips for nerve cuffs [`be23067`](https://github.com/alan-wu/flatmapvuer/commit/be2306743b5353617d0258a50688b3c97fcfc958)
- split up popup boolean and creation [`5fe897c`](https://github.com/alan-wu/flatmapvuer/commit/5fe897cc7afe2ba467531cdd261f70107e3e0af7)
## [v0.3.0-beta-2](https://github.com/alan-wu/flatmapvuer/compare/v0.3.0-beta-1...v0.3.0-beta-2) - 2022-05-23
### Commits
- Improve label lookup. [`fceec12`](https://github.com/alan-wu/flatmapvuer/commit/fceec12276af56d28a9fbbc1f88c7bc984b17aef)
## [v0.3.0-beta-1](https://github.com/alan-wu/flatmapvuer/compare/v0.3.0-beta-0...v0.3.0-beta-1) - 2022-05-23
### Commits
- Handle missing data gratefully. [`875c5a0`](https://github.com/alan-wu/flatmapvuer/commit/875c5a0402808e0e05a6b58f708edcd6fbc47bf5)
## [v0.3.0-beta-0](https://github.com/alan-wu/flatmapvuer/compare/v0.2.5...v0.3.0-beta-0) - 2022-05-23
### Commits
- Create upstream-downstream tooltips [`3d2215f`](https://github.com/alan-wu/flatmapvuer/commit/3d2215f2d8ce6c2c4615505dac27c034d6b53434)
- Add pubmed queries for nerve cuffs [`81ec823`](https://github.com/alan-wu/flatmapvuer/commit/81ec8239dc7c5d7476a496797df33420532b8852)
- Make semicolons consistent and use provide/inject for apis [`60bd15d`](https://github.com/alan-wu/flatmapvuer/commit/60bd15d2984425c0a3f73b5d051634e936002230)
## [v0.2.5](https://github.com/alan-wu/flatmapvuer/compare/v0.2.5-beta-1...v0.2.5) - 2022-05-19
### Merged
- Build in element ui to avoid styles being used in global space. [`#65`](https://github.com/alan-wu/flatmapvuer/pull/65)
## [v0.2.5-beta-1](https://github.com/alan-wu/flatmapvuer/compare/v0.1.33...v0.2.5-beta-1) - 2022-05-11
### Merged
- Pan zoom events. Icon updates. Show/hide UI APIs. [`#62`](https://github.com/alan-wu/flatmapvuer/pull/62)
- Bump url-parse from 1.5.3 to 1.5.10 [`#60`](https://github.com/alan-wu/flatmapvuer/pull/60)
- Bump follow-redirects from 1.14.7 to 1.14.8 [`#58`](https://github.com/alan-wu/flatmapvuer/pull/58)
- Fix an issue with icon [`#56`](https://github.com/alan-wu/flatmapvuer/pull/56)
- Fix a bug causing compilation error upstream. [`#55`](https://github.com/alan-wu/flatmapvuer/pull/55)
- Increment package version [`#54`](https://github.com/alan-wu/flatmapvuer/pull/54)
- Update tooltip for non-rat flatmaps [`#53`](https://github.com/alan-wu/flatmapvuer/pull/53)
- Use Scss instead. [`#52`](https://github.com/alan-wu/flatmapvuer/pull/52)
- Dynamic markers, outline and colour chooser. [`#51`](https://github.com/alan-wu/flatmapvuer/pull/51)
- Species check [`#49`](https://github.com/alan-wu/flatmapvuer/pull/49)
- Set background colour and opacity at start up. [`#3`](https://github.com/alan-wu/flatmapvuer/pull/3)
- Tehsurfer gazelle pop ups [`#2`](https://github.com/alan-wu/flatmapvuer/pull/2)
- Resolve conflicts and bugs. [`#1`](https://github.com/alan-wu/flatmapvuer/pull/1)
### Commits
- Increment package version. [`19f90a8`](https://github.com/alan-wu/flatmapvuer/commit/19f90a8aa3a3b3c103f7b4a7f18c46fa001b4b95)
- Stylesheets are now in scss. [`4a944f3`](https://github.com/alan-wu/flatmapvuer/commit/4a944f35257a7e34b0144d111845f0cf4273f816)
- Update package-lock.json [`f0afe8f`](https://github.com/alan-wu/flatmapvuer/commit/f0afe8f369ecb42e91ef97f626bc5ad4fb7887c9)
## v0.1.33 - 2021-06-21
### Merged
- Improve tooltip style. [`#48`](https://github.com/alan-wu/flatmapvuer/pull/48)
- UI improvements [`#46`](https://github.com/alan-wu/flatmapvuer/pull/46)
- Update flatmap viewer which include an update on callback. [`#45`](https://github.com/alan-wu/flatmapvuer/pull/45)
- Add an option to set the flatmap api endpoint. [`#44`](https://github.com/alan-wu/flatmapvuer/pull/44)
- Implement saving/getting state of flatmap [`#43`](https://github.com/alan-wu/flatmapvuer/pull/43)
- Update dependencies. [`#42`](https://github.com/alan-wu/flatmapvuer/pull/42)
- Export is now named. Version updated to 0.1.28. [`#41`](https://github.com/alan-wu/flatmapvuer/pull/41)
- Now built without bundling external node modules. [`#40`](https://github.com/alan-wu/flatmapvuer/pull/40)
- Documentation [`#38`](https://github.com/alan-wu/flatmapvuer/pull/38)
- Fix Display all checkbox problem with reset. [`#37`](https://github.com/alan-wu/flatmapvuer/pull/37)
- Version0.1.25 [`#36`](https://github.com/alan-wu/flatmapvuer/pull/36)
- Version0.1.24 [`#35`](https://github.com/alan-wu/flatmapvuer/pull/35)
- Version0.1.23 [`#34`](https://github.com/alan-wu/flatmapvuer/pull/34)
- Tooltip update [`#33`](https://github.com/alan-wu/flatmapvuer/pull/33)
- Versions.1.22 [`#32`](https://github.com/alan-wu/flatmapvuer/pull/32)
- Version0.1.21 [`#31`](https://github.com/alan-wu/flatmapvuer/pull/31)
- Bump version to 0.1.20. [`#30`](https://github.com/alan-wu/flatmapvuer/pull/30)
- Added Help hovers [`#28`](https://github.com/alan-wu/flatmapvuer/pull/28)
- Add a button to toggle the background colour. [`#29`](https://github.com/alan-wu/flatmapvuer/pull/29)
- Version0.1.19 [`#27`](https://github.com/alan-wu/flatmapvuer/pull/27)
- Version0.1.18 [`#26`](https://github.com/alan-wu/flatmapvuer/pull/26)
- Version0.1.17 [`#25`](https://github.com/alan-wu/flatmapvuer/pull/25)
- Version0.1.16 [`#24`](https://github.com/alan-wu/flatmapvuer/pull/24)
- Version0.1.15 [`#23`](https://github.com/alan-wu/flatmapvuer/pull/23)
- Bump flatmap viewer and this package version. [`#22`](https://github.com/alan-wu/flatmapvuer/pull/22)
- Version0.1.13 [`#21`](https://github.com/alan-wu/flatmapvuer/pull/21)
- Version0.1.12 [`#19`](https://github.com/alan-wu/flatmapvuer/pull/19)
- Update flatmap viewer to 0.9.10. [`#18`](https://github.com/alan-wu/flatmapvuer/pull/18)
- Viewe0.9.9 test [`#1`](https://github.com/alan-wu/flatmapvuer/pull/1)
- Add emit for when flatmap is changed [`#17`](https://github.com/alan-wu/flatmapvuer/pull/17)
- Updaet flatmapviewer. [`#16`](https://github.com/alan-wu/flatmapvuer/pull/16)
- Bump version and make some stylistic changes. [`#15`](https://github.com/alan-wu/flatmapvuer/pull/15)
- Bump flatmap version to 0.9.4 [`#14`](https://github.com/alan-wu/flatmapvuer/pull/14)
- Add the apis required to display a popup. [`#13`](https://github.com/alan-wu/flatmapvuer/pull/13)
- Add the ability to adjust species at startup. [`#12`](https://github.com/alan-wu/flatmapvuer/pull/12)
- Increment version number [`#11`](https://github.com/alan-wu/flatmapvuer/pull/11)
- Update map viewer to v0.9.3 [`#10`](https://github.com/alan-wu/flatmapvuer/pull/10)
- Flatmap viewer 0.9 release [`#9`](https://github.com/alan-wu/flatmapvuer/pull/9)
- Add a multiflatmapvuer. [`#8`](https://github.com/alan-wu/flatmapvuer/pull/8)
- Remove undefined label from returned labels list. [`#7`](https://github.com/alan-wu/flatmapvuer/pull/7)
- Add ready event, getLabels and stylistic changes. [`#6`](https://github.com/alan-wu/flatmapvuer/pull/6)
- Add label to payload. [`#5`](https://github.com/alan-wu/flatmapvuer/pull/5)
- Fix a critical bug. [`#4`](https://github.com/alan-wu/flatmapvuer/pull/4)
- Add README.md. [`#3`](https://github.com/alan-wu/flatmapvuer/pull/3)
- Use resizeSensor to detect resizing. [`#2`](https://github.com/alan-wu/flatmapvuer/pull/2)
- First revision of the vue component of flatmap viwer. [`#1`](https://github.com/alan-wu/flatmapvuer/pull/1)
### Commits
- Increment version to 0.1.33. [`3202fa0`](https://github.com/alan-wu/flatmapvuer/commit/3202fa043c2e511994ce239e860c576dbaf155b9)
- Increment flatmapviewer to 1.0.3 which fixes cases of labels. [`7564d1d`](https://github.com/alan-wu/flatmapvuer/commit/7564d1dc5b431f9546f9ba90d10e3ed1d3f21060)
- Add more support for flatmap v0.9.2. [`b74b957`](https://github.com/alan-wu/flatmapvuer/commit/b74b957a4e3848f26e4bc0f97b1eed89a51bfe01)
```
flatmap-marker.js
```export default '<div class="flatmap-marker"><svg display="block" height="41px" width="27px" viewBox="0 0 27 41"><g fill-rule="nonzero"><g transform="translate(3.0, 29.0)" fill="#000000"><ellipse opacity="0.04" cx="10.5" cy="5.80029008" rx="10.5" ry="5.25002273"></ellipse><ellipse opacity="0.04" cx="10.5" cy="5.80029008" rx="10.5" ry="5.25002273"></ellipse><ellipse opacity="0.04" cx="10.5" cy="5.80029008" rx="9.5" ry="4.77275007"></ellipse><ellipse opacity="0.04" cx="10.5" cy="5.80029008" rx="8.5" ry="4.29549936"></ellipse><ellipse opacity="0.04" cx="10.5" cy="5.80029008" rx="7.5" ry="3.81822308"></ellipse><ellipse opacity="0.04" cx="10.5" cy="5.80029008" rx="6.5" ry="3.34094679"></ellipse><ellipse opacity="0.04" cx="10.5" cy="5.80029008" rx="5.5" ry="2.86367051"></ellipse><ellipse opacity="0.04" cx="10.5" cy="5.80029008" rx="4.5" ry="2.38636864"></ellipse></g><g fill="#005974"><path d="M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"></path></g><g opacity="0.25" fill="#000000"><path d="M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"></path></g><g transform="translate(6.0, 7.0)" fill="#FFFFFF"></g><g transform="translate(8.0, 8.0)"><circle fill="#000000" opacity="0.25" cx="5.5" cy="5.5" r="5.4999962"></circle><circle fill="#FFFFFF" cx="5.5" cy="5.5" r="5.4999962"></circle></g></g></svg></div>'```
index.js
```// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import FlatmapVuer from "./FlatmapVuer.vue";
import MultiFlatmapVuer from "./MultiFlatmapVuer.vue";
export {
FlatmapVuer,
MultiFlatmapVuer
};
```
|
ABacidore/ABacidoreECS
|
ABacidore/ABacidoreECS
README.md
```# ABacidoreECS
My github website
```
|
ABialoskorski/APO-2019
|
ABialoskorski/APO-2019
use-cases.md
```Opis skrócony przypadków użycia
===============================
Aktorzy procesu i ich cele
--------------------------
Aktor Cel
----------- -----------------------------
Dostawca Dodanie brakujących produktów
Klient Kupno produktu
Serwisant Przeprowadza przegląd maszyny
Komunikator automatu Powiadomienie dostawcy
Komunikator automatu Powiadomienie serwisanta
Słownik
-------
Hasło Opis
----------- -----------------------------
Dostawca Dostawca to podmiot zajmujący się uzupełnianiem towarów w automacie
Komunikator automatu Urządzenie wysyłające powiadomienia do odpowiednich podmiotów
Ekran Ekran musi wyświetlać minimum 3 cyfry w wielkości i kontraście który widoczny
jest dla przeciętnej osoby z odległości 50 cm.
Podajnik: Urządzenie do wydawania gotowycj produktów. W jednym
podajniku jest jeden rodzaj produktu.
Pojemnik na monety: Każdy nominał ma swój pojemnik
Pojemnik na banknoty: Każdy nominał banknota ma swój pojemnik
produkt gotowy: Np baton, czy puszka napoju
produkt do przygotowania: Produkt wymagający przygotowania w podgrzewaczu
Przypadki użycia
----------------
### Use case 1: Uzupełnienie brakujących produktów
Dostawca otwiera automat.
Dostawca Przełącza automat w tryb serwisowy.
Dostawca uzupełnia brakujące towary.
Dostawca zamyka automat i wyłącza tryb serwisowy.
### Use case 2: Powiadomienie o braku towaru
Komunikator automatu wysyła powiadomienie do dostawcy o braku towaru.
### Use case 3: Powiadomienie o usterce
Komunikator automatu wysyła powiadomienie do serwisanta o usterce.
### Use case 4: Kupno gotowego produktu
Klient wybiera produkt.
Klient wybiera metodę płatności.
Klient realizuje płatność za pomocą karty lub gotówki.
Automat wydaje produkt.
Automat wydaje resztę lub pokwitowanie z banku.
### Use case 5: Kupno przygotowywanego produktu
Klient wybiera przygotowywany produkt.
Klient wybiera metodę płatności.
Klient realizuje płatność za pomocą karty lub gotówki
Automat przygotowuje produkt.
Automat wyświetla pozostały czas do przygotowania produktu.
Automat wydaje produkt.
Automat wydaje resztę lub pokwitowanie z banku.
### Use case 6: Przeprowadzenie przeglądu maszyny
Serwisant dokonuje uwierzytelnienia.
Serwisant otwiera autoamat
Serwisant przełącza automat w tryb serwisowy.
Automat potwierdza przełączenie się w stan serwisowy
Serwisant testuje część mechaniczną automatu.
Automat przekazuje informacje o ewentualnych ustarkach.
Serwisant zapisuje w raporcie ewentualne usterki
Serwisant potwierdza w systemie "zaliczenie" danej części mechanicznej
Automat potwierdza pomyślne zakończenie serwisu.
Serwisant zamyka automat.
Automat wyłącza tryb serwisowy.
Serwisant wysyła raport.```
use-case-4.md
```# Artur Białoskórski
Use Case 4: Kupno gotowego produktu
=====================
**Aktor podstawowy:** Klient
Główni odbiorcy i oczekiwania względem systemu:
-----------------------------------------------
- Klient: Oczekuje szybkiego zakupu wybranego produktu, przy jak najmniejszej liczbie wykonanych czynności.
- Właściciel automatu: Chce poprawnie zrealizowanego procesu kupna produktu przez klientów. Chce zadowolenia klientów.
- Dostawca: Chce nieskomplikowanej autoryzacji i dostępu do automatu spożywczego w celu uzupełnienia produktow.
Warunki wstępne:
----------------
Klient jest zdecydowany na produkt dostępny w automacie i posiada odpowiednią sumę pieniędzy potrzebną do zakupu.
Warunki końcowe:
----------------
Klient zapłacił wymaganą kwotę w przypadku płatności kartą, lub jeśli płatność była gotówką otrzymał w razie potrzeby należną resztę.
Automat wydał klientowi wybrany przez niego produkt.
Scenariusz główny (ścieżka podstawowa):
---------------------------------------
1. Klient podchodzi do automatu spożywczego z chęcią zakupu produktów.
2. Klient wybiera produkt i wpisuje w terminalu numer produktu odpowiadający numerom rozpisanym przy danych produktach.
3. Automat wyświetla na ekranie informacje o wybranym produkcie i jego cenę.
4. Klient zatwierdza wybrany produkt.
5. Automat wyświetla na ekranie okno wyboru typu płatności.
6. Klient wybiera metodę płatności - kartą lub gotówką.
7. Klient wybrał płatność kartą i przyłożył kartę do terminala w celu płatności.
8. Klient wpisuje kod PIN karty w terminalu.
9. Automat wysyła zapytanie o autoryzację transakcji do Systemu Bankowego i żąda potwierdzenia możliwości zrealizowania transakcji.
10. Automat wyświetla informację o udanej płatności kartą.
11. Automat drukuje pokwitowanie z banku.
12. Automat wydaje wybrany produkt do podajnika.
Rozszerzenia (ścieżki alternatywne):
------------------------------------
2. Klient wpisał do terminala numer, do którego nie ma przypisanego żadnego produktu.
1. Automat wyświetla komunikat o błędnym wyborze.
2. Automat jeszcze raz wyświetla okno wyboru produktu.
2. Klient rezygnuje z kupna produktu i wybiera opcję zakończ.
1. Automat powraca do stanu przed wyborem produktu.
6. Klient wybrał płatność gotówka.
1. Klient wprowadza gotówkę do przeznaczonego i oznaczonego miejsca.
2. Automat wskazuje kwotę wprowadzoną i resztę należną klientowi.
3. Automat do koszyka na pieniądze wydaje resztę.
8. Klient nie posiada wystarczających środków na koncie.
1. Automat wyświetla komunikat o braku środków na koncie.
2. Automat jeszcze raz wyświetla okno wyboru produktu.
8. Klient wpisał błędny kod PIN.
1. Automat wyświetla komunikat o wpisaniu błędnego PIN'u.
2. Automat jeszcze raz wyświetla okno wyboru produktu.
Wymagania specjalne:
--------------------
Klient posiada gotówkę w Polskiej aktualnej walucie.
Wymagania technologiczne oraz ograniczenia na wprowadzane dane:
---------------------------------------------------------------
2. Numer produktu wprowadzony przez ekran dotykowy musi odpowiadać numerom rozpisanym przy produktach.
2. Niezbędny ekran dotykowy, kolory muszą być kontrastowe.
2. Możliwość interfejsu wielojęzycznego.
12. Automat musi posiadać podanik na produkty.
Kwestie otwarte:
----------------
- Klient może w każdej chwili zrezygnować.```
use-case-1.md
```# Łukasz Kubiak
Use Case 1: Nazwa ...
=====================
**Aktor podstawowy:** ...
Główni odbiorcy i oczekiwania względem systemu:
-----------------------------------------------
- Odbiorca1: oczekiwania ...
- Odbiorca2: oczekiwania ...
- Odbiorca3: oczekiwania ...
Warunki wstępne:
----------------
...
Warunki końcowe:
----------------
...
Scenariusz główny (ścieżka podstawowa):
---------------------------------------
1. ...
2. ...
3. ...
Rozszerzenia (ścieżki alternatywne):
------------------------------------
*a. ...
3a. ...
3b. ...
Wymagania specjalne:
--------------------
- ...
- ...
- ...
Wymagania technologiczne oraz ograniczenia na wprowadzane dane:
---------------------------------------------------------------
2a. ...
2b. ...
3a. ...
Kwestie otwarte:
----------------
- ...
- ...
- ...
```
README.md
```# Automat Spożywczy
## Wiktor Bałaban, Artur Białoskórski, Łukasz Kubiak
### Wiktor - useCase 6
### Łukasz - useCase 1
### Artur - useCase 4```
use-case-6.md
```# Wiktor Bałaban
Use Case 6: Przeprowadzenie przeglądu maszyny
=====================
**Aktor podstawowy:** Serwisant
Główni odbiorcy i oczekiwania względem systemu:
-----------------------------------------------
- Klient: oczekuje szybkiego serwisu, ponieważ podczas serwisu nie może kupować produktów
- Serwisant: oczekuje jasnych komunikatów z automatu, co jest nie tak, albo co działa dobrze
Warunki wstępne:
----------------
Automat działa
Warunki końcowe:
----------------
Automat działa, stan magazynowy produktów w systemie i w automacie jest taki sam
Scenariusz główny (ścieżka podstawowa):
---------------------------------------
1. Serwisant dokonuje uwierzytelnienia.
2. Serwisant otwiera autoamat.
3. Serwisant przełącza automat w tryb serwisowy.
4. Automat potwierdza przełączenie się w tryb serwisowy.
5. Serwisant testuje część mechaniczną automatu.
6. Automat przekazuje informacje o ewentualnych ustarkach.
7. Serwisant zapisuje w raporcie ewentualne usterki
8. Serwisant potwierdza w systemie "zaliczenie" danej części mechanicznej
*Serwisant wykonuje kroki 5, 6, 7, 8 dla każdej części mechanicznej uwzględnionej w serwisie*
9. Automat potwierdza pomyślne zakończenie serwisu.
10. Serwisant zamyka automat.
11. Automat wyłącza tryb serwisowy.
12. Serwisant wysyła raport.
Rozszerzenia (ścieżki alternatywne):
------------------------------------
*a. W dowolnym momencie system może się zawiesić.
Ponieważ serwis ma być wykonany jak najsprawiniej, automat "pamięta" kiedy zatrzymany został przegląd.
1. Serwisant resetuje automat.
2. Automat ponownie uruchamia się.
3. Automat przełącza się w tryb serwisowy.
4. Automat potwierdza przełączenie się w tryb serwisowy.
5. Serwisant przechodzi do 5. w którym przerwał.
*b. W dowolnym momencie automat może się wyłączyć z przyczyn zewnętrznych (np: brak zasilania)
Ponieważ serwis ma być wykonany jak najsprawiniej, automat "pamięta" kiedy zatrzymany został przegląd.
1. Serwisant czeka na przywrócenie zasilania.
2. Automat włącza się.
3. Automat przełącza się w tryb serwisowy.
4. Automat potwierdza przełączenie się w tryb serwisowy.
5. Serwisant przechodzi do 5. w którym przerwał.
2a. Automat nie otwiera się
Nie możliwe jest kontynuowanie serwisu.
6a. Brak błędu. Automat przekazuje komunikat o braku błędu.
6b. Wystąpił błąd znany dla automatu. Automat przekazuje komunikat z kodem błędu który wystąpił.
6c. Wystąpił błąd nieznany dla automatu. Automat przekazuje komunikat o nieznanym błędzie.
9b. Automat zamknięty zanim zostanie ukończony pomyślnie serwis.
Automat przywraca się do stanu przed zakończeniem serwisu
Wymagania specjalne:
--------------------
- Można testować przygotowywanie produktów (np. przez wykonanie testowej porcji produktu)
Wymagania technologiczne oraz ograniczenia na wprowadzane dane:
---------------------------------------------------------------
1a. Uwierzytelnianie za pomocą klucza
6. Automat wyświetla komunikaty na Ekranie
4,9. Potwierdzenie poprzez zapalenie lampki
Kwestie otwarte:
----------------
- Informacja o możliwości usterki przed jej wystąpieniem
- Wybór części do testowania przed rozpoczęciem testów
- Automatyczne generowanie raportu i wysyłanie go przez Komunikator automatu
```
system-events.md
```Zdarzenia systemowe
===================
Use case 1: Uzupełnienie brakujących produktów
-----------------
- otworzenie automatu
- przełączenie automatu w tryb serwisowy
- zamknięcie automatu
Use case 2: Powiadomienie o braku towaru
-----------------
jest to use-case wewnętrzny
Use case 3: Powiadomienie o usterce
-----------------
jest to use-case wewnętrzny
Use case 4: Kupno gotowego produktu
-----------------
- wpisanie numeru produktu
- zatwierdzenie produktu przez klienta
- wybór metody płatności przez klienta
- przyłożenie karty do terminala
- włożenie karty do terminala
- wpisanie kodu pin
- wprowadzenie monety do przeznaczonego i oznaczonego miejsca
- wprowadzenie banknotu do przeznaczonego i oznaczonego miejsca
- informacja o wydaniu gotowego produktu do podajnika
Use case 5: Kupno przygotowywanego produktu
-----------------
- wpisanie numeru produktu
- zatwierdzenie produktu przez klienta
- wybór metody płatności przez klienta
- przyłożenie karty do terminala
- włożenie karty do terminala
- wpisanie kodu pin
- wprowadzenie monety do przeznaczonego i oznaczonego miejsca
- wprowadzenie banknotu do przeznaczonego i oznaczonego miejsca
- informacja o wydaniu gotowego produktu do podajnika
Use case 6: Przeprowadzenie przeglądu maszyny
-----------------
- otworzenie automatu
- przełączenie automatu w tryb serwisowy
- potwierdzenie w systemie "przeglądu" danej części mechanicznej
- zamknięcie automatu
- reset automatu przez serwisanta poprzez wciśnięcie przycisku reset
```
|
ABonaplata/house-prices-eda-python
|
ABonaplata/house-prices-eda-python
README.md
```# House Prices: Análisis exploratorio de datos con Python
Previamente publicado en [Kaggle Kernels](https://www.kaggle.com/abonaplata/analisis-exploratorio-de-datos-con-python/).
El estudio previo de los datos o EDA es una etapa crítica en la ciencia de datos, y sin duda la que consume más tiempo.
Siguiendo los pasos de [Pedro Marcelino](https://www.kaggle.com/pmarcelino), que a su vez seguía el capítulo 'Examining your data' de [Hair et al. (2013)](https://www.amazon.com/gp/product/9332536503/), voy a realizar un completo análisis del conjunto de datos [House Prices: Advanced Regression Techniques](https://www.kaggle.com/c/house-prices-advanced-regression-techniques) de Kaggle, que espero que resulte útil a la comunidad.
Voy a dividir el análisis en los siguientes apartados:
1. Comprender el problema
2. Estudio univariable
3. Estudio multivariable
4. Limpieza básica de los datos
5. Comprobación de suposiciones
## 1. El problema
Para entender realmente el conjunto de datos, voy a estudiar el significado y la relevancia de cada variable con respecto al problema. Intentaré responder a diversas cuestiones sobre ellas, como:
* La relevancia de la variable en la compra de una casa.
* La importancia de la variable.
* Solapamiento con otras variables.
En la competición de Kaggle 'House prices' se indica que el problema es la predicción del precio de las viviendas, por lo que la variable objetivo es 'SalePrice'. Las demás variables se describen de la siguiente manera:
* <b>MSSubClass</b>: clase de construcción
* <b>MSZoning</b>: clasificación de la zona
* <b>LotFrontage</b>: pies lineales de calle de la parcela
* <b>LotArea</b>: tamaño de la parcela en pies cuadrados
* <b>Street</b>: tipo de acceso por carretera
* <b>Alley</b>: tipo de acceso al callejón
* <b>LotShape</b>: forma de la parcela
* <b>LandContour</b>: planitud de la parcela
* <b>Utilities</b>: servicios públicos disponibles
* <b>LotConfig</b>: Configuración de parcela
* <b>LandSlope</b>: pendiente de la parcela
* <b>Neighborhood</b>: ubicación física dentro de los límites de la ciudad de Ames
* <b>Condition1</b>: proximidad a la carretera principal o al ferrocarril
* <b>Condition2</b>: proximidad a la carretera principal o al ferrocarril (si hay un segundo)
* <b>BldgType</b>: tipo de vivienda
* <b>HouseStyle</b>: estilo de vivienda
* <b>OverallQual</b>: calidad general del material y del acabado
* <b>OverallCond</b>: condición general
* <b>YearBuilt</b>: fecha original de construcción
* <b>YearRemodAdd</b>: fecha de remodelación
* <b>RoofStyle</b>: tipo de cubierta
* <b>RoofMatl</b>: material del techo
* <b>Exterior1st</b>: revestimiento exterior de la casa
* <b>Exterior2nd</b>: revestimiento exterior de la casa (si hay más de un material)
* <b>MasVnrType</b>: tipo de revestimiento de mampostería
* <b>MasVnrArea</b>: área de revestimiento de mampostería en pies cuadrados
* <b>ExterQual</b>: calidad del material exterior
* <b>ExterCond</b>: estado del material en el exterior
* <b>Foundation</b>: tipo de cimentación
* <b>BsmtQual</b>: altura del sótano
* <b>BsmtCond</b>: estado general del sótano
* <b>BsmtExposure</b>: paredes del sótano a nivel de calle o de jardín
* <b>BsmtFinType1</b>: calidad del área acabada del sótano
* <b>BsmtFinSF1</b>: pies cuadrados de la superficie acabada tipo 1
* <b>BsmtFinType2</b>: calidad de la segunda superficie acabada (si existe)
* <b>BsmtFinSF2</b>: Pies cuadrados de la superficie acabada tipo 2
* <b>BsmtUnfSF</b>: pies cuadrados del área sin terminar del sótano
* <b>TotalBsmtSF</b>: pies cuadrados totales del sótano
* <b>Heating</b>: tipo de calefacción
* <b>HeatingQC</b>: calidad y estado de la calefacción
* <b>CentralAir</b>: aire acondicionado central
* <b>Electrical</b>: sistema eléctrico
* <b>1erFlrSF</b>: área en pies cuadrados de la primera planta (o planta baja)
* <b>2ndFlrSF</b>: área en pies cuadrados de la segunda planta
* <b>LowQualFinSF</b>: pies cuadrados acabados de baja calidad (todos los pisos)
* <b>GrLivArea</b>: superficie habitable por encima del nivel del suelo en pies cuadrados
* <b>BsmtFullBath</b>: cuartos de baño completos en el sótano
* <b>BsmtHalfBath</b>: medio baño del sótano
* <b>FullBath</b>: baños completos sobre el nivel del suelo
* <b>HalfBath</b>: medios baños sobre el nivel del suelo
* <b>Bedroom</b>: número de dormitorios por encima del nivel del sótano
* <b>Kitchen</b>: número de cocinas
* <b>KitchenQual</b>: calidad de la cocina
* <b>TotRmsAbvGrd</b>: total de habitaciones por encima del nivel del suelo (no incluye baños)
* <b>Functional</b>: valoración de la funcionalidad de la vivienda
* <b>Fireplaces</b>: número de chimeneas
* <b>FireplaceQu</b>: calidad de la chimenea
* <b>GarageType</b>: ubicación del garaje
* <b>GarageYrBlt</b>: año de construcción del garaje
* <b>GarageFinish</b>: acabado interior del garaje
* <b>GarageCars</b>: tamaño del garaje en capacidad de coches
* <b>GarageArea</b>: tamaño del garaje en pies cuadrados
* <b>GarageQual</b>: calidad de garaje
* <b>GarageCond</b>: condición de garaje
* <b>PavedDrive</b>: calzada asfaltada
* <b>WoodDeckSF</b>: area de plataforma de madera en pies cuadrados
* <b>OpenPorchSF</b>: área de porche abierto en pies cuadrados
* <b>EnclosedPorch</b>: área de porche cerrada en pies cuadrados
* <b>3SsnPorch</b>: área de porche de tres estaciones en pies cuadrados
* <b>ScreenPorch</b>: superficie acristalada del porche en pies cuadrados
* <b>PoolArea</b>: área de la piscina en pies cuadrados
* <b>PoolQC</b>: calidad de la piscina
* <b>Fence</b>: calidad de la valla
* <b>MiscFeature</b>: característica miscelánea no cubierta en otras categorías
* <b>MiscVal</b>: valor en dólares de la característica miscelánea
* <b>MoSold</b>: mes de venta
* <b>YrSold</b>: año de venta
* <b>SaleType</b>: tipo de venta
* <b>SaleCondition</b>: Condiciones de venta
## 2. Análisis univariable: 'SalePrice'
La variable 'SalePrice' es la variable objetivo de este conjunto de datos. En pasos posteriores a este análisis exploratorio de datos se realizaría una predicción del valor de esta variable, por lo que voy a estudiarla con mayor detenimiento. A simple vista se pueden apreciar:
* Una desviación con respecto a la distribución normal.
* Una asimetría positiva.
* Algunos picos.
### Resumiendo:
* 'GrLivArea' y 'TotalBsmtSF' mantienen una relación lineal positiva con 'SalePrice', aumentando en el mismo sentido. En el caso de 'TotalBsmtSF', la pendiente de esta relación es muy acentuada.
* 'OverallQual' y 'YearBuilt' también parecen relacionadas con 'SalePrice' (más fuerte en el primer caso), tal y como se puede observar en los diagramas de cajas.
Sólo he explorado cuatro variables, pero hay muchas otras a analizar.
## 3. Análisis multivariable
Hasta ahora sólo me he dejado llevar por la intuición para el análisis de las variables que he creído importantes. Es hora de un análisis más objetivo.
Para ello voy a realizar las siguientes pruebas de correlación:
* Matriz de correlación general: El mapa de calor es una forma visual muy útil para para conocer las variables y sus relaciones. A primera vista hay dos variables que llaman la atención: 'TotalBsmtSF' y '1stFlrSF', seguidas por las variables 'Garage*X*'. En ambos casos parece haber una correlación significativa; en realidad es tan fuerte que podría indicar multicolinealidad, es decir, que básicamente ofrecen la misma información. Con respecto a las correlaciones de la variable 'SalePrice', destacan las vistas anteriormente ('GrLivArea', 'TotalBsmtSF' y 'OverallQual'), pero hay otras que también deberían ser tenidas en cuenta.
* Matriz de correlación centrada en la variable 'SalePrice': En estas matrices de correlación se puede observar:
* 'OverallQual', 'GrLivArea' y 'TotalBsmtSF' están fuertemente correladas con 'SalePrice'.
* 'GarageCars' y 'GarageArea' también están fuertemente correladas pero, como he comentado anteriormente, el número de coches que se pueden aparcar en un garaje es una consecuencia de su superficie. Es por esto que sólo voy a mantener una de estas variables en el análisis, 'GarageCars', ya que está más correlada con 'SalePrice'.
* 'TotalBsmtSF' y '1stFloor' plantean la misma situación. En este caso mantendré 'TotalBsmtSF'.
* 'FullBath' también está correlada con 'SalePrice'. Parece que a la gente le gusta darse un baño en casa...
* 'TotRmsAbvGrd' y 'GrLivArea', otro caso de multicolinealidad.
* 'YearBuilt' también está ligeramente correlada con 'SalePrice'.
* Diagramas de dispersión entre las variables más correladas.
## 4. Limpieza de datos
### Datos desaparecidos
Antes de tratar los datos faltantes o missing values, es importante determinar su prevalencia y su aleatoriedad, ya que pueden implicar una reducción del tamaño de la muestra. También hay que asegurarse que la gestión de los datos desaparecidos no esté sesgada o esconda una verdad incómoda.
Por razones prácticas voy a eliminar las variables con más de un 15% de datos faltantes (p.ej. 'PoolQC', 'MiscFeature', 'Alley', etc.); no creo que las echemos de menos, no parecen aspectos importantes a considerar al comprar una casa.
Con respecto a las variables 'Garage*X*', observo el mismo número de datos desaparecidos, hecho que quizás habría que estudiar con más detenimiento. Pero, dado que la información más relevante en cuanto al garaje ya está recogida por la variable 'GarageCars', y que sólo se trata de un 5% de datos faltantes, borraré las citadas variables 'Garage*X*', además de las 'Bsmt*X*' bajo la misma lógica.
En cuanto a las variables 'MasVnrArea' y 'MasVnrType', se puede decir que no son esenciales y que, incluso, tienen una fuerte correlación con 'YearBuilt' y 'OverallQual'. No parece que se vaya a perder mucha información si elimino 'MasVnrArea' and 'MasVnrType'.
Para finalizar, encuentro un dato faltante en la variable 'Electrical'. Ya que sólo se trata de una observación, voy a borrarla y a mantener la variable.
En resumen, voy a borrar todas las variables con datos desaparecidos, excepto la variable 'Electrical'; en este caso sólo voy a borrar la observación con el dato faltante.
### Datos atípicos
Los datos atípicos u outliers pueden afectar marcadamente el modelo, además de suponer una fuente de información en sí misma. Su tratamiento es un asunto complejo que requiere más atención; por ahora sólo voy a hacer un análisis rápido a través de la desviación estándar de la variable 'SalePrice' y a realizar un par de diagramas de dispersión.
#### Análisis univariable
La primera tarea en este caso es establecer un umbral que defina una observación como valor atípico. Para ello voy a estandarizar los datos, es decir, transformar los valores datos para que tengan una media de 0 y una desviación estándar de 1.
* Los valores bajos son similares y no muy alejados del 0.
* Los valores altos están muy alejados del 0. Los valores superiores a 7 están realmente fuera de rango.
#### Análisis bivariable
Este diagrama de dispersión muestra un par de cosas interesantes:
* Los dos valores más altos de la variable 'GrLivArea' resultan extraños. Sólo puedo especular, pero podría tratarse de terrenos agrícolas o muy degradados, algo que explicaría su bajo precio. Lo que está claro es que estos dos puntos son atípicos, por lo que voy a proceder a eliminarlos.
* Las dos observaciones más altas de la variable 'SalePrice' se corresponden con las que observamos en el análisis univariable anterior. Son casos especiales, pero parece que siguen la tendencia general, por lo que voy a mantenerlas.
Aunque se pueden observar algunos valores bastante extremos (p.ej. TotalBsmtSF > 3000), parece que conservan la tendencia, por lo que voy a mantenerlos.
## 5. Comprobación de normalidad
Ya he realizado cierta limpieza de datos y estudiado la variable 'SalePrice'. Ahora voy a comprobar si 'SalePrice' cumple las asunciones estadísticas que nos permiten aplicar las técnicas del análisis multivariable.
De acuerdo con [Hair et al. (2013)](https://www.amazon.com/gp/product/9332536503/), hay que comprobar cuatro suposiciones fundamentales:
* <b>Normalidad</b> - Cuando hablamos de normalidad lo que queremos decir es que los datos deben parecerse a una distribución normal. Es importante porque varias pruebas estadísticas se basan en esta suposición. Sólo voy a comprobar la normalidad de la variable 'SalePrice', aunque resulte un tanto limitado ya que no asegura la normalidad multivariable. Además, si resolvemos la normalidad evitamos otros problemas, como la homocedasticidad.
* <b>Homocedasticidad</b> - La homocedasticidad se refiere a la suposición de que las variables dependientes tienen el mismo nivel de varianza en todo el rango de las variables predictoras, según [(Hair et al., 2013)](https://www.amazon.com/gp/product/9332536503/). La homocedasticidad es deseable porque queremos que el término de error sea el mismo en todos los valores de las variables independientes.
* <b>Linealidad</b>- La forma más común de evaluar la linealidad es examinar los diagramas de dispersión y buscar patrones lineales. Si los patrones no son lineales, valdría la pena explorar las transformaciones de datos. Sin embargo, no voy a entrar en esto porque la mayoría de los gráficos de dispersión que hemos visto parecen tener relaciones lineales.
* <b>Ausencia de errores correlacionados</b> - Esto ocurre a menudo en series temporales, donde algunos patrones están relacionados en el tiempo. Tampoco voy a tocar este asunto.
### En búsqueda de la normalidad
El objetivo es estudiar la variable 'SalePrice' de forma fácil, comprobando:
* <b>Histograma</b> - Curtosis y asimetría.
* <b>Gráfica de probabilidad normal</b> - La distribución de los datos debe ajustarse a la diagonal que representa la distribución normal.
De estos gráficos se desprende que 'SalePrice' no conforma una distribución normal. Muestra picos, asimetría positiva y no sigue la línea diagonal; aunque una simple transformación de datos puede resolver el problema.
Terminado el trabajo con 'SalePrice', voy a seguir con 'GrLivArea'. La variable 'GrLivArea' muestra asimetría.
Prosigo con el estudio de la variable 'TotalBsmtSF'. Estos gráficos nos muestran que la variable 'TotalBsmtSF':
* Presenta asimetrías.
* Hay un número significativo de observaciones con valor cero (casas sin sótano).
* El valor cero no nos permite hacer transformaciones logarítmicas.
Para aplicar una transformación logarítmica, crearé una variable binaria (tener o no tener sótano). Después, aplicaré la transformación logarítmica a todas las observaciones que no sean cero, ignorando aquellas con valor cero. De esta manera podré transformar los datos, sin perder el efecto de tener o no sótano.
### En búsqueda de la homocedasticidad
El mejor método para probar la homocedasticidad para dos variables métricas es de forma gráfica. Las desviaciones de una dispersión uniforme se muestran mediante formas tales como conos (pequeña dispersión a un lado del gráfico, gran dispersión en el lado opuesto) o diamantes (un gran número de puntos en el centro de la distribución).
Empiezo por 'SalePrice' y 'GrLivArea'. Las anteriores versiones de este gráfico de dispersión (antes de las transformaciones logarítmicas), tenían una forma cónica. Como puede apreciarse, el gráfico actual ya no tiene una forma cónica. Tan solo asegurando la normalidad en algunas variables, hemos resuelto el problema de la homocedasticidad.
Ahora vamos a comprobar 'SalePrice' con 'TotalBsmtSF'. Podemos decir que, en general, la variable 'SalePrice' muestra niveles equivalentes de varianza en todo el rango de 'TotalBsmtSF'.
Convierto las variables categóricas en variables ficticias o dummies.
## Conclusión
A lo largo de este kernel he puesto en práctica muchas de las estrategias propuestas por [Hair et al. (2013)](https://www.amazon.com/gp/product/9332536503/). He estudiado las variables, analizado 'SalePrice' a solas y con las variables más correladas, he lidiado con datos faltantes y valores atípicos, he probado algunos de los supuestos estadísticos fundamentales e incluso he transformado variables categoriales en variables dummy. Todo un abanico de técnicas en Python, usando las librerías [Pandas](https://pandas.pydata.org/), [Matplotlib](https://matplotlib.org/), [Seaborn](https://seaborn.pydata.org/), [NumPy](https://www.numpy.org/), [SciPy](https://www.scipy.org/) y [Scikit-learn](https://scikit-learn.org/stable/).
Se han quedado algunos asuntos en el tintero, pero no ha estado mal para empezar.
No quiero finalizar este ejercicio sin dar antes las gracias públicamente a Pedro Marcelino por su magnífico trabajo, del que éste es poco más que una traducción y retoque.
## Referencias
* [Pedro Marcelino](https://www.kaggle.com/pmarcelino)
* [Hair et al., 2013, Multivariate Data Analysis, 7th Edition](https://www.amazon.com/gp/product/9332536503/)
```
|
ABouchebaba/todoList
|
ABouchebaba/todoList
TacheAdapter.java
```package com.example.malistedetches;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
import java.util.ArrayList;
public class TacheAdapter extends ArrayAdapter {
private final Context context;
private final ArrayList<String[]> data;
private final int layoutResourceId;
public TacheAdapter(Context context, int layoutResourceId, ArrayList<String[]> data) {
super(context, layoutResourceId, data);
this.context = context;
this.data = data;
this.layoutResourceId = layoutResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder._id = (TextView)row.findViewById(R.id.entry_id_txt);
holder.title = (TextView)row.findViewById(R.id.entry_title_txt);
row.setTag(holder);
}
else
{
holder = (ViewHolder)row.getTag();
}
String[] tache = data.get(position);
holder._id.setText(tache[0]);
holder.title.setText(tache[1]);
return row;
}
static class ViewHolder
{
TextView _id;
TextView title;
}
}
```
TodoEntrySchema.java
```package com.example.malistedetches.db;
import android.provider.BaseColumns;
public class TodoEntrySchema {
public static final String DB_NAME = "com.example.mytodolist.db";
public static final int DB_VERSION = 1;
public class TodoEntry implements BaseColumns{
public static final String TABLE = "todo_entries";
public static final String COL_TODOENTRY = "title";
}
}
```
MainActivity.java
```package com.example.malistedetches;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.MenuBuilder;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.example.malistedetches.db.TodoEntryDBHelper;
import com.example.malistedetches.db.TodoEntrySchema;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private TodoEntryDBHelper todoEntryDBHelper;
private ArrayAdapter<String[]> arrayAdapter;
private ArrayList<String[]> loadData(){
String table = TodoEntrySchema.TodoEntry.TABLE;
String column = TodoEntrySchema.TodoEntry.COL_TODOENTRY;
String[] columns = new String[]{"_id", column};
Cursor cursor = todoEntryDBHelper
.getReadableDatabase()
.query(table, columns, null, null, null, null, null );
ArrayList<String[]> taches = new ArrayList<>();
while (cursor.moveToNext() ){
String task = cursor.getString(cursor.getColumnIndex(column));
String _id = cursor.getString(cursor.getColumnIndex("_id"));
taches.add( new String[]{_id, task});
Log.d("loadData", _id);
}
return taches;
}
private void updateTodoEntriesList(){
List<String[]> taches = loadData();
arrayAdapter.clear();
arrayAdapter.addAll(taches);
arrayAdapter.notifyDataSetChanged();
}
public void finishTask(View btn){
ViewGroup parent = (ViewGroup)btn.getParent();
TextView _id_txt = parent.findViewById(R.id.entry_id_txt);
String _id = _id_txt.getText().toString();
String table = TodoEntrySchema.TodoEntry.TABLE;
String[] whereArgs = new String[]{_id};
todoEntryDBHelper.getWritableDatabase().delete(table, "_id = ?", whereArgs);
updateTodoEntriesList();
Log.d( "delete" ,_id_txt.getText().toString());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
todoEntryDBHelper = new TodoEntryDBHelper(this);
ListView todoEntries = findViewById(R.id.todoEntries);
arrayAdapter = new TacheAdapter(this, R.layout.todo_entry, loadData());
todoEntries.setAdapter(arrayAdapter);
updateTodoEntriesList();
}
@SuppressLint("RestrictedApi")
@ Override
public boolean onCreateOptionsMenu( Menu menu ) {
getMenuInflater().inflate( R.menu.main_menu , menu ) ;
((MenuBuilder)menu).setOptionalIconsVisible(true);
return super.onCreateOptionsMenu( menu ) ;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getTitle().equals("Ajouter tache")){
// Log.d(TAG, "L'item Ajouter tache a ete selectionee");
final EditText todoEntryEditText = new EditText ( this ) ;
AlertDialog dialog = new AlertDialog . Builder ( this )
. setTitle ("Ajouter une tache")
. setMessage ("Veuillez saisir la description de la tache.")
. setView ( todoEntryEditText )
. setPositiveButton ("Ajouter", new
DialogInterface. OnClickListener () {
@ Override
public void onClick ( DialogInterface dialog , int which ) {
// Get user entry
String todoentry = String.valueOf( todoEntryEditText.getText() ) ;
// Get table name and column name
String table = TodoEntrySchema.TodoEntry.TABLE;
String column = TodoEntrySchema.TodoEntry.COL_TODOENTRY;
// Prepare values to insert
ContentValues contentValues = new ContentValues();
contentValues.put(column, todoentry);
// Insert value in DB
todoEntryDBHelper
.getWritableDatabase()
.insertWithOnConflict(table,
null,
contentValues,
SQLiteDatabase.CONFLICT_REPLACE);
updateTodoEntriesList();
Log.d(TAG, todoentry);
}
})
. setNegativeButton ("Annuler", null )
. create () ;
dialog . show () ;
}
return super.onOptionsItemSelected(item);
}
}```
TodoEntryDBHelper.java
```package com.example.malistedetches.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class TodoEntryDBHelper extends SQLiteOpenHelper{
public TodoEntryDBHelper ( Context context ) {
super ( context , TodoEntrySchema.DB_NAME , null , TodoEntrySchema.DB_VERSION ) ;
}
@ Override
public void onCreate ( SQLiteDatabase db ) {
String table = TodoEntrySchema.TodoEntry.TABLE;
String col_todo_entry = TodoEntrySchema.TodoEntry.COL_TODOENTRY;
String createTable =
"CREATE TABLE "+ table
+" ( _id INTEGER PRIMARY KEY AUTOINCREMENT , "
+ col_todo_entry + " TEXT NOT NULL)";
db . execSQL ( createTable ) ;
}
@ Override
public void onUpgrade ( SQLiteDatabase db , int oldVersion , int newVersion ) {
String table = TodoEntrySchema.TodoEntry.TABLE;
String dropTable = "DROP TABLE IF EXISTS " + table;
db . execSQL ( dropTable ) ;
onCreate ( db ) ;
}
}
```
|
AC0RN-Wizard/Kodi
|
AC0RN-Wizard/Kodi
README.md
```# Kodi
AC0RN Build Wizard for Kodi
```
|
ACBullen/reddit-querier
|
ACBullen/reddit-querier
App.test.js
```import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import renderer from "react-test-renderer";
import {shallow} from "enzyme";
import rest from 'rest';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
});
it('fetches posts and comments', ()=> {
const component = shallow(<App />);
component.state.username = "kijafa";
component.find('button').simulate('click');
return component.state.posts.length === 25 && component.state.comments.length === 25;
});
```
App.js
```import React, { Component } from 'react';
import logo from './logo.svg';
import axios from 'axios';
import {getPosts, getComments} from './fetches';
import './App.css';
class App extends Component {
constructor(){
super();
this.state = {
"posts" : {},
"comments" : {},
"username" : ""
}
this.updateUsername = this.updateUsername.bind(this);
this.fetchPosts = this.fetchPosts.bind(this);
}
// componentWillMount(){
// axios.get("https://www.reddit.com/user/ZadocPaet/submitted.json").then((r)=>console.log(r));
// }
updateUsername(e){
this.setState({"username" : e.target.value});
}
fetchPosts(){
getPosts(this.state.username)
.then((r)=>this.setState({"posts" : r.data.data.children}));
getComments(this.state.username)
.then((r)=>this.setState({"comments" : r.data.data.children}));
}
buildLis(obj){
let ar = [];
for (let i = 0; i < 25; i++) {
if (obj[i]){
ar.push(obj[i]);
} else {
break;
}
}
ar.sort((a,b)=> b.data.score - a.data.score)
return ar.map((el, i)=>{
if (i === 0){
console.log(el);
}
return(
<li className="info" key={i}>{this.buildLi(el.data)}</li>
)
})
}
buildLi(post){
let link = post.link_permalink || post.permalink;
let title = post.link_title || post.title;
let score = post.score;
let body = post.body || '';
return(
<div>
<h5>Score: {score}</h5>
<h5>Title: {title}</h5>
<h5>Link: {link}</h5>
<p>{body}</p>
</div>
)
}
render() {
return (
<div className="App">
<div>
<input onInput={this.updateUsername} value={this.state.username}/>
<button onClick={this.fetchPosts}>Get Comments/Posts</button>
</div>
<div>
Posts:
<ul>
{this.buildLis(this.state.posts)}
</ul>
Comments:
<ul>
{this.buildLis(this.state.comments)}
</ul>
<br/>
</div>
</div>
);
}
}
export default App;
```
fetches.js
```import axios from 'axios';
export const getPosts = (username)=>(
axios.get(`https://www.reddit.com/user/${username}/submitted.json`)
)
export const getComments = (username) =>(
axios.get(`https://www.reddit.com/user/${username}/comments.json`)
)
```
|
ACC-Batlab-Makerspace/mysql-connector-c-
|
ACC-Batlab-Makerspace/mysql-connector-c-
README.md
```# mysql-connector-c-
```
|
ACloseOne/zombs-royale
|
ACloseOne/zombs-royale
script.js
```/* 1. Create our character as a simple circle
2. Make a start button
3. Make a line for a stick gun
4. Make a leader board
WORKING 5. Control characters with arrow and WASD keys
DONE 6. Need to make a gameboard way bigger than the screen
7. Kill everyone by shooting them to win
DONE 8. Aim with the mouse
9. Have chests that contain weapons
10. When you get hit your health degrades
11. We need buildings which contains chests and windows
12. Make it mutliplayer
13. The world shrinks into smaller zones based on a time variable
14. Create a inset map (press M)
15. Create air drops which contain cool stuff
16. Have zombie characters that chase you
MAKE GAME WITH BORDERS
MAKE A DEADLY WEAPON
MAKE CHESTS
MAKE BUILDINGS/HOUSES
MAKE MANY BUSHES
MAKE A WEAPON THAT AIMS
*/
/* ADD VARIABLES HERE */
var canvas = document.querySelector('canvas');
var tools = canvas.getContext('2d');
var images = {
tile: { url: '//mrlera.wisen.space/capture/load/6DiIVWK1O4tUbo6TTYgAvFFI.png', image: new Image() },
lollipop: { url: '//mrlera.wisen.space/capture/load/xt_ht-rheityyypr-257rhoz.png', image: new Image() },
bush: { url: '//mrlera.wisen.space/capture/load/kjFJM9XwclT7aYeLa_ka2p8R.png', image: new Image() },
crate: { url: '//mrlera.wisen.space/capture/load/o8uns8p8uet7wxb8nqiuynvt.png', image: new Image() }
}
var maxPlayers = 2;
var countdownTimer = 5;
var coolDownPeriod = 5;
var isCoolDown = false;
var it;
var gameStarted = false;
var countdownDiv = document.querySelector('#countdown');
var isLeader = false;
var socket;
var time;
var gameWorld, me, bushes, crates, resources;
var characterName = prompt("WHAT's YOUR NAME?");
if(characterName.length > 10) location.href = 'https://www.wisen.space'
/* ADD FUNCTIONS HERE */
function World() {
this.width = 15;
this.height = 15;
this.x = Math.random()*(this.width-0.5) + 0.25;
this.y = Math.random()*(this.height-0.5) + 0.25;
this.image = images.tile.image;
var tileWidth = 0.05;
var tileHeight = 0.05;
this.calculateScreenCoordinates = function(obj) {
return {
x: (obj.x + 0.5 - this.x)*canvas.width
, y: (obj.y + 0.5 - this.y)*canvas.height
, w: obj.width*canvas.width
, h: obj.height*canvas.width
}
}
// MOVING THE SCREEN WITH ME
this.move = function() {
this.x += me.velocity.x;
this.y += me.velocity.y;
if(this.x < me.width || this.x > gameWorld.width - me.width){
this.x -= me.velocity.x;
}
if(this.y < me.height || this.y > gameWorld.height - me.height){
this.y -= me.velocity.y;
}
}
this.draw = function() {
// WORLD MUST ALWAYS BE DRAWN IN A WAY THAT THE MAIN CHARACTER IS IN THE MIDDLE OF THE SCREEN
// DRAWING SCREEN
tileHeight = tileWidth*canvas.width/canvas.height;
var tileCountX = 1/tileWidth + 2;
var tileCountY = 1/tileHeight + 2;
var tw = tileWidth*canvas.width;
var th = tileHeight*canvas.height;
var offx = this.x*canvas.width % tw;
var offy = this.y*canvas.height % th;
for(var ny = -1; ny < tileCountY; ny++) {
for(var nx = -1; nx < tileCountX; nx++) {
tools.drawImage(this.image, nx*tw-offx ,ny*th-offy, tw, th);
}
}
var wallLeft = Math.min(1, 0.5 - this.x)*canvas.width;
var wallTop = Math.min(1, 0.5 - this.y)*canvas.height;
var wallRight = Math.min(1, this.width - this.x + 0.5)*canvas.width;
var wallBottom = Math.min(1, this.height - this.y + 0.5)*canvas.height;
if(wallLeft > 0) {
tools.beginPath();
tools.fillStyle = '#AFDA55';
tools.fillRect(0, 0, wallLeft, canvas.height);
tools.closePath();
}
if(wallTop > 0) {
tools.beginPath();
tools.fillStyle = '#AFDA55';
tools.fillRect(0, 0, canvas.width, wallTop);
tools.closePath();
}
if(wallRight > 0) {
tools.beginPath();
tools.fillStyle = '#AFDA55';
tools.fillRect(wallRight, 0, Math.ceil(canvas.width-wallRight), canvas.height);
tools.closePath();
}
if(wallBottom > 0) {
tools.beginPath();
tools.fillStyle = '#AFDA55';
tools.fillRect(0, wallBottom, canvas.width, Math.ceil(canvas.height- wallBottom));
tools.closePath();
}
}
}
function Bush(options) {
this.bodyRadius = 0.1;
this.width = this.bodyRadius*2;
this.height = this.bodyRadius*2;
this.x = options ? options.x : Math.random()*(gameWorld.width - this.width);
this.y = options ? options.y : Math.random()*(gameWorld.height - this.height);
this.image = images.bush.image;
this.trans = 0.8;
this.move = function () {
}
this.draw = function() {
var s = gameWorld.calculateScreenCoordinates(this);
tools.globalAlpha = this.trans;
tools.drawImage(this.image, s.x, s.y, s.w, s.h);
tools.globalAlpha = 1;
}
}
function Crate(options) {
this.width = 0.05;
this.height = 0.05;
this.x = options ? options.x : Math.random()*(gameWorld.width - this.width);
this.y = options ? options.y : Math.random()*(gameWorld.height - this.height);
this.image = images.crate.image;
this.move = function () {
}
this.draw = function() {
var s = gameWorld.calculateScreenCoordinates(this);
tools.drawImage(this.image, s.x, s.y, s.w, s.h);
}
}
function Projectile() {
this.radius = 5;
this.color = 'orange';
this.move = function() {
if(!this.hasFired) return;
this.x += 1;
}
this.draw = function(x,y) {
tools.beginPath();
tools.fillStyle = this.color;
tools.arc(x, y, this.radius, 0, Math.PI*2);
tools.fill();
tools.closePath();
}
}
function Weapon(options) {
this.width = options.width;
this.height = options.height;
this.color = options.color;
this.image = images[options.image] ? images[options.image].image : undefined;
this.x = 0;
this.y = 0;
this.r = 0;
this.angle = 0;
this.velocity = {
x: 0, y: 0
}
this.projectile = null;
this.load = function() {
if(this.projectile) return;
this.projectile = new Projectile();
}
this.fire = function() {
if(!this.projectile) return;
this.projectile = null;
}
this.throw = function() {
this.velocity.x = 1;
}
this.draw = function(cx, cy, cr, angle) {
if(this.velocity.x) {
this.velocity.x += 10;
};
tools.save();
this.x = cx + this.velocity.x;
this.y = cy;
this.r = cr;
this.angle = angle;
tools.translate(this.x, this.y);
tools.rotate(this.angle - Math.PI);
if(this.image) {
tools.drawImage(this.image,
this.image.width*.1, this.image.height*.05, this.image.width*.8, this.image.height*.9,
0.5*this.width, this.r-this.height, this.width, this.height);
} else if(this.color) {
tools.fillStyle = this.color;
tools.fillRect(0, this.r, this.width, this.height);
}
if(this.projectile) this.projectile.draw(0, -0.8*this.height);
tools.restore();
}
}
function Character(player, socket) {
player = player || {};
var wand = new Weapon({width: 1, height:100, color: 'cyan'});
var lollipop = new Weapon({width:50, height:100, image: 'lollipop'});
var notItColor = '#white';
var itColor = 'red';
this.speed = 0.01;
this.bodyRadius = 0.03;
this.handRadius = 0.013;
this.width = (this.bodyRadius + this.handRadius)*1.75;
this.height = (this.bodyRadius + this.handRadius)*1.75;
this.color = notItColor;
this.handColor = black;
this.outlineColor = 'black';
this.angle = Math.PI / 5;
this.direction = { x: 0, y: 0, theta: 0 }
this.weapon = lollipop // wand;
this.id = player.id || (performance.now() + (Math.random()+'').split('.')[1]).replace(/\./g, '');
this.x = player.x;
this.y = player.y;
this.velocity = {
x:0, y: 0
}
this.socket = player.socket || socket;
this.name = player.name;
this.move = function () {
this.x += this.velocity.x;
this.y += this.velocity.y;
if(this.x < this.width || this.x > gameWorld.width - this.width){
this.x -= this.velocity.x;
}
if(this.y < this.height || this.y > gameWorld.height - this.height){
this.y -= this.velocity.y;
}
var c = this;
crates.forEach(function(crate) {
if(collides(c, crate)){
console.log("COLLIDE BUSH")
}
});
if(it === c.id) {
var nowItPlayer = resources.find(function(resource) {
if(isCoolDown) return false;
if(!(resource instanceof Character)) return false;
if(resource.id === it ) return false;
return collides(c, resource );
});
if(nowItPlayer) {
console.log('NOW IT PLAYER', it)
it = nowItPlayer.id;
startCoolDown();
}
}
}
this.rotate = function(mouseX,mouseY) {
this.direction.x = mouseX - canvas.width/2;
this.direction.y = mouseY - canvas.height/2;
var atan = Math.atan(this.direction.y/this.direction.x);
atan += this.direction.x >= 0 ? Math.PI/2 : 3*Math.PI/2;
this.direction.theta = atan;
}
this.draw = function() {
var r = this.bodyRadius*canvas.width;
var s = gameWorld.calculateScreenCoordinates(this);
var b = r*Math.cos(this.angle);
var d = r*Math.sin(this.angle);
var ct = Math.cos(this.direction.theta);
var st = Math.sin(this.direction.theta);
this.color = this.id === it ? itColor : notItColor;
function rotateCircle(px, py, radius) {
var rx = px*ct - py*st;
var ry = px*st + py*ct;
var handX = s.x + rx;
var handY = s.y + ry;
tools.arc(handX, handY, radius*canvas.width, 0,Math.PI*2);
return {x: handX, y: handY, r: radius*canvas.width};
}
/* LEFT HAND */
tools.beginPath();
tools.lineWidth=2;
tools.strokeStyle = this.outlineColor;
tools.fillStyle = this.handColor;
var leftHand = rotateCircle(-d, -b, this.handRadius);
tools.fill();
tools.stroke();
tools.closePath();
/* RIGHT HAND */
tools.beginPath();
var rightHand = rotateCircle(d, -b, this.handRadius);
tools.fill();
tools.stroke();
tools.closePath();
/* BODY */
tools.beginPath();
tools.lineWidth=2;
tools.strokeStyle = this.outlineColor;
tools.fillStyle = this.handColor;
tools.arc(s.x,s.y, r, 0,Math.PI*2);
tools.fill();
tools.stroke();
tools.closePath();
/* NAME TAG */
tools.fillStyle = 'blue';
tools.fillText(this.name, s.x-r/2, s.y);
// if(this.weapon) {
// this.weapon.draw(leftHand.x, leftHand.y, leftHand.r, Math.PI + this.direction.theta);
// }
}
this.update = function(player) {
Object.assign(this, player);
}
}
function startCoolDown() {
isCoolDown = true;
setTimeout(function() {
isCoolDown = false;
}, coolDownPeriod*1000);
}
function getGameState() {
return {
id: me.id
, timestamp: new Date()
, x: gameWorld.width - gameWorld.x
, y: gameWorld.height - gameWorld.y
}
}
function animate() {
tools.clearRect(0,0,canvas.width, canvas.height);
resources.forEach(function(resource) {
if(resource instanceof Weapon) return;
resource.move();
resource.draw();
});
window.requestAnimationFrame(animate);
}
function resizeCanvas() {
var bodySize = document.body.getBoundingClientRect();
canvas.width = bodySize.width;
canvas.height = bodySize.height;
}
function addSocketEvents() {
socket = io('/tunnel');
//generateWorld();
socket.on('newleader', () => {
console.log('newleader');
isLeader = true;
if(!resources) {
generateWorld(socket.id);
}
})
socket.on('userconnected', (socketId) => {
console.log('userconnected', socketId);
if(isLeader) {
socket.emit('updateworld', getWorldState());
}
});
socket.on('announceresponse', (data) => {
countdownDiv.innerHTML = data.data.time;
})
socket.on('gamestartedresponse', (data) => {
console.log('GAMESTARTED RESPONSE', data.data);
it = data.data.it;
console.log('GAME STARTED RESPONSE IT', it);
startCoolDown();
gameStarted = true;
})
socket.on('updateworldresponse', (data) => {
if(!resources) {
console.log('generating world')
generateWorld(socket.id, data.data);
}
})
socket.on('userdisconnected', (socketId) => {
console.log('userdisconnected', socketId);
resources = (resources || []).filter(resource => resource.socket !== socketId);
});
socket.on('updatestateresponse', (data) => {
var player = data.data;
var socketId = data.socket;
var character = (resources || []).find(resource => resource.id === player.id);
if(character) {
character.update(player);
} else {
character = new Character(player, socketId);
(resources || []).splice(1, 0, character);
(resources || []).splice(2, 0, character.weapon);
}
});
socket.on('tagresponse', (data) => {
alert(data)
})
}
function initializeSockets() {
restfull.post({
path: '/tunnel/register'
,data : {
events: ['updatestate', 'updateworld', 'gamestarted', 'announce']
}
}, (err, resp) => {
if(err || resp.error) {
return console.log(err || resp.error)
}
addSocketEvents();
});
}
function loadResources() {
var loadedResourceCount = 0;
var resources = Object.keys(images);
resources.forEach(function(resource) {
images[resource].image.onload = function() {
loadedResourceCount++;
if(loadedResourceCount === resources.length) {
initializeSockets();
}
}
images[resource].image.src = images[resource].url;
})
}
function changeDirection(key) {
// CHALLENGE: WHAT DO WE MODIFY HERE TO MOVE THE WORLD?
if(key.keyCode === 37 || key.key === 'a') {
// LEFT
me.velocity.x = -me.speed;
socket.emit('updatestate', getState());
}
else if(key.keyCode === 38 || key.key === 'w') {
// UP
me.velocity.y = -me.speed;
socket.emit('updatestate', getState());
}
else if(key.keyCode === 39 || key.key === 'd') {
// RIGHT
me.velocity.x = me.speed;
socket.emit('updatestate', getState());
}
else if(key.keyCode === 40 || key.key === 's') {
// DOWN
me.velocity.y = me.speed;
socket.emit('updatestate', getState());
}
}
function stopCharacter(e) {
if(e.keyCode === 38 || e.key === 'w' || e.direction === 8) {
me.velocity.x = 0;
me.velocity.y = 0;
socket.emit('updatestate', getState());
}
if(e.keyCode === 37 || e.key === 'a' || e.direction === 2) {
me.velocity.x = 0;
me.velocity.y = 0;
socket.emit('updatestate', getState());
}
if(e.keyCode === 40 || e.key === 's' || e.direction === 16) {
me.velocity.x = 0;
me.velocity.y = 0;
socket.emit('updatestate', getState());
}
if(e.keyCode === 39 || e.key === 'd' || e.direction === 4) {
me.velocity.x = 0;
me.velocity.y = 0;
socket.emit('updatestate', getState());
}
}
function rotate(e) {
me.rotate(e.clientX, e.clientY);
socket.emit('updatestate', getState());
}
function moveCharacter(e) {
gameWorld.velocity.x = -gameWorld.speed*Math.sin(me.direction.theta);
gameWorld.velocity.y = gameWorld.speed*Math.cos(me.direction.theta);
}
function throwWeapon() {
// if(!me.weapon) return;
// me.weapon.throw();
// socket.emit('updatestate', getState());
}
function getState() {
return me;
}
function emitGameStarted() {
gameStarted = true;
players = resources.filter(resource => resource instanceof Character);
console.log('STARTING GAME', players);
var playerNumber = parseInt(Math.random()*players.length);
it = players[playerNumber].id;
console.log('STARTING GAME IT', it);
startCoolDown();
socket.emit('gamestarted', {it: it});
}
function announce() {
time--;
if(time === 0) {
emitGameStarted();
} else {
setTimeout(announce, 1000);
}
countdownDiv.innerHTML = time;
socket.emit('announce', {time: time});
}
function getWorldState() {
var players = resources.filter(resource => resource instanceof Character);
if(players.length === maxPlayers-1) {
time = countdownTimer;
setTimeout(announce, 1000);
}
return {
bushes: bushes,
players: players,
crates: crates
}
}
function generateWorld(socketId, data) {
gameWorld = new World();
me = new Character({x: gameWorld.x, y: gameWorld.y }, socketId);
me.name = characterName;
resources = [gameWorld, me, me.weapon]
// NEXT ADD OTHER PLAYERS
if(data) {
data.players.forEach((player) => {
var character = new Character(player);
resources.push(character);
resources.push(character.weapon);
})
}
bushes = [];
while(bushes.length < 500) {
var bushData = data ? data.bushes[bushes.length] : undefined;
bushes.push(new Bush(bushData));
}
crates = [];
while(crates.length < 500) {
var crateData = data ? data.crates[crates.length] : undefined;
crates.push(new Crate(crateData));
}
resources = resources.concat(crates);
resources = resources.concat(bushes);
addEventListeners();
animate();
socket.emit('updatestate', getState());
}
function collides(thing1, thing2) {
if((thing1.y + thing1.height) < thing2.y) {
return false;
}
if((thing2.y + thing2.height) < thing1.y) {
return false;
}
if((thing1.x + thing1.width) < thing2.x) {
return false;
}
if((thing2.x + thing2.width) < thing1.x) {
return false;
}
return true;
}
/* ADD EVENT LISTENERS HERE */
function addEventListeners() {
window.addEventListener('resize', resizeCanvas);
window.addEventListener('keydown', changeDirection);
window.addEventListener('keyup', stopCharacter);
window.addEventListener('mousemove', rotate);
window.addEventListener('click', throwWeapon);
}
/* CODE TO RUN WHEN PAGE LOADS */
resizeCanvas();
loadResources();
```
|
ACruzadoP/48_react_form_practice
|
ACruzadoP/48_react_form_practice
App.js
```import React, {Component} from "react"
class App extends Component {
constructor() {
super()
this.state = {
firstName: "",
lastName: "",
age: "",
gender: "",
destination: "",
lactose: false,
vegan: false,
peanut: false,
diabetic: false,
gluten: false,
kosher: false,
halal: false
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event) {
const {name, value, type, checked} = event.target
type === "checkbox" ?
this.setState({[name]: checked}) :
this.setState({[name]: value})
}
handleSubmit() {
console.log("Información enviada =D")
}
render() {
return (
<main>
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.firstName}
name="firstName"
placeholder="First Name"
onChange={this.handleChange}
/>
<br />
<input
type="text"
value={this.state.lastName}
name="lastName"
placeholder="Last Name"
onChange={this.handleChange}
/>
<br />
<input
type="text"
value={this.state.age}
name="age"
placeholder="Age"
onChange={this.handleChange}
/>
<br /><br />
<label>Gender: <br />
<input
type="radio"
name="gender"
value="Male"
checked={this.state.gender === "Male"}
name="gender"
onChange={this.handleChange}
/> Male
</label>
<label>
<input
type="radio"
name="gender"
value="Female"
checked={this.state.gender === "Female"}
name="gender"
onChange={this.handleChange}
/> Female
</label>
<br /><br />
<label>Location: </label>
<select
value={this.state.destination}
onChange={this.handleChange}
name="destination"
>
<option value="">-- Please Choose a destination --</option>
<option value="Asia">Asia</option>
<option value="América">América</option>
<option value="África">África</option>
<option value="Antártida">Antártida</option>
<option value="Europa">Europa</option>
<option value="Oceanía">Oceanía</option>
</select>
<br /><br />
<label>Dietary restrictions_:
<br />
<input
type="checkbox"
checked={this.state.lactose}
name="lactose"
onChange={this.handleChange}
/> Lactose Intolerance
</label><br />
<label>
<input
type="checkbox"
checked={this.state.vegan}
name="vegan"
onChange={this.handleChange}
/> Vegetarian and Vegans
</label><br />
<label>
<input
type="checkbox"
checked={this.state.peanut}
name="peanut"
onChange={this.handleChange}
/> Peanut Allergies
</label><br />
<label>
<input
type="checkbox"
checked={this.state.diabetic}
name="diabetic"
onChange={this.handleChange}
/> Diabetic
</label><br />
<label>
<input
type="checkbox"
checked={this.state.gluten}
name="gluten"
onChange={this.handleChange}
/> Gluten Free
</label><br />
<label>
<input
type="checkbox"
checked={this.state.kosher}
name="kosher"
onChange={this.handleChange}
/> Kosher
</label><br />
<label>
<input
type="checkbox"
checked={this.state.halal}
name="halal"
onChange={this.handleChange}
/> Halal
</label>
<br />
<button>Submit</button>
</form>
<hr />
<h2>Entered information:</h2>
<p>Your name: {this.state.firstName} {this.state.lastName}</p>
<p>Your age: {this.state.age}</p>
<p>Your gender: {this.state.gender}</p>
<p>Your destination: {this.state.destination}</p>
<p>
Your dietary restrictions:
{this.state.lactose && " Lactose Intolerance,"}
{this.state.vegan && " Vegetarian/Vegan,"}
{this.state.peanut && " Peanut Allergy,"}
{this.state.diabetic && " Diabetic,"}
{this.state.gluten && " Gluten Free,"}
{this.state.kosher && " Kosher,"}
{this.state.halal && " Halal,"}
</p>
</main>
)
}
}
export default App
```
README.md
```This is 48th screencast, called "48. React Form Practice"<br />
https://scrimba.com/course/glearnreact
Challenge: Wire up the partially-finished travel form so that it works! All information should be populating the text below the form in real-time as you're filling it out.
```
|
ADA-ANU/METABASE-to-Twitter-updates
|
ADA-ANU/METABASE-to-Twitter-updates
Constants.py
```import dotenv
import os
dotenv.load_dotenv()
# API_METABASE_AUTHENTICATION_ENDPOINT = "https://dataverse-dev.ada.edu.au/metabase/api/session"
API_METABASE_AUTHENTICATION_ENDPOINT = "https://reporting.ada.edu.au/api/session"
API_WP_AUTHENTICATION_ENDPOINT = "http://sw-dev.ada.edu.au:8085/wp-json/aam/v2/authenticate"
API_WP_GETPOSTS_PUBLISH = "http://sw-dev.ada.edu.au:8085/wp-json/wp/v2/posts?categories=26"
API_WP_GETPOSTS_UPDATE = "http://sw-dev.ada.edu.au:8085/wp-json/wp/v2/posts?categories=27"
API_WP_UPDATEPOSTS = "http://sw-dev.ada.edu.au:8085/wp-json/wp/v2/posts/"
API_WP_VALIDATE = "http://sw-dev.ada.edu.au:8085/wp-json/aam/v1/validate-jwt"
# API_DATASETS_QUERY_NEWPUBLICATION = "https://dataverse-dev.ada.edu.au/metabase/api/card/396/query/json"
API_DATASETS_QUERY_NEWPUBLICATION = "https://reporting.ada.edu.au/api/card/471/query/json"
# API_DATASETS_QUERY_NEWPUPDATE = "https://dataverse-dev.ada.edu.au/metabase/api/card/397/query/json"
API_DATASETS_QUERY_NEWPUPDATE = "https://reporting.ada.edu.au/api/card/472/query/json"
API_WP_CREATEPOSTS = "http://sw-dev.ada.edu.au:8085/wp-json/wp/v2/posts"
API_DATAVERSES_PUBLISHDATASET = "https://dataverse-dev.ada.edu.au/api/datasets/"
API_DATAVERSES_CREATEDATASET = "https://dataverse-dev.ada.edu.au/api/dataverses/DEV-ADA/datasets/"
API_METABASE_AUTHENTICATION_HEADER = {
'Content-Type': 'application/json'
}
API_METABASE_AUTHENTICATION_BODY = {
"username": os.getenv("METABASE_USERNAME"),
"password": os.getenv("METABASE_PASSWORD")
}
API_WP_AUTHENTICATION_HEADER = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
API_WP_POSTS_HEADER = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
API_WP_AUTHENTICATION_BODY = {
"username": os.getenv("WP_USERNAME"),
"password": os.getenv("WP_PASSWORD"),
"issueJWT": "true"
}
API_WP_VALIDATE_HEADER = {
'Content-Type': 'application/json'
}
API_WP_CREATEPOTS_HEADER = {
'Content-Type': 'application/x-www-form-urlencoded'
}
API_DATAVERSES_PUBLISHDATASET_HEADER = {
"X-Dataverse-key": os.getenv("DATAVERSE_TOKEN")
}
dateDiff = 14
consumer_key = os.getenv("CONSUMER_KEY")
consumer_secret = os.getenv("CONSUMER_SECRET")
access_token = os.getenv("ACCESS_TOKEN")
access_token_secret = os.getenv("ACCESS_TOKEN_SECRET")
```
README.md
```# METABASE-to-Twitter-updates
#### To check the log
- use 'docker exec -it [Container_name] /bin/bash' to access the docker container.
- use 'tail -f cron_log.log' to check the log's file
```
AdaTwitterBot.py
```#!/usr/bin/env python
import requests
import json
import Constants
import tweepy
from datetime import datetime
import pytz
newlyPublished = []
newlyUpdated = []
wpToken = ""
waitingToTweet = []
tweetCount = 0
newDS_Sorted = {}
updatedDS_Sorted = {}
def currentDateTime():
d_naive = datetime.now()
timezone = pytz.timezone("Australia/ACT")
d_aware = timezone.localize(d_naive).strftime('%Y-%m-%d %H:%M:%S')
return d_aware
def datasetHeader(session_token):
header = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Metabase-Session': session_token
}
return header
def fetchMetabaseSessionToken():
try:
r = requests.post(Constants.API_METABASE_AUTHENTICATION_ENDPOINT, data=json.dumps(Constants.API_METABASE_AUTHENTICATION_BODY), headers=Constants.API_METABASE_AUTHENTICATION_HEADER)
if r.status_code == 200:
token = (json.loads(r.text)["id"])
return token
except Exception as error:
print('ERROR', error)
def fetchDatasets():
print(currentDateTime() + " Ada Twitter Bot is fetching data from Metabase")
sessionToken = fetchMetabaseSessionToken()
# print(sessionToken, datasetHeader(sessionToken))
try:
r = requests.post(Constants.API_DATASETS_QUERY_NEWPUBLICATION, headers=datasetHeader(sessionToken))
if 200 <= r.status_code <= 299:
res = json.loads(r.text)
if len(res) > 0:
for i in res:
if i["owner_id"] in newDS_Sorted:
newDS_Sorted[i["owner_id"]].append(i)
else:
newDS_Sorted[i["owner_id"]] = [i]
print("keys: ", newDS_Sorted.keys(), len(newDS_Sorted.keys()))
# print("15490: ", len(newDS_Sorted[15409]))
# newlyPublished.append(i)
except Exception as error:
print('ERROR 56', error)
try:
r = requests.post(Constants.API_DATASETS_QUERY_NEWPUPDATE, headers=datasetHeader(sessionToken))
if 200 <= r.status_code <= 299:
res = json.loads(r.text)
if len(res) > 0:
for i in res:
if i["owner_id"] in updatedDS_Sorted:
updatedDS_Sorted[i["owner_id"]].append(i)
else:
updatedDS_Sorted[i["owner_id"]] = [i]
# newlyUpdated.append(i)
print("keys: ", updatedDS_Sorted.keys(), len(updatedDS_Sorted.keys()))
except Exception as error:
print('ERROR 67', error)
print(currentDateTime() + " Fetch done.")
def createTwitterAPI():
# authentication of consumer key and secret
auth = tweepy.OAuthHandler(Constants.consumer_key, Constants.consumer_secret)
# authentication of access token and secret
auth.set_access_token(Constants.access_token, Constants.access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
try:
api.verify_credentials()
except:
print("Error found in authentication")
return api
def updateTwitter(content, category):
global tweetCount, waitingToTweet
api = createTwitterAPI()
tweet = ""
if len(content) > 0:
if category == "26":
print(currentDateTime() + " Ada Twitter Bot is updating the status with Newly Published Dataset.")
elif category == "27":
print(currentDateTime() + " Ada Twitter Bot is updating the status with Recently Updated Dataset.")
for i in content.keys():
if len(content[i]) >= 5:
print("more than 5 datasets: ", i)
temp = tweetCompositionBulk(content[i], category)
waitingToTweet.append(temp)
else:
print("less than 5 datasets: ", i)
for ele in range(len(content[i])):
# print(content[i])
temp = tweetCompositionSimple(content[i][ele], ele, category)
waitingToTweet.append(temp)
# print(waitingToTweet)
# for i in range(len(content)):
# print(content[i])
# temp = tweetCompositionSimple(content[i], i, category)
# waitingToTweet.append(temp)
# if len(temp) > 400:
# tempT = temp[0:400] + "..."
# waitingToTweet.append(tempT)
# elif len(tweet) > 0 and len(tweet + tweetCompositionSimple(content[i], i, category)) > 400:
# waitingToTweet.append(tweet)
# tweet = tweetCompositionSimple(content[i], i, category)
# if i == len(content) - 1:
# waitingToTweet.append(tweet)
# else:
# tweet += tweetCompositionSimple(content[i], i, category)
# if i == len(content) - 1:
# waitingToTweet.append(tweet)
# update the status
if len(waitingToTweet) > 0:
waitingToTweet = waitingToTweet[0:10]
for i in waitingToTweet:
try:
api.update_status(status=i)
tweetCount += 1
except Exception as error:
print(error)
print(currentDateTime() + " " + str(tweetCount) + " tweets have been updated.")
tweetCount = 0
waitingToTweet = []
def tweetCompositionSimple(content, num, category):
# print(content)
title = content['dataset_title']
if len(title) > 280:
title = title[0:280] + " ..."
description = content['dataset_description']
url = content['URL']
doi = content['DOI']
if category == "27":
publicationDate = content['publication date']
version = str(content['versionnumber']) + "." + str(content['minorversionnumber'])
tweet = "Updated dataset on our Dataverse: " + "\r\n" \
+ "\r\n" \
+ title + " V" + version + " " +"\r\n" \
+ url + "\r\n"
elif category == "26":
publicationDate = content['publish date']
tweet = "New dataset on our Dataverse: " + "\r\n" \
+ "\r\n" \
+ title + "\r\n" \
+ url + "\r\n"
return tweet
def tweetCompositionBulk(content, category):
dvTitle = content[0]['owner_name']
if len(dvTitle) > 280:
dvTitle = dvTitle[0:280] + " ..."
# description = content['dataset_description']
owner_url = content[0]['owner_URL']
# doi = content['DOI']
if category == "27":
# publicationDate = content['publication date']
# version = str(content['versionnumber']) + "." + str(content['minorversionnumber'])
tweet = str(len(content)) + " datasets updated on our Dataverse: " + "\r\n" \
+ "\r\n" \
+ dvTitle + "\r\n" \
+ owner_url + "\r\n"
elif category == "26":
# publicationDate = content['publish date']
tweet = str(len(content)) + " new datasets published on our Dataverse: " + "\r\n" \
+ "\r\n" \
+ dvTitle + "\r\n" \
+ owner_url + "\r\n"
return tweet
def main():
fetchDatasets()
if len(newDS_Sorted.values()) > 0:
# print('skipped')
updateTwitter(newDS_Sorted, "26")
else:
print(currentDateTime() + " There is no Newly Published Dataset.")
if len(updatedDS_Sorted.values()) > 0:
updateTwitter(updatedDS_Sorted, "27")
else:
print(currentDateTime() + " There is no Recently Updated Dataset")
if __name__ == "__main__":
main()
```
css.py
```p = 'font-size:1.3em;padding-bottom:1%'
content = 'font-size:1.5em;padding-bottom:5%;padding-top:5%'
```
|
ADHIRAJ-iit/test
|
ADHIRAJ-iit/test
README.md
```<!doctype html>
<html>
<head>
<title>IIT KGP</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
}
#topbar {
margin: auto;
background-color: blue;
width: 1350px;
height: 80px;
color: white;
}
.start {
padding: 10px 0 0 10px;
}
.start p {
float: right;
}
.fir {
background-color: darkblue;
}
.sec {
color: darkblue;
background-color: white;
}
#menu {
color: white;
background-color: darkblue;
width: 1350px;
height: 160px;
}
.name {
border-top: 2px white solid;
border-bottom: 2px white solid;
padding: 2px;
}
.m {
font-size: 200%;
float: left;
}
.n {
float: right;
}
#t {
background-color: rgb(130, 211, 8);
color: white;
width: 1350px;
height: 80px;
}
.d {
float: right;
border: 2px black solid;
}
.w {
color: indigo
}
#s {
color: blue;
border: 2px gray solid;
}
</style>
</head>
<body>
<div id="topbar">
<div class="start">
| About IIT KGP |Old Website
<br />
<p class="lower">A-A=A+|<span class="fir">A</span> <span class="sec">A</span>|</p>
</div>
</div>
<div id="menu">
<br />
<span class="name">
INDIAN INSITITUTE OF TECHNOLOGY KHARAGPUR
</span>
<img src="images/logo.JPG" width=50px height=50px />
<br />
<br />
<br />
<br />
<span class="m">
MENU
</span>
<span class="n">
_
<br />
_
</span>
</div>
<img src="images/iit.JPG" width=1350px height=240px/>
<div id="t">
<span class="d">
___
<br />
___
<br />
___
</span>
</div>
<div id="f">
<hr />
<span class="w">
NEWS
</span>
<hr />
</div>
<div id="s">
Summer vacations preponed
<hr /> Mess continues in halls during lockdown
<hr /> Award in Asia conclave
<hr />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<hr />
<input type="submit" value="All News" />
</div>
</body>
</html>
```
|