branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/main | <repo_name>audrius-void/webdriverio-starter<file_sep>/test/specs/01-hello-world.spec.ts
describe("Online store home page", () => {
it("should have a right title", async () => {
await browser.url("/");
expect(browser).toHaveTitle("My Store");
});
});
<file_sep>/test/pages/sign-in-page.ts
class SignInPage {
get emailInput() {
return $("#email");
}
get passwordInput() {
return $("#passwd");
}
get signInButton() {
return $("#SubmitLogin");
}
async open() {
await browser.url("index.php?controller=authentication&back=my-account");
}
async enterEmail(email: string) {
await (await this.emailInput).setValue(email);
}
async enterPassword(password: string) {
await (await this.passwordInput).setValue(password);
}
async clickSignIn() {
await (await this.signInButton).click();
}
async signIn(email: string, password: string) {
await this.enterEmail(email);
await this.enterPassword(password);
await this.clickSignIn();
}
}
export default new SignInPage();
<file_sep>/test/specs/02-selectors.spec.ts
describe("Synthetic tests for demonstrating different selectors", () => {
before(async () => {
await browser.url("/");
});
it("should find 'Sign in' link in top navigation bar and check that its text is 'Sign in'", async () => {
const link = await $("=Sign in");
expect(await link.getText()).toBe("Sign in");
});
it("should find phone number in top navigation bar and check that it is 0123-456-789", async () => {
const spanEl = await $(".shop-phone");
const phone = await spanEl.$("strong");
//Alternative selectors:
//const phone = await $(".shop-phone strong");
//const phone = await $("strong=0123-456-789");
expect(await phone.getText()).toBe("0123-456-789");
});
it("should find last product and check that its price without discount is $20.50", async () => {
const products = await $$("#homefeatured li");
const price = await products[products.length - 1].$(".right-block .old-price");
//Alternative selector:
//const price = await $("#homefeatured li:last-child .right-block .old-price");
expect(await price.getText()).toBe("$20.50");
});
it("should find phone number in footer and check that it's value is (347) 466-7432", async () => {
const liElems = await $$("#block_contact_infos li");
const phone = await liElems[1].$("span");
//Alternative selectors:
//const phone = await $("#block_contact_infos .icon-phone+span");
//const phone = await $("#block_contact_infos li:nth-child(2) span");
expect(await phone.getText()).toBe("(347) 466-7432");
});
it("should find Newsletter subscription input field and check that it's value is 'Enter your e-mail'", async () => {
const input = await $("#newsletter-input");
expect(await input.getValue()).toBe("Enter your e-mail");
});
it("should find the first product and check that its title is 'Faded Short Sleeve T-Shirts'", async () => {
const products = await $$("#homefeatured li");
const title = await products[0].$(".product-name");
//Alternative selectors:
//const title = await $("=Faded Short Sleeve T-shirts");
//const title = await $("#homefeatured li:first-child a.product-name");
expect(await title.getText()).toBe("Faded Short Sleeve T-shirts");
});
});
<file_sep>/test/data/test-data.ts
class TestData {
emailAddress = "<EMAIL>";
password = "<PASSWORD>";
orderId = "12345";
message = "Hello, I have an issue";
}
export default new TestData();
<file_sep>/test/specs/08-add-to-cart-through-search.spec.ts
import SignInPage from "../pages/sign-in-page";
import TestData from "../data/test-data";
describe("Adding an item to cart", () => {
before(async () => {
});
it("should add an item to cart through search bar", async () => {
});
});
<file_sep>/test/pages/contact-us-page.ts
class ContactUsPage {
get subjectHeadingDropdown() {
return $("#id_contact");
}
get emailInput() {
return $("#email");
}
get orderIdInput() {
return $("#id_order");
}
get messageTextArea() {
return $("#message");
}
get sendButton() {
return $("#submitMessage");
}
get successMessage() {
return $(".alert-success");
}
async open() {
await browser.url("/index.php?controller=contact");
}
async selectSubjectHeading(subjectHeading: string) {
await (await this.subjectHeadingDropdown).selectByVisibleText(subjectHeading);
}
async enterEmail(email: string) {
await (await this.emailInput).setValue(email);
}
async enterOrderId(orderId: string) {
await (await this.orderIdInput).setValue(orderId);
}
async enterMessage(message: string) {
await (await this.messageTextArea).setValue(message);
}
async clickSend() {
await (await this.sendButton).click();
}
async isSuccessMessageDisplayed() {
return (await this.successMessage).isDisplayed();
}
}
export default new ContactUsPage();
<file_sep>/test/specs/06-waits.spec.ts
describe("Waits", () => {
it("should add the first product to cart", async () => {
await browser.url("/");
const product = await $("#homefeatured li:first-child");
await product.moveTo();
const quickViewLink = await $("#homefeatured li:first-child .quick-view");
await quickViewLink.waitForDisplayed();
await quickViewLink.click();
const iframe = await $(".fancybox-iframe");
await iframe.waitForDisplayed();
await browser.switchToFrame(iframe);
const addButton = await $("#add_to_cart button");
await addButton.waitForDisplayed();
await addButton.click();
await browser.switchToFrame(null);
const successMessage = await $(".layer_cart_product h2");
await successMessage.waitForDisplayed();
expect(await successMessage.getText()).toBe("Product successfully added to your shopping cart");
});
});
<file_sep>/test/specs/04-form-test.spec.ts
describe("Contact form test", () => {
before(async () => {
await browser.url("/index.php?controller=contact");
});
it("should send a customer service message", async () => {
const email = await $("#email");
await email.setValue("<EMAIL>");
const dropdown = await $("#id_contact");
await dropdown.selectByVisibleText("Customer service");
const orderRef = await $("#id_order");
await orderRef.setValue("12345");
const msg = await $("#message")
await msg.setValue("Hello, I got an issue");
const sendButton = await $("#submitMessage");
await sendButton.click();
const successMsg = await $(".alert-success");
expect(await successMsg.isDisplayed()).toBe(true);
});
});
<file_sep>/test/pages/my-account-page.ts
class MyAccountPage {
get title() {
return $("h1");
}
}
export default new MyAccountPage();
<file_sep>/test/specs/05-page-object-pattern.spec.ts
import ContactUsPage from "../pages/contact-us-page";
import TestData from "../data/test-data";
describe("Page object pattern", () => {
before(async () => {
await ContactUsPage.open();
});
it("should send a customer service message", async () => {
await ContactUsPage.selectSubjectHeading("Customer service");
await ContactUsPage.enterEmail(TestData.emailAddress);
await ContactUsPage.enterOrderId(TestData.orderId);
await ContactUsPage.enterMessage(TestData.message);
await ContactUsPage.clickSend();
expect(await ContactUsPage.successMessage).toBeDisplayed();
})
})
<file_sep>/test/specs/03-basic-actions.spec.ts
describe("Basic actions", () => {
it("should open 'Contact us' page", async () => {
await browser.url("/");
const link = await $("=Contact us");
await link.click();
const title = await $("h1");
expect(await title.getText()).toBe("CUSTOMER SERVICE - CONTACT US");
});
});
<file_sep>/test/specs/07-sign-in.spec.ts
import MyAccountPage from "../pages/my-account-page";
import SignInPage from "../pages/sign-in-page";
import TestData from "../data/test-data";
describe("Sign in page", () => {
before(async () => {
await SignInPage.open();
});
it("should sign in to online store", async () => {
await SignInPage.signIn(TestData.emailAddress, TestData.password);
expect(await MyAccountPage.title).toHaveText("MY ACCOUNT");
});
});
<file_sep>/test/specs/09-buying-an-item.spec.ts
import MyAccountPage from "../pages/my-account-page";
import SignInPage from "../pages/sign-in-page";
import TestData from "../data/test-data";
describe("Buying an item", () => {
beforeEach(async () => {
});
it("should buy items in shopping cart", async () => {
});
});
| d3a08ca6c9313747f3fa33434eb7a62e8d4aea82 | [
"TypeScript"
] | 13 | TypeScript | audrius-void/webdriverio-starter | e62fd1eadb8c4d39cf36af259bc5fa385f3f73e5 | b11c0085ff1a7414931f22fb75f6ddccd3208d3d |
refs/heads/master | <repo_name>AbbasAsadi/TicTacToe<file_sep>/app/src/main/java/com/example/tic_tac_toe/four_in_a_row/FourInRowFragment.java
package com.example.tic_tac_toe.four_in_a_row;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.example.tic_tac_toe.R;
import com.google.android.material.snackbar.Snackbar;
/**
* A simple {@link Fragment} subclass.
*/
public class FourInRowFragment extends Fragment {
private int redPlayerScore = 0;
private int yellowPlayerScore = 0;
private ImageView[][] cells;
private View boardView;
private Board board;
private ViewHolder viewHolder;
private static int numberOfRows = 6;
private static int numberOfColumns = 7;
private Snackbar snackbar;
public FourInRowFragment() {
// Required empty public constructor
}
private class ViewHolder {
public TextView redPlayerWinTextView;
public TextView yellowPlayerWinTextView;
public ImageView turnIndicatorImageView;
public Button resetButton;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_four_in_row, container, false);
board = new Board(numberOfRows, numberOfColumns);
viewHolder = new ViewHolder();
initUi(view);
buildCells();
boardView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_UP: {
int col = colAtX(motionEvent.getX());
if (col != -1)
drop(col);
}
}
return true;
}
});
viewHolder.redPlayerWinTextView.setText("0");
viewHolder.yellowPlayerWinTextView.setText("0");
viewHolder.turnIndicatorImageView.setImageResource(resourceForTurn());
viewHolder.resetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (snackbar != null){
snackbar.dismiss();
}
reset();
}
});
return view;
}
private void initUi(View view) {
boardView = view.findViewById(R.id.game_board_four_in_a_row);
viewHolder.redPlayerWinTextView = view.findViewById(R.id.score_red_player_four_in_a_row);
viewHolder.yellowPlayerWinTextView = view.findViewById(R.id.score_yellow_player_four_in_a_row);
viewHolder.turnIndicatorImageView = view.findViewById(R.id.turn_image_four_in_a_row);
viewHolder.resetButton = view.findViewById(R.id.reset_button_four_in_a_row);
}
private void buildCells() {
cells = new ImageView[numberOfRows][numberOfColumns];
for (int r = 0; r < numberOfRows; r++) {
ViewGroup row = (ViewGroup) ((ViewGroup) boardView).getChildAt(r);
row.setClipChildren(false);
for (int c = 0; c < numberOfColumns; c++) {
ImageView imageView = (ImageView) row.getChildAt(c);
imageView.setImageResource(android.R.color.transparent);
cells[r][c] = imageView;
}
}
}
private void drop(int col) {
if (board.winCondition)
return;
int row = board.lastAvailableRow(col);
if (row == -1) {
return;
}
final ImageView cell = cells[row][col];
float move = -(cell.getHeight() * row + cell.getHeight());
cell.setY(move);
cell.setImageResource(resourceForTurn());
TranslateAnimation anim = new TranslateAnimation(0, 0, 0, Math.abs(move));
anim.setDuration(200);
anim.setFillAfter(true);
cell.startAnimation(anim);
board.occupyCell(row, col);
if (board.checkForWin()) {
win();
} else if (board.noWinner()) {
showSnackBar(Color.LTGRAY , "No winner!!!");
} else {
changeTurn();
}
}
private void win() {
int color;
if (board.turn == Board.Turn.RED_PLAYER) {
color = Color.RED;
redPlayerScore++;
} else {
color = Color.YELLOW;
yellowPlayerScore++;
}
String temp = redPlayerScore + "";
viewHolder.redPlayerWinTextView.setText(temp);
temp = yellowPlayerScore + "";
viewHolder.yellowPlayerWinTextView.setText(temp);
if (board.turn == Board.Turn.RED_PLAYER) {
showSnackBar(color , "Red won!!!");
} else {
showSnackBar(color , "Yellow won");
}
}
private void changeTurn() {
board.toggleTurn();
viewHolder.turnIndicatorImageView.setImageResource(resourceForTurn());
}
private int colAtX(float x) {
float colWidth = cells[0][0].getWidth();
int col = (int) x / (int) colWidth;
if (col < 0 || col > 6)
return -1;
return col;
}
private int resourceForTurn() {
switch (board.turn) {
case RED_PLAYER:
return R.drawable.red_bead;
case YELLOW_PLAYER:
return R.drawable.yellow_bead;
}
return R.drawable.red_bead;
}
private void reset() {
board.reset();
viewHolder.turnIndicatorImageView.setImageResource(resourceForTurn());
for (int i = 0; i < numberOfRows; i++) {
for (int j = 0; j < numberOfColumns; j++) {
cells[i][j].setImageResource(android.R.color.transparent);
}
}
}
private void showSnackBar(int color, String message) {
snackbar = Snackbar.make(getActivity().findViewById(android.R.id.content), message, Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("reset", new View.OnClickListener() {
@Override
public void onClick(View view) {
reset();
}
});
snackbar.setActionTextColor(color);
snackbar.show();
}
}
<file_sep>/README.md
# tic_tac_toe
a tic toe toe and 4 in row android game


<file_sep>/app/src/main/java/com/example/tic_tac_toe/tic_tac_toe/TicTacToeFragment.java
package com.example.tic_tac_toe.tic_tac_toe;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.tic_tac_toe.R;
import com.google.android.material.snackbar.Snackbar;
/**
* A simple {@link Fragment} subclass.
*/
public class TicTacToeFragment extends Fragment implements View.OnClickListener {
private static final int YELLOW_CODE = 0;
private static final int RED_CODE = 1;
private static final int NOT_PLAYED = 2;
private static final int NO_WINNER = -1;
private int activePlayer = RED_CODE;
private int winner = NO_WINNER;
private int redPlayerScore = 0;
private int yellowPlayerScore = 0;
private LinearLayout bord;
private ImageView house1;
private ImageView house2;
private ImageView house3;
private ImageView house4;
private ImageView house5;
private ImageView house6;
private ImageView house7;
private ImageView house8;
private ImageView house9;
private ImageView turnImageView;
private Snackbar snackbar;
private Button resetButton;
private TextView scoreRedPlayerTextView;
private TextView scoreYellowPlayerTextView;
int[] gameState = {NOT_PLAYED, NOT_PLAYED, NOT_PLAYED,
NOT_PLAYED, NOT_PLAYED, NOT_PLAYED,
NOT_PLAYED, NOT_PLAYED, NOT_PLAYED};
int[][] winningPositions = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8},
{0, 3, 6}, {1, 4, 7}, {2, 5, 8},
{0, 4, 8}, {2, 4, 6}};
public TicTacToeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tic_tac_toe, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
initUi(view);
setOnClickUi();
super.onViewCreated(view, savedInstanceState);
}
private void initUi(@NonNull View view) {
house1 = view.findViewById(R.id.house1_tic_tac_toe);
house2 = view.findViewById(R.id.house2_tic_tac_toe);
house3 = view.findViewById(R.id.house3_tic_tac_toe);
house4 = view.findViewById(R.id.house4_tic_tac_toe);
house5 = view.findViewById(R.id.house5_tic_tac_toe);
house6 = view.findViewById(R.id.house6_tic_tac_toe);
house7 = view.findViewById(R.id.house7_tic_tac_toe);
house8 = view.findViewById(R.id.house8_tic_tac_toe);
house9 = view.findViewById(R.id.house9_tic_tac_toe);
turnImageView = view.findViewById(R.id.turn_image_tic_tac_toe);
scoreRedPlayerTextView = view.findViewById(R.id.score_red_player_tic_tac_toe);
scoreYellowPlayerTextView = view.findViewById(R.id.score_yellow_player_tic_tac_toe);
resetButton = view.findViewById(R.id.reset_button_tic_tac_toe);
bord = view.findViewById(R.id.bord_tic_tac_toe);
}
private void setOnClickUi() {
house1.setOnClickListener(this);
house2.setOnClickListener(this);
house3.setOnClickListener(this);
house4.setOnClickListener(this);
house5.setOnClickListener(this);
house6.setOnClickListener(this);
house7.setOnClickListener(this);
house8.setOnClickListener(this);
house9.setOnClickListener(this);
resetButton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.reset_button_tic_tac_toe) {
if (snackbar != null) {
snackbar.dismiss();
}
reset(null);
} else {
int tag = Integer.parseInt((String) view.getTag());
if (winner != NO_WINNER || gameState[tag] != NOT_PLAYED) {
return;
}
ImageView bead = (ImageView) view;
bead.setScaleX(0.2f);
bead.setScaleY(0.2f);
if (activePlayer == RED_CODE) {
bead.setImageResource(R.drawable.red_bead);
gameState[tag] = RED_CODE;
activePlayer = YELLOW_CODE;
turnImageView.setImageResource(R.drawable.yellow_bead);
} else if (activePlayer == YELLOW_CODE) {
bead.setImageResource(R.drawable.yellow_bead);
gameState[tag] = YELLOW_CODE;
activePlayer = RED_CODE;
turnImageView.setImageResource(R.drawable.red_bead);
}
bead.animate().scaleX(1f).scaleY(1f).setDuration(150);
//Check Winner
winnerMsg();
}
}
public void winnerMsg() {
winner = checkWinner();
if (winner != NO_WINNER || filled()) {
if (winner == NO_WINNER) {
showSnackBar(Color.GRAY, "No Winner");
} else if (winner == RED_CODE) {
redPlayerScore++;
showSnackBar(Color.RED, "Red Player won");
} else if (winner == YELLOW_CODE) {
yellowPlayerScore++;
showSnackBar(Color.YELLOW, "Yellow Player won");
}
scoreRedPlayerTextView.setText(redPlayerScore + "");
scoreYellowPlayerTextView.setText(yellowPlayerScore + "");
}
}
//no winner : -1
//red : RED_CODE
//yellow : YELLOW_CODE
public int checkWinner() {
for (int[] positions : winningPositions) {
if (gameState[positions[0]] == gameState[positions[1]] &&
gameState[positions[1]] == gameState[positions[2]] &&
gameState[positions[0]] != NOT_PLAYED) {
return gameState[positions[0]];
}
}
return NO_WINNER;
}
public Boolean filled() {
for (int i = 0; i < gameState.length; i++) {
if (gameState[i] == NOT_PLAYED) {
return false;
}
}
return true;
}
public void reset(View view) {
//active player
activePlayer = RED_CODE;
turnImageView.setImageResource(R.drawable.red_bead);
//winner
winner = NO_WINNER;
//gameState
for (int i = 0; i < gameState.length; i++) {
gameState[i] = NOT_PLAYED;
}
//playground
for (int i = 0; i < bord.getChildCount(); i++) {
LinearLayout row = (bord.getChildAt(i) instanceof LinearLayout) ?
(LinearLayout) bord.getChildAt(i) : null;
if (row == null) return;
for (int j = 0; j < row.getChildCount(); j++) {
ImageView iv = (row.getChildAt(j) instanceof ImageView) ?
(ImageView) row.getChildAt(j) : null;
if (iv == null) return;
iv.setImageResource(0);
}
}
}
private void showSnackBar(int color, String message) {
bord.setEnabled(false);
snackbar = Snackbar.make(getActivity().findViewById(android.R.id.content), message, Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("reset", new View.OnClickListener() {
@Override
public void onClick(View view) {
reset(null);
}
});
snackbar.setActionTextColor(color);
snackbar.show();
}
}
<file_sep>/app/src/main/java/com/example/tic_tac_toe/four_in_a_row/Board.java
package com.example.tic_tac_toe.four_in_a_row;
public class Board {
private int numberOfColumns;
private int numberOfRows;
private BoardLogic boardLogic;
public boolean winCondition;
public Cell[][] cells;
public enum Turn {
RED_PLAYER, YELLOW_PLAYER
}
public Turn turn;
public Board( int rows , int cols) {
numberOfRows = rows;
numberOfColumns = cols;
cells = new Cell[rows][cols];
reset();
}
public void reset() {
winCondition = false;
turn = Turn.RED_PLAYER;
for (int row = 0; row < numberOfRows; row++) {
for (int col = 0; col < numberOfColumns; col++) {
cells [row][col] = new Cell();
}
}
}
/* public Object clone() {
Board newBoard = new Board(this.numberOfRows, this.numberOfColumns );
for (int i = 0; i< this.numberOfRows; i++) {
newBoard.cells[i] = this.cells[i].clone();
}
return newBoard;
}*/
public int lastAvailableRow(int col) {
for (int row = numberOfRows - 1; row >= 0; row--) {
if (cells[row][col].empty) {
return row;
}
}
return -1;
}
public void occupyCell( int row , int col) {
cells[row][col].setPlayer(turn);
}
public void toggleTurn() {
if (turn == Turn.RED_PLAYER) {
turn = Turn.YELLOW_PLAYER;
} else {
turn = Turn.RED_PLAYER;
}
}
public boolean checkForWin() {
boardLogic = new BoardLogic(turn , cells , numberOfRows , numberOfColumns);
if(boardLogic.checkForWin()){
winCondition = true;
}
return boardLogic.checkForWin();
}
public boolean noWinner(){
for (int i = 0 ; i < numberOfColumns ; i++ ){
if (lastAvailableRow(i) != -1){
return false;
}
}
return true;
}
}
| d388a11012ad11a48c66f9a4690e3e5f3ad87f7a | [
"Markdown",
"Java"
] | 4 | Java | AbbasAsadi/TicTacToe | b15406193b1a3134c01faddc6d22e5188ee85808 | 553daccd21d762bb11714e033120944593754b52 |
refs/heads/master | <repo_name>franmakek/fran<file_sep>/public/config.js
System.config({
baseURL: "/",
defaultJSExtensions: true,
transpiler: "babel",
babelOptions: {
"optional": [
"runtime",
"optimisation.modules.system"
]
},
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
bundles: {
// "build.js": [
// "app/main.js",
// "app/pages/z270.hbs!github:davis/plugin-hbs@1.2.3.js",
// "github:components/handlebars.js@4.0.10/handlebars.runtime.js",
// "app/pages/z269.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z268.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z267.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z266.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z265.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z264.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z263.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z262.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z261.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z260.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z259.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z258.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z257.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z256.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z255.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z254.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z253.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z252.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z251.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z250.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z249.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z248.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z247.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z246.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z245.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z244.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z243.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z242.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z241.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z240.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z239.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z238.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z237.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z236.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z235.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z234.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z233.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z232.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z231.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z230.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z229.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z228.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z227.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z226.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z225.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z224.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z223.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z222.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z221.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z220.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z219.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z218.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z217.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z216.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z215.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z214.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z213.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z212.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z211.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z210.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z209.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z208.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z207.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z206.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z205.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z204.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z203.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z202.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z201.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z200.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z199.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z198.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z197.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z196.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z195.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z194.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z193.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z192.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z191.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z190.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z189.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z188.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z187.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z186.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z185.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z184.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z183.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z182.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z181.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z180.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z179.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z178.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z177.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z176.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z175.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z174.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z173.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z172.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z171.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z170.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z169.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z168.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z167.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z166.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z165.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z164.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z163.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z162.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z161.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z160.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z159.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z158.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z157.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z156.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z155.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z154.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z153.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z152.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z151.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z150q.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z150.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z149.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z148.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z147.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z146.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z145.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z144.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z143.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z142.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z141.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z140.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z139.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z138.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z137.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z136.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z135.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z134.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z133.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z132.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z131.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z130.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z129.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z128.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z127.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z126.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z125.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z124.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z123.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z122.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z121.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z120.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z119.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z118.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z117.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z116.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z115.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z114.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z113.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z112.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z111.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z110.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z109.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z108.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z107.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z106.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z105.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z104.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z103.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z102.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z101.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/cetiri.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/tri.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/bdva.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/dva.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/pet.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z90.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z89.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z88.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z87.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z86.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z85.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z84.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z83.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z82.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z81.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z100.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z99.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z98.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z97.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z96.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z95.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z94.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z93.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z92.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z91.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z80.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z79.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z78.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z77.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z76.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z75.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z74.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z73.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z72.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z71.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z70.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z69.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z68.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z67.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z66.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z65.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z64.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z63.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z62.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z61.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z60.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z59.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z58.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z57.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z56.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z55.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z54.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z53.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z52.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z51.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z50.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z49.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z48.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z47.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z46.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z45.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z44.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z43.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z42.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z41.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z40.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z39.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z38.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z37.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z36.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z35.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z34.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z33.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z32.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z31.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z30.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z29.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z28.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z27.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z26.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z25.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z24.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z23.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z22.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z21.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z20.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z19.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z18.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z16.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z17.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z15.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z14.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z13.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z12.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z11.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z10.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z9a.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z9.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z8.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z7.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z6.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z5.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z4.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z3.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z2.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z1.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a158.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a156.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a154.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a152.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a150.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a148.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a146.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a144.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a142.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a140.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a138.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a136.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a134.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a132.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a130.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a128.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a126.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a124.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a122.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a120.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a118.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a116.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a114.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a112.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a110.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a108.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a106.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a104.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a102.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a100.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a155.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a153.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a151.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a149.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a147.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a145.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a143.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a141.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a139.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a137.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a135.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a133.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a131.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a129.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a127.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a125.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a123.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a121.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a119.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a117.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a115.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a113.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a111.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a109.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a107.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a105.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a103.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a101.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a99.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a97.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a98.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a96.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a95.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a94.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a93.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a92.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a90.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a88.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a86.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a84.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a82.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a80.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a78.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a76.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a74.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a72.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a70.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a68.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a66.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a64.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a91.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a89.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a87.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a85.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a83.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a81.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a79.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a77.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a75.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a73.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a71.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a69.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a67.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a65.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a63.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a61.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a59.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a57.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a55.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a53.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a62.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a60.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a58.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a56.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a54.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a52.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a50.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a48.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a46.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a44.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a42.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a40.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a38.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a36.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a34.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/b32.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a32.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a51.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a49.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a45.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a47.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a43.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a41.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a39.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a35.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a37.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a33.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x40.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x38.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x36.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a31.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x34.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x32.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x30.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x28.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x26.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x24.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x22.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/b26.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/b24.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a30.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a28.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a26.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a24.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a22.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a20.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a29.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a27.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a25.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a23.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a21.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a19.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a17.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a18.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a16.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a15.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/b14.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a14.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a13.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/b6.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/bcetiri.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/b12.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a12.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a11.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/b10.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a10.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a9.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a7.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/ycetiri.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/ydva.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y20.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y18.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y16.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y14.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y12.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y6.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y10.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y8.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a8.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a6.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/jedan.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/prvi.hbs!github:davis/plugin-hbs@1.2.3.js",
// "npm:backbone@1.3.3.js",
// "npm:backbone@1.3.3/backbone.js",
// "github:jspm/nodelibs-process@0.1.2.js",
// "github:jspm/nodelibs-process@0.1.2/index.js",
// "npm:process@0.11.10.js",
// "npm:process@0.11.10/browser.js",
// "npm:jquery@3.2.1.js",
// "npm:jquery@3.2.1/dist/jquery.js",
// "npm:underscore@1.8.3.js",
// "npm:underscore@1.8.3/underscore.js",
// "app/Router.js",
// "npm:babel-runtime@5.8.38/helpers/class-call-check.js",
// "npm:babel-runtime@5.8.38/helpers/create-class.js",
// "npm:babel-runtime@5.8.38/core-js/object/define-property.js",
// "npm:core-js@1.2.7/library/fn/object/define-property.js",
// "npm:core-js@1.2.7/library/modules/$.js",
// "npm:babel-runtime@5.8.38/helpers/inherits.js",
// "npm:babel-runtime@5.8.38/core-js/object/set-prototype-of.js",
// "npm:core-js@1.2.7/library/fn/object/set-prototype-of.js",
// "npm:core-js@1.2.7/library/modules/$.core.js",
// "npm:core-js@1.2.7/library/modules/es6.object.set-prototype-of.js",
// "npm:core-js@1.2.7/library/modules/$.set-proto.js",
// "npm:core-js@1.2.7/library/modules/$.ctx.js",
// "npm:core-js@1.2.7/library/modules/$.a-function.js",
// "npm:core-js@1.2.7/library/modules/$.an-object.js",
// "npm:core-js@1.2.7/library/modules/$.is-object.js",
// "npm:core-js@1.2.7/library/modules/$.export.js",
// "npm:core-js@1.2.7/library/modules/$.global.js",
// "npm:babel-runtime@5.8.38/core-js/object/create.js",
// "npm:core-js@1.2.7/library/fn/object/create.js",
// "npm:babel-runtime@5.8.38/helpers/get.js",
// "npm:babel-runtime@5.8.38/core-js/object/get-own-property-descriptor.js",
// "npm:core-js@1.2.7/library/fn/object/get-own-property-descriptor.js",
// "npm:core-js@1.2.7/library/modules/es6.object.get-own-property-descriptor.js",
// "npm:core-js@1.2.7/library/modules/$.object-sap.js",
// "npm:core-js@1.2.7/library/modules/$.fails.js",
// "npm:core-js@1.2.7/library/modules/$.to-iobject.js",
// "npm:core-js@1.2.7/library/modules/$.defined.js",
// "npm:core-js@1.2.7/library/modules/$.iobject.js",
// "npm:core-js@1.2.7/library/modules/$.cof.js"
// ] // "build.js": [
// "app/main.js",
// "app/pages/z270.hbs!github:davis/plugin-hbs@1.2.3.js",
// "github:components/handlebars.js@4.0.10/handlebars.runtime.js",
// "app/pages/z269.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z268.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z267.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z266.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z265.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z264.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z263.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z262.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z261.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z260.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z259.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z258.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z257.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z256.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z255.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z254.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z253.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z252.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z251.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z250.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z249.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z248.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z247.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z246.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z245.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z244.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z243.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z242.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z241.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z240.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z239.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z238.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z237.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z236.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z235.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z234.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z233.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z232.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z231.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z230.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z229.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z228.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z227.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z226.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z225.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z224.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z223.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z222.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z221.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z220.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z219.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z218.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z217.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z216.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z215.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z214.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z213.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z212.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z211.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z210.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z209.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z208.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z207.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z206.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z205.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z204.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z203.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z202.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z201.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z200.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z199.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z198.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z197.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z196.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z195.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z194.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z193.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z192.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z191.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z190.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z189.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z188.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z187.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z186.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z185.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z184.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z183.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z182.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z181.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z180.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z179.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z178.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z177.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z176.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z175.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z174.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z173.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z172.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z171.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z170.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z169.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z168.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z167.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z166.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z165.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z164.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z163.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z162.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z161.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z160.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z159.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z158.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z157.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z156.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z155.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z154.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z153.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z152.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z151.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z150q.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z150.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z149.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z148.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z147.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z146.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z145.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z144.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z143.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z142.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z141.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z140.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z139.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z138.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z137.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z136.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z135.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z134.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z133.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z132.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z131.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z130.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z129.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z128.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z127.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z126.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z125.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z124.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z123.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z122.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z121.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z120.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z119.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z118.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z117.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z116.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z115.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z114.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z113.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z112.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z111.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z110.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z109.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z108.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z107.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z106.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z105.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z104.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z103.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z102.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z101.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/cetiri.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/tri.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/bdva.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/dva.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/pet.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z90.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z89.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z88.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z87.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z86.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z85.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z84.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z83.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z82.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z81.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z100.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z99.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z98.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z97.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z96.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z95.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z94.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z93.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z92.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z91.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z80.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z79.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z78.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z77.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z76.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z75.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z74.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z73.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z72.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z71.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z70.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z69.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z68.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z67.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z66.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z65.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z64.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z63.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z62.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z61.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z60.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z59.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z58.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z57.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z56.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z55.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z54.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z53.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z52.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z51.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z50.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z49.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z48.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z47.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z46.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z45.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z44.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z43.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z42.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z41.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z40.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z39.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z38.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z37.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z36.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z35.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z34.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z33.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z32.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z31.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z30.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z29.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z28.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z27.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z26.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z25.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z24.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z23.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z22.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z21.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z20.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z19.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z18.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z16.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z17.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z15.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z14.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z13.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z12.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z11.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z10.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z9a.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z9.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z8.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z7.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z6.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z5.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z4.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z3.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z2.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/z1.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a158.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a156.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a154.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a152.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a150.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a148.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a146.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a144.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a142.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a140.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a138.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a136.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a134.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a132.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a130.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a128.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a126.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a124.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a122.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a120.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a118.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a116.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a114.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a112.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a110.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a108.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a106.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a104.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a102.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a100.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a155.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a153.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a151.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a149.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a147.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a145.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a143.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a141.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a139.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a137.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a135.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a133.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a131.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a129.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a127.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a125.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a123.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a121.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a119.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a117.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a115.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a113.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a111.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a109.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a107.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a105.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a103.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a101.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a99.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a97.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a98.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a96.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a95.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a94.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a93.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a92.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a90.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a88.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a86.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a84.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a82.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a80.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a78.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a76.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a74.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a72.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a70.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a68.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a66.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a64.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a91.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a89.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a87.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a85.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a83.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a81.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a79.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a77.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a75.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a73.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a71.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a69.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a67.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a65.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a63.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a61.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a59.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a57.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a55.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a53.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a62.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a60.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a58.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a56.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a54.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a52.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a50.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a48.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a46.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a44.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a42.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a40.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a38.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a36.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a34.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/b32.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a32.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a51.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a49.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a45.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a47.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a43.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a41.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a39.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a35.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a37.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a33.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x40.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x38.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x36.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a31.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x34.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x32.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x30.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x28.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x26.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x24.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/x22.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/b26.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/b24.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a30.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a28.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a26.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a24.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a22.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a20.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a29.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a27.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a25.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a23.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a21.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a19.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a17.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a18.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a16.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a15.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/b14.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a14.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a13.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/b6.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/bcetiri.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/b12.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a12.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a11.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/b10.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a10.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a9.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a7.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/ycetiri.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/ydva.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y20.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y18.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y16.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y14.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y12.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y6.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y10.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/y8.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a8.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/a6.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/jedan.hbs!github:davis/plugin-hbs@1.2.3.js",
// "app/pages/prvi.hbs!github:davis/plugin-hbs@1.2.3.js",
// "npm:backbone@1.3.3.js",
// "npm:backbone@1.3.3/backbone.js",
// "github:jspm/nodelibs-process@0.1.2.js",
// "github:jspm/nodelibs-process@0.1.2/index.js",
// "npm:process@0.11.10.js",
// "npm:process@0.11.10/browser.js",
// "npm:jquery@3.2.1.js",
// "npm:jquery@3.2.1/dist/jquery.js",
// "npm:underscore@1.8.3.js",
// "npm:underscore@1.8.3/underscore.js",
// "app/Router.js",
// "npm:babel-runtime@5.8.38/helpers/class-call-check.js",
// "npm:babel-runtime@5.8.38/helpers/create-class.js",
// "npm:babel-runtime@5.8.38/core-js/object/define-property.js",
// "npm:core-js@1.2.7/library/fn/object/define-property.js",
// "npm:core-js@1.2.7/library/modules/$.js",
// "npm:babel-runtime@5.8.38/helpers/inherits.js",
// "npm:babel-runtime@5.8.38/core-js/object/set-prototype-of.js",
// "npm:core-js@1.2.7/library/fn/object/set-prototype-of.js",
// "npm:core-js@1.2.7/library/modules/$.core.js",
// "npm:core-js@1.2.7/library/modules/es6.object.set-prototype-of.js",
// "npm:core-js@1.2.7/library/modules/$.set-proto.js",
// "npm:core-js@1.2.7/library/modules/$.ctx.js",
// "npm:core-js@1.2.7/library/modules/$.a-function.js",
// "npm:core-js@1.2.7/library/modules/$.an-object.js",
// "npm:core-js@1.2.7/library/modules/$.is-object.js",
// "npm:core-js@1.2.7/library/modules/$.export.js",
// "npm:core-js@1.2.7/library/modules/$.global.js",
// "npm:babel-runtime@5.8.38/core-js/object/create.js",
// "npm:core-js@1.2.7/library/fn/object/create.js",
// "npm:babel-runtime@5.8.38/helpers/get.js",
// "npm:babel-runtime@5.8.38/core-js/object/get-own-property-descriptor.js",
// "npm:core-js@1.2.7/library/fn/object/get-own-property-descriptor.js",
// "npm:core-js@1.2.7/library/modules/es6.object.get-own-property-descriptor.js",
// "npm:core-js@1.2.7/library/modules/$.object-sap.js",
// "npm:core-js@1.2.7/library/modules/$.fails.js",
// "npm:core-js@1.2.7/library/modules/$.to-iobject.js",
// "npm:core-js@1.2.7/library/modules/$.defined.js",
// "npm:core-js@1.2.7/library/modules/$.iobject.js",
// "npm:core-js@1.2.7/library/modules/$.cof.js"
// ]
},
map: {
"babel": "npm:babel-core@5.8.38",
"babel-runtime": "npm:babel-runtime@5.8.38",
"backbone": "npm:backbone@1.3.3",
"core-js": "npm:core-js@1.2.7",
"handlebars": "github:components/handlebars.js@4.0.10",
"hbs": "github:davis/plugin-hbs@1.2.3",
"jquery": "npm:jquery@3.2.1",
"underscore": "npm:underscore@1.8.3",
"github:davis/plugin-hbs@1.2.3": {
"handlebars": "github:components/handlebars.js@4.0.10"
},
"github:jspm/nodelibs-assert@0.1.0": {
"assert": "npm:assert@1.4.1"
},
"github:jspm/nodelibs-buffer@0.1.1": {
"buffer": "npm:buffer@5.0.6"
},
"github:jspm/nodelibs-path@0.1.0": {
"path-browserify": "npm:path-browserify@0.0.0"
},
"github:jspm/nodelibs-process@0.1.2": {
"process": "npm:process@0.11.10"
},
"github:jspm/nodelibs-util@0.1.0": {
"util": "npm:util@0.10.3"
},
"github:jspm/nodelibs-vm@0.1.0": {
"vm-browserify": "npm:vm-browserify@0.0.4"
},
"npm:assert@1.4.1": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"util": "npm:util@0.10.3"
},
"npm:babel-runtime@5.8.38": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:backbone@1.3.3": {
"process": "github:jspm/nodelibs-process@0.1.2",
"underscore": "npm:underscore@1.8.3"
},
"npm:buffer@5.0.6": {
"base64-js": "npm:base64-js@1.2.1",
"ieee754": "npm:ieee754@1.1.8"
},
"npm:core-js@1.2.7": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.2"
},
"npm:inherits@2.0.1": {
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:path-browserify@0.0.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:process@0.11.10": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"vm": "github:jspm/nodelibs-vm@0.1.0"
},
"npm:util@0.10.3": {
"inherits": "npm:inherits@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:vm-browserify@0.0.4": {
"indexof": "npm:indexof@0.0.1"
}
}
});
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('{any?}', function ($any = null) {
return view('base');
})->where('any', '.*');
//Route::get('dva', function () {
// return view('pages.dva');
//});
//
//Route::get('/tri', function () {
// return view('pages.tri');
//});
//
//Route::get('/cetri', function () {
// return view('pages.cetri');
//});
//
//Route::get('/cetri', function () {
// return view('pages.cetri');
//});
//
//Route::get('/cetri', function () {
// return view('pages.cetri');
//});
//
//Route::get('/pet', function () {
// return view('pages.pet');
//});
//
//Route::get('/sest', function () {
// return view('pages.sest');
//});
//
//Route::get('/sedam', function () {
// return view('pages.sedam');
//});
//
//Route::get('/osam', function () {
// return view('pages.osam');
//});
//
//Route::get('/devet', function () {
// return view('pages.devet');
//});
//
//Route::get('/deset', function () {
// return view('pages.deset');
//});
//
//Route::get('/jedanaest', function () {
// return view('pages.jedanaest');
//});
//
//Route::get('/dvanaest', function () {
// return view('pages.dvanaest');
//});
//Route::get('/trinaest', function () {
// return view('pages.trinaest');
//});
//
//Route::get('/cetrnaest', function () {
// return view('pages.cetrnaest');
//});
//
//Route::get('/1', function () {
// return view('pages.1');
//});
//Route::get('/2', function () {
// return view('pages.2');
//});
//
//Route::get('/3', function () {
// return view('pages.3');
//});
//
//Route::get('/4', function () {
// return view('pages.4');
//});
//
//Route::get('/5', function () {
// return view('pages.5');
//});
//
//Route::get('/6', function () {
// return view('pages.6');
//});
//
//Route::get('/7', function () {
// return view('pages.7');
//});
//Route::get('/8', function () {
// return view('pages.8');
//});
//
//Route::get('/petnaest', function () {
// return view('pages.petnaest');
//});
//
//Route::get('/šesnaest', function () {
// return view('pages.šesnaest');
//});
//
//
//Route::get('/sedamnaest', function () {
// return view('pages.sedamnaest');
//});
//Route::get('/osamnaest', function () {
// return view('pages.osamnaest');
//});
//
//Route::get('/devetnaest', function () {
// return view('pages.devetnaest');
//});
//
//Route::get('/9', function () {
// return view('pages.9');
//});
//Route::get('/10', function () {
// return view('pages.10');
//});
//Route::get('/devetnaest', function () {
// return view('pages.devetnaest');
//});
//
//Route::get('/dvadeset', function () {
// return view('pages.dvadeset');
//});
//
//Route::get('/11', function () {
// return view('pages.11');
//});
//Route::get('/12', function () {
// return view('pages.12');
//});
//Route::get('/dvadesetjedan', function () {
// return view('pages.dvadesetjedan');
//});
//Route::get('/dvadesetdva', function () {
// return view('pages.dvadesetdva');
//});
//
//Route::get('/dvadesettri', function () {
// return view('pages.dvadesettri');
//});
//
//Route::get('/dvadesetcetiri', function () {
// return view('pages.dvadesetcetiri');
//});
//Route::get('/dvadesetpet', function () {
// return view('pages.dvadesetpet');
//});
//Route::get('/13', function () {
// return view('pages.13');
//});
//
//Route::get('/dvadesetsest', function () {
// return view('pages.dvadesetsest');
//});
//
//Route::get('/dvadesetsedam', function () {
// return view('pages.dvadesetsedam');
//});
//Route::get('/15', function () {
// return view('pages.15');
//});
//Route::get('/16', function () {
// return view('pages.16');
//
//});Route::get('/17', function () {
// return view('pages.17');
//
//});Route::get('/18', function () {
// return view('pages.18');
//});
//
//Route::get('/dvadesetosam', function () {
// return view('pages.dvadesetosam');
//});
//
//Route::get('/dvadesetdevet', function () {
// return view('pages.dvadesetdevet');
//});
//Route::get('/trideset', function () {
// return view('pages.trideset');
//});
//Route::get('/tridesetjedan', function () {
// return view('pages.tridesetjedan');
//});
//Route::get('/tridesetdva', function () {
// return view('pages.tridesetdva');
//});
//Route::get('/tridesettri', function () {
// return view('pages.tridesettri');
//});
//Route::get('/tridesetcetiri', function () {
// return view('pages.tridesetcetiri');
//});
//Route::get('/tridesetpet', function () {
// return view('pages.tridesetpet');
//});
//Route::get('/tridesetsest', function () {
// return view('pages.tridesetsest');
//});
//Route::get('/tridesetsedam', function () {
// return view('pages.tridesetsedam');
//});
//Route::get('/tridesetosam', function () {
// return view('pages.tridesetosam');
//});
//Route::get('/tridesetdevet', function () {
// return view('pages.tridesetdevet');
//});
//Route::get('/cetrdeset', function () {
// return view('pages.cetrdetsest');
//});
//Route::get('/cetrdesetjedan', function () {
// return view('pages.cetrdesetjedan');
//});
//Route::get('/cetrdesetdva', function () {
// return view('pages.cetrdesetdva');
//});
//Route::get('/cetrdesettri', function () {
// return view('pages.cetrdesettri');
//});
//Route::get('/cetrdesetcetiri', function () {
// return view('pages.cetrdesetcetiri');
//});
//Route::get('/cetrdesetpet', function () {
// return view('pages.cetrdesetpet');
//});
//Route::get('/cetrdesetsest', function () {
// return view('pages.cetrdesetsest');
//});
//Route::get('/cetrdesetsedam', function () {
// return view('pages.cetrdesetsedam');
//});
//Route::get('/19', function () {
// return view('pages.19');
//});
//Route::get('/20', function () {
// return view('pages.20');
//});
//Route::get('/cetrdesetosam', function () {
// return view('pages.cetrdesetosam');
// });
//Route::get('/cetrdesetdevet', function () {
// return view('pages.cetrdesetdevet');
// });
//Route::get('/21', function () {
// return view('pages.21');
//});
//Route::get('/22', function () {
// return view('pages.22');
//});
//
//Route::get('/pedeset', function () {
// return view('pages.pedeset');
//});
//Route::get('/pedesetjedan', function () {
// return view('pages.pedesetjedan');
//});
//Route::get('/23', function () {
// return view('pages.23');
//});
//
//
//Route::get('/24', function () {
// return view('pages.24');
//});
//
//Route::get('/pedesetdva', function () {
// return view('pages.pedesetdva');
//});
//Route::get('/pedesettri', function () {
// return view('pages.pedesettri');
//});
//Route::get('/25', function () {
// return view('pages.25');
//});
//Route::get('/26', function () {
// return view('pages.26');
//});
//
//Route::get('/pedesetcetiri', function () {
// return view('pages.pedesetcetiri');
//});
//Route::get('/pedesetpet', function () {
// return view('pages.pedesetpet');
//});
//Route::get('/27', function () {
// return view('pages.27');
//});
//Route::get('/28', function () {
// return view('pages.28');
//});
//Route::get('/29', function () {
// return view('pages.29');
//});
//
//Route::get('/30', function () {
// return view('pages.30');
//});
//Route::get('/31', function () {
// return view('pages.31');
//});
//Route::get('/32', function () {
// return view('pages.32');
//});
//Route::get('/33', function () {
// return view('pages.33');
//});
//Route::get('/34', function () {
// return view('pages.34');
//});
//Route::get('/35', function () {
// return view('pages.35');
//});
//
//Route::get('/36', function () {
// return view('pages.36');
//});
//Route::get('/37', function () {
// return view('pages.37');
//});
//Route::get('/38', function () {
// return view('pages.38');
//});
//Route::get('/39', function () {
// return view('pages.39');
// });
//Route::get('/40', function () {
// return view('pages.40');
// });
//Route::get('/40', function () {
// return view('pages.40');
// });
//Route::get('/41', function () {
// return view('pages.41');
// });
//Route::get('/41', function () {
// return view('pages.41');
// });
//Route::get('/42', function () {
// return view('pages.42');
// });
//Route::get('/43', function () {
// return view('pages.43');
// });
//
//Route::get('/44', function () {
// return view('pages.44');
// });
//Route::get('/45', function () {
// return view('pages.45');
// });
//Route::get('/46', function () {
// return view('pages.46');
// });
//Route::get('/47', function () {
// return view('pages.47');
// });
//Route::get('/48', function () {
// return view('pages.48');
// });
//Route::get('/49', function () {
// return view('pages.49');
// });
//Route::get('/50', function () {
// return view('pages.50');
// });
//Route::get('/51', function () {
// return view('pages.51');
// });
//Route::get('/52', function () {
// return view('pages.52');
// });
//Route::get('/53', function () {
// return view('pages.53');
// });
//Route::get('/54', function () {
// return view('pages.54');
// });
//Route::get('/55', function () {
// return view('pages.55');
// });
//Route::get('/pedesetsest', function () {
// return view('pages.pedesetsest');
//});
//Route::get('/pedesetsedam', function () {
// return view('pages.pedesetsedam');
//});
//Route::get('/pedesetosam', function () {
// return view('pages.pedesetosam');
//});
//Route::get('/pedesetdevet', function () {
// return view('pages.pedesetdevet');
//});
//Route::get('/sesdeset', function () {
// return view('pages.sesdeset');
//});
//Route::get('/sesdesetjedan', function () {
// return view('pages.sesdesetjedan');
//});
//Route::get('/sesdesetdva', function () {
// return view('pages.sesdesetdva');
//});
//Route::get('/sesdesettri', function () {
// return view('pages.sesdesettri');
//});
//Route::get('/sesdesetcetiri', function () {
// return view('pages.sesdesetcetiri');
//});
//Route::get('/sesdesetpet', function () {
// return view('pages.sesdesetpet');
//});
//Route::get('/sesdesetsest', function () {
// return view('pages.sesdesetsest');
//});
//Route::get('/sesdesetsedam', function () {
// return view('pages.sesdesetsedam');
//});
//Route::get('/sesdesetosam', function () {
// return view('pages.sesdesetosam');
//});
//Route::get('/sesdesetdevet', function () {
// return view('pages.sesdesetdevet');
//});
//Route::get('/sedamdeset', function () {
// return view('pages.sedamdeset');
//});
//Route::get('/sedamdesetdva', function () {
// return view('pages.sedamdesetdva');
//});
//Route::get('/sedamdesetjedan', function () {
// return view('pages.sedamdesetdva');
//});
//Route::get('/sedamdesettri', function () {
// return view('pages.sedamdesettri');
//});
//Route::get('/sedamdesetcetiri', function () {
// return view('pages.sedamdesetcetiri');
//});
//Route::get('/sedamdesetpet', function () {
// return view('pages.sedamdesetpet');
//});
//Route::get('/sedamdesetsest', function () {
// return view('pages.sedamdesetsest');
//});
//Route::get('/sedamdesetsedam', function () {
// return view('pages.sedamdesetsedam');
//});
//Route::get('/sedamdesetosam', function () {
// return view('pages.sedamdesetosam');
//});
//Route::get('/sedamdesetdevet', function () {
// return view('pages.sedamdesetdevet');
//});
//Route::get('/osamdeset', function () {
// return view('pages.osamdeset');
//});
//Route::get('/osamdesetjedan', function () {
// return view('pages.osamdesetjedan');
//});
//Route::get('/osamdesetdva', function () {
// return view('pages.osamdesetdva');
//});
//Route::get('/osamdesettri', function () {
// return view('pages.osamdesettri');
//});
//Route::get('/osamdesetcetiri', function () {
// return view('pages.osamdesetcetiri');
//});
//Route::get('/osamdesetpet', function () {
// return view('pages.osamdesetpet');
//});
//Route::get('/osamdesetsest', function () {
// return view('pages.osamdesetsest');
//});
//Route::get('/osamdesetsedam', function () {
// return view('pages.osamdesetsedam');
//});
//Route::get('/osamdesetosam', function () {
// return view('pages.osamdesetosam');
//});<file_sep>/public/js/custom.js
var gifTime = 10000;
var vc1 = 8800;
var vc2 = 3400;
var vc3 = 7900;
var vc4 = 9600;
var vc5 = 7200;
var vc6 = 4100;
var vc7 = 11200;
var vc8 = 4800;
var vc9 = 2300;
var vc10 = 1300;
var vc11 = 3600;
var vc12 = 4600;
var vc13 = 5500;
var vc14 = 5100;
var vc15 = 12500;
var vc16 = 5800;
var vc17 = 12500;
var vc18 = 5800;
var vc19 = 4100;
var vc20 = 4000;
var vc21 = 3000;
var vm1 = 5580;
var vm2 = 10500;
var vm3 = 2800;
var vm4 = 7500;
var vm5 = 6100;
var vm6= 6500;
var vm7 = 12800;
var vm8 = 8500;
var vm9 = 3700;
var vm10 = 8700;
var vm11 = 7000;
var vm12 = 5000;
var vm13 = 9000;
var vm14 = 12000;
var vm15 = 5000;
function changeWallImage(imageType){
console.log('change image')
/*tu promjenit vrijeme kad se pokaze slika*/
var time = 3500;
var image;
if(imageType == undefined)
{
imageType = localStorage.getItem('clicked-img');
}
var horizontalImages = [
'/images/wall/h1.png',
'/images/wall/h2.png'
];
var verticalImages = [
'/images/wall/v1.png',
'/images/wall/v2.png'
];
/*tu dodat slike*/
var allImages = [
'/images/wall/h1.png',
'/images/wall/h2.png',
'/images/wall/v1.png',
'/images/wall/v2.png'
];
if(imageType == "vertical")
{
image = verticalImages[Math.floor(Math.random()*verticalImages.length)];
}
else if(imageType == "horizontal")
{
image = horizontalImages[Math.floor(Math.random()*horizontalImages.length)];
}
else
{
image = horizontalImages[Math.floor(Math.random()*horizontalImages.length)];
}
setTimeout(function(){
$('.wall-image').fadeOut(500)
}, time - 1500);
setTimeout(function(){
$('.wall-image').attr("src", image).fadeIn(500);
}, time);
}
var lastClickedImg = localStorage.getItem('clicked-img');
if(lastClickedImg === null)
{
changeWallImage('horizontal');
localStorage.setItem('clicked-img', 'horizontal');
}
else if(lastClickedImg === "horizontal")
{
changeWallImage('vertical');
localStorage.setItem('clicked-img', 'vertical');
}
else{
changeWallImage('horizontal');
localStorage.setItem('clicked-img', 'horizontal');
}
| e504211bcd7546f21a54553428243ff277ba0afa | [
"JavaScript",
"PHP"
] | 3 | JavaScript | franmakek/fran | d054a0f91ba0a15c5cc987d7536270c4d8826c2a | d93d08138e34bcd470189508285f21499c6213dc |
refs/heads/master | <repo_name>evasuryani/CODER-PWD<file_sep>/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
// $data = [
// "nama_lomba" => "Web Design",
// "id_bidang" => 1,
// "tgl_perlombaan" => "2016/04/18",
// "deskripsi" => "Test 123",
// "link" => "google.com",
// "poster" => "jdks"
// ];
// DB::table('perlombaan')->insert($data);
$data = [
"nama_bidang" => "Atletik"
];
DB::table('bidang')->insert($data);
}
}
<file_sep>/app/Http/Controllers/PerlombaanController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Perlombaan;
use Illuminate\Http\Request;
use Session;
use Uploader;
class PerlombaanController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\View\View
*/
public function index(Request $request)
{
return view('perlombaan.index');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function store(Request $request)
{
$validate=[
'nama_lomba' => 'required',
'id_bidang' => 'required|exists:bidang',
'tgl_perlombaan' => 'required',
'deskripsi' => 'required',
'link' => 'required',
'poster' => 'required|mimes:jpeg,png,jpg|max:2048',
];
$this->validate($request,$validate);
$input = $request->all();
if ($request->hasFile('poster') && $request->file('poster')->isValid()) {
$filename = $input['nama_lomba']. "." . $request->file('poster')->getClientOriginalExtension();
$request->file('poster')->storeAs('', $filename);
$input['poster'] = $filename;
}
Perlombaan::create($input);
return redirect('/home')->with('success','Item Created Successfully');
}
/**
* Display the specified resource.
*
* @param int $id
*
* @return \Illuminate\View\View
*/
public function show($id)
{
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
*
* @return \Illuminate\View\View
*/
public function edit($id)
{
$data['perlombaan'] = \App\Perlombaan::where('id_lomba', $id)->first();
return view('perlombaan.index')->with($data);
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function update($id, Request $request)
{
$validate=[
'nama_lomba' => 'required',
'id_bidang' => 'required|exists:bidang',
'tgl_perlombaan' => 'required',
'deskripsi' => 'required',
'link' => 'required',
];
$this->validate($request,$validate);
$input = $request->all();
$perlombaan = \App\Perlombaan::where('id_lomba', $id)->first();
if ($request->hasFile('poster') && $request->file('poster')->isValid()) {
$filename = $input['nama_lomba']. "." . $request->file('poster')->getClientOriginalExtension();
$request->file('poster')->storeAs('', $filename);
$input['poster'] = $filename;
}
$perlombaan->update($input);
return redirect('/home')->with('success','Item Edited Successfully');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function destroy($id)
{
$perlombaan = \App\Perlombaan::where('id_lomba', $id)->first();
$perlombaan->delete();
Session::flash('flash_message', 'Perlombaan deleted!');
return redirect('home');
}
}
<file_sep>/app/Perlombaan.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Perlombaan extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'perlombaan';
/**
* The database primary key value.
*
* @var string
*/
protected $primaryKey = 'id_lomba';
/**
* Attributes that should be mass-assignable.
*
* @var array
*/
protected $fillable = ['id_lomba', 'id','nama_lomba','id_bidang','tgl_perlombaan','deskripsi','link','poster'];
public function bidang_lomba(){
return $this->hasOne('\App\Bidang', 'id_bidang', 'id_bidang');
}
public function user(){
return $this->hasOne('\App\User', 'id', 'id');
}
}
<file_sep>/app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data['data'] = \App\Perlombaan::all();
return view('home')->with($data);
}
// public function index(Request $request)
// {
// $perlombaan['data'] = \App\Perlombaan::where('id', $id)->get();
// return view('home')->with($perlombaan);
// }
public function show($id)
{
$perlombaan['data'] = \App\Perlombaan::where('id', $id)->get();
return view('home')->with($perlombaan);
}
public function destroy($id)
{
$perlombaan = \App\Perlombaan::where('id_lomba', $id)->first();
$perlombaan->delete();
Session::flash('flash_message', 'Perlombaan deleted!');
return redirect('home');
}
// public function edit($id)
// {
// $data['result'] = \App\Perlombaan::where('id_lomba', $id)->first();
//
// return view('perlombaan.index')->with($data);
// }
}
<file_sep>/database/migrations/2017_03_29_132108_create_perlombaans_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreatePerlombaansTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('perlombaan', function(Blueprint $table) {
$table->increments('id_lomba');
$table->string('nama_lomba', 150);
$table->integer('id');
$table->integer('id_bidang');
$table->date('tgl_perlombaan');
$table->text('deskripsi');
$table->string('link',200);
$table->string('poster',150);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('perlombaan');
}
}
| c73b6b121d99c30144647858e3e6f634ed045fdf | [
"PHP"
] | 5 | PHP | evasuryani/CODER-PWD | f2a7676722557a81591d4549a73434bb80039fab | cf0daabe929ad6db83b164bb6f4162be7f1659ab |
refs/heads/master | <file_sep># Generated by Django 2.2.7 on 2019-11-21 00:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('adopt', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='pet',
name='name',
field=models.CharField(help_text='Name of Pet', max_length=100),
),
migrations.AlterField(
model_name='pet',
name='species',
field=models.CharField(help_text='Species of animal', max_length=50),
),
]
<file_sep>from django.core.management.base import BaseCommand
from adopt.models import Pet
import csv
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('csv_file')
def handle(self,*args,**options):
with open(options['csv_file']) as fp:
reader = csv.DictReader(fp)
data = list(reader)
for item in data:
p = Pet(
name = item["name"],
species = item["species"],
birth_date = item["birth_date"],
sex = item["sex"],
)
p.save()
<file_sep>from django.db import models
from django.utils.translation import gettext as _
#gettext:can write strings at any language we want
#can run a command to search all the strings
#for translators to translate the strings.
#So we can have ea multilingual application easily.
# Create your models here.
class Pet(models.Model):
species = models.CharField(
help_text=_('Species of animal'),
max_length = 50,
)
name = models.CharField(
help_text=_('Name of Pet'),
max_length = 100,
)
birth_date = models.DateField(
help_text=_('Birth Date'),
)
MALE = 'male'
FEMALE = 'female'
OTHER = 'other'
SEX_CHOICES = (
(MALE, 'Male'),
(FEMALE,'Female'),
(OTHER,'Other'),
)
sex = models.CharField(
help_text=_('Sex of pet'),
max_length=16, # no need of that large
choices = SEX_CHOICES,
default=OTHER, # default choice
)
def __str__(self):
return self.name
<file_sep>from django.contrib import admin
# Register your models here.
from .models import Pet
admin.site.register(Pet) # tell django to create forms on ui.
<file_sep>from django.http import HttpResponse
from django.shortcuts import render
import random
from .models import Pet
from .forms import PetForm
# Create your views here.
#def all_pets(request):
# text = ''
# pets = Pet.objects.all()
# for pet in pets:
# text += pet.name + ','
# return HttpResponse(text)
def all_pets(request):
pets = Pet.objects.all()
context = {
'pets':pets,
}
return render(request,'adopt/all.html',context)
def pet_details(request,pet_id):
pet = Pet.objects.get(id=pet_id)
return HttpResponse(pet.name)
def add_pet(request):
if request.method == 'POST':
#check data with form
form = PetForm(request.POST)
if form.is_valid():
form.save()
return redirect(f'/adopt/list')
else:
form = PetForm()
context = {
'form':form,
}
return render(request,'adopt/edit.html',context)
def edit_pet(request,pet_id):
pet = Pet.objects.get(id=pet_id)
if request.method == 'POST':
#check data with form
form = PetForm(request.POST, instance=pet)
if form.is_valid():
form.save()
return redirect(f'/adopt/{pet_id}')
else:
form = PetForm(instance=pet)
#build a new empty form
context = {
'form':form,
}
return render(request,'adopt/edit.html',context)
| 46ae6bfef9d2478872a962f5514ad963e9729d28 | [
"Python"
] | 5 | Python | cicyhqy/toolsproject | ae48ed7096aef57f43533e4b9460c2d1dcf4e74a | ab84c502112093067867c490440b53f0ac8d160f |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
namespace Exam
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class PhotoGallery : Page
{
public PhotoGallery()
{
this.InitializeComponent();
}
private void btn_back(object sender, RoutedEventArgs e)
{
var rootFrame = Window.Current.Content as Frame;
rootFrame.Navigate(typeof(MainPage));
}
private async void btn_getPhoto(object sender, RoutedEventArgs e)
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
// Application now has read/write access to the picked file
Debug.WriteLine(file.Path);
Debug.WriteLine(file.DateCreated);
this.name.Text = file.DisplayName;
this.file_path.Text = file.Path;
this.Date.Text = file.DateCreated.ToString();
}
else
{
Debug.WriteLine("fail");
}
}
}
}
| fe840ebc79347092d9c5a686b348f6399984e8dd | [
"C#"
] | 1 | C# | QuangPoppy163/EXAM_EAP_2 | 6f545d0de511bdd5b8f131351ea687e96b30d6b5 | 49131dd28d68c607524b3e4aebfd5f40d3ad2b35 |
refs/heads/master | <repo_name>MichTrek/QuestStore<file_sep>/src/main/resources/static/js/script.js
alert("bla0");<file_sep>/src/main/tests/Server/MentorArtifactsTest.java
package Server;
import com.sun.net.httpserver.HttpExchange;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
class MentorArtifactsTest {
@Test
void handleIsCookieTypeAccessTrue() throws Exception{
MentorArtifacts mentorArtifactsToTest = spy(new MentorArtifacts());
doReturn(true).when(mentorArtifactsToTest).isCookieTypeAsAcces(any(),any());
String result = mentorArtifactsToTest.createResponse();
HttpExchange httpExchange = mock(HttpExchange.class);
OutputStream os = new ByteArrayOutputStream();
when(httpExchange.getResponseBody()).thenReturn(os);
mentorArtifactsToTest.handle(httpExchange);
verify(mentorArtifactsToTest, never()).loadLoginSite(httpExchange);
verify(mentorArtifactsToTest, times(1)).sendResponse(result, httpExchange);
}
@Test
void handleIsCookieTypeAccessFalse() throws Exception{
MentorArtifacts mentorArtifactsToTest = spy(new MentorArtifacts());
doReturn(false).when(mentorArtifactsToTest).isCookieTypeAsAcces(any(),any());
doNothing().when(mentorArtifactsToTest).loadLoginSite(any());
HttpExchange httpExchange = mock(HttpExchange.class);
String result = mentorArtifactsToTest.createResponse();
OutputStream os = new ByteArrayOutputStream();
when(httpExchange.getResponseBody()).thenReturn(os);
mentorArtifactsToTest.handle(httpExchange);
verify(mentorArtifactsToTest, never()).sendResponse(result, httpExchange);
verify(mentorArtifactsToTest, times(1)).loadLoginSite(httpExchange);
}
}<file_sep>/src/main/java/dao/StudentDAO.java
package dao;
import java.sql.ResultSet;
import java.util.List;
public interface StudentDAO {
String autoriseStudent(String login, String password);
List<ResultSet> showWallet(int id);
void buyArtifacts(int howMuch, int id_artifact, int id_student);
void buyArtifactTogether();
ResultSet showMyLevel(int id);
}
<file_sep>/src/main/java/createDB/CategoryTable.java
package createDB;
import dao.DataBaseConnector;
public class CategoryTable {
private DataBaseConnector dbConnector = new DataBaseConnector();
public CategoryTable() {
this.dbConnector.connect();
creatingCategoryTable();
}
public void creatingCategoryTable() {
String querry = "CREATE TABLE IF NOT EXISTS quests_category(" +
"quest_category_id SERIAL PRIMARY KEY, " +
"category_name TEXT, " +
"cool_con_bonus INTEGER" +
"); ";
createCategory(querry);
}
public void createCategory(String querry) {
this.dbConnector.updateQuery(querry);
}
}
<file_sep>/src/main/java/model/Wallet.java
package model;
import java.util.List;
public class Wallet {
private int coolCoinsAmount;
private List<Artifact> artifactList;
public Wallet(int coolCoinsAmount, List<Artifact> artifactList) {
this.coolCoinsAmount = coolCoinsAmount;
this.artifactList = artifactList;
}
public int getCoolCoinsAmount() {
return coolCoinsAmount;
}
public List<Artifact> getArtifactList() {
return artifactList;
}
}
<file_sep>/src/main/java/dao/MentorDAO.java
package dao;
import model.Student;
import model.Wallet;
import java.util.List;
public interface MentorDAO {
String autoriseMentor(String login, String password);
void createStudent(String name, String last_name, String _class, String email, String phone_number, String coolCoins, String lvl, String password);
void addQuest(String quest_name, int quest_value, int category);
void addQuestCategory(String category_name, int cool_coins_bonus);
void addArtifactToShop(String artifact_name, int artifact_value, int artifact_quantity);
void editQuest(int id, String quest_name, int quest_value, int quest_category);
void archiveQuest(int id_student, int id_quest, String status);
List<Student> showStudents();
Wallet showStudentsWallet(int id_student);
void removeStudentById(String idStudent);
}
<file_sep>/src/main/java/dao/SessionDAOSQL.java
package dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SessionDAOSQL implements SessionDAO {
private DataBaseConnector dbConnector = new DataBaseConnector();
@Override
public void deleteUserBySessionId(String sessionId) throws SQLException {
String sql = "DELETE FROM session WHERE session_id LIKE ?;";
dbConnector.connect();
PreparedStatement stmt = dbConnector.getConnection().prepareStatement(sql);
stmt.setString(1, sessionId);
stmt.executeUpdate();
}
@Override
public String getTypeBySessionId(String sessionId) throws SQLException {
String type="";
ResultSet rs = dbConnector.query("SELECT type FROM session WHERE session_id LIKE '"+sessionId+"'");
if(rs.next()){
type = rs.getString(1);
}
return type;
}
@Override
public String getUserIdBySessionId(String sessionId) throws SQLException {
int userId = 0;
ResultSet rs = dbConnector.query("SELECT user_id FROM session WHERE session_id LIKE '"+sessionId+"'");
if(rs.next()){
userId = rs.getInt(1);
}
return Integer.toString(userId);
}
@Override
public boolean isThereSessionId(String sessionId) throws SQLException {
boolean result;
ResultSet rs = dbConnector.query("SELECT * FROM session WHERE session_id LIKE '"+sessionId+"'");
if(rs.next()==false){
result=false;
}
else{
result=true;
}
return result;
}
@Override
public void addSession(String sessionId, String type, int Id) {
String sql = "INSERT INTO session " +
"VALUES(?,?,?);";
try {
dbConnector.connect();
PreparedStatement stmt = dbConnector.getConnection().prepareStatement(sql);
stmt.setString(1, sessionId);
stmt.setString(2, type);
stmt.setInt(3, Id);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
<file_sep>/src/main/java/model/Student.java
package model;
public class Student {
private int id;
private String firstName;
private String lastName;
private String clas;
private String email;
private String phone_number;
int coolCoins;
int level;
public Student(int id, String firstName, String lastName, String clas, String email, String phone_number, int coolCoins, int level) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.clas = clas;
this.email = email;
this.phone_number = phone_number;
this.coolCoins = coolCoins;
this.level = level;
}
public int getCoolCoins() {
return coolCoins;
}
public int getLevel() {
return level;
}
public String getClas() {
return clas;
}
public int getId() {
return id;
}
public String getfirstName() {
return firstName;
}
public String getlastName() {
return lastName;
}
public String getEmail() {
return email;
}
public String getPhone_number() {
return phone_number;
}
}
<file_sep>/src/main/java/dao/MentorDAOSQL.java
package dao;
import model.Artifact;
import model.Student;
import model.Wallet;
import view.View;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MentorDAOSQL implements MentorDAO {
DataBaseConnector dbConnector = new DataBaseConnector();
@Override
public String autoriseMentor(String login, String password) {
ResultSet rs = dbConnector.query("SELECT id FROM mentors WHERE email LIKE '" + login+ "'AND password LIKE '"+password+"';");
int outrput=0;
try {
if (rs.next()) {
outrput=rs.getInt(1);
}
}
catch (SQLException e){
e.printStackTrace();
}
if(outrput!=0) {
return Integer.toString(outrput);
}
return null;
}
@Override
public void createStudent(String name, String last_name, String _class, String email, String phone_number, String coolCoins, String lvl, String password) {
int coins = Integer.parseInt(coolCoins);
int level = Integer.parseInt(lvl);
String sql = "INSERT INTO students (first_name, last_name, class, email, phone_number, cool_coins, level, password) " +
"VALUES(?,?,?,?,?,?,?,?);";
try {
dbConnector.connect();
PreparedStatement stmt = dbConnector.getConnection().prepareStatement(sql);
stmt.setString(1, name);
stmt.setString(2, last_name);
stmt.setString(3, _class);
stmt.setString(4, email);
stmt.setString(5, phone_number);
stmt.setInt(6, coins);
stmt.setInt(7, level);
stmt.setString(8, password);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void removeStudentById(String idStudent){
int id = Integer.parseInt(idStudent);
String sql = "DELETE FROM students WHERE id = (?);";
try{
dbConnector.connect();
PreparedStatement preparedStatement = dbConnector.getConnection().prepareStatement(sql);
preparedStatement.setInt(1,id);
preparedStatement.executeUpdate();
}catch (SQLException e ){
e.printStackTrace();
}
}
@Override
public void addQuest(String quest_name, int quest_value, int category) {
String sql = "INSERT INTO students (quest_name, quest_value, category) " +
"VALUES(?,?,?);";
try {
dbConnector.connect();
PreparedStatement stmt = dbConnector.getConnection().prepareStatement(sql);
stmt.setString(1, quest_name);
stmt.setInt(2, quest_value);
stmt.setInt(3, category);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void addQuestCategory(String name, int bonus) {
String sql = "INSERT INTO category (category_name, cool_coin_bonus) " +
"VALUES(?,?);";
try {
dbConnector.connect();
PreparedStatement stmt = dbConnector.getConnection().prepareStatement(sql);
stmt.setString(1, name);
stmt.setInt(2, bonus);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void addArtifactToShop(String artifact_name, int artifact_value, int artifact_quantity) {
PreparedStatement stmt;
try {
if (dbConnector.query("SELECT * FROM artifacts WHERE artifact_name LIKE " + " '" + artifact_name + "';").next() == false) {
insertIntoArtifactToshop(artifact_name, artifact_value, artifact_quantity);
} else {
updateArtifactToShop(artifact_name, artifact_quantity);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public List<Student> showStudents() {
List<Student> studentList = new ArrayList<>();
ResultSet rs = dbConnector.query("SELECT * FROM students");
try {
while (rs.next()) {
Student student = new Student(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getInt(7), rs.getInt(8));
studentList.add(student);
}
} catch (SQLException e) {
e.printStackTrace();
}
return studentList;
}
private void updateArtifactToShop(String artifact_name, int artifact_quantity) throws SQLException {
PreparedStatement stmt;
String sql = "UPDATE artifacts SET quantity = quantity + ?" +
"WHERE artifact_name = ?;";
dbConnector.connect();
stmt = dbConnector.getConnection().prepareStatement(sql);
stmt.setInt(1, artifact_quantity);
stmt.setString(2, artifact_name);
stmt.executeUpdate();
}
private void insertIntoArtifactToshop(String artifact_name, int artifact_value, int artifact_quantity) throws SQLException {
PreparedStatement stmt;
String sql = "INSERT INTO artifacts (artifact_name, artifact_cost, quantity) " +
"VALUES (?,?,?);";
dbConnector.connect();
stmt = dbConnector.getConnection().prepareStatement(sql);
stmt.setString(1, artifact_name);
stmt.setInt(2, artifact_value);
stmt.setInt(3, artifact_quantity);
stmt.executeUpdate();
}
@Override
public void editQuest(int id, String quest_name, int quest_value, int quest_category) {
String sql = "UPDATE artifacts SET quest_name = ?, quest_value = ?, quest_category = ?" +
"WHERE quest_id = ?;";
dbConnector.connect();
try {
PreparedStatement stmt = dbConnector.getConnection().prepareStatement(sql);
stmt.setString(1, quest_name);
stmt.setInt(2, quest_value);
stmt.setInt(3, quest_category);
stmt.setInt(4, id);
stmt.executeUpdate();
} catch (SQLException e) {
}
}
@Override
public void archiveQuest(int id_student, int id_quest, String status) {
String sql = "UPDATE students_quests SET quest_status = ?" +
"WHERE id_quest= ? AND id_student = ?;";
dbConnector.connect();
try {
PreparedStatement stmt = dbConnector.getConnection().prepareStatement(sql);
stmt.setString(1, status);
stmt.setInt(2, id_quest);
stmt.setInt(3, id_student);
stmt.executeUpdate();
} catch (SQLException e) {
}
}
@Override
public Wallet showStudentsWallet(int id) {
ResultSet rs = dbConnector.query("SELECT cool_coins FROM students WHERE id =" + id);
ResultSet rs2 = dbConnector.query("SELECT artifact_name, students_artifacts.quantity FROM artifacts RIGHT JOIN students_artifacts ON artifacts.id_artifact = students_artifacts.id_artifact WHERE students_artifacts.id_student = " + id);
int coolCoins = 0;
String artifactName = "";
int quantity = 0;
List<Artifact> artifactList = new ArrayList<>();
coolCoins = getCoolCoins(rs, coolCoins);
try {
while (rs2.next()) {
artifactName = rs2.getString("artifact_name");
quantity = rs2.getInt("quantity");
artifactList.add(new Artifact(artifactName,quantity));
}
} catch (SQLException e) {
e.printStackTrace();
}
Wallet wallet = new Wallet(coolCoins, artifactList);
return wallet;
}
private int getCoolCoins(ResultSet rs, int coolCoins) {
try {
while (rs.next()) {
coolCoins = rs.getInt("cool_coins");
}
} catch (SQLException e) {
e.printStackTrace();
}
return coolCoins;
}
public static void main(String[] args) {
MentorDAOSQL mds = new MentorDAOSQL();
View view = new View();
// mds.createStudent("adam", "maczek", "1b", "<EMAIL>", "0700990880", 45, 0);
// mds.addQuest("zrobic_sniadanie",100, 2);
// mds.addArtifactToShop("skecz", 10, 2);
// view.printResultSet(mds.showStudents());
// view.printStudentList(mds.showStudents());
// view.printResultSet(mds.showStudentsWallet(3).get(0));
// view.printResultSet(mds.showStudentsWallet(3).get(1));
view.printWallet(mds.showStudentsWallet(2));
}
}
<file_sep>/src/main/java/Server/Index.java
package Server;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import dao.*;
import model.baseUserData;
import org.jtwig.JtwigModel;
import org.jtwig.JtwigTemplate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpCookie;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class Index implements HttpHandler {
MentorDAO mDao = new MentorDAOSQL();
AdminDAO aDao = new AdminDAOSQL();
StudentDAO sDao = new StudentDAOSQL();
SessionDAO sesDao = new SessionDAOSQL();
@Override
public void handle(HttpExchange httpExchange) throws IOException {
String method = httpExchange.getRequestMethod();
if(method.equals("GET")) {
String response = loginSiteTwigString();
sendResponse(response, httpExchange);
}
if(method.equals("POST")){
baseUserData user = new baseUserData();
String url = readURL(httpExchange);
String login = parseURL(url).get("login");
String password = parseURL(url).get("password");
if (login != null && password != null) {
login = login.replace("%40", "@");
user = autorise(login, password);
}
if(user.getId()!=null) {
Random generator = new Random();
int cookieId = generator.nextInt(100000) + 1;
sesDao.addSession(Integer.toString(cookieId),user.getType(), Integer.parseInt(user.getId()));
String response = loginSiteTwigString();
HttpCookie cookie = new HttpCookie("sessionId", Integer.toString(cookieId));
httpExchange.getResponseHeaders().add("Set-Cookie", cookie.toString());
loadHomeSite(httpExchange);
}
else{
loadHomeSite(httpExchange);
}
}
}
private void loadHomeSite(HttpExchange httpExchange) throws IOException {
httpExchange.getResponseHeaders().add("Location", "/loginn");
httpExchange.sendResponseHeaders(302,0);
OutputStream os = httpExchange.getResponseBody();
os.write("".getBytes());
os.close();
}
//TODO test
private String loginSiteTwigString() {
JtwigTemplate template = JtwigTemplate.classpathTemplate("templates/index.twig");
JtwigModel model = JtwigModel.newModel();
return template.render(model);
}
//TODO Test
private baseUserData autorise(String login, String password) {
baseUserData user = new baseUserData();
String admin=aDao.autoriseAdmin(login,password);
String student=sDao.autoriseStudent(login,password);
String mentor=mDao.autoriseMentor(login,password);
if(admin!=null){
user.setId(admin);
user.setType("admin");
}
if(student!=null){
user.setId(student);
user.setType("student");
}
if(mentor!=null){
user.setId(mentor);
user.setType("mentor");
}
return user;
}
public String readURL(HttpExchange httpExchange) throws IOException{
InputStreamReader isr = new InputStreamReader(httpExchange.getRequestBody(), "utf-8");
BufferedReader br = new BufferedReader(isr);
return br.readLine();
}
public void sendResponse(String response,HttpExchange httpExchange) throws IOException{
httpExchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
//TODO Test
public Map<String,String> parseURL(String URL) {
Map<String,String> login = new HashMap();
String[] pairsURL=URL.split("&");
for(String pair : pairsURL){
String[] keyValue = pair.split("=");
if(keyValue.length>1){
login.put(keyValue[0],keyValue[1]);
}
}
return login;
}
}
<file_sep>/src/main/java/createDB/CreateDB.java
package createDB;
public class CreateDB {
public static void main(String[] args) {
AdminTable createAdminTable = new AdminTable();
MentorTable createMentorTable = new MentorTable();
StudentArtifactTable createStudentArtifactTable = new StudentArtifactTable();
QuestTable createQuestTable = new QuestTable();
ArtifactsTable createArtifactsTable = new ArtifactsTable();
StudentsQuestTable createStudentsQuestTable = new StudentsQuestTable();
StudentArtifactTable createStudentArtifactTable1 = new StudentArtifactTable();
ClassTable createClassTable = new ClassTable();
StudentTable createStudentTable = new StudentTable();
CategoryTable createCategoryTable = new CategoryTable();
SessionTable createSessionTable = new SessionTable();
}
}
<file_sep>/src/main/java/Server/Shop.java
package Server;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.jtwig.JtwigModel;
import org.jtwig.JtwigTemplate;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;
public class Shop extends LogIn implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
try {
if (isCookieTypeAsAcces("student", httpExchange)) {
sendResponse(createResponse(), httpExchange);
}
else {
loadLoginSite(httpExchange);
}
}catch (SQLException e){
e.printStackTrace();
}
}
String createResponse() {
JtwigTemplate template = JtwigTemplate.classpathTemplate("templates/shop.twig");
JtwigModel model = JtwigModel.newModel();
return template.render(model);
}
}<file_sep>/src/main/java/Server/Mentor.java
package Server;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.sql.SQLException;
public class Mentor extends LogIn implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
try {
if (isCookieTypeAsAcces("mentor", httpExchange)) {
String method = httpExchange.getRequestMethod();
if(method.equals("POST")) {
logOut(httpExchange);
}
loadJtwig("templates/mentor.twig",httpExchange);
}
else {
loadLoginSite(httpExchange);
}
}catch (SQLException e){
e.printStackTrace();
}
}
}<file_sep>/src/main/resources/static/js/adminMentors.js
var email = document.getElementById("email");
var button = document.getElementById("button");
function addMentor(){
var id = document.getElementById("id");
var name = document.getElementById("name");
var surname = document.getElementById("surname");
alert("You added: \n id: " + id.value+" name : "+name.value+" sur: "+surname.value);
}
function removeMentor(){
var id = document.getElementById("idToRemove");
alert("Mentor deleted " + id.value)
}
<file_sep>/src/main/java/Jtwig.java
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.jtwig.JtwigModel;
import org.jtwig.JtwigTemplate;
import java.io.IOException;
import java.io.OutputStream;
public class Jtwig implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
JtwigTemplate template = JtwigTemplate.classpathTemplate("templates/template1.twig");
JtwigModel model = JtwigModel.newModel();
model.with("name", "<NAME>");
String response = template.render(model);
httpExchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}<file_sep>/src/main/java/dao/AdminDAO.java
package dao;
import model.Mentormod;
import java.util.List;
public interface AdminDAO {
String autoriseAdmin(String login,String password);
void createMentor(String first_name, String last_name, String email, String phone_number, String password);
void createClass(String class_name);
void editMentor(String columnToChange, String update, int id);
List<Mentormod> getMentors();
Mentormod showMentorById(int id);
void createLevelOfExperience();
void removeMentorById(String id);
}
<file_sep>/src/main/java/Server/User.java
package Server;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import dao.MentorDAOSQL;
import dao.SessionDAOSQL;
import model.Wallet;
import org.jtwig.JtwigModel;
import org.jtwig.JtwigTemplate;
import java.io.IOException;
import java.net.HttpCookie;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class User extends LogIn implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
try {
if (isCookieTypeAsAcces("student", httpExchange)) {
String method = httpExchange.getRequestMethod();
if(method.equals("POST")) {
logOut(httpExchange);
}
JtwigTemplate template = JtwigTemplate.classpathTemplate("templates/user.twig");
JtwigModel model = JtwigModel.newModel();
HttpCookie cookie = findCurrentCookie(httpExchange).get(0);
String currentSesion=cookie.getValue();
SessionDAOSQL sessionDAOSQL = new SessionDAOSQL();
String userId = sessionDAOSQL.getUserIdBySessionId(currentSesion);
int userIntId = Integer.parseInt(userId);
MentorDAOSQL mentorDAOSQL = new MentorDAOSQL();
Wallet wallet = mentorDAOSQL.showStudentsWallet(userIntId);
model.with("wallet",wallet);
String response = template.render(model);
sendResponse(response,httpExchange);
}
else {
loadLoginSite(httpExchange);
}
}catch (SQLException e){
e.printStackTrace();
}
}
}<file_sep>/src/main/java/createDB/StudentTable.java
package createDB;
import dao.DataBaseConnector;
public class StudentTable {
private DataBaseConnector dbConnector = new DataBaseConnector();
public StudentTable() {
this.dbConnector.connect();
creatingStudentTable();
}
public void creatingStudentTable() {
String querry = "CREATE TABLE IF NOT EXISTS students(" +
"id SERIAL PRIMARY KEY, " +
"first_name TEXT, " +
"last_name TEXT, " +
"class TEXT, " +
"email TEXT, " +
"phone_number TEXT, " +
"cool_coins INTEGER, " +
"level INTEGER," +
"password text NOT NULL); ";
createStudent(querry);
}
public void createStudent(String querry) {
String sql = querry;
this.dbConnector.updateQuery(sql);
}
}
<file_sep>/src/main/java/dao/StudentDAOSQL.java
package dao;
import view.View;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class StudentDAOSQL implements StudentDAO {
private DataBaseConnector dataBaseConnector = new DataBaseConnector();
private View view = new View();
@Override
public String autoriseStudent(String login, String password) {
ResultSet rs = dataBaseConnector.query("SELECT id FROM students WHERE email LIKE '" + login+ "'AND password LIKE '"+password+"';");
int output=0;
try {
if (rs.next()) {
output=rs.getInt(1);
}
}
catch (SQLException e){
e.printStackTrace();
}
if(output!=0) {
return Integer.toString(output);
}
return null;
}
@Override
public List<ResultSet> showWallet(int id) {
List<ResultSet> resultSetList = new ArrayList<>();
ResultSet rs = dataBaseConnector.query("SELECT cool_coins FROM students WHERE id =" + id);
ResultSet rs2 = dataBaseConnector.query("SELECT artifact_name FROM artifacts RIGHT JOIN students_artifacts ON artifacts.id_artifact = students_artifacts.id_artifact WHERE students_artifacts.id_student = " + id);
resultSetList.add(rs);
resultSetList.add(rs2);
return resultSetList;
}
@Override
public void buyArtifacts(int howMuch, int id_artifact, int id_student) {
// student 1 chce kupic 2 artifact ilosc 5, wiec w artifacts updateuje quantity o minus 5 dla artifactu 2
// student 1 traci cool_coinsy o ilosc artifact value * ilosc kupionych,
// students artifact table ma insertowane lub updateowane ze student 1 ma 5 artifactow nr 2
String sql = "UPDATE artifacts SET quantity = quantity-? WHERE id_artifact = ?;" +
"UPDATE students SET cool_coins = cool_coins - ((SELECT artifact_cost FROM artifacts WHERE id_artifact = ?) * ?) WHERE students.id = ?;";
String sql2 = "";
updateQuantityAndCoolCoins(howMuch, id_artifact, id_student, sql, sql2);
try {
if (dataBaseConnector.query("SELECT * FROM students_artifacts WHERE id_artifact = " + id_artifact + " AND id_student = " + id_student + ";").next() == false) {
insertToStudentsArtifactsIfNotExists(howMuch, id_artifact, id_student);
} else {
updateStudentsArtifacts(howMuch, id_artifact, id_student);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void updateStudentsArtifacts(int howMuch, int id_artifact, int id_student) throws SQLException {
String sql2;
sql2 = "UPDATE students_artifacts SET quantity = quantity + ? WHERE id_artifact = " + id_artifact + " AND id_student = " + id_student + ";";
dataBaseConnector.connect();
PreparedStatement stmt = dataBaseConnector.getConnection().prepareStatement(sql2);
stmt.setInt(1, howMuch);
stmt.executeUpdate();
}
private void insertToStudentsArtifactsIfNotExists(int howMuch, int id_artifact, int id_student) throws SQLException {
String sql2;
sql2 = "INSERT INTO students_artifacts VALUES (?,?,?);";
dataBaseConnector.connect();
PreparedStatement stmt = dataBaseConnector.getConnection().prepareStatement(sql2);
stmt.setInt(1, id_artifact);
stmt.setInt(2, id_student);
stmt.setInt(3, howMuch);
stmt.executeUpdate();
}
private void updateQuantityAndCoolCoins(int howMuch, int id_artifact, int id_student, String sql, String sql2) {
try {
dataBaseConnector.connect();
PreparedStatement stmt = dataBaseConnector.getConnection().prepareStatement(sql);
PreparedStatement stmt2 = dataBaseConnector.getConnection().prepareStatement(sql2);
stmt.setInt(1, howMuch);
stmt.setInt(2, id_artifact);
stmt.setInt(3, id_artifact);
stmt.setInt(4, howMuch);
stmt.setInt(5, id_student);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void buyArtifactTogether() {
}
@Override
public ResultSet showMyLevel(int id) {
ResultSet rs = dataBaseConnector.query("SELECT level FROM students WHERE id =" + id);
return rs;
}
public static void main(String[] args) {
StudentDAOSQL studentDAOSQL = new StudentDAOSQL();
View view = new View();
view.printListOfResultSet(studentDAOSQL.showWallet(1));
// view.printResultSet(studentDAOSQL.showMyLevel(1));
// studentDAOSQL.buyArtifacts(3, 2, 4);
}
}
<file_sep>/src/main/tests/Server/AdminCoinsTest.java
package Server;
import com.sun.net.httpserver.HttpExchange;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import static org.mockito.Mockito.*;
class AdminCoinsTest {
@Test
void handleIsCookieTypeAccessTrue() throws Exception{
AdminCoins adminCoinsToTest = spy(new AdminCoins());
doReturn(true).when(adminCoinsToTest).isCookieTypeAsAcces(any(),any());
String result = adminCoinsToTest.createResponse();
HttpExchange httpExchange = mock(HttpExchange.class);
OutputStream os = new ByteArrayOutputStream();
when(httpExchange.getResponseBody()).thenReturn(os);
adminCoinsToTest.handle(httpExchange);
verify(adminCoinsToTest, never()).loadLoginSite(httpExchange);
verify(adminCoinsToTest, times(1)).sendResponse(result, httpExchange);
}
@Test
void handleIsCookieTypeAccessFalse() throws Exception{
AdminCoins adminCoinsToTest = spy(new AdminCoins());
doReturn(false).when(adminCoinsToTest).isCookieTypeAsAcces(any(),any());
doNothing().when(adminCoinsToTest).loadLoginSite(any());
HttpExchange httpExchange = mock(HttpExchange.class);
String result = adminCoinsToTest.createResponse();
OutputStream os = new ByteArrayOutputStream();
when(httpExchange.getResponseBody()).thenReturn(os);
adminCoinsToTest.handle(httpExchange);
verify(adminCoinsToTest, never()).sendResponse(result, httpExchange);
verify(adminCoinsToTest, times(1)).loadLoginSite(httpExchange);
}
}<file_sep>/src/main/tests/Server/ShopTest.java
package Server;
import com.sun.net.httpserver.HttpExchange;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import static org.mockito.Mockito.*;
class ShopTest {
@Test
void handleIsCookieTypeAccessTrue() throws Exception{
Shop shopToTest = spy(new Shop());
doReturn(true).when(shopToTest).isCookieTypeAsAcces(any(),any());
String result = shopToTest.createResponse();
HttpExchange httpExchange = mock(HttpExchange.class);
OutputStream os = new ByteArrayOutputStream();
when(httpExchange.getResponseBody()).thenReturn(os);
shopToTest.handle(httpExchange);
verify(shopToTest, never()).loadLoginSite(httpExchange);
verify(shopToTest, times(1)).sendResponse(result, httpExchange);
}
@Test
void handleIsCookieTypeAccessFalse() throws Exception{
Shop shopToTest = spy(new Shop());
doReturn(false).when(shopToTest).isCookieTypeAsAcces(any(),any());
doNothing().when(shopToTest).loadLoginSite(any());
HttpExchange httpExchange = mock(HttpExchange.class);
String result = shopToTest.createResponse();
OutputStream os = new ByteArrayOutputStream();
when(httpExchange.getResponseBody()).thenReturn(os);
shopToTest.handle(httpExchange);
verify(shopToTest, never()).sendResponse(result, httpExchange);
verify(shopToTest, times(1)).loadLoginSite(httpExchange);
}
}
| 90d319df761d63b5bf09b08098894786ffa682b2 | [
"JavaScript",
"Java"
] | 21 | JavaScript | MichTrek/QuestStore | 5d0152d928b4b53a3ff2748afde01ee51a3bff1a | 6c901057c458a35eeea3025455f0e83d3134ecf9 |
refs/heads/master | <file_sep>var express = require('express');
var mongoose = require('mongoose');
var appsettings = require('../appsettings');
var book = require('../models/book');
var bodyParser = require('body-parser');
var bookRouter = express.Router();
bookRouter.route('/')
.get(function(request, response){
mongoose.connect(appsettings.mongoUrl);
var filter = {};
if(request.query.genre){
filter.genre = request.query.genre;
}
book.find(filter, function (error, books) {
if(error){
response.status(500).send(error);
}
else{
response.json(books);
}
});
})
.post(function(request, response){
mongoose.connect(appsettings.mongoUrl);
var b = new book(request.body);
b.save();
response.status(201).send(b);
});
bookRouter.use('/:id', function(request, response, next){
mongoose.connect(appsettings.mongoUrl);
book.findById(request.params.id, function(error, book){
if(error){
response.status(500).send(error);
}
if(book){
request.book = book;
next();
}
else{
response.status(404).send(`Book with id ${request.params.id} not found`);
}
});
});
bookRouter.route('/:id')
.get(function(request, response){
response.json(request.book);
})
.put(function(request, response){
request.book.title = request.body.title;
request.book.author = request.body.author;
request.book.genre = request.body.genre;
request.book.read = request.body.read;
request.book.save();
response.status(202).json(request.book);
})
.patch(function(request, response){
if(request.body._id)
delete request.body._id;
for(var key in request.body){
request.book[key] = request.body[key];
}
request.book.save(function(err){
if(err){
response.status(500).send('Error while saving the book');
}
else{
response.status(202).send(request.book);
}
});
})
.delete(function(request, response){
request.book.remove();
request.book.save(function(err){
if(err){
response.status(500).send('Error while saving the book');
}
else{
response.status(204).send('removed');
}
});
});
module.exports = bookRouter; | 5e05749d59e96748a64531cfb6a56bff9aee2c8a | [
"JavaScript"
] | 1 | JavaScript | mehul230588/nodeAPI | 60eac98ded250bc9b554b9fb5f19bc8a2d4211b3 | c1d2d34e532b336b4ff3038f2214fdb8506b544e |
refs/heads/master | <file_sep># obc-db-query<file_sep>package main
import (
"encoding/binary"
"flag"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/kr/pretty"
"github.com/openblockchain/obc-peer/protos"
"github.com/tecbot/gorocksdb"
)
func main() {
var dbPath string
flag.StringVar(&dbPath, "d", "", "Database path")
flag.Parse()
opts := gorocksdb.NewDefaultOptions()
defer opts.Destroy()
opts.SetCreateIfMissing(false)
db, h, err := gorocksdb.OpenDbColumnFamilies(opts, dbPath,
[]string{"default", "blockchainCF", "indexesCF", "stateDeltaCF", "stateCF"},
[]*gorocksdb.Options{opts, opts, opts, opts, opts})
if err != nil {
fmt.Printf(err.Error() + "\n")
return
}
opt := gorocksdb.NewDefaultReadOptions()
defer opt.Destroy()
iterator := db.NewIteratorCF(opt, h[1])
res := make(map[string]interface{}, 0)
iterator.SeekToFirst()
for ; iterator.Valid(); iterator.Next() {
key := iterator.Key()
val := iterator.Value()
keyData := string(append([]byte(nil), key.Data()...))
if keyData == "blockCount" {
data := append([]byte(nil), val.Data()...)
res[keyData] = binary.BigEndian.Uint64(data)
} else {
block := &protos.Block{}
data := append([]byte(nil), val.Data()...)
err := proto.Unmarshal(data, block)
if err != nil {
fmt.Printf(err.Error() + "\n")
return
}
res[keyData] = block
}
}
pretty.Printf("%# v\n", res)
}
| 57f70aa0e42c45f5b1a97dd9196420a1e9fd8c2b | [
"Markdown",
"Go"
] | 2 | Markdown | s-matyukevich/obc-db-query | da428bf6daca2e965c59b512a84a714adc83bc97 | c119283e171fdc20eff74c0eaf84731625330435 |
refs/heads/master | <file_sep># github-local-remote
[![crates.io version][1]][2] [![build status][3]][4]
[![downloads][5]][6] [![docs.rs docs][7]][8]
Find the GitHub url, repo and username for a local directory.
- [Documentation][8]
- [Crates.io][2]
- [Releases][9]
## Usage
```rust
extern crate github_local_remote;
fn main() {
let res = github_local_remote::stat(".").unwrap();
println!("result {:?}", res);
}
```
## Installation
```sh
$ cargo add github-local-remote
```
## License
[MIT](./LICENSE-MIT) OR [Apache-2.0](./LICENSE-APACHE)
[1]: https://img.shields.io/crates/v/github-local-remote.svg?style=flat-square
[2]: https://crates.io/crates/github-local-remote
[3]: https://img.shields.io/travis/yoshuawuyts/github-local-remote.svg?style=flat-square
[4]: https://travis-ci.org/yoshuawuyts/github-local-remote
[5]: https://img.shields.io/crates/d/github-local-remote.svg?style=flat-square
[6]: https://crates.io/crates/github-local-remote
[7]: https://img.shields.io/badge/docs-latest-blue.svg?style=flat-square
[8]: https://docs.rs/github-local-remote
[9]: https://github.com/yoshuawuyts/github-local-remote/releases
<file_sep>#![cfg_attr(feature = "nightly", deny(missing_docs))]
#![cfg_attr(feature = "nightly", feature(external_doc))]
#![cfg_attr(feature = "nightly", doc(include = "../README.md"))]
#![cfg_attr(test, deny(warnings))]
#![forbid(unsafe_code, missing_debug_implementations)]
#[macro_use]
extern crate failure;
extern crate git2;
mod error;
pub use error::{Error, ErrorKind, Result};
use failure::ResultExt;
use git2::Repository;
use std::convert::AsRef;
use std::path::Path;
/// Remote represenation.
#[derive(Debug, Clone)]
pub struct Remote {
url: String,
user: String,
repo: String,
}
impl Remote {
/// Get the url.
pub fn url(&self) -> &str {
&self.url
}
/// Get the user.
pub fn user(&self) -> &str {
&self.user
}
/// Get the repo.
pub fn repo(&self) -> &str {
&self.repo
}
}
/// Find out what the GitHub url, user and repo are for a directory
pub fn stat(path: impl AsRef<Path>) -> ::Result<Remote> {
let path = path.as_ref();
let repo = Repository::open(path).context(::ErrorKind::Git)?;
let remote = repo
.find_remote("origin")
.context(::ErrorKind::GitRemoteOrigin)?;
let url = remote.url().ok_or(::ErrorKind::GitRemoteUrl)?;
let parts: Vec<&str> = url.split(":").collect();
let repo_username = parts.get(1).ok_or(::ErrorKind::GitHubUrl)?;
let repo_username = repo_username.replace(".git", "");
let parts: Vec<&str> = repo_username.split("/").collect();
let user = parts.get(0).ok_or(::ErrorKind::GitHubUrl)?;
let repo = parts.get(1).ok_or(::ErrorKind::GitHubUrl)?;
Ok(Remote {
url: format!("https://github.com/{}", repo_username),
repo: repo.to_string(),
user: user.to_string(),
})
}
<file_sep>## 2018-09-04, Version 0.1.1
### Commits
- [[`161106d600`](https://github.com/yoshuawuyts/github-local-remote/commit/161106d60058138fb26829c5f36d8c96866c89cf)] (cargo-release) version 0.1.1 (Yoshua Wuyts)
- [[`e516082fb7`](https://github.com/yoshuawuyts/github-local-remote/commit/e516082fb7e34eaecffb5ef6eb2614ac13ac5d7c)] fix url (Yoshua Wuyts)
- [[`1ac8c76ed9`](https://github.com/yoshuawuyts/github-local-remote/commit/1ac8c76ed9eb0f0b4c32f9e2fe4fc106b05aa2b1)] finalize (Yoshua Wuyts)
- [[`eee21105d2`](https://github.com/yoshuawuyts/github-local-remote/commit/eee21105d2cc7c3b9a45b9d328006af1b93edf4f)] . (Yoshua Wuyts)
### Stats
```diff
.github/CODE_OF_CONDUCT.md | 75 ++++++++++++-
.github/CONTRIBUTING.md | 63 ++++++++++-
.github/ISSUE_TEMPLATE.md | 9 +-
.github/ISSUE_TEMPLATE/bug_report.md | 23 ++++-
.github/ISSUE_TEMPLATE/feature_request.md | 30 +++++-
.github/ISSUE_TEMPLATE/question.md | 18 +++-
.github/PULL_REQUEST_TEMPLATE.md | 21 +++-
.github/stale.yml | 17 +++-
.gitignore | 7 +-
.travis.yml | 13 ++-
CERTIFICATE | 37 ++++++-
Cargo.toml | 15 ++-
LICENSE-APACHE | 190 +++++++++++++++++++++++++++++++-
LICENSE-MIT | 21 +++-
README.md | 37 ++++++-
examples/main.rs | 6 +-
rustfmt.toml | 2 +-
src/error.rs | 94 +++++++++++++++-
src/lib.rs | 67 +++++++++++-
tests/test.rs | 1 +-
20 files changed, 746 insertions(+)
```
<file_sep>[package]
name = "github-local-remote"
version = "0.1.1"
license = "MIT OR Apache-2.0"
repository = "https://github.com/yoshuawuyts/github-local-remote"
documentation = "https://docs.rs/github-local-remote"
description = "Find the GitHub url, repo and username for a local directory"
authors = ["<NAME> <<EMAIL>>"]
readme = "README.md"
[dependencies]
failure = "0.1.2"
git2 = "0.7.5"
[dev-dependencies]
<file_sep>extern crate github_local_remote;
fn main() {
let res = github_local_remote::stat(".").unwrap();
println!("result {:?}", res);
}
| 98162090b8e933af318b304aeaae81bd01f3d175 | [
"Markdown",
"Rust",
"TOML"
] | 5 | Markdown | yoshuawuyts/github-local-remote | 84e9f28bcd26729ef0a49aed652115fc1ec0767a | 24220b2eced6abe789bff79d14005dc124aa3c5f |
refs/heads/main | <file_sep># PhotonBinaryProject
HTML ui and http request file to remotely change the binary value displayed on neopixels
Photon code included if anyone is interested
<file_sep>
#include "Particle.h"
#include "neopixel.h"
#include "math.h"
SYSTEM_MODE(AUTOMATIC);
// IMPORTANT: Set pixel COUNT, PIN and TYPE
#define PIXEL_PIN D2
#define PIXEL_COUNT 10
#define PIXEL_TYPE WS2813
#define BIT_WIDTH 8
Adafruit_NeoPixel strip(PIXEL_COUNT, PIXEL_PIN, PIXEL_TYPE);
bool eightBit[BIT_WIDTH];
int decimal;
void setup()
{
strip.begin();
Particle.function("change", number);
Particle.function("clear", clear);
Particle.variable("decimal", decimal);
}
void loop()
{
for(int i = 0 ; i < strip.numPixels(); i++){
if(eightBit[i]){
strip.setPixelColor(i,100,100,100);
} else{
strip.setPixelColor(i,0,0,0);
}
}
strip.show();
decimal = toDecimal();
}
int number(String num){
uint16_t change = atoi(num);
eightBit[change] = !eightBit[change];
return 0;
}
int clear(String args){
for(int i = 0; i < BIT_WIDTH; i++){
eightBit[i] = false;
}
return 0;
}
int toDecimal(){
int sum = 0;
for(int i = 0; i < BIT_WIDTH; i++){
if(eightBit[i]){
sum += pow(2,i);
}
}
return sum;
}
| bc069c487ee498e9c30aaa0f2e9c8e42b16c4927 | [
"Markdown",
"C++"
] | 2 | Markdown | GavinMce/PhotonBinaryProject | 140d9e1b8a224f794e3f0fbe3cf090719c3d45fb | afa628e0c11989be8cc14bb16ad45acd84fa02dd |
refs/heads/master | <file_sep>// Your code here
razzle()
function razzle() {
console.log("You've been razzled!")
}
function razzle(lawyer="Billy", target="'em") {
console.log(`${lawyer} razzle-dazzles ${target}!`);
}
razzle()
razzle("Methuselah", "T'challah")
function saturdayFun(target="roller-skate") {
return `This Saturday, I want to ${target}!`
};
let mondayWork = function(target ="go to the office") {
return `This Monday, I will ${target}.`
};
function wrapAdjective(symbol="*") {
return function(param="special") {
return `You are ${symbol}${param}${symbol}!`
}
};
let Calculator= {
add: function(a, b) {
return a + b
},
subtract: function(a, b) {
return a - b
},
multiply: function(a, b) {
return a * b
},
divide: function (a, b) {
return a/b
}
};
function actionApplyer(startingNumber, array) {
for(const el of array) {
startingNumber = el(startingNumber)
}
return startingNumber
} | 2f36cf615115d1e3516c4b1d3b886077dcb13029 | [
"JavaScript"
] | 1 | JavaScript | Chrispolanco/js-advanced-functions-basic-functions-review-lab-online-web-pt-081219 | 82d1f602cbc03ef9e40b758f05dacbd5a059a285 | f7a17cc37e5a33cac074daf8801a75c531cc0146 |
refs/heads/main | <repo_name>aljazjelen/ECU-Mark1-OLD<file_sep>/Core/Inc/crankshaft.h
/*
* crankshaft.h
*
* Created on: Oct 4, 2020
* Author: aljaz
*/
#include "stm32l0xx_hal.h"
#ifndef INC_CRANKSHAFT_H_
#define INC_CRANKSHAFT_H_
extern int Crank_ShaftFreqHz;
extern int Crank_ShaftFreqHzRaw;
extern uint32_t Crank_PosDiff; // Global Variable to track Crankshaft Tooth New timing difference
extern uint32_t Crank_PosDiffOld; // Global Variable to track Crankshaft Tooth Old timing difference
extern uint8_t Crank_TeethCount; // Global Variable of exact Current Tooth Number
extern uint32_t Crank_RotDelta;
extern uint16_t Crank_Angle;
extern uint32_t Crank_DivAngle; // Global Variable used to calculate angle between 2 rising edges of the tooth
extern uint8_t Cam_CycleStart;
// Locals
extern uint16_t Crank_LastCapturedEdgeTime;
extern uint8_t Crank_bErrToothJump;
// Parameters
extern uint8_t Crank_TeethNmbr_P;
extern uint8_t Crank_MissingTeethNmbr_P;
// Functions
extern void Crank_HalGeberDriver(TIM_HandleTypeDef *htim);
extern void Crank_CamPositionSync(); // TODO used to synchronise with CAM, to see which halfcycle is it
extern void Crank_TeethCounterReset();
extern void Crank_AngleCalc();
#endif /* INC_CRANKSHAFT_H_ */
<file_sep>/Core/Src/ignition.c
/*
* ignition.c
*
* Created on: Sep 21, 2020
* Author: <NAME>
*/
#include "ignition.h"
//#include "stm32l0xx_hal.h"
int Ignition_DwellTimeUs = 1000; // Global Variable for Dwell Time of ignition coils, calculated from maps (1000us to 2000us)
int Ignition_AngleDegree = 5; // Ignition angle BTDC
uint32_t Ignition_TimeToFireCyl1 = 0; // Time in us to firing a Cylinder 1
uint32_t Ignition_TimeToFireCyl2 = 0; // Time in us to firing a Cylinder 2
uint32_t Ignition_TimeToFireCyl3 = 0; // Time in us to firing a Cylinder 3
uint32_t Ignition_TimeToFireCyl4 = 0; // Time in us to firing a Cylinder 4
int Ignition_FireToothCyl1 = 1; // Tooth at which the counter starts to count to align to correct angle for firing Cyl 1
int Ignition_FireToothCyl2 = 20; // Tooth at which the counter starts to count to align to correct angle for firing Cyl 2
int Ignition_FireToothCyl3 = 9; // Tooth at which the counter starts to count to align to correct angle for firing Cyl 3
int Ignition_FireToothCyl4 = 40; // Tooth at which the counter starts to count to align to correct angle for firing Cyl 4
int Ignition_DwellToothCyl1 = 1; // Tooth at which the counter starts to count to align to correct angle for dwelling Cyl 1
int Ignition_DwellToothCyl2 = 20; // Tooth at which the counter starts to count to align to correct angle for dwelling Cyl 2
int Ignition_DwellToothCyl3 = 9; // Tooth at which the counter starts to count to align to correct angle for dwelling Cyl 3
int Ignition_DwellToothCyl4 = 40; // Tooth at which the counter starts to count to align to correct angle for dwelling Cyl 4
uint8_t Ignition_CoilStateCyl1 = IDLE;
uint8_t Ignition_CoilStateCyl2 = IDLE;
uint8_t Ignition_CoilStateCyl3 = IDLE;
uint8_t Ignition_CoilStateCyl4 = IDLE;
int *pAwellTimeUs = &Ignition_DwellTimeUs;
int *pAngleDegree = &Ignition_AngleDegree;
int Ignition_DefineIgnitionTeeth(int AngleOfIgnition,uint8_t CrankTeethNmbr, uint8_t CrankMissingTeethNmbr){
int triggerTooth = 0;
triggerTooth = (CrankTeethNmbr+CrankMissingTeethNmbr)*AngleOfIgnition/360+1;
return triggerTooth;
}
/**
* @brief Ignition Function which will set the ignition timer and the tooth number at which timer has to start counting, in order to fire at exact angle.
* @param CylId - Cylinder Number, AngleOfIgnition - Angle (0-360) at which the Coil shall fire, CrankShaftHz - Frequency of Crankshaft, CrankTeethNmbr - Number of teeth on the wheel, CrankMissingTeethNmbr - Number of missing teeth
* @retval None
*/
void Ignition_SetIgnitionTiming(int CylId, int AngleOfIgnition, int CrankShaftHz, uint8_t CrankTeethNmbr, uint8_t CrankMissingTeethNmbr){
int TriggerTooth;
TriggerTooth = Ignition_DefineIgnitionTeeth(AngleOfIgnition,CrankTeethNmbr,CrankMissingTeethNmbr);
float triggerAngle;
float delayAngle;
uint32_t Ignition_TimeToFire;
// Perform correction if angle is after the missing teeth
if (TriggerTooth == CrankTeethNmbr){
TriggerTooth = 0;
delayAngle = 0;
}
else{
triggerAngle = (TriggerTooth-1)*360/(CrankTeethNmbr+CrankMissingTeethNmbr);
delayAngle = AngleOfIgnition - triggerAngle;
Ignition_TimeToFire = Ignition_AngleToUs(CrankShaftHz,delayAngle);
}
/* correction in case CCR and ARR dont work with 0
*
*/
if (Ignition_TimeToFire == 0)
Ignition_TimeToFire = 1;
switch (CylId)
{
case 1:
Ignition_FireToothCyl1 = TriggerTooth;
Ignition_TimeToFireCyl1 = Ignition_TimeToFire;
break;
case 2:
Ignition_FireToothCyl2 = TriggerTooth;
Ignition_TimeToFireCyl2 = Ignition_TimeToFire;
break;
case 3:
Ignition_FireToothCyl3 = TriggerTooth;
Ignition_TimeToFireCyl3 = Ignition_TimeToFire;
break;
case 4:
Ignition_FireToothCyl4 = TriggerTooth;
Ignition_TimeToFireCyl4 = Ignition_TimeToFire;
break;
}
}
uint32_t Ignition_AngleToUs(int CrankShaftHz, float AngleDegree){
return HAL_RCC_GetPCLK1Freq()*AngleDegree/360/CrankShaftHz/TIM22->PSC;
}
void Ignition_StartTimerFireCylinder(int CylId){
uint32_t fireStartInUs = 0;
switch (CylId)
{
case 1:
fireStartInUs = Ignition_TimeToFireCyl1;
Ignition_CoilStateCyl1 = FIRE;
break;
case 2:
fireStartInUs = Ignition_TimeToFireCyl2;
break;
case 3:
fireStartInUs = Ignition_TimeToFireCyl3;
Ignition_CoilStateCyl3 = FIRE;
break;
case 4:
fireStartInUs = Ignition_TimeToFireCyl4;
break;
}
// set proper GPIO to choose the cylinder (1,2,3,4)?
// toggle the timer which will start counting to fire dwelling and then spark
TIM22->ARR = fireStartInUs + 100;
TIM22->CCR1 = fireStartInUs;
TIM22->CCR2 = TIM22->ARR+10;//to disable
TIM22->EGR = 1;
TIM22->CR1 |= TIM_CR1_CEN;
// TODO only for cyl1
//HAL_TIM_OnePulse_Start(TIM22,1);
}
void Ignition_StartTimerDwellCylinder(int CylId,int dwellStartInUs){
switch (CylId)
{
case 1:
//fireStartInUs = Ignition_TimeToFireCyl1;
Ignition_CoilStateCyl1 = DWELL;
break;
case 2:
//fireStartInUs = Ignition_TimeToFireCyl2;
break;
case 3:
//fireStartInUs = Ignition_TimeToFireCyl3;
Ignition_CoilStateCyl3 = DWELL;
break;
case 4:
//fireStartInUs = Ignition_TimeToFireCyl4;
break;
}
// Dwell selected ignition coil for cylinder
//TIM22->CCR1 = TIM22->ARR+1;
//TIM22->CCR2 = 10;
TIM22->ARR = 100;
TIM22->CCR1 = 10;
TIM22->CCR2 = TIM22->ARR+10;
TIM22->EGR = 1;
TIM22->CR1 |= TIM_CR1_CEN;
//Ignition_CoilStateCyl1 = DWELL;
//HAL_GPIO_WritePin(GPIOC,GPIO_PIN_3,GPIO_PIN_SET);
}
<file_sep>/Core/Inc/interruptConfig.h
/*
* interruptConfig.h
*
* Created on: Oct 5, 2020
* Author: aljaz
*/
#ifndef INC_INTERRUPTCONFIG_H_
#define INC_INTERRUPTCONFIG_H_
#endif /* INC_INTERRUPTCONFIG_H_ */
<file_sep>/Core/Src/crankshaft.c
/*
* Crankshaft.c
*
* Created on: Oct 4, 2020
* Author: aljaz
*/
#include "crankshaft.h"
int Crank_ShaftFreqHz = 0; // Global Variable of estimated Crankshaft frequency in Hz (filtered)
int Crank_ShaftFreqHzRaw = 0; // Global Variable of estimated Crankshaft freq in Hz (non filtered, no missing tooth compensation)
uint32_t Crank_RotDelta = 0; // Global Variable of exact delta time between 2 teeth
uint32_t Crank_PosDiff = 0; // Global Variable to track Crankshaft Tooth New timing difference
uint32_t Crank_PosDiffOld = 0; // Global Variable to track Crankshaft Tooth Old timing difference
uint8_t Crank_TeethCount = 0; // Global Variable of exact Current Tooth Number
uint16_t Crank_Angle = 0; // Global Variable of estimated Crankshaft Angle
uint32_t Crank_DivAngle = 0; // Global Variable used to calculate angle between 2 rising edges of the tooth
// TODO move to own files (engine. where all central variables are)
uint16_t Engine_Angle = 0; // Global Variable of estimated Engine System
// TODO move to own files (cam, where cam related drivers are stored)
uint8_t Cam_CycleStart = 0; // Global Variable to trach the start of Camshaft (0) is start, (1) is 2nd half cycle.
// Locals
uint16_t Crank_LastCapturedEdgeTime = 0; // Global Time Stamp for last detected edge from Hal Sensor
uint8_t Crank_bErrToothJump = 0; // Global Error flag when counted teeth and total tooth number dont match
// Parameters
uint8_t Crank_TeethNmbr_P = 17; // Global Parameter for total number of teeth on the Crankshaft
uint8_t Crank_MissingTeethNmbr_P = 1;// Global Parameter for missing number of teeth on the Crankshaft
// TODO add a parameter which varries threshold for missing tooth detection algorithm
/* All Possible Init Stuff */
void Crank_Init(){
Crank_DivAngle = 360/Crank_TeethNmbr_P;
}
/* Driver for calculating the speed and resetting the counter upon empty slot */
void Crank_HalGeberDriver(TIM_HandleTypeDef *htim){
uint16_t capturedValue;
//int Crank_ShaftFreqHzRaw = 0;
//channelId = PWM_IC_CHANNEL_FLOW_METER;
// Get CCR register for the specific Timer and Channel
capturedValue = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_2);
if( capturedValue > Crank_LastCapturedEdgeTime )
// Compute the input signal frequency
Crank_RotDelta = capturedValue - Crank_LastCapturedEdgeTime;
else
// Timer counter overflow
Crank_RotDelta = ( 0xFFFF - Crank_LastCapturedEdgeTime ) + capturedValue;
// Compute the input signal frequency
Crank_RotDelta = Crank_RotDelta*(1+htim->Instance->PSC);
Crank_ShaftFreqHzRaw = HAL_RCC_GetPCLK1Freq()/Crank_RotDelta/(Crank_TeethNmbr_P+1); // calculate frequency
// Update the last captured value
Crank_LastCapturedEdgeTime = capturedValue;
Crank_PosDiff = Crank_RotDelta;
// Check for the empty tooth - if the difference between timestamps is bigger than usually.
if(((Crank_PosDiff-Crank_PosDiffOld) >= 0.7*Crank_PosDiffOld) && (Crank_PosDiff >= Crank_PosDiffOld)){
Crank_PosDiffOld = Crank_PosDiff;
Crank_ShaftFreqHz = Crank_ShaftFreqHz; // take the last valid value in case the tooth is missing
if (Crank_TeethCount >= Crank_TeethNmbr_P-1){
Crank_bErrToothJump = 1;
}else
Crank_bErrToothJump = 0;
Crank_TeethCounterReset(); // reset the counter due to the larger space between teeth
}
else{
Crank_PosDiffOld = Crank_PosDiff;
Crank_ShaftFreqHz = 0.5*Crank_ShaftFreqHz + 0.5*Crank_ShaftFreqHzRaw; // filter frequency if the tooth isnt missing
//Crank_TeethCount++;
}
}
/* Helper funcion for Teeth Counter reset */
void Crank_TeethCounterReset(){
Crank_TeethCount = 1;
}
/* Teeth Counter */
void Crank_TeethCounter(){
if (Crank_TeethCount < Crank_TeethNmbr_P)
Crank_TeethCount = Crank_TeethCount + 1;
else
Crank_TeethCounterReset();
}
/* Calculation of Crankshaft angle */
void Crank_AngleCalc(){
Crank_TeethCounter();
Crank_Angle = 360*(Crank_TeethCount-1)/(Crank_TeethNmbr_P+Crank_MissingTeethNmbr_P);
}
/* Used to synchronise angle calculation considering twice slower rotation of camshaft */
void Crank_CamPositionSync(){
Engine_Angle = Crank_Angle + Cam_CycleStart*360;
}
<file_sep>/Core/Src/main.c
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2020 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <string.h>
#include <stdio.h>
#include "interruptConfig.h"
#include "ignition.h"
#include "crankshaft.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
int triggerTooth;
float triggerAngle;
float delayAngle;
uint32_t timeToIgnition;
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
TIM_HandleTypeDef htim2;
TIM_HandleTypeDef htim21;
TIM_HandleTypeDef htim22;
/* USER CODE BEGIN PV */
uint32_t captures[2];
volatile uint8_t captureDone = 0;
//volatile float frequency = 0;
//volatile float period = 0;
uint16_t count = 0;
uint32_t diffCapture = 0;
__IO uint32_t IgniteDwellTime = 1000;
uint8_t Crank_HalfCycleFlag = 0;
int angleToIgnite = 120;
int currentToothAngle = 0;
// HAL GEBER DECLARATIONS
//uint32_t CrankShaftFreqHz = 0;
//uint32_t *pCrankShaftFreqHz = &crankShaftFreqHz;
//int adcVal;
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_TIM2_Init(void);
static void MX_TIM22_Init(void);
static void MX_TIM21_Init(void);
static void MX_NVIC_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_TIM2_Init();
MX_TIM22_Init();
MX_TIM21_Init();
/* Initialize interrupts */
MX_NVIC_Init();
/* USER CODE BEGIN 2 */
// Start all TIM channels and Interrupts related to TIM
HAL_TIM_OnePulse_Start_IT(&htim22, TIM_CHANNEL_1);
//HAL_TIM_OnePulse_Start_IT(&htim22, TIM_CHANNEL_2);
HAL_TIM_Base_Start_IT(&htim22);
/*
//HAL_TIM_IC_Start_DMA(&htim2, HAL_TIM_ACTIVE_CHANNEL_2, (uint32_t*) captures, 2);
//HAL_TIM_Base_Start_IT(&htim2);
//HAL_TIM_Base_Start_IT(&htim21);
*/
HAL_TIM_Base_Start_IT(&htim21);
HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_2);
HAL_TIM_OC_Start_IT(&htim21, TIM_CHANNEL_2);
HAL_Delay(500);
/* All module Inits */
Crank_Init();
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
//Ignition_SetIgnitionTiming(10,20,30);
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLLMUL_4;
RCC_OscInitStruct.PLL.PLLDIV = RCC_PLLDIV_2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief NVIC Configuration.
* @retval None
*/
static void MX_NVIC_Init(void)
{
/* TIM21_IRQn interrupt configuration */
HAL_NVIC_SetPriority(TIM21_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(TIM21_IRQn);
/* TIM22_IRQn interrupt configuration */
HAL_NVIC_SetPriority(TIM22_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(TIM22_IRQn);
/* TIM2_IRQn interrupt configuration */
HAL_NVIC_SetPriority(TIM2_IRQn, 1, 0);
HAL_NVIC_EnableIRQ(TIM2_IRQn);
/* EXTI4_15_IRQn interrupt configuration */
HAL_NVIC_SetPriority(EXTI4_15_IRQn, 2, 0);
HAL_NVIC_EnableIRQ(EXTI4_15_IRQn);
}
/**
* @brief TIM2 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM2_Init(void)
{
/* USER CODE BEGIN TIM2_Init 0 */
/* USER CODE END TIM2_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_IC_InitTypeDef sConfigIC = {0};
/* USER CODE BEGIN TIM2_Init 1 */
/* USER CODE END TIM2_Init 1 */
htim2.Instance = TIM2;
htim2.Init.Prescaler = 43;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 65535;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_IC_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_RISING;
sConfigIC.ICSelection = TIM_ICSELECTION_DIRECTTI;
sConfigIC.ICPrescaler = TIM_ICPSC_DIV1;
sConfigIC.ICFilter = 0;
if (HAL_TIM_IC_ConfigChannel(&htim2, &sConfigIC, TIM_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM2_Init 2 */
/* USER CODE END TIM2_Init 2 */
}
/**
* @brief TIM21 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM21_Init(void)
{
/* USER CODE BEGIN TIM21_Init 0 */
/* USER CODE END TIM21_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM21_Init 1 */
/* USER CODE END TIM21_Init 1 */
htim21.Instance = TIM21;
htim21.Init.Prescaler = 31;
htim21.Init.CounterMode = TIM_COUNTERMODE_UP;
htim21.Init.Period = 10000;
htim21.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim21.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
if (HAL_TIM_Base_Init(&htim21) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim21, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_OC_Init(&htim21) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim21, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_TIMING;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_OC_ConfigChannel(&htim21, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM21_Init 2 */
/* USER CODE END TIM21_Init 2 */
}
/**
* @brief TIM22 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM22_Init(void)
{
/* USER CODE BEGIN TIM22_Init 0 */
/* USER CODE END TIM22_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM22_Init 1 */
/* USER CODE END TIM22_Init 1 */
htim22.Instance = TIM22;
htim22.Init.Prescaler = 31;
htim22.Init.CounterMode = TIM_COUNTERMODE_UP;
htim22.Init.Period = 10;
htim22.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim22.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
if (HAL_TIM_Base_Init(&htim22) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim22, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_Init(&htim22) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_OnePulse_Init(&htim22, TIM_OPMODE_SINGLE) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim22, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 100;
sConfigOC.OCPolarity = TIM_OCPOLARITY_LOW;
sConfigOC.OCFastMode = TIM_OCFAST_ENABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim22, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim22, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM22_Init 2 */
//__HAL_TIM_ENABLE(&htim22);
/* USER CODE END TIM22_Init 2 */
HAL_TIM_MspPostInit(&htim22);
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{ GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_2|GPIO_PIN_3, GPIO_PIN_RESET);
/*Configure GPIO pins : PC2 PC3 */
GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/*Configure GPIO pin : PA8 */
GPIO_InitStruct.Pin = GPIO_PIN_8;
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING_FALLING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
/* USER CODE BEGIN 4 */
float angleOfIgnition = 120;
float tempAngle = 0;
void Scheduler_10ms(){
// Call all 10ms related functions
//HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_3);
IgniteDwellTime = 1000;
//TIM22->CCR1 = dwellTime;
//TIM22->ARR = 2500;
// angle to spark has to be small enough to fit in the speed but large enough to allow dwell
// dwell time around 2ms, means that one halfCycle is limited to min 2ms, which is 4ms for one crankshaft rotation which is 250hz with current method (works with 180hz and 130 degrees)
tempAngle = tempAngle + 0.1;
angleOfIgnition = tempAngle;
angleOfIgnition = 120;
if (tempAngle >= 90){
tempAngle = 0;
}
Ignition_SetIgnitionTiming(1,20,Crank_ShaftFreqHz,Crank_TeethNmbr_P,Crank_MissingTeethNmbr_P);
Ignition_SetIgnitionTiming(3,130,Crank_ShaftFreqHz,Crank_TeethNmbr_P,Crank_MissingTeethNmbr_P);
//Ignition_SetIgnitionTiming(2000,angleToIgnite,Crank_ShaftFreqHz);
//TIM22->CR1 |= TIM_CR1_CEN;
if (IgniteDwellTime >= 2000)
IgniteDwellTime = 1000;
else
IgniteDwellTime = IgniteDwellTime +1;
//HAL_Delay(100);
if (angleToIgnite >= 120){
angleToIgnite = 80;
}
else
angleToIgnite = angleToIgnite + 1;
angleToIgnite = 120;
}
void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim){
if(htim == &htim22){
// Ignition OPM TIM Channels
if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1){
// Cylinder 1
if (Ignition_CoilStateCyl1 == DWELL){
//GPIOC->BSRR = GPIO_PIN_3;
HAL_GPIO_WritePin(GPIOC,GPIO_PIN_3,GPIO_PIN_SET);
}
if (Ignition_CoilStateCyl1 == FIRE){
//GPIOC->BRR = GPIO_PIN_3;
HAL_GPIO_WritePin(GPIOC,GPIO_PIN_3,GPIO_PIN_RESET);
}
// Cylinder 3
if (Ignition_CoilStateCyl3 == DWELL){
//GPIOC->BSRR = GPIO_PIN_3; // TODO use different pin in future . the one that corresponds cyl3
HAL_GPIO_WritePin(GPIOC,GPIO_PIN_2,GPIO_PIN_SET);
}
if (Ignition_CoilStateCyl3 == FIRE){
//GPIOC->BRR = GPIO_PIN_3;; // TODO use different pin in future . the one that corresponds cyl3
HAL_GPIO_WritePin(GPIOC,GPIO_PIN_2,GPIO_PIN_RESET);
}
}
if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2){
//HAL_GPIO_WritePin(GPIOC,GPIO_PIN_3,GPIO_PIN_SET);
}
//HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_3);
}
}
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin){
//HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_3);
//HAL_GPIO_WritePin(GPIOC,GPIO_PIN_3,GPIO_PIN_RESET);
if (GPIO_Pin == GPIO_PIN_8){
if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_8))
Cam_CycleStart = 1;
else
Cam_CycleStart = 0;
}else{
__NOP();
}
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if(htim == &htim21){
// Call the 10ms task
Scheduler_10ms();
}else{
__NOP();
}
}
void HAL_TIM_IC_CaptureCallback( TIM_HandleTypeDef *htim ){
if(htim == &htim2){
if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2 ){
//HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_3);
// Ignite before halgeber driver, if the tooth is fine. There is huge delay (30-40us) in high speed9:
Crank_AngleCalc(); // roughly 10us computation time
//Cam_HalGeberDriver(####);
Crank_CamPositionSync();
Crank_HalfCycleFlag = 0; // every reset of the crankshaft (initial value) is start of a new cycle. halfCycle == 1 when we are in the 2nd part of camshaft rotation.
//htim2->Instance->CR1 = 1000;
//htim2.Instance->CR1 = 1000;
if (Crank_TeethCount == 1){
Ignition_StartTimerDwellCylinder(1,10);
//Ignition_FireCylinder(1);
}
if (Crank_TeethCount == Ignition_FireToothCyl1){
//HAL_GPIO_WritePin(GPIOC,GPIO_PIN_3,GPIO_PIN_SET);
Ignition_StartTimerFireCylinder(1);
}
if (Crank_TeethCount == 6){
Ignition_StartTimerDwellCylinder(3,10);
//Ignition_FireCylinder(1);
}
if (Crank_TeethCount == Ignition_FireToothCyl3){
//HAL_GPIO_WritePin(GPIOC,GPIO_PIN_3,GPIO_PIN_SET);
Ignition_StartTimerFireCylinder(3);
}
/*
if (Crank_TeethCount == 15){
//TIM22->CR1 |= TIM_CR1_CEN;
if (Crank_HalfCycleFlag == 0){
Ignition_FireCylinder(3,timeToIgnition);
}
else{
//Ignition_FireCylinderB(4);
}
}*/
Crank_HalGeberDriver(&htim2);
}
}else{
__NOP();
}
}
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/Core/Inc/ignition.h
/*
* ignition.h
*
* Created on: Sep 21, 2020
* Author: <NAME>
*/
#include "stm32l0xx_hal.h"
#ifndef INC_IGNITION_H_
#define INC_IGNITION_H_
extern int Ignition_DwellTimeUs; // Dwell Time shall be kept minimum 1.5ms
extern int *pAwellTimeUs; // Pointer to Dwell Time if needed
extern int Ignition_AngleDegree; // Angle degree to firing of cylinder from a given point.
extern int *pAngleDegree;
enum Ignition_CoilStates {
IDLE = 0,
DWELL = 1,
FIRE = 2
};
extern uint8_t Ignition_CoilStateCyl1;
extern uint8_t Ignition_CoilStateCyl2;
extern uint8_t Ignition_CoilStateCyl3;
extern uint8_t Ignition_CoilStateCyl4;
extern uint32_t Ignition_TimeToFire; // Time in us to firing a cylinder
extern int Ignition_FireToothCyl1; // Tooth at which the counter starts to count to align to correct angle for firing Cyl 1
extern int Ignition_FireToothCyl2; // Tooth at which the counter starts to count to align to correct angle for firing Cyl 2
extern int Ignition_FireToothCyl3; // Tooth at which the counter starts to count to align to correct angle for firing Cyl 3
extern int Ignition_FireToothCyl4; // Tooth at which the counter starts to count to align to correct angle for firing Cyl 4
extern int Ignition_DwellToothCyl1; // Tooth at which the counter starts to count to align to correct angle for dwelling Cyl 1
extern int Ignition_DwellToothCyl2; // Tooth at which the counter starts to count to align to correct angle for dwelling Cyl 2
extern int Ignition_DwellToothCyl3; // Tooth at which the counter starts to count to align to correct angle for dwelling Cyl 3
extern int Ignition_DwellToothCyl4; // Tooth at which the counter starts to count to align to correct angle for dwelling Cyl 4
extern void Ignition_SetIgnitionTiming(int CylId, int AngleOfIgnition, int CrankShaftHz, uint8_t CrankTeethNmbr, uint8_t CrankMissingTeethNmbr);
extern void Ignition_StartTimerFireCylinder(int CylId); // Release Dwelling and Fire the spar
extern void Ignition_StartTimerDwellCylinder(int CylId, int dwellStartInUs);
extern uint32_t Ignition_AngleToUs(int CrankShaftHz, float AngleDegree);
#endif /* INC_IGNITION_H_ */
| 0ce88860181973c6f8d63e2e13dc7982aa66412e | [
"C"
] | 6 | C | aljazjelen/ECU-Mark1-OLD | ad6e7a2b183c20adb6506a49c605701984c28e71 | 0eb625b8f7da7d34e26ad1e96f07671318865299 |
refs/heads/master | <repo_name>wpyin/xuelei<file_sep>/export.php
<?php
$dir=dirname(__FILE__);//查找当前脚本所在路径
require $dir."/PHPExcel/PHPExcel.php";//引入PHPExcel
require $dir."/db.php";//引入mysql操作类文件
$db = new db($phpexcel);//实例化db类
$objPHPExcel=new PHPExcel();//实例化phpexcel类 等同于创建一个excel
for ($i=1; $i <8 ; $i++) {
if($i>1){
$objPHPExcel->createSheet();
}
$objPHPExcel->setActiveSheetIndex($i-1);
$objSheet=$objPHPExcel->getActiveSheet();//获取当前活动sheet
$objSheet->setTitle($i."周");
//判断第几天
if($i == '1'){
$weeknum = '一';
}
if($i == '2'){
$weeknum = '二';
}
if($i == '3'){
$weeknum = '三';
}
if($i == '4'){
$weeknum = '四';
}
if($i == '5'){
$weeknum = '五';
}
if($i == '6'){
$weeknum = '六';
}
if($i == '7'){
$weeknum = '日';
}
$data=$db->getDataByWeek($weeknum);
//print_r($data);die;
$objSheet->setCellValue("A1","编号")->setCellValue("B1","姓名")->setCellValue("C1","教室")->setCellValue("D1","节次");//填充数据
$j=2;
foreach ($data as $key => $val) {
$objSheet->setCellValue("A".$j,$val['id'])->setCellValue("B".$j,$val['name'])->setCellValue("C".$j,$val['jiaoshi'])->setCellValue("D".$j,$val['danwei']);
$j++;
}
}
$objWriter=PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');//生成excel文件
$objWriter->save($dir."/export_1.xls");//保存文件
?><file_sep>/另一种方法/test.php
<?php
header("Content-Type:text/html; charset=utf8");
require_once("./user.class.php");
$user = new User("HelloWorld","123456");
//$user->insert();
//$users = User::getAllUser();
$users= $user->getUserByName("SELECT * FROM kebiao ");
foreach ($users as $u) {
echo "<br/>".$u->name."<br/>".$u->danwei."<br/>";
}
?> | 842735c5e1f6453154f01ae9e5e44c4e67f10b55 | [
"PHP"
] | 2 | PHP | wpyin/xuelei | 6cb8b007f95833f3e05a6380256048358d7b05f8 | 44ca859e3a08db6c56fda011cb7451990ca960ee |
refs/heads/master | <repo_name>Jacklwln/motion_planning_nearest_neighbours<file_sep>/README.md
# motion_planning_nearest_neighbours
MPNN, kd-tree nearest neighbor implementation for mixed topologies based on Yershova and LaValle's paper.
So to compile: g++ -std=c++14 -o main main.cpp -larmadillo -lGLEW -lGL -lglfw
The kd-tree works in layers, and you pass the topology for each coordinate (0 = real line, 1 = circle (S_1) ), and bounds...
bounds for the S_1 layers are [0,1]. Sorry!
The example is a kd-tree on a torus; which is a cartesian product S_1 x S_1. Added an extra parameter for the sake of experimentation.

The red point is the nearest neighbour, on a torus, to the position of the mouse.
The yellow points are the K nearest neighbours of the mouse.
May later be used for a RRT implementation.
<file_sep>/main.cpp
#include <GL/glew.h>
#include <GL/gl.h>
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <stdio.h>
#include "mpnn.hpp"
#include <cmath>
#include <armadillo>
using namespace arma;
using namespace std;
GLFWwindow * window = nullptr;
static void error_callback(int error, const char* description)
{
fputs(description, stderr);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
vec mouse_x = zeros<vec>(2);
int win_x = 640;
int win_y = 640;
static void cursor_callback(GLFWwindow* window, double x, double y)
{
mouse_x(0) = x / win_x;
mouse_x(1) = 1.0 - y / win_y;
}
int init_gl_window()
{
glfwSetErrorCallback(error_callback);
if (!glfwInit())
return -1;
window = glfwCreateWindow(win_x,win_y,"Nearest Neighbor on Torus",nullptr,nullptr);
if (!window)
{
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glewInit();
glfwSwapInterval(1);
glfwSetKeyCallback(window, key_callback);
glfwSetCursorPosCallback(window, cursor_callback);
return 0;
}
void recurse(kd_node * & node)
{
if(node == nullptr) return;
glBegin(GL_LINE_LOOP);
glColor3d(0.0,0.0,0.0);
glVertex2d(2.0*node->l_x(0)-1.0,2.0*node->l_x(1)-1.0);
glVertex2d(2.0*node->h_x(0)-1.0,2.0*node->l_x(1)-1.0);
glVertex2d(2.0*node->h_x(0)-1.0,2.0*node->h_x(1)-1.0);
glVertex2d(2.0*node->l_x(0)-1.0,2.0*node->h_x(1)-1.0);
glEnd();
if(node->l)
recurse(node->l);
if(node->r)
recurse(node->r);
}
int main(int argc,char ** argv)
{
srand(time(nullptr));
if(init_gl_window()<0) return -1;
float t = 0.;
vec mu = ones<vec>(2);
ivec topo = ones<ivec>(2);
kd_tree T(ones<vec>(2),ones<ivec>(2),zeros<vec>(2),ones<vec>(2));
mat X = randu<mat>(2,atoi(argv[1]));
for(int i=0;i<X.n_cols;i++)
{
T.insert(X.col(i));
}
mat Y = 2.0*X-1.0;
while (!glfwWindowShouldClose(window))
{
glfwGetFramebufferSize(window, &win_x, &win_y);
glViewport(0, 0, win_x, win_y);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glClearColor(1.0,1.0,1.0,1.0);
recurse(T.root);
glPointSize(5);
glBegin(GL_POINTS);
glColor3d(0.0,1.0,0.0);
glVertex2d(2.0*mouse_x(0)-1.0,2.0*mouse_x(1)-1.0);
uvec n_idx = zeros<uvec>(20);
T.searchK(mouse_x,n_idx);
for(uword i=0;i<X.n_cols;i++)
{
int idx = -1;
for(uword k=0;k<n_idx.n_elem;k++)
if(n_idx[k] == i)
{
idx = k;
break;
}
if(idx < 0)
glColor3d(0.0,0.0,1.0);
else if(idx == 0)
glColor3d(1.0,0.0,0.0);
else
glColor3d(1.0,1.0,0.0);
glVertex2d(Y(0,i),Y(1,i));
}
glEnd();
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| e9e2355bd025c290627604a6f4df746feacfca20 | [
"Markdown",
"C++"
] | 2 | Markdown | Jacklwln/motion_planning_nearest_neighbours | 623e4f0cf97bd9e16fd9eceaee050fcf59001ea5 | 1876d1187c45925973a02b46d668149d3d553dee |
refs/heads/master | <file_sep>.PHONY: clean
SHA1 = $(shell git rev-parse --short HEAD)
GIT_TAG = $(shell git describe --abbrev=0 --tags | sed 's/\./-/g')
install:
bundle install --path vendor
clean:
rm -rf _site/
rm -rf .sass-cache/
build-latest: clean
bundle exec jekyll build --baseurl /latest
build-tag: clean
bundle exec jekyll build --baseurl /$(GIT_TAG)
build-dev: clean
bundle exec jekyll build --baseurl /dev
build-commit: clean
bundle exec jekyll build --baseurl /$(SHA1)
serve-latest: clean
bundle exec jekyll serve --baseurl /latest
serve-tag: clean
bundle exec jekyll serve --baseurl /$(GIT_TAG)
serve-dev: clean
bundle exec jekyll serve --baseurl /dev
serve-commit: clean
bundle exec jekyll serve --baseurl /$(SHA1)
<file_sep>======================================
Contributing to Sceptre Migration Tool
======================================
Thanks for your interest in Sceptre Migration Tool! We greatly appreciate any contributions to the project.
- `Code of Conduct`_
- `How to Contribute`_
- `Report Bugs`_
- `Enhancement Proposal`_
- `Contributing Code`_
- `Get Started`_
- `Credits`_
Code of Conduct
---------------
This project adheres to the Contributor Covenant `code of conduct <http://contributor-covenant.org/version/1/4/>`_. By participating, you are expected to uphold this code. Please report unacceptable behaviour to <EMAIL>.
How to Contribute
-----------------
Report Bugs
***********
Before submitting a bug, please check our `issues page <https://github.com/oazmon/sceptre_migration_tool/issues>`_ to see if it's already been reported.
When reporting a bug, fill out the required template, and please include as much detail as possible as it helps us resolve issues faster.
Enhancement Proposal
********************
Enhancement proposals should:
* Use a descriptive title.
* Provide a step-by-step description of the suggested enhancement.
* Provide specific examples to demonstrate the steps.
* Describe the current behaviour and explain which behaviour you expected to see instead.
* Keep the scope as narrow as possible, to make it easier to implement.
Contributing Code
*****************
Contributions should be made in response to a particular GitHub Issue. We find it easier to review code if we've already discussed what it should do, and assessed if it fits with the wider codebase.
Beginner friendly issues are marked with the ``beginner friendly`` tag. We'll endeavour to write clear instructions on what we want to do, why we want to do it, and roughly how to do it. Feel free to ask us any questions that may arise.
A good pull request:
* Is clear.
* Works across all supported version of Python.
* Complies with the existing codebase style (`flake8 <http://flake8.pycqa.org/en/latest/>`_, `pylint <https://www.pylint.org/>`_).
* Includes `docstrings <https://www.python.org/dev/peps/pep-0257/>`_ and comments for unintuitive sections of code.
* Includes documentation for new features.
* Includes tests cases that demonstrates the previous flaw that now passes with the included patch, or demonstrates the newly added feature. Tests should have 100% code coverage.
* Is appropriately licensed (Apache 2.0).
Please keep in mind:
* The benefit of contribution must be compared against the cost of maintaining the feature, as maintenance burden of new contributions are usually put on the maintainers of the project.
Get Started
-----------
1. Fork the ``sceptre_migration_tool`` repository on GitHub.
2. Clone your fork locally::
$ git clone <EMAIL>:<github_username>/sceptre_migration_tool.git
3. Install sceptre migration tool for development (we recommend you use a `virtual environment <http://docs.python-guide.org/en/latest/dev/virtualenvs/>`_):
.. code-block:: shell
$ cd sceptre_migration_tool/
$ pip install -r requirements.txt
$ pip install -e .
4. Create a branch for local development:
.. code-block:: shell
$ git checkout -b <branch-name>
5. When you're done making changes, check that your changes pass linting, unit tests and have sufficient coverage:
Check linting:
.. code-block:: shell
$ make lint
Run unit tests or coverage in your current environment - (handy for quickly running unit tests):
.. code-block:: shell
$ make test
$ make coverage
Note: Sceptre Migration Tool aims to be compatible with Python 2 & 3, please run unit test against both versions. You will need the corresponding versions of Python installed on your system.
Run unit tests and coverage using tox for Python 2.7 and 3.6:
.. code-block:: shell
$ tox -e py27
$ tox -e py36
If you use pyenv to manage Python versions, try `pip install tox-pyenv` to make tox and pyenv play nicely.
6. Make sure the changes comply with the pull request guidelines in the section on `Contributing Code`_.
7. Commit and push your changes.
Commit messages should follow `these guidelines <https://github.com/erlang/otp/wiki/Writing-good-commit-messages>`_.
Use the following commit message format ``[Resolves #issue_number] Short description of change``.
e.g. ``[Resolves #123] Fix description of resolver syntax in documentation``
8. Submit a pull request through the GitHub website.
Credits
-------
This document took inspiration from the CONTRIBUTING files of the `Atom <https://github.com/atom/atom/blob/abccce6ee9079fdaefdecb018e72ea64000e52ef/CONTRIBUTING.md>`_ and `Boto3 <https://github.com/boto/boto3/blob/e85febf46a819d901956f349afef0b0eaa4d906d/CONTRIBUTING.rst>`_ projects.
<file_sep># -*- coding: utf-8 -*-
"""
sceptre_migration_tool.importer.environment
This module imports config and templates from
AWS for a given stack or environment.
"""
from __future__ import print_function
import os
import logging
import sys
from sceptre.connection_manager import ConnectionManager
from sceptre.environment import Environment
from . import stack
from .migration_environment import MigrationEnvironment
import_stack_list = []
def import_stack(env, aws_stack_name, sceptre_stack_path, template_path):
config_path = "/".join([env.path, sceptre_stack_path])
logger = logging.getLogger(__name__)
logger.info("%s - Importing stack", config_path)
migration_environment = _create_migration_environment(env)
stack.import_stack(
migration_environment=migration_environment,
aws_stack_name=aws_stack_name,
template_path=template_path,
config_path=config_path
)
logger.info("%s - Stack imported", config_path)
def import_env(env):
logger = logging.getLogger(__name__)
logger.info("%s - Importing environment", env.path)
migration_environment = _create_migration_environment(env)
describe_stacks_kwargs = {}
while True:
response = migration_environment.connection_manager.call(
service='cloudformation',
command='describe_stacks',
kwargs=describe_stacks_kwargs
)
for aws_stack in response['Stacks']:
stack.import_stack(
migration_environment=migration_environment,
aws_stack_name=aws_stack['StackName'],
template_path=os.path.join(
'templates',
'aws-import',
aws_stack['StackName'] + '.yaml'
),
config_path="/".join([env.path, aws_stack['StackName']])
)
if 'NextToken' not in response or not response['NextToken']:
break
describe_stacks_kwargs['NextToken'] = response['NextToken']
logger.info("%s - Environment imported", env.path)
def _ensure_env_dir_exists(sceptre_dir, env_path):
abs_path = os.path.join(
sceptre_dir,
env_path.replace("\\", "/")
)
if(not os.path.isdir(abs_path)):
os.makedirs(abs_path)
def import_list(sceptre_dir, options, list_fobj):
logger = logging.getLogger(__name__)
logger.info("Importing from list")
global import_stack_list
import_stack_list = MigrationEnvironment.read_import_stack_list(list_fobj)
for item in import_stack_list:
import_stack(
Environment(
sceptre_dir=sceptre_dir,
environment_path=item[MigrationEnvironment.PART_ENV],
options=options
),
item[MigrationEnvironment.PART_AWS_STACK_NAME],
item[MigrationEnvironment.PART_SCEPTRE_STACK_NAME],
item[MigrationEnvironment.PART_TEMPLATE_PATH]
)
def generate_import_list(env, list_file_obj=sys.stdout):
logger = logging.getLogger(__name__)
logger.info("Generating Import List")
migration_environment = _create_migration_environment(env)
describe_stacks_kwargs = {}
while True:
response = migration_environment.connection_manager.call(
service='cloudformation',
command='describe_stacks',
kwargs=describe_stacks_kwargs
)
for aws_stack in response['Stacks']:
_output_list_line(env.path, aws_stack, list_file_obj)
if 'NextToken' not in response or not response['NextToken']:
break
describe_stacks_kwargs['NextToken'] = response['NextToken']
def _output_list_line(env_path, aws_stack, list_file_obj):
print(
env_path,
aws_stack['StackName'],
aws_stack['StackName'],
os.path.join(
'templates',
'aws-import',
aws_stack['StackName'] + '.yaml'
),
file=list_file_obj
)
def _create_migration_environment(env):
env_config = env._get_config()
connection_manager = ConnectionManager(
region=env_config.get("region"),
iam_role=env_config.get("iam_role"),
profile=env_config.get("profile")
)
migration_environment = \
MigrationEnvironment(connection_manager, env_config, import_stack_list)
return migration_environment
<file_sep>
import logging
import os
from click.testing import CliRunner
from mock import patch, sentinel
from sceptre_migration_tool import cli
class TestCli(object):
def setup_method(self, test_method):
self.runner = CliRunner()
def test_setup_logging_with_debug(self):
logger = cli.setup_logging(True)
assert logger.getEffectiveLevel() == logging.DEBUG
assert logging.getLogger("botocore").getEffectiveLevel() == \
logging.INFO
# Silence logging for the rest of the tests
logger.setLevel(logging.CRITICAL)
def test_setup_logging_without_debug(self):
logger = cli.setup_logging(False)
assert logger.getEffectiveLevel() == logging.INFO
assert logging.getLogger("botocore").getEffectiveLevel() == \
logging.CRITICAL
# Silence logging for the rest of the tests
logger.setLevel(logging.CRITICAL)
@patch("sceptre_migration_tool.migrator.import_stack")
@patch("sceptre_migration_tool.cli.os.getcwd")
@patch("sceptre_migration_tool.cli.Environment")
def test_import_stack_default_template_dir(
self, mock_env, mock_getcwd, mock_import_stack
):
mock_getcwd.return_value = sentinel.cwd
result = self.runner.invoke(
cli.cli,
["import-stack", "dev", "vpc", "fake-aws-stack"]
)
assert result.exit_code == 0
mock_env.assert_called_with(
sceptre_dir=sentinel.cwd,
environment_path=u'dev',
options={}
)
fake_template_path = os.path.join(
"templates",
"fake-aws-stack.yaml"
)
mock_import_stack.assert_called_with(
mock_env.return_value,
"fake-aws-stack",
"vpc",
fake_template_path
)
@patch("sceptre_migration_tool.migrator.import_stack")
@patch("sceptre_migration_tool.cli.os.getcwd")
@patch("sceptre_migration_tool.cli.Environment")
def test_import_stack_user_template_dir(
self, mock_env, mock_getcwd, mock_import_stack
):
mock_getcwd.return_value = sentinel.cwd
fake_template_path = "user-templates/fake-aws-stack.yaml"
result = self.runner.invoke(cli.cli, [
"import-stack",
"--template", fake_template_path,
"dev",
"vpc",
"fake-aws-stack"
]
)
assert 0 == result.exit_code
mock_env.assert_called_with(
sceptre_dir=sentinel.cwd,
environment_path=u'dev',
options={}
)
mock_import_stack.assert_called_with(
mock_env.return_value,
"fake-aws-stack",
"vpc",
fake_template_path
)
@patch("sceptre_migration_tool.migrator.import_env")
@patch("sceptre_migration_tool.cli.os.getcwd")
@patch("sceptre_migration_tool.cli.Environment")
def test_import_env(
self, mock_env, mock_getcwd, mock_import_env
):
mock_getcwd.return_value = sentinel.cwd
result = self.runner.invoke(cli.cli, ["import-env", "dev"])
assert 0 == result.exit_code
mock_env.assert_called_with(
sceptre_dir=sentinel.cwd,
environment_path=u'dev',
options={}
)
mock_import_env.assert_called_with(
mock_env.return_value
)
@patch("sceptre_migration_tool.cli.migrator.import_list")
@patch("sceptre_migration_tool.cli.open")
@patch("sceptre_migration_tool.cli.os.getcwd")
def test_import_list(
self, mock_getcwd, mock_open, mock_import_list
):
mock_getcwd.return_value = sentinel.cwd
result = self.runner.invoke(cli.cli, [
"import-list", "--list-path", "fake-list-path"
])
assert 0 == result.exit_code
mock_import_list.assert_called_once_with(
sentinel.cwd,
{},
mock_open.return_value.__enter__.return_value
)
@patch("sceptre_migration_tool.cli.migrator.generate_import_list")
@patch("sceptre_migration_tool.cli.open")
@patch("sceptre_migration_tool.cli.Environment")
@patch("sceptre_migration_tool.cli.os.getcwd")
def test_generate_import_list(
self, mock_getcwd, mock_import_env,
mock_open, mock_generate_import_list
):
mock_getcwd.return_value = sentinel.cwd
result = self.runner.invoke(cli.cli, [
"generate-import-list", "dev", "--list-path", "fake-list-path"
])
assert 0 == result.exit_code
mock_generate_import_list.assert_called_once_with(
mock_import_env.return_value,
mock_open.return_value.__enter__.return_value
)
@patch("sceptre_migration_tool.cli.migrator.generate_import_list")
@patch("sceptre_migration_tool.cli.open")
@patch("sceptre_migration_tool.cli.Environment")
@patch("sceptre_migration_tool.cli.os.getcwd")
def test_generate_import_list__to_stdout(
self, mock_getcwd, mock_import_env,
mock_open, mock_generate_import_list
):
mock_getcwd.return_value = sentinel.cwd
result = self.runner.invoke(cli.cli, [
"generate-import-list", "dev"
])
assert 0 == result.exit_code
mock_open.assert_not_called()
mock_generate_import_list.assert_called_once()
<file_sep>'''
Created on Nov 29, 2017
@author: <NAME>
'''
import re
from sceptre_migration_tool.reverse_resolvers import ReverseResolver
class ReverseIntuitAmi(ReverseResolver):
def __init__(self, *args, **kwargs):
super(ReverseIntuitAmi, self).__init__(*args, **kwargs)
def precendence(self):
return 90
def suggest(self, value):
suggestion = '!intuit_ami' \
if re.match('ami-[0-9a-f]+$', value) else None
self.logger.debug(
"IntuitAmi Suggestion for '%s' is '%s'",
value,
suggestion
)
return suggestion
<file_sep>
from mock import Mock
from sceptre_migration_tool.reverse_resolvers.reverse_intuit_ami\
import ReverseIntuitAmi
from sceptre_migration_tool.migration_environment import MigrationEnvironment
class MockConfig(dict):
pass
class TestReverseIntuitAmi(object):
def setup_method(self, test_method):
self.mock_connection_manager = Mock()
self.mock_environment_config = MockConfig()
self.mock_environment_config['user_variables'] = {}
self.reverse_intuit_ami = ReverseIntuitAmi(
MigrationEnvironment(
connection_manager=self.mock_connection_manager,
environment_config=self.mock_environment_config
)
)
def test_config_correctly_initialised(self):
assert self.reverse_intuit_ami.migration_environment\
.connection_manager == self.mock_connection_manager
assert self.reverse_intuit_ami.migration_environment\
.environment_config == self.mock_environment_config
assert self.reverse_intuit_ami.precendence() == 90
def test_suggest1(self):
assert self.reverse_intuit_ami.suggest("value") is None
def test_suggest2(self):
assert self.reverse_intuit_ami.suggest("ami") is None
def test_suggest3(self):
assert self.reverse_intuit_ami.suggest("ami-") is None
def test_suggest4(self):
assert self.reverse_intuit_ami.suggest(" ami-1") is None
def test_suggest5(self):
assert self.reverse_intuit_ami.suggest("ami-1 ") is None
def test_suggest6(self):
assert self.reverse_intuit_ami.suggest("ami-1 1") is None
def test_suggest7(self):
assert self.reverse_intuit_ami.suggest("ami-1") == '!intuit_ami'
def test_suggest8(self):
assert self.reverse_intuit_ami.suggest("ami-6f46da0f") == '!intuit_ami'
<file_sep>---
layout: docs
---
# FAQ
## What format template does the migration tool create?
The tool creates by default YAML files from the AWS CloudFormation Template, unless the --template option is used.
In that case, it produces either .json or .yaml depending on what the user specified.<file_sep>'''
Created on Nov 29, 2017
@author: <NAME>
'''
from sceptre_migration_tool.reverse_resolvers import ReverseResolver
class ReverseStackOutput(ReverseResolver):
def __init__(self, *args, **kwargs):
super(ReverseStackOutput, self).__init__(*args, **kwargs)
self._stack_output = None
self._stack_output_external = None
def precendence(self):
return 20
def suggest(self, value):
if self._stack_output is None:
self._get_stack_output()
if value in self._stack_output:
stack_name, suggestion = self._stack_output[value]
if stack_name == self.migration_environment.config_path:
suggestion = None
self.logger.debug(
"%s - Internal Stack Suggestion for '%s' is '%s'",
self.migration_environment.config_path,
value,
suggestion
)
return suggestion
if value in self._stack_output_external:
stack_name, suggestion = self._stack_output_external[value]
self.logger.debug(
"%s - External Stack Suggestion for '%s' is '%s'",
self.migration_environment.config_path,
value,
suggestion
)
return suggestion
self.logger.debug(
"%s - Stack Suggestion for '%s' is 'None'",
self.migration_environment.config_path,
value
)
return None
def _get_stack_output(self):
"""
Communicates with AWS Cloudformation to fetch stack outputs.
It updates both self._stack_outputs and self._stack_output_external
with reverse indexes of stack output
"""
self.logger.debug("Collecting stack outputs...")
self._stack_output = {}
self._stack_output_external = {}
list_stacks_kwargs = {}
while True:
response = self.migration_environment.connection_manager.call(
service="cloudformation",
command="describe_stacks",
kwargs=list_stacks_kwargs
)
for stack in response["Stacks"]:
self._build_reverse_lookup(stack)
if 'NextToken' in response \
and response['NextToken'] is not None:
list_stacks_kwargs = {'NextToken': response['NextToken']}
else:
break
self.logger.debug("Outputs: %s", self._stack_output)
self.logger.debug("Outputs external: %s", self._stack_output)
def _build_reverse_lookup(self, stack):
if 'Outputs' not in stack or not stack['Outputs']:
return
# internal_stack_name = \
# self.migration_environment.get_internal_stack(stack['StackName'])
# if internal_stack_name:
# self._build_internal_stack_lookup(
# internal_stack_name,
# stack['Outputs']
# )
# else:
self._build_external_stack_lookup(
stack['StackName'],
stack['Outputs']
)
def _build_internal_stack_lookup(self, stack_name, outputs):
for output in outputs:
self._add_to_reverse_lookup(
stack_name=stack_name,
output=output,
target_dict=self._stack_output,
resolver_name="stack_output"
)
def _build_external_stack_lookup(self, stack_name, outputs):
for output in outputs:
self._add_to_reverse_lookup(
stack_name=stack_name,
output=output,
target_dict=self._stack_output_external,
resolver_name="stack_output_external"
)
def _add_to_reverse_lookup(
self, stack_name, output, target_dict, resolver_name
):
if 'ExportName' in output:
return
key = output['OutputKey']
value = output['OutputValue']
if value in target_dict:
self.logger.warning(
"Skipping %s stack reverse lookup."
" Duplicate Value: key=%s, value=%s",
stack_name, key, value
)
return
target_dict[value] = (
stack_name,
"!{} '{}::{}'".format(resolver_name, stack_name, key)
)
<file_sep>from behave import given, when, then
import time
import os
from botocore.exceptions import ClientError
from sceptre.environment import Environment
from helpers import read_template_file, get_cloudformation_stack_name
from helpers import retry_boto_call
@given('stack "{stack_name}" does not exist') # noqa: F811
def step_impl(context, stack_name):
full_name = get_cloudformation_stack_name(context, stack_name)
status = get_stack_status(context, full_name)
if status is not None:
delete_stack(context, full_name)
status = get_stack_status(context, full_name)
assert (status is None)
@given('stack "{stack_name}" exists in "{desired_status}" state') # noqa: F811
def step_impl(context, stack_name, desired_status):
full_name = get_cloudformation_stack_name(context, stack_name)
status = get_stack_status(context, full_name)
if status != desired_status:
delete_stack(context, full_name)
if desired_status == "CREATE_COMPLETE":
body = read_template_file(context, "valid_template.json")
create_stack(context, full_name, body)
elif desired_status == "CREATE_FAILED":
body = read_template_file(context, "invalid_template.json")
kwargs = {"OnFailure": "DO_NOTHING"}
create_stack(context, full_name, body, **kwargs)
elif desired_status == "UPDATE_COMPLETE":
body = read_template_file(context, "valid_template.json")
create_stack(context, full_name, body)
body = read_template_file(context, "updated_template.json")
update_stack(context, full_name, body)
elif desired_status == "ROLLBACK_COMPLETE":
body = read_template_file(context, "invalid_template.json")
kwargs = {"OnFailure": "ROLLBACK"}
create_stack(context, full_name, body, **kwargs)
status = get_stack_status(context, full_name)
assert (status == desired_status)
@given('stack "{stack_name}" exists using "{template_name}"') # noqa: F811
def step_impl(context, stack_name, template_name):
full_name = get_cloudformation_stack_name(context, stack_name)
status = get_stack_status(context, full_name)
if status != "CREATE_COMPLETE":
delete_stack(context, full_name)
body = read_template_file(context, template_name)
create_stack(context, full_name, body)
status = get_stack_status(context, full_name)
assert (status == "CREATE_COMPLETE")
@given('stack "{stack_name}" does not exist in config') # noqa: F811
def step_impl(context, stack_name):
filepath = os.path.join(
context.sceptre_dir, "config", stack_name + '.yaml'
)
os.remove(filepath) if os.path.isfile(filepath) else None
@when('the user imports AWS stack "{aws_stack_name}" into ' # noqa: F811
'Sceptre stack "{stack_name}" and template "{template_name}"')
def step_impl(context, aws_stack_name, stack_name, template_name):
full_aws_stack_name = get_cloudformation_stack_name(
context,
aws_stack_name
)
env = Environment(context.sceptre_dir, os.path.dirname(stack_name))
stack_base_name = os.path.basename(stack_name)
context.response = env.import_stack(
full_aws_stack_name,
stack_base_name,
template_name
)
@then('stack "{stack_name}" exists in "{desired_status}" state') # noqa: F811
def step_impl(context, stack_name, desired_status):
full_name = get_cloudformation_stack_name(context, stack_name)
status = get_stack_status(context, full_name)
assert (status == desired_status)
@then('stack "{stack_name}" does not exist') # noqa: F811
def step_impl(context, stack_name):
full_name = get_cloudformation_stack_name(context, stack_name)
status = get_stack_status(context, full_name)
assert (status is None)
@then('stack "{stack_name}" file exists in config') # noqa: F811
def step_impl(context, stack_name):
filepath = os.path.join(
context.sceptre_dir, "config", stack_name + '.yaml'
)
assert os.path.exists(
filepath
), "stack '{}' not found at '{}'".format(stack_name, filepath)
def get_stack_status(context, stack_name):
try:
stack = retry_boto_call(context.cloudformation.Stack, stack_name)
retry_boto_call(stack.load)
return stack.stack_status
except ClientError as e:
if e.response['Error']['Code'] == 'ValidationError' \
and e.response['Error']['Message'].endswith("does not exist"):
return None
else:
raise e
def create_stack(context, stack_name, body, **kwargs):
retry_boto_call(
context.client.create_stack,
StackName=stack_name, TemplateBody=body, **kwargs
)
wait_for_final_state(context, stack_name)
def update_stack(context, stack_name, body, **kwargs):
stack = retry_boto_call(context.cloudformation.Stack, stack_name)
retry_boto_call(stack.update, TemplateBody=body, **kwargs)
wait_for_final_state(context, stack_name)
def delete_stack(context, stack_name):
stack = retry_boto_call(context.cloudformation.Stack, stack_name)
retry_boto_call(stack.delete)
waiter = context.client.get_waiter('stack_delete_complete')
waiter.config.delay = 4
waiter.config.max_attempts = 240
waiter.wait(StackName=stack_name)
def wait_for_final_state(context, stack_name):
stack = retry_boto_call(context.cloudformation.Stack, stack_name)
delay = 2
max_retries = 150
attempts = 0
while attempts < max_retries:
retry_boto_call(stack.load)
if not stack.stack_status.endswith("IN_PROGRESS"):
return
attempts += 1
time.sleep(delay)
raise Exception("Timeout waiting for stack to reach final state.")
<file_sep>
from mock import Mock, patch
from sceptre_migration_tool.reverse_resolvers.reverse_exports\
import ReverseExports
from sceptre_migration_tool.migration_environment import MigrationEnvironment
class MockConfig(dict):
pass
class TestReverseExports(object):
def setup_method(self, test_method):
self.mock_connection_manager = Mock()
self.mock_environment_config = MockConfig()
self.mock_environment_config['user_variables'] = {}
self.reverse_exporter = ReverseExports(
MigrationEnvironment(
connection_manager=self.mock_connection_manager,
environment_config=self.mock_environment_config
)
)
def test_config_correctly_initialised(self):
assert self.reverse_exporter.migration_environment\
.connection_manager == self.mock_connection_manager
assert self.reverse_exporter.migration_environment\
.environment_config == self.mock_environment_config
assert self.reverse_exporter.precendence() == 10
@patch("sceptre_migration_tool.reverse_resolvers.reverse_exports."
"ReverseExports._get_exports")
def test_suggest__no_suggestions(self, mock_get_exports):
mock_get_exports.return_value = {}
assert self.reverse_exporter.suggest("value") is None
mock_get_exports.assert_called_once()
@patch("sceptre_migration_tool.reverse_resolvers.reverse_exports."
"ReverseExports._get_exports")
def test_suggest__has_suggestions(self, mock_get_exports):
mock_get_exports.return_value = {'value': '!stack_export key'}
assert self.reverse_exporter.suggest("value") == '!stack_export key'
mock_get_exports.assert_called_once()
def test__get_exports__none_found(self):
self.mock_connection_manager.call.return_value = {
'Exports': []
}
result = self.reverse_exporter._get_exports()
assert result == {}
self.mock_connection_manager.call.assert_called_once_with(
service="cloudformation",
command="list_exports",
kwargs={}
)
def test__get_exports__some_found(self):
self.mock_connection_manager.call.side_effect = [
{
'Exports': [
{
'Name': 'fake-key1',
'Value': 'fake-value1'
}
],
'NextToken': 'fake-next'
},
{
'Exports': [
{
'Name': 'fake-key2',
'Value': 'fake-value2'
},
{
'Name': 'fake-dup-key1',
'Value': 'fake-value1'
}
]
}
]
result = self.reverse_exporter._get_exports()
assert result == {
'fake-value1': "!stack_export 'fake-key1'",
'fake-value2': "!stack_export 'fake-key2'"
}
assert 2 == self.mock_connection_manager.call.call_count
self.mock_connection_manager.call.assert_any_call(
service="cloudformation",
command="list_exports",
kwargs={}
)
self.mock_connection_manager.call.assert_any_call(
service="cloudformation",
command="list_exports",
kwargs={'NextToken': 'fake-next'}
)
<file_sep># -*- coding: utf-8 -*-
from StringIO import StringIO
from mock import patch, sentinel, Mock, PropertyMock
from sceptre.environment import Environment
from sceptre_migration_tool.migration_environment import MigrationEnvironment
from sceptre_migration_tool import migrator
class TestMigrator_ensure_env_dir_exists(object):
@patch("sceptre_migration_tool.cli.os.makedirs")
@patch("sceptre_migration_tool.cli.os.path.isdir")
def test_is_dir(self, mock_isdir, mock_makedirs):
mock_isdir.return_value = True
migrator._ensure_env_dir_exists("sceptre_dir", "environment\\path")
mock_isdir.assert_called_once_with("sceptre_dir/environment/path")
mock_makedirs.assert_not_called()
@patch("sceptre_migration_tool.cli.os.makedirs")
@patch("sceptre_migration_tool.cli.os.path.isdir")
def test_is_NOT_dir(self, mock_isdir, mock_makedirs):
mock_isdir.return_value = False
migrator._ensure_env_dir_exists("sceptre_dir", "environment\\path")
mock_isdir.assert_called_once_with("sceptre_dir/environment/path")
mock_makedirs.assert_called_once_with("sceptre_dir/environment/path")
class TestMigrator(object):
@patch("sceptre.environment.Environment._load_stacks")
@patch(
"sceptre.environment.Environment.is_leaf", new_callable=PropertyMock
)
@patch("sceptre.environment.Environment._validate_path")
def setup_method(
self, test_method, mock_validate_path,
mock_is_leaf, mock_load_stacks
):
mock_is_leaf.return_value = True
mock_load_stacks.return_value = sentinel.stacks
mock_validate_path.return_value = "environment_path"
self.environment = Environment(
sceptre_dir="sceptre_dir",
environment_path="environment_path",
options=sentinel.options
)
# Run the rest of the tests against a leaf environment
self.environment._is_leaf = True
@patch("sceptre_migration_tool.stack.import_stack")
@patch("sceptre_migration_tool.migrator"
"._create_migration_environment")
def test_import_stack(
self, mock_migration_environment,
mock_import_stack
):
migrator.import_stack(
self.environment,
aws_stack_name='fake-aws-stack',
sceptre_stack_path='fake-sceptre-stack',
template_path='fake-template-path'
)
mock_import_stack.assert_called_once_with(
migration_environment=mock_migration_environment.return_value,
aws_stack_name='fake-aws-stack',
template_path='fake-template-path',
config_path='environment_path/fake-sceptre-stack'
)
@patch("sceptre_migration_tool.stack.import_stack")
@patch("sceptre_migration_tool.migrator"
"._create_migration_environment")
def test_import_env(
self, mock_migration_environment,
mock_import_stack
):
mock_connection_manager =\
mock_migration_environment.return_value.connection_manager
mock_connection_manager.call.side_effect = [
{
'Stacks': [
{
'StackName': 'fake-aws-stack1'
}
],
'NextToken': 'StackName2'
},
{
'Stacks': [
{
'StackName': 'fake-aws-stack2'
}
]
}
]
migrator.import_env(self.environment)
assert 2 == mock_import_stack.call_count
mock_import_stack.assert_any_call(
migration_environment=mock_migration_environment
.return_value,
aws_stack_name='fake-aws-stack1',
config_path='environment_path/fake-aws-stack1',
template_path='templates/aws-import/fake-aws-stack1.yaml'
)
mock_import_stack.assert_any_call(
migration_environment=mock_migration_environment
.return_value,
aws_stack_name='fake-aws-stack2',
config_path='environment_path/fake-aws-stack2',
template_path='templates/aws-import/fake-aws-stack2.yaml'
)
@patch("sceptre_migration_tool.migrator.import_stack")
@patch("sceptre_migration_tool.migrator.Environment")
@patch("sceptre_migration_tool.migration_environment"
".MigrationEnvironment.read_import_stack_list")
def test_import_list__empty_list(
self, mock_read_import_stack_list,
mock_environment,
mock_import_stack
):
mock_read_import_stack_list.return_value = []
migrator.import_list(
"sceptre_dir", sentinel.options, sentinel.list_fobj
)
mock_read_import_stack_list.assert_called_once_with(sentinel.list_fobj)
mock_environment.assert_not_called()
mock_import_stack.assert_not_called()
@patch("sceptre_migration_tool.migrator.import_stack")
@patch("sceptre_migration_tool.migrator.Environment")
@patch("sceptre_migration_tool.migration_environment"
".MigrationEnvironment.read_import_stack_list")
def test_import_list__data(
self, mock_read_import_stack_list,
mock_environment,
mock_import_stack
):
fake_item = ('1', '2', '3', '4')
mock_read_import_stack_list.return_value = [fake_item]
migrator.import_list(
"sceptre_dir", sentinel.options, sentinel.list_fobj
)
mock_read_import_stack_list.assert_called_once_with(sentinel.list_fobj)
mock_environment.assert_called_once_with(
sceptre_dir="sceptre_dir",
environment_path=fake_item[MigrationEnvironment.PART_ENV],
options=sentinel.options
)
mock_import_stack.assert_called_once_with(
mock_environment.return_value,
fake_item[MigrationEnvironment.PART_AWS_STACK_NAME],
fake_item[MigrationEnvironment.PART_SCEPTRE_STACK_NAME],
fake_item[MigrationEnvironment.PART_TEMPLATE_PATH]
)
@patch("sceptre_migration_tool.migrator"
"._create_migration_environment")
def test_generate_import_list__empty(
self, mock_migration_environment
):
mock_connection_manager =\
mock_migration_environment.return_value.connection_manager
mock_connection_manager.call.return_value = {
'Stacks': []
}
try:
list_fobj = StringIO()
migrator.generate_import_list(
self.environment, list_fobj
)
assert "" == list_fobj.getvalue()
finally:
list_fobj.close()
mock_connection_manager.call.assert_called_once_with(
service='cloudformation',
command='describe_stacks',
kwargs={}
)
@patch("sceptre_migration_tool.migrator"
"._create_migration_environment")
def test_generate_import_list__data(
self, mock_migration_environment
):
mock_connection_manager =\
mock_migration_environment.return_value.connection_manager
mock_connection_manager.call.side_effect = [
{
'Stacks': [
{
'StackName': 'name1'
},
{
'StackName': 'name2'
}
],
'NextToken': 'next'
},
{
'Stacks': [
{
'StackName': 'name3'
}
]
}
]
try:
list_fobj = StringIO()
migrator.generate_import_list(
self.environment, list_fobj
)
assert list_fobj.getvalue() == '\n'.join([
'environment_path name1 name1 templates/aws-import/name1.yaml',
'environment_path name2 name2 templates/aws-import/name2.yaml',
'environment_path name3 name3 templates/aws-import/name3.yaml',
''
])
finally:
list_fobj.close()
mock_connection_manager.call.call_count = 2
class TestEnvironment__create_migration_environment(object):
@patch("sceptre_migration_tool.migrator.ConnectionManager")
def test_happy_case(self, mock_ConnectionManager):
mock_env = Mock()
mock_env._get_config.return_value = {
"region": 'fake-region',
"iam_role": 'fake-iam-role',
"profile": 'fake-profile',
"user_variables": {}
}
result = migrator._create_migration_environment(mock_env)
assert result.connection_manager == mock_ConnectionManager.return_value
assert result.environment_config == mock_env._get_config()
mock_ConnectionManager.assert_called_once_with(
region='fake-region',
iam_role='fake-iam-role',
profile='fake-profile'
)
<file_sep>---
layout: docs
---
# Command Line Interface
Sceptre Migration Tool can be used as a command line tool. Sceptre Migration Tool commands take the format:
```
$ sceptre_migration_tool [GLOBAL_OPTIONS] COMMAND [ARGS] [COMMAND_OPTIONS]
```
Running sceptre migration tool without a subcommand will display help, showing a list of the available commands.
## Global Options
- `--debug`: Turn on debug logging.
- `--dir`: Specify the sceptre directory with an absolute or relative path.
- `--var`: Overwrite an arbitrary config item. For more information, see the section on [Templating]({{ site.baseurl }}/docs/environment_config.html#templating).
- `--var-file`: Overwrite arbitrary config item(s) with data from a variables file. For more information, see the section on [Templating]({{ site.baseurl }}/docs/environment_config.html#templating).
## Commands
The available commands are:
```
$ sceptre_migration_tool generate-import-list
$ sceptre_migration_tool import-env
$ sceptre_migration_tool import-list
$ sceptre_migration_tool import-stack
```
## Command Options
Command options differ depending on the command, and can be found by running:
```shell
$ sceptre_migration_tool COMMAND --help
```
<file_sep>#!/bin/bash
###############################################################################
# Script to build environment and pipeline
# @author: oazmon
###############################################################################
#
# determine the script base directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
BASE_DIR="$( cd ${SCRIPT_DIR}/.. && pwd )"
WORK_DIR="${BASE_DIR}"
# Log levels (e.g.: trace debug info warn error)
log_level=(error warn info)
# Setting script to exit on error
set -e
# -----------------------------------------------------------------------------
# Initializing variables
# -----------------------------------------------------------------------------
. ${SCRIPT_DIR}/common.sh
. ${BASE_DIR}/sceptre.run.properties
VARS_FILE=$BASE_DIR/vars.yaml
SCEPTRE_OPTS="${SCEPTRE_OPTS} --var-file ${VAR_FILE}"
# Apply debug, if requested
if [ ! -z ${DEBUG} ]; then
SCEPTRE_OPTS="--debug $SCEPTRE_OPTS"
fi
#------------------------------------------------------------------------------
# function that outputs script usage/help
#------------------------------------------------------------------------------
function script_usage() {
trap - EXIT
echo "--------------------------------------------------------------------------------"
echo "Description: A Script to manage AWS using Sceptre"
echo ""
echo "Usage: ${BASH_SOURCE[1]} [command] [additional arguments]"
echo " <empty> - runs import"
echo " import - imports all environments."
echo " Arguments: none"
echo " import-env - imports a single environment."
echo " Arguments: environment"
echo " import-stack - imports a single stack."
echo " Arguments: environment and stack"
echo " help - script usage"
echo ""
echo "E.g.:"
echo " sh ./${BASH_SOURCE[1]}"
echo "--------------------------------------------------------------------------------"
}
#------------------------------------------------------------------------------
# Helper function to determine if Python is running in a virtualenv
#------------------------------------------------------------------------------
function get_python_virtual() {
python -c '
import sys
if hasattr(sys, "real_prefix"):
print("virtual")
else:
print("real")
'
}
#------------------------------------------------------------------------------
# Setup Sceptre Run
#------------------------------------------------------------------------------
function setup_sceptre_migration_tool_run() {
show_hosting_info
log "info" ":::::::::::::::::::::::: Setting up sceptre_migration_tool"
if [ $(type sceptre_migration_tool >/dev/null 2>&1; echo $?) -ne 0 ]; then
if [ $(type python >/dev/null 2>&1; echo $?) -ne 0 ]; then
log "error" "Unable to automatically install Python. Please install it yourself."
exit -1
fi
if [ $(type pip >/dev/null 2>&1; echo $?) -ne 0 ]; then
log "error" "Unable to automatically install 'pip' (Python package installer). Please install it yourself."
exit -1
fi
if [[ ! "${log_level[@]}" =~ "debug" ]]; then
pip_logging="-q"
fi
if [ $(get_python_virtual) == "virtual" ]; then
pip_user=""
else
pip_user="--user"
fi
pip install --upgrade ${pip_user} ${pip_logging} sceptre_migration_tool
fi
sceptre_migration_tool_path=$(
cd $(pip show sceptre_migration_tool | grep '^Location' | cut -d: -f2-)
sceptre_migration_tool=$(pip show sceptre_migration_tool -f | grep 'bin/sceptre_migration_tool')
cd $(dirname ${sceptre_migration_tool})
echo $PWD
)
export PATH="$PATH:${sceptre_migration_tool_path}"
log "debug" "PATH=${PATH}"
read -r -a VARS_YAML <<<$(parse_yaml ${VARS_FILE})
obtain_credentials VARS_YAML
make_vpc_id_array VARS_YAML result_array
for item in ${result_array[@]}; do
SCEPTRE_OPTS="$SCEPTRE_OPTS --var $item"
done
export SCEPTRE_OPTS
log "debug" "SCEPTRE_OPTS=${SCEPTRE_OPTS}"
}
#------------------------------------------------------------------------------
# Run Sceptre Migration Tool
#------------------------------------------------------------------------------
function run_sceptre_migration_tool() {
args=${@}
log "info" "--------------------------------------------------------------------------------"
log "info" "Run sceptre_migration_tool ${args}"
log "info" "--------------------------------------------------------------------------------"
run_in ${WORK_DIR} sceptre_migration_tool ${SCEPTRE_OPTS} ${args}
}
#------------------------------------------------------------------------------
# Unconditional Cleanup at End
#------------------------------------------------------------------------------
function finish() {
exit_code=$?
# closing message
script_endtime=$(date +"%s")
script_diff=$(($script_endtime-$script_startime))
if [ ${exit_code} -eq 0 ]; then
ending="SUCCESS"
else
ending="FAILURE"
fi
log "info" "--------------------------------------------------------------------------------"
log "info" "${ending} '${BASH_SOURCE[1]} $@'; Duration: $(($script_diff / 3600 ))H:$((($script_diff % 3600) / 60))M:$(($script_diff % 60))S; exit_code=${exit_code}"
log "info" "--------------------------------------------------------------------------------"
}
#------------------------------------------------------------------------------
# Main script entry point
#------------------------------------------------------------------------------
function main() {
script_startime=$(date +"%s")
log "info" "--------------------------------------------------------------------------------"
log "info" "Starting '${BASH_SOURCE[1]} $@'..."
log "info" "--------------------------------------------------------------------------------"
process_paws_if_needed
command=${1}
case "$command" in
"help" )
script_usage
;;
* )
setup_sceptre_migration_tool_run
run_sceptre_migration_tool ${@}
;;
esac
}
#------------------------------------------------------------------------------
# Execute main script entry point
#------------------------------------------------------------------------------
trap finish EXIT
main ${@}
# >>>>>> End of File <<<<<<
<file_sep>---
layout: docs
---
# Terminology
The following terms will be used though the rest of the Sceptre documentation:
- **Environment Path**: A slash ('/') separated list of directory names which details how to move from the top level config directory to an environment directory. For example, with the following directory structure, the environment path would simply be `dev`:
```
.
└── config
└── dev
├── config.yaml
└── vpc.yaml
```
In the following directory structure, the environment path would be `account-1/dev/eu-west-1`:
```
.
└── config
└── account-1
└── dev
└── eu-west-1
├── config.yaml
└── vpc.yaml
```
- **Import**: In the context of Sceptre Migration Tool commands, `import` means to create a Sceptre stack config file and template file from an AWS existing stack.
- **Sceptre Directory**: The directory which stores the top level config directory.
<file_sep># -*- coding: utf-8 -*-
"""
sceptre_migration_tool.importer.stack
This module imports a Stack class from AWS.
"""
import logging
from sceptre.stack import Stack
from sceptre_migration_tool.config import import_config
from sceptre_migration_tool.template import import_template
logger = logging.getLogger(__name__)
def import_stack(
migration_environment,
aws_stack_name,
template_path,
config_path):
template = import_template(
migration_environment,
aws_stack_name,
template_path
)
logger.info("%s - Imported AWS CloudFormation template into '%s'"
" into '%s'", config_path, aws_stack_name, template_path)
import_config(
migration_environment,
aws_stack_name,
config_path,
template
)
logger.info(
"%s - Imported stack config from AWS CloudFormation stack '%s' ",
config_path,
aws_stack_name
)
return Stack(
name=config_path,
environment_config=migration_environment.environment_config,
connection_manager=migration_environment.connection_manager
)
<file_sep>
from mock import Mock, patch
from sceptre_migration_tool.reverse_resolvers.reverse_stack_output\
import ReverseStackOutput
from sceptre_migration_tool.migration_environment import MigrationEnvironment
class MockConfig(dict):
pass
class TestReverseStackOutput(object):
def setup_method(self, test_method):
self.mock_connection_manager = Mock()
self.mock_environment_config = MockConfig()
self.mock_environment_config['user_variables'] = {}
self.reverse_stack_output = ReverseStackOutput(
MigrationEnvironment(
connection_manager=self.mock_connection_manager,
environment_config=self.mock_environment_config
)
)
def test_config_correctly_initialised(self):
assert self.reverse_stack_output.migration_environment\
.connection_manager == self.mock_connection_manager
assert self.reverse_stack_output.migration_environment\
.environment_config == self.mock_environment_config
assert self.reverse_stack_output.precendence() == 20
def test__add_to_reverse_lookup__has_export(self):
reverse_lookup = {}
self.reverse_stack_output._add_to_reverse_lookup(
stack_name='fake-stack-name',
output={
'ExportName': 'fake-export',
'OutputKey': 'fake-key1',
'OutputValue': 'value1'
},
target_dict=reverse_lookup,
resolver_name='fake-resolver'
)
assert {} == reverse_lookup
def test__add_to_reverse_lookup__good(self):
reverse_lookup = {}
self.reverse_stack_output._add_to_reverse_lookup(
stack_name='fake-stack-name',
output={
'OutputKey': 'fake-key1',
'OutputValue': 'value1'
},
target_dict=reverse_lookup,
resolver_name='fake-resolver'
)
assert reverse_lookup == {
'value1': (
"fake-stack-name",
"!fake-resolver 'fake-stack-name::fake-key1'"
)
}
def test__add_to_reverse_lookup__dup(self):
reverse_lookup = {'value1': 'fake-older-value'}
self.reverse_stack_output._add_to_reverse_lookup(
stack_name='fake-stack-name',
output={
'OutputKey': 'fake-key1',
'OutputValue': 'value1'
},
target_dict=reverse_lookup,
resolver_name='fake-resolver'
)
assert reverse_lookup == {'value1': 'fake-older-value'}
@patch("sceptre_migration_tool.reverse_resolvers.reverse_stack_output."
"ReverseStackOutput._add_to_reverse_lookup")
def test__build_external_stack_lookup(
self, mock_add_one
):
self.reverse_stack_output._stack_output_external = {}
self.reverse_stack_output._build_external_stack_lookup(
stack_name='fake-stack-name',
outputs=[
{
'OutputKey': 'fake-key1',
'OutputValue': 'value1'
},
{
'OutputKey': 'fake-key2',
'OutputValue': 'value2'
}
]
)
assert 2 == mock_add_one.call_count
mock_add_one.assert_any_call(
stack_name='fake-stack-name',
output={
'OutputKey': 'fake-key1',
'OutputValue': 'value1'
},
target_dict=self.reverse_stack_output._stack_output_external,
resolver_name="stack_output_external"
)
mock_add_one.assert_any_call(
stack_name='fake-stack-name',
output={
'OutputKey': 'fake-key2',
'OutputValue': 'value2'
},
target_dict=self.reverse_stack_output._stack_output_external,
resolver_name="stack_output_external"
)
@patch("sceptre_migration_tool.reverse_resolvers.reverse_stack_output."
"ReverseStackOutput._add_to_reverse_lookup")
def test__build_internal_stack_lookup(
self, mock_add_one
):
self.reverse_stack_output._stack_output = {}
self.reverse_stack_output._build_internal_stack_lookup(
stack_name='fake-stack-name',
outputs=[
{
'OutputKey': 'fake-key1',
'OutputValue': 'value1'
},
{
'OutputKey': 'fake-key2',
'OutputValue': 'value2'
}
]
)
assert 2 == mock_add_one.call_count
mock_add_one.assert_any_call(
stack_name='fake-stack-name',
output={
'OutputKey': 'fake-key1',
'OutputValue': 'value1'
},
target_dict=self.reverse_stack_output._stack_output,
resolver_name="stack_output"
)
mock_add_one.assert_any_call(
stack_name='fake-stack-name',
output={
'OutputKey': 'fake-key2',
'OutputValue': 'value2'
},
target_dict=self.reverse_stack_output._stack_output,
resolver_name="stack_output"
)
@patch("sceptre_migration_tool.reverse_resolvers.reverse_stack_output."
"ReverseStackOutput._build_external_stack_lookup")
@patch("sceptre_migration_tool.reverse_resolvers.reverse_stack_output."
"ReverseStackOutput._build_internal_stack_lookup")
def test__build_reverse_lookup__no_outputs(
self, mock_build_internal, mock_build_external
):
self.reverse_stack_output._build_reverse_lookup({})
mock_build_internal.assert_not_called()
mock_build_external.assert_not_called()
# @patch("sceptre_migration_tool.reverse_resolvers.reverse_stack_output."
# "ReverseStackOutput._build_external_stack_lookup")
# @patch("sceptre_migration_tool.reverse_resolvers.reverse_stack_output."
# "ReverseStackOutput._build_internal_stack_lookup")
# def test__build_reverse_lookup__internal_stack(
# self, mock_build_internal, mock_build_external
# ):
# mock_get_internal_stack = Mock()
# mock_get_internal_stack.return_value = 'fake-internal-stack-name'
# self.reverse_stack_output.migration_environment.get_internal_stack =\
# mock_get_internal_stack
# stack = {
# 'StackName': 'fake-stack-name',
# 'Outputs': [
# {
# 'OutputKey': 'fake-key1',
# 'OutputValue': 'value1'
# },
# {
# 'OutputKey': 'fake-key2',
# 'OutputValue': 'value2'
# }
# ]
# }
# self.reverse_stack_output._build_reverse_lookup(stack)
# mock_build_internal.assert_called_once_with(
# 'fake-internal-stack-name',
# stack['Outputs']
# )
# mock_build_external.assert_not_called()
@patch("sceptre_migration_tool.reverse_resolvers.reverse_stack_output."
"ReverseStackOutput._build_external_stack_lookup")
@patch("sceptre_migration_tool.reverse_resolvers.reverse_stack_output."
"ReverseStackOutput._build_internal_stack_lookup")
def test__build_reverse_lookup__external_stack(
self, mock_build_internal, mock_build_external
):
mock_get_external_stack = Mock()
mock_get_external_stack.return_value = None
self.reverse_stack_output.migration_environment.get_external_stack =\
mock_get_external_stack
stack = {
'StackName': 'fake-stack-name',
'Outputs': [
{
'OutputKey': 'fake-key1',
'OutputValue': 'value1'
},
{
'OutputKey': 'fake-key2',
'OutputValue': 'value2'
}
]
}
self.reverse_stack_output._build_reverse_lookup(stack)
mock_build_internal.assert_not_called()
mock_build_external.assert_called_once_with(
stack['StackName'],
stack['Outputs']
)
def test__get_stack_output__no_stacks(self):
self.mock_connection_manager.call.return_value = {
'Stacks': []
}
self.reverse_stack_output._get_stack_output()
assert {} == self.reverse_stack_output._stack_output
assert {} == self.reverse_stack_output._stack_output_external
@patch("sceptre_migration_tool.reverse_resolvers.reverse_stack_output."
"ReverseStackOutput._build_reverse_lookup")
def test__get_stack_output__good(self, mock_build_reverse_lookup):
self.mock_stack1 = Mock()
self.mock_stack2 = Mock()
self.mock_stack3 = Mock()
self.mock_connection_manager.call.side_effect = [
{
'Stacks': [
self.mock_stack1,
self.mock_stack2
],
'NextToken': 'fake-next-token'
},
{
'Stacks': [
self.mock_stack3
]
}
]
self.reverse_stack_output._get_stack_output()
assert mock_build_reverse_lookup.call_count == 3
mock_build_reverse_lookup.assert_any_call(self.mock_stack1)
mock_build_reverse_lookup.assert_any_call(self.mock_stack2)
mock_build_reverse_lookup.assert_any_call(self.mock_stack3)
@patch("sceptre_migration_tool.reverse_resolvers.reverse_stack_output."
"ReverseStackOutput._get_stack_output")
def test_suggest__not_found(self, mock_get_stack_output):
def _get_stack_output_side_effect():
self.reverse_stack_output._stack_output = {}
self.reverse_stack_output._stack_output_external = {}
mock_get_stack_output.side_effect = _get_stack_output_side_effect
assert self.reverse_stack_output.suggest('fake-value') is None
mock_get_stack_output.assert_called_once()
@patch("sceptre_migration_tool.reverse_resolvers.reverse_stack_output."
"ReverseStackOutput._get_stack_output")
def test_suggest__is_internal(self, mock_get_stack_output):
def _get_stack_output_side_effect():
self.reverse_stack_output._stack_output = {
'fake-value': ('fake-stack-name', 'fake-internal-key')
}
self.reverse_stack_output._stack_output_external = {}
mock_get_stack_output.side_effect = _get_stack_output_side_effect
assert self.reverse_stack_output.suggest('fake-value') ==\
'fake-internal-key'
mock_get_stack_output.assert_called_once()
@patch("sceptre_migration_tool.reverse_resolvers.reverse_stack_output."
"ReverseStackOutput._get_stack_output")
def test_suggest__is_internal_and_same_stack(self, mock_get_stack_output):
def _get_stack_output_side_effect():
self.reverse_stack_output._stack_output = {
'fake-value': ('fake-stack-name', 'fake-internal-key')
}
self.reverse_stack_output._stack_output_external = {}
self.reverse_stack_output.migration_environment.config_path = \
'fake-stack-name'
mock_get_stack_output.side_effect = _get_stack_output_side_effect
assert self.reverse_stack_output.suggest('fake-value') is None
mock_get_stack_output.assert_called_once()
@patch("sceptre_migration_tool.reverse_resolvers.reverse_stack_output."
"ReverseStackOutput._get_stack_output")
def test_suggest__is_external(self, mock_get_stack_output):
def _get_stack_output_side_effect():
self.reverse_stack_output._stack_output = {}
self.reverse_stack_output._stack_output_external = {
'fake-value': ('fake-stack-name', 'fake-external-key')
}
mock_get_stack_output.side_effect = _get_stack_output_side_effect
result = self.reverse_stack_output.suggest('fake-value')
assert result == 'fake-external-key'
mock_get_stack_output.assert_called_once()
<file_sep>---
layout: page
---
# About
Sceptre Migration Tool is a tool to import configuration from AWS into Sceptre. Currently, the tool imports AWS Cloudformation scripts.
The tool is accessible as a CLI tool, or as a Python module.
## Motivation
Many teams start creating CloudFormation manually or with other tools and with to migrate to use Sceptre. This could be a delicate process to do manually.
This tool imports the stacks as-is and allow further incremental massaging, to make the process of migration more Robust.
The migration tool was developed separate from Sceptre (it imports Sceptre internally) to reduce the complexity of the core code for what is basically a one time use.
## Overview
The migration tool is used by a relationship between AWS Cloudformation stacks and the corresponding template files and YAML config files in the Sceptre configuration directory tree.
For a tutorial on using Sceptre, see [Get Started](https://sceptre.cloudreach.com/latest/docs/get_started.html).
## Code
Sceptre Migration Tools source code can be found on [Github](https://github.intuit.com/SBSEG-EPIC/sceptre-migration-tool).
Bugs and feature requests should be raised via our [Issues](https://github.intuit.com/SBSEG-EPIC/sceptre-migration-tool/issues) page.
<file_sep>---
layout: docs
---
# Installation
This assumes that you have Python installed. A thorough guide on installing Python can be found [here](http://docs.python-guide.org/en/latest/starting/installation/). We highly recommend using Sceptre Migration Tool from within a `virtualenv`. Notes on installing and setting up `virtualenv` can be found [here](http://docs.python-guide.org/en/latest/dev/virtualenvs/).
Install Sceptre:
```shell
$ pip install sceptre_migration_tool
```
Validate installation by printing out Sceptre Migration Tool's version number:
```shell
$ sceptre_migration_tool --version
Sceptre Migration Tool, version <x.x.x>
```
Update Sceptre Migration Tool:
```shell
$ pip install sceptre_migration_tool -U
```
<file_sep># -*- coding: utf-8 -*-
# import pytest
from mock import patch, Mock
from sceptre.connection_manager import ConnectionManager
from sceptre_migration_tool import stack
from sceptre_migration_tool.migration_environment import MigrationEnvironment
class TestStack(object):
class MockConfig(dict):
pass
def setup_method(self, test_method):
connection_manager = Mock(spec=ConnectionManager)
environment_config = self.MockConfig()
environment_config['sceptre_dir'] = 'fake-spectre-dir'
environment_config['user_variables'] = {}
self.migration_environment = MigrationEnvironment(
connection_manager, environment_config)
@patch("sceptre_migration_tool.stack.Stack")
@patch("sceptre_migration_tool.stack.import_config")
@patch("sceptre_migration_tool.stack.import_template")
def test_import_stack(self, mock_template, mock_config, mock_stack):
mock_template.return_value = Mock()
mock_connection_manager =\
self.migration_environment.connection_manager
mock_environment_config =\
self.migration_environment.environment_config
mock_connection_manager.call.return_value = {
'TemplateBody': 'fake-body'
}
result = stack.import_stack(
self.migration_environment,
'fake-aws-stack-name',
'fake-template-path.yaml',
'fake-config-path'
)
assert result is not None
mock_template.assert_called_once_with(
self.migration_environment,
'fake-aws-stack-name',
'fake-template-path.yaml'
)
mock_config.assert_called_once_with(
self.migration_environment,
'fake-aws-stack-name',
'fake-config-path',
mock_template.return_value
)
mock_stack.assert_called_once_with(
connection_manager=mock_connection_manager,
environment_config=mock_environment_config,
name='fake-config-path'
)
<file_sep>---
layout: docs
---
# Get Started
## Install
This tutorial assumes that you have installed Sceptre Migration Tool and Sceptre. Instructions on how to do this are found in the section on [installation]({{ site.url }}{{ site.baseurl }}/docs/install.html).
## Directory Structure
Create the following directory structure in a clean directory named `sceptre-example`:
```shell
.
├── config
│ └── dev
│ ├── config.yaml
└── templates
```
On Unix systems, this can be done with the following commands:
```
$ mkdir config config/dev templates
$ touch config/dev/config.yaml
```
`vpc.json` will contain a CloudFormation template, `vpc.yaml` will contain config relevant to that template, and `config.yaml` will contain environment config.
### config.yaml
Add the following config to `config.yaml`:
```yaml
project_code: sceptre-example
region: us-west-2
```
Sceptre prefixes stack names with the `project_code`. Resources will be built in the AWS region `region`.
## Commands
### Import stack
We can import a stack with the following command by replacing 'aws-stack' with the name of an actual stack in AWS that exists in the region specified above:
```shell
$ sceptre import-stack dev sample aws-stack
```
This command must be run from the `sceptre-examples` directory.
## Next Steps
Further details can be found in the full [documentation]({{ site.url }}{{ site.baseurl }}/docs).
<file_sep>--index-url https://artifact.intuit.com/artifactory/api/pypi/pypi-intuit/simple
behave==1.2.6
coverage==4.5.1
docutils==0.14
flake8==3.5.0
mock==2.0.0
pytest==3.5.0
pytest-runner==4.2
tox==2.9.1
troposphere==2.1.2
wheel==0.30.0
<file_sep>#!/bin/bash
###############################################################################
# This script is used by the CI build system.
# Human users should use the Makefile
#
# @author: oazmon
###############################################################################
#
# determine the script base directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
BASE_DIR=${SCRIPT_DIR}
# configure os specific features
type shred >/dev/null 2>&1
has_shred=$?
# Setting script to exit on error
set -e
# -----------------------------------------------------------------------------
# Initializing variables
# -----------------------------------------------------------------------------
# OS Name
os=`uname`
# Log levels (e.g.: info warn debug trace)
log_level=(error warn info debug)
if [[ "${log_level[@]}" =~ "trace" ]]; then
set -x
fi
# Relative path to Build directory
BUILD_DIR=${BASE_DIR}/build-application
# Relative path to application directory
APPLICATION_DIR=${BASE_DIR}
# Distribution directory
APPLICATION_DIST_DIR=${APPLICATION_DIR}/dist
# Get artifact version setup.py
ARTIFACT_VERSION=`python3.6 ${APPLICATION_DIR}/setup.py --version`
# Get artifact name from application configuration
ARTIFACT_ID=`python3.6 ${APPLICATION_DIR}/setup.py --name`
# PYPI Credentials
PYPIRC=$HOME/.pypirc
# Git Credentials
GITCRED=/tmp/gitcredfile
#------------------------------------------------------------------------------
# Function that logs to standard out like log4j
# Usage: log "[level]" "[text]"
#------------------------------------------------------------------------------
function log() {
if [[ "${log_level[@]}" =~ "${1}" ]]; then
#echo "`date -u +%Y-%m-%d:%H:%M:%S` | ${1} | ${BASH_SOURCE[1]}:${FUNCNAME[1]}:${BASH_LINENO[0]} | ${2}"
echo "`date -u +%Y-%m-%d:%H:%M:%S` | ${1} | ${2}"
fi
}
#------------------------------------------------------------------------------
# Function that echo a command and then executes it
# Usage: echo_exec [cmd]
#------------------------------------------------------------------------------
function echo_exec() {
CALL_CMD="$*"
log "info" "${CALL_CMD}"
${CALL_CMD}
}
#------------------------------------------------------------------------------
# Function that runs an echo_exec in the current context and in the specified
# directory and returns without changing directories
# Usage: run_id [directory cmd]
#------------------------------------------------------------------------------
function run_in() {
pushd .
log "debug" "Changing to ${1} directory..."
cd $1
shift 1
echo_exec $*
log "debug" "Changing back to previous directory..."
popd
}
#------------------------------------------------------------------------------
# Publish application WHL, test, and deploy-package artifacts
#------------------------------------------------------------------------------
function publish_application_artifacts() {
# Publish to nexus only if CICD Service (Jenkins) build
if [ -z $BUILD_NUMBER ]; then
# This is NOT triggered through CI and NOT running in Jenkins
log "info" "-------------------------------------------------------------------------------"
log "info" " Skipping 'deploy' since this is not triggered through CI and \${BUILD_NUMBER} is empty"
log "info" "-------------------------------------------------------------------------------"
exit 0
fi
if [ X"master" != X"$GIT_BRANCH" ]; then
# This is the branch from which we release
log "info" "-------------------------------------------------------------------------------"
log "info" " Skipping 'deploy' since this is not the master branch"
log "info" "-------------------------------------------------------------------------------"
exit 0
fi
[ -z "${PYPI_USERNAME}" ] && log "error" "The required PYPI_USERNAME environment variable is not set. Please do: export PYPI_USERNAME && exit 1
[ -z "${PYPI_TOKEN}" ] && log "error" "The required PYPI_TOKEN environment variable is not set. Please do: export PYPI_TOKEN && exit 1
cat >${PYPIRC} <<EOF
[distutils]
index-servers =
local
[local]
repository: https://artifact.intuit.com/artifactory/api/pypi/pypi-local-sceptre
username: ${PYPI_USERNAME}
password: ${<PASSWORD>}
EOF
# Following is executed by finish function
# shred -n 25 -u -z ${PYPIRC}
log "info" "-------------------------------------------------------------------------------"
log "info" " Publishing artifact Python wheel file WHL file to PyPI..."
log "info" "-------------------------------------------------------------------------------"
python3.6 setup.py bdist_wheel build -b build.d upload -r local
log "info" "------------------------------------------------------------------------------"
log "info" " Publishing artifact Python wheel file ZIP file to PyPI..."
log "info" "-------------------------------------------------------------------------------"
python3.6 setup.py sdist upload -r local
log "info" "-------------------------------------------------------------------------------"
log "info" " Tagging build in git..."
log "info" "-------------------------------------------------------------------------------"
git config --global push.default simple
echo ${GIT_PWD} > ${GITCRED}
# Following is executed by finish function
# shred -n 25 -u -z ${GITCRED}
export SLUSER=$(echo $GIT_PWD | sed 's/^.*\/\///' | sed 's/:.*//')
git config --global user.name "$SLUSER" --quiet
git config --global user.email "$<EMAIL>" --quiet
git config --global credential.helper "store --file=/tmp/gitcredfile" –quiet
TAG=` echo "${BUILDER_NAME}_${GIT_BRANCH}_${ARTIFACT_VERSION}" | tr . _ | tr - _`
log "info" "Setting Tag: '${TAG}'"
git tag -m "SCM Label from CICD service" -a $TAG -f
git push --tag --force
log "info" "-------------------------------------------------------------------------------"
log "info" " Publishing artifacts is complete"
log "info" "-------------------------------------------------------------------------------"
}
#------------------------------------------------------------------------------
# General hosting information. Add as needed to help troubleshoot build issues.
#------------------------------------------------------------------------------
function show_hosting_info() {
log "info" ":::::::::::::::::::::::: `date +%H:%M:%S` beginning build host information \"$0\""
# some system info
if [ X"$os" = X"Darwin" ]; then
log "info" ":::::::::::::::::::::::: hostname for OS/X:"
hostname -f
else
log "info" ":::::::::::::::::::::::: hostname, including FQDN and all IP addresses:"
hostname --fqdn
hostname -a
hostname --all-ip-addresses
fi
log "info" ":::::::::::::::::::::::: uname -a"
uname -a
if [ -r "/proc/version" ] ; then
log "info" ":::::::::::::::::::::::: contents of /proc/version:"
cat /proc/version
fi
if [ -r "/etc/redhat-release" ] ; then
log "info" ":::::::::::::::::::::::: contents of /etc/redhat-release:"
cat /etc/redhat-release
elif [ -r "/etc/os-release" ] ; then
log "info" ":::::::::::::::::::::::: contents of /etc/os-release:"
cat /etc/os-release
elif [ X"$os" = "Linux" ] ; then
log "info" ":::::::::::::::::::::::: hmmm.... anything matching /etc/\*-release that might tell us about the OS\?"
ls -l /etc/*-release
fi
echo :::::::::::::::::::::::: pwd, ls -la, df -h
pwd
pwd -P
ls -la
df -h
echo :::::::::::::::::::::::: uptime, ntpstat, date
uptime
if ! ntpstat 2>&1 ; then
echo problem with ntpstat \($?\)
fi
date '+%Y-%m-%d %H:%M:%S -- TZ: %Z %:z -- year# %G week# %V day# %j'
echo :::::::::::::::::::::::: envars w/o secrets, passwords, or tokens
printenv | grep -vi -e pass -e secret -e token | sort
echo :::::::::::::::::::::::: about git: which, version, and status
which git
git --version
git status
echo :::::::::::::::::::::::: git log --pretty=oneline --abbrev-commit --graph --decorate --max-count=10
git log --pretty=oneline --abbrev-commit --graph --decorate --max-count=10 | cat
echo :::::::::::::::::::::::: about python: which + version
echo "Default Python version:"
which python
python --version 2>&1
echo "Python 2.7 version:"
python2.7 --version 2>&1
echo "Python 3.6 version:"
python3.6 --version 2>&1
log "info" ":::::::::::::::::::::::: `date +%H:%M:%S` ending build host information \"$0\""
}
function shred_it() {
if [ -e ${1} ]; then
if [ $has_shred -eq 0 ]; then
shred -n 25 -u -z ${1}
else
rm -fr ${1}
fi
fi
}
function finish() {
exit_code=$?
# clean up for publish_application_artifacts
shred_it ${GITCRED}
shred_it ${PYPIRC}
# closing message
script_endtime=$(date +"%s")
script_diff=$(($script_endtime-$script_startime))
log "info" "================================================================================"
log "info" ""
log "info" ""
log "info" "Ending '${BASH_SOURCE[1]} $@'; Duration: $(($script_diff / 3600 ))H:$((($script_diff % 3600) / 60))M:$(($script_diff % 60))S; exit_code=${exit_code}"
log "info" ""
log "info" ""
log "info" "================================================================================"
}
#------------------------------------------------------------------------------
# Main script execution
#------------------------------------------------------------------------------
function main() {
log "info" "================================================================================"
log "info" ""
log "info" ""
log "info" "STARTING USER BUILD:"
log "info" ""
log "info" ""
log "info" "================================================================================"
script_startime=$(date +"%s")
log "info" "--------------------------------------------------------------------------------"
log "info" "Starting '${BASH_SOURCE[1]} $@'..."
log "info" "--------------------------------------------------------------------------------"
export PATH=/opt/python/python-2.7.14/bin:/opt/python/python-3.6.4/bin:/home/ibpslave/.local/bin/:$PATH
show_hosting_info
make clean install-make-tools lint test-all dist
publish_application_artifacts
}
#------------------------------------------------------------------------------
# Main execution
#------------------------------------------------------------------------------
trap finish EXIT
main ${@}
# >>>>>> End of File <<<<<<
<file_sep># -*- coding: utf-8 -*-
import json
import pytest
from mock import patch, Mock
from sceptre.connection_manager import ConnectionManager
from sceptre.exceptions import UnsupportedTemplateFileTypeError
from sceptre_migration_tool import template
from sceptre_migration_tool.exceptions import ImportFailureError
from sceptre_migration_tool.migration_environment import MigrationEnvironment
class TestTemplate(object):
class MockConfig(dict):
pass
def setup_method(self, test_method):
connection_manager = Mock(spec=ConnectionManager)
environment_config = self.MockConfig()
environment_config.sceptre_dir = 'fake-spectre-dir'
environment_config['user_variables'] = {}
self.migration_environment = MigrationEnvironment(
connection_manager, environment_config)
@patch("sceptre_migration_tool.template._write_template")
@patch("sceptre_migration_tool.template._normalize_template_for_write")
def test_import_template__json_template_new_json_target(
self, mock_normalize, mock_write):
fake_template_body = {
'TemplateBody': {
'Key': 'Value'
}
}
fake_template_body_string = \
json.dumps(fake_template_body['TemplateBody'])
mock_connection_manager =\
self.migration_environment.connection_manager
mock_connection_manager.call.return_value = fake_template_body
mock_normalize.return_value = fake_template_body_string
template.import_template(
self.migration_environment,
'fake-aws-stack-name',
'templates/fake-template-path.json'
)
mock_connection_manager.call.assert_called_once_with(
service='cloudformation',
command='get_template',
kwargs={
'StackName': 'fake-aws-stack-name',
'TemplateStage': 'Original'
}
)
mock_normalize.assert_called_once_with(
fake_template_body['TemplateBody'],
'.json'
)
mock_write.assert_called_once_with(
'fake-spectre-dir/templates/fake-template-path.json',
fake_template_body_string
)
def test__normalize_template_for_write_json_to_json(self):
result = template._normalize_template_for_write(
{'Key': 'Value'},
".json"
)
assert result == '{"Key": "Value"}'
def test__normalize_template_for_write_yaml_to_json(self):
result = template._normalize_template_for_write(
'Key: Value\n',
".json"
)
assert result == '{"Key": "Value"}'
def test__normalize_template_for_write_json_to_yaml(self):
result = template._normalize_template_for_write(
{'Key': 'Value'},
".yaml"
)
assert result == 'Key: Value\n'
def test__normalize_template_for_write_yaml_to_yaml(self):
result = template._normalize_template_for_write(
'Key: Value\n',
".yaml"
)
assert result == 'Key: Value\n'
def test__normalize_template_for_write_yaml_to_unsupported(self):
with pytest.raises(UnsupportedTemplateFileTypeError):
template._normalize_template_for_write('Key: Value\n', ".txt")
@patch("sceptre_migration_tool.template.open")
@patch("os.makedirs")
@patch("os.path.isfile")
def test__write_template__new_file(
self, mock_isfile, mock_makedirs, mock_open
):
mock_isfile.return_value = False
template._write_template('fake-path/fake-file', 'fake-body')
mock_makedirs.assert_called_once_with('fake-path')
mock_open.called_once_with('fake-path')
mock_open.return_value.__enter__.return_value\
.write.called_once_with('fake-body/fake-file', 'w')
@patch("sceptre_migration_tool.template.open")
@patch("os.path.isfile")
def test__write_template__existing_same_file(self, mock_isfile, mock_open):
mock_isfile.return_value = True
mock_open.return_value.__enter__.return_value\
.read.return_value = 'fake-body: !Ref value'
template._write_template('fake-path', 'fake-body: !Ref value')
mock_open.called_once_with('fake-path', 'r')
mock_open.return_value.read.called_once()
mock_open.return_value.__enter__.return_value\
.write.assert_not_called()
@patch("sceptre_migration_tool.template.open")
@patch("os.path.isfile")
def test__write_template__existing_diff_file(self, mock_isfile, mock_open):
mock_isfile.return_value = True
mock_open.return_value.__enter__.return_value\
.read.return_value = 'fake-diff-body'
with pytest.raises(ImportFailureError):
template._write_template('fake-path', 'fake-body')
mock_open.called_once_with('fake-path')
mock_open.return_value.read.called_once()
mock_open.write.assert_not_called()
<file_sep>---
layout: docs
---
# Documentation
This documentation acts as an in-depth reference for all of Sceptre Migration Tool's features.
Beginners should consider reading our [getting started guide]({{ site.url }}{{ site.baseurl }}/docs/get_started.html), which provides a walk-through tutorial.
<file_sep># -*- coding: utf-8 -*-
"""
sceptre_migration_tool.importer.template
This module imports a Sceptre Template class.
"""
from six import string_types
import json
import logging
import os
import yaml
from sceptre.template import Template
from sceptre.exceptions import UnsupportedTemplateFileTypeError
from .exceptions import ImportFailureError
def import_template(migration_environment, aws_stack_name, template_path):
"""
Saves a template imported from AWS CloudFormation.
:param path: The absolute path to the file which stores the template.
:type path: str
:param body: The body of the imported template.
:type region: str or dict
:raises: UnsupportedTemplateFileTypeError
"""
abs_template_path = os.path.join(
migration_environment.environment_config.sceptre_dir,
template_path
)
logging.getLogger(__name__).debug(
"%s - Preparing to Import CloudFormation to %s",
os.path.basename(template_path).split(".")[0],
abs_template_path
)
response = migration_environment.connection_manager.call(
service='cloudformation',
command='get_template',
kwargs={
'StackName': aws_stack_name,
'TemplateStage': 'Original'
}
)
_write_template(
abs_template_path,
_normalize_template_for_write(
response['TemplateBody'],
os.path.splitext(template_path)[1]
)
)
template = Template(abs_template_path, [])
template.relative_template_path = template_path
return template
# If body is a string it is a YAML string;
# otherwise, it is a dict resulting from JSON document.
def _normalize_template_for_write(body, ext):
if ext == ".json":
# if it's YAML, make it a dict
if isinstance(body, string_types):
body = yaml.safe_load(body)
# now make it a JSON string
body = json.dumps(body)
elif ext == ".yaml":
# if it's JSON, make it a YAML string
if not isinstance(body, string_types):
body = yaml.safe_dump(body, default_flow_style=False)
else:
raise UnsupportedTemplateFileTypeError(
"Template file has has extension {}. Only .yaml, "
"and .json are supported, when importing from AWS.".format(ext)
)
return body
def _write_template(path, body):
if not os.path.isfile(path):
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
with open(path, 'w') as template_file:
template_file.write(body)
else:
with open(path, 'r') as template_file:
existing_body = template_file.read()
if yaml.load(existing_body) != yaml.load(body):
raise ImportFailureError(
"Unable to import template. "
"File already exists and is different: "
"file = {}, existing_body={}, new_body={}"
.format(path, existing_body, body)
)
<file_sep>sceptre\_migration\_tool package
================================
Subpackages
-----------
.. toctree::
sceptre_migration_tool.reverse_resolvers
Submodules
----------
sceptre\_migration\_tool\.cli module
------------------------------------
.. automodule:: sceptre_migration_tool.cli
:members:
:undoc-members:
:show-inheritance:
sceptre\_migration\_tool\.config module
---------------------------------------
.. automodule:: sceptre_migration_tool.config
:members:
:undoc-members:
:show-inheritance:
sceptre\_migration\_tool\.exceptions module
-------------------------------------------
.. automodule:: sceptre_migration_tool.exceptions
:members:
:undoc-members:
:show-inheritance:
sceptre\_migration\_tool\.migration\_environment module
-------------------------------------------------------
.. automodule:: sceptre_migration_tool.migration_environment
:members:
:undoc-members:
:show-inheritance:
sceptre\_migration\_tool\.migrator module
-----------------------------------------
.. automodule:: sceptre_migration_tool.migrator
:members:
:undoc-members:
:show-inheritance:
sceptre\_migration\_tool\.stack module
--------------------------------------
.. automodule:: sceptre_migration_tool.stack
:members:
:undoc-members:
:show-inheritance:
sceptre\_migration\_tool\.template module
-----------------------------------------
.. automodule:: sceptre_migration_tool.template
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: sceptre_migration_tool
:members:
:undoc-members:
:show-inheritance:
<file_sep>sceptre\_migration\_tool\.reverse\_resolvers package
====================================================
Submodules
----------
sceptre\_migration\_tool\.reverse\_resolvers\.reverse\_exports module
---------------------------------------------------------------------
.. automodule:: sceptre_migration_tool.reverse_resolvers.reverse_exports
:members:
:undoc-members:
:show-inheritance:
sceptre\_migration\_tool\.reverse\_resolvers\.reverse\_intuit\_ami module
-------------------------------------------------------------------------
.. automodule:: sceptre_migration_tool.reverse_resolvers.reverse_intuit_ami
:members:
:undoc-members:
:show-inheritance:
sceptre\_migration\_tool\.reverse\_resolvers\.reverse\_stack\_output module
---------------------------------------------------------------------------
.. automodule:: sceptre_migration_tool.reverse_resolvers.reverse_stack_output
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: sceptre_migration_tool.reverse_resolvers
:members:
:undoc-members:
:show-inheritance:
<file_sep># -*- coding: utf-8 -*-
"""
sceptre_migration_tool.cli
This module implements the Sceptre Migration Tool CLI
"""
import os
import logging
from logging import Formatter
import warnings
import click
import colorama
import yaml
from . import __version__
from sceptre import cli as sceptre_cli
from sceptre.environment import Environment
from sceptre_migration_tool import migrator
@click.group()
@click.version_option(version=__version__, prog_name="Sceptre Migration Tool")
@click.option("--debug", is_flag=True, help="Turn on debug logging.")
@click.option(
"--dir", "directory", help="Specify sceptre_migration_tool directory.")
@click.option(
"--var", multiple=True, help="A variable to template into config files.")
@click.option(
"--var-file", type=click.File("rb"),
help="A YAML file of variables to template into config files.")
@click.pass_context
def cli(
ctx, debug, directory, var, var_file
): # pragma: no cover
"""
Implements sceptre_migration_tool's CLI.
"""
setup_logging(debug)
colorama.init()
# Enable deprecation warnings
warnings.simplefilter("always", DeprecationWarning)
ctx.obj = {
"options": {},
"sceptre_dir": directory if directory else os.getcwd()
}
user_variables = {}
if var_file:
user_variables.update(yaml.safe_load(var_file.read()))
if var:
# --var options overwrite --var-file options
for variable in var:
variable_key, variable_value = variable.split("=")
user_variables.update({variable_key: variable_value})
if user_variables:
ctx.obj["options"]["user_variables"] = user_variables
@cli.command(name="import-stack")
@sceptre_cli.stack_options
@click.argument("aws_stack_name")
@click.option("--template", "template_path", help="Specify template path.")
@click.pass_context
@sceptre_cli.catch_exceptions
def import_stack(ctx, environment, stack, aws_stack_name, template_path):
"""
Import a Sceptre stack from AWS Cloudformation.
"""
if not template_path:
template_path = os.path.join(
"templates",
aws_stack_name + ".yaml"
)
migrator.import_stack(
Environment(
sceptre_dir=ctx.obj["sceptre_dir"],
environment_path=environment,
options=ctx.obj["options"]
),
aws_stack_name,
stack,
template_path
)
@cli.command(name="import-list")
@click.option("--list-path", "list_path", required=True,
help="Specify the file containing the list of stacks to import. "
"Each line in the list represents one stack and has 4 space "
"delimited values: "
"environment sceptre-stack-name aws-stack-name {template-path} "
"The last is optional and if not specified by template will "
"be assumed as templates/aws-import/{aws-stack-name}.yaml")
@click.pass_context
@sceptre_cli.catch_exceptions
def import_list(ctx, list_path):
"""
Import a list of Sceptre stack from AWS Cloudformation.
"""
with open(list_path, 'r') as fobj:
migrator.import_list(ctx.obj["sceptre_dir"], ctx.obj["options"], fobj)
@cli.command(name="generate-import-list")
@click.option("--list-path", "list_path",
help="Specify the list output file.")
@click.pass_context
@sceptre_cli.environment_options
@sceptre_cli.catch_exceptions
def generate_import_list(ctx, environment, list_path):
"""
Generate import a list of Sceptre stack from AWS Cloudformation.
"""
env = Environment(
sceptre_dir=ctx.obj["sceptre_dir"],
environment_path=environment,
options=ctx.obj["options"]
)
if list_path:
with open(list_path, 'w') as list_file_obj:
migrator.generate_import_list(env, list_file_obj)
else:
migrator.generate_import_list(env)
@cli.command(name="import-env")
@sceptre_cli.environment_options
@click.pass_context
@sceptre_cli.catch_exceptions
def import_env(ctx, environment):
"""
Import a Sceptre environment from a set of AWS CloudFormation stacks.
"""
env = Environment(
sceptre_dir=ctx.obj["sceptre_dir"],
environment_path=environment,
options=ctx.obj["options"]
)
migrator.import_env(env)
def setup_logging(debug):
"""
Sets up logging.
By default, the python logging module is configured to push logs to stdout
as long as their level is at least INFO. The log format is set to
"[%(asctime)s] - %(name)s - %(message)s" and the date format is set to
"%Y-%m-%d %H:%M:%S".
After this function has run, modules should:
.. code:: python
import logging
logging.getLogger(__name__).info("my log message")
:param debug: A flag indication whether to turn on debug logging.
:type debug: bool
:no_colour: A flag to indicating whether to turn off coloured output.
:type no_colour: bool
:returns: A logger.
:rtype: logging.Logger
"""
if debug:
sceptre_logging_level = logging.DEBUG
logging.getLogger("botocore").setLevel(logging.INFO)
else:
sceptre_logging_level = logging.INFO
# Silence botocore logs
logging.getLogger("botocore").setLevel(logging.CRITICAL)
formatter = Formatter(
fmt="[%(asctime)s] - %(name)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
log_handler = logging.StreamHandler()
log_handler.setFormatter(formatter)
logger = logging.getLogger("sceptre")
logger.addHandler(log_handler)
logger.setLevel(sceptre_logging_level)
logger = logging.getLogger("sceptre_migration_tool")
logger.addHandler(log_handler)
logger.setLevel(sceptre_logging_level)
return logger
<file_sep>'''
Created on Nov 29, 2017
@author: <NAME>
'''
from sceptre_migration_tool.reverse_resolvers import ReverseResolver
class ReverseExports(ReverseResolver):
def __init__(self, *args, **kwargs):
super(ReverseExports, self).__init__(*args, **kwargs)
self._exports = None
def precendence(self):
return 10
def suggest(self, value):
if self._exports is None:
self._exports = self._get_exports()
suggestion = self._exports[value] if value in self._exports else None
self.logger.debug(
"Export Suggestion for '%s' is '%s'",
value,
suggestion
)
return suggestion
def _get_exports(self):
"""
Communicates with AWS Cloudformation to fetch exports.
:returns: A formatted version of the stack exports.
:rtype: dict
"""
self.logger.debug("Collecting exports...")
exports = {}
list_exports_kwargs = {}
while True:
response = self.migration_environment.connection_manager.call(
service="cloudformation",
command="list_exports",
kwargs=list_exports_kwargs
)
for export in response["Exports"]:
if export["Value"] in exports:
self.logger.warning(
"Skipping %s export reverse lookup."
" Duplicate Value=%s",
export["Name"],
export["Value"]
)
else:
key = export["Value"]
export_key = export["Name"]
exports[key] = "!stack_export '" + export_key + "'"
if 'NextToken' in response \
and response['NextToken'] is not None:
list_exports_kwargs = {'NextToken': response['NextToken']}
else:
break
self.logger.debug("Exports: %s", exports)
return exports
<file_sep># -*- coding: utf-8 -*-
import abc
import six
import logging
@six.add_metaclass(abc.ABCMeta)
class ReverseResolver():
"""
ReverseResolver is an abstract base class that should be inherited by all
reverse-resolvers. Environment config and the connection manager are
supplied to the class, as they may be of use to inheriting classes.
:param environment_config: The environment_config from config.yaml files.
:type environment_config: sceptre.config.Config
:param connection_manager: A connection manager.
:type connection_manager: sceptre.connection_manager.ConnectionManager
:param argument: Arguments to pass to the resolver.
:type argument: str
"""
def __init__(
self,
migration_environment=None
):
self.logger = logging.getLogger(__name__)
self.migration_environment = migration_environment
@abc.abstractmethod
def precendence(self):
"""
An integer between 1 and 99 (inclusive) which indicates precedence
of the reverse resolver. Lower values indicate higher precedence.
"""
pass # pragma: no cover
@abc.abstractmethod
def suggest(self, argument):
"""
An abstract method which must be overwritten by all inheriting classes.
This method is called to reverse resolve a value into a call to a
resolver in the config's parameters.
Implementation of this method in subclasses must return a suitable
string, or None to indicate they are unable to resolve.
"""
pass # pragma: no cover
<file_sep>=======
History
=======
0.0.1 (TBD)
------------------
* First release.
<file_sep># -*- coding: utf-8 -*-
"""
sceptre_migration_tool.config
This module imports an AWS stack configuration into Sceptre.
"""
from __future__ import print_function
import os
import yaml
import logging
from .exceptions import ImportFailureError
def default_ctor(loader, tag_suffix, node):
return tag_suffix + ' ' + str(node.value)
yaml.add_multi_constructor('!', default_ctor)
def import_config(
migration_environment,
aws_stack_name,
config_path,
template
):
abs_config_path = os.path.join(
migration_environment.environment_config.sceptre_dir,
'config',
config_path + ".yaml"
)
if os.path.isfile(config_path):
raise ImportFailureError(
"Unable to import config. "
"File already exists: file = {}".format(abs_config_path)
)
response = migration_environment.connection_manager.call(
service='cloudformation',
command='describe_stacks',
kwargs={
'StackName': aws_stack_name
}
)
migration_environment.set_resolution_context(
config_path,
aws_stack_name,
response['Stacks'][0],
template
)
with open(abs_config_path, 'w') as config_fobj:
writer = ConfigFileWriter(
config_fobj,
migration_environment
)
writer.write()
class ConfigFileWriter(object):
def __init__(self, config_fobj, migration_environment):
self.logger = logging.getLogger(__name__)
self.config_fobj = config_fobj
self.migration_environment = migration_environment
self.aws_stack = migration_environment.aws_stack
def write(self):
self._write_template_path()
self._write_stack_name()
self._write_protect()
self._write_role_arn()
self._write_parameters()
self._write_stack_tags()
def _write_template_path(self):
print(
'template_path: ' +
self.migration_environment.template.relative_template_path,
file=self.config_fobj
)
def _write_stack_name(self):
print(
'stack_name: ' + self.migration_environment.aws_stack_name,
file=self.config_fobj
)
def _write_protect(self):
if 'EnableTerminationProtection' in self.aws_stack \
and self.aws_stack['EnableTerminationProtection']:
print('protect: True', file=self.config_fobj)
def _write_role_arn(self):
if 'RoleARN' in self.aws_stack and self.aws_stack['RoleARN']:
print(
'role_arn: ' + self.aws_stack['RoleARN'],
file=self.config_fobj
)
def _get_template_parameters(self):
# we use YAML only as JSON is a subset
template_body = yaml.load(self.migration_environment.template.body)
return template_body['Parameters'] \
if 'Parameters' in template_body else {}
def _write_parameters(self):
if 'Parameters' in self.aws_stack and self.aws_stack['Parameters']:
print('parameters:', file=self.config_fobj)
template_parameters = self._get_template_parameters()
aws_stack_parameter_list = sorted(
self.aws_stack['Parameters'],
key=lambda x: x['ParameterKey']
)
for parameter in aws_stack_parameter_list:
key = parameter['ParameterKey']
value = parameter['ParameterValue']
template_parameter = template_parameters[key]
if 'Default' in template_parameter \
and value == template_parameter['Default']:
print(
" #{}: '{}'".format(key, value),
file=self.config_fobj
)
else:
suggested_value = \
self.migration_environment.suggest(value)
print(
" {}: {}".format(key, suggested_value),
file=self.config_fobj
)
def _write_stack_tags(self):
if 'Tags' in self.aws_stack and len(self.aws_stack['Tags']) > 0:
print('stack_tags:', file=self.config_fobj)
for tag in self.aws_stack['Tags']:
print(
' "{}": "{}"'.format(
tag['Key'],
tag['Value']
),
file=self.config_fobj
)
<file_sep>--index-url https://artifact.intuit.com/artifactory/api/pypi/pypi-intuit/simple
sceptre==1.3.1<file_sep># -*- coding: utf-8 -*-
from sceptre.exceptions import SceptreException
class ImportFailureError(SceptreException):
"""
Error raised when import of a stack from AWS fails.
"""
<file_sep># Docs
This directory contains the code for Sceptre Migration Tool [docs](https://sceptre.intuit.com).
The docs is written using the [Jekyll](https://jekyllrb.com) framework.
## Ruby
Jekyll depends on Ruby. Documentation on installing Ruby can be found [here](https://www.ruby-lang.org/en/documentation/installation/).
## Install Jekyll
Jekyll and its dependencies can be installed with:
```shell
make install
```
## Build and serve docs locally
The docs can be built with:
```shell
make docs-latest
```
To serve the docs and watch for changes, run:
```shell
make serve-latest
```
View them at `http://localhost:4000/latest/`
<file_sep># -*- coding: utf-8 -*-
import logging
import os
import re
from sceptre.helpers import get_subclasses
from sceptre.template import Template
from sceptre_migration_tool.reverse_resolvers import ReverseResolver
class MigrationEnvironment(object):
PART_ENV = 0
PART_SCEPTRE_STACK_NAME = 1
PART_AWS_STACK_NAME = 2
PART_TEMPLATE_PATH = 3
@classmethod
def read_import_stack_list(cls, list_fobj):
import_stack_list = []
for line in list_fobj.readlines():
item = cls._parse_import_stack_item(line)
if item:
import_stack_list.append(item)
return import_stack_list
@classmethod
def _parse_import_stack_item(cls, line):
if line.startswith('#'):
return None
parts = line.split()
if len(parts) < 3:
return None
return (
parts[cls.PART_ENV],
parts[cls.PART_SCEPTRE_STACK_NAME],
parts[cls.PART_AWS_STACK_NAME],
parts[cls.PART_TEMPLATE_PATH] if len(parts) > 3 else
os.path.join(
"templates",
"aws-import",
parts[cls.PART_AWS_STACK_NAME] + ".yaml"
)
)
def __init__(self,
connection_manager, environment_config, import_stack_list=[]
):
self.logger = logging.getLogger(__name__)
self.connection_manager = connection_manager
self.environment_config = environment_config
self.import_stack_list = import_stack_list
self._reversed_env_config = {
str(v): "{{ var." + str(k) + " }}"
for k, v
in self.environment_config['user_variables'].items()
}
self._config_re_pattern = '|'.join(
[
re.escape(str(config_value))
for config_value
in self.environment_config['user_variables'].values()
]
)
self._reverse_resolver_list = None
self.config_path = ""
self.aws_stack_name = ""
self.aws_stack = {}
self.template = Template("", {})
@property
def reverse_resolver_list(self):
if self._reverse_resolver_list is None:
self._reverse_resolver_list = []
self._add_reverse_resolvers(
os.path.join(
os.path.dirname(__file__),
"reverse_resolvers"
)
)
self._add_reverse_resolvers(
os.path.join(
self.environment_config.sceptre_dir,
"reverse_resolvers"
)
)
self._reverse_resolver_list.sort(key=lambda r: r.precendence())
self.logger.debug(
"reverse_resolver_list = %s",
str(self._reverse_resolver_list)
)
return self._reverse_resolver_list
def get_internal_stack(self, stack):
for item in self.import_stack_list:
if stack == item[self.PART_AWS_STACK_NAME]:
return "{}/{}".format(
item[self.PART_ENV],
item[self.PART_SCEPTRE_STACK_NAME]
)
return None
def _add_reverse_resolvers(self, directory):
classes = get_subclasses(
directory=directory, class_type=ReverseResolver
)
self.logger.debug(
"_add_reverse_resolvers for directory %s are %s",
directory,
str(classes)
)
for node_class in classes.values():
self._reverse_resolver_list.append(
node_class(
self
)
)
def set_resolution_context(
self, config_path, aws_stack_name, aws_stack, template
):
self.config_path = config_path
self.aws_stack_name = aws_stack_name
self.aws_stack = aws_stack
self.template = template
def suggest(self, value):
if value in self._reversed_env_config:
suggestion = "'" + self._reversed_env_config[value] + "'"
else:
suggestion = self._scan_resolvers_for_suggestion(value)
suggestion = self._reverse_env_config(suggestion) \
if suggestion else "'" + value + "'"
self.logger.debug("Resolution for '%s' is %s", value, suggestion)
return suggestion
def _scan_resolvers_for_suggestion(self, value):
for reverse_resolver in self.reverse_resolver_list:
suggestion = reverse_resolver.suggest(value)
if suggestion:
return suggestion
return None
def _reverse_env_config(self, value):
def reverse(m):
return self._reversed_env_config[m.group(0)]
if self._config_re_pattern:
return re.sub(
self._config_re_pattern,
reverse,
value
)
return value
<file_sep>
# from mock import Mock
from mock import sentinel
# import pytest
from sceptre_migration_tool.migration_environment import MigrationEnvironment
from sceptre_migration_tool.reverse_resolvers import ReverseResolver
class MockConfig(dict):
pass
class MockReverseResolver(ReverseResolver):
"""
MockReverseResolver inherits from the abstract base class ReverseResolver,
and implements the abstract methods. It is used to allow testing on
ReverseResolver, which is not otherwise instantiable.
"""
mock_precendence = 99
mock_suggtestion = None
def precendence(self):
return self.mock_precendence
def suggest(self, argument):
return self.mock_suggtestion
class TestReverseResolver(object):
class MockConfig(dict):
pass
def setup_method(self, test_method):
self.mock_environment_config = self.MockConfig()
self.mock_environment_config.sceptre_dir = 'fake-spectre-dir'
self.mock_environment_config['user_variables'] = {}
self.reverse_exporter = MockReverseResolver(
MigrationEnvironment(
connection_manager=sentinel.connection_manager,
environment_config=self.mock_environment_config
)
)
def test_config_correctly_initialised(self):
assert self.reverse_exporter.migration_environment\
.connection_manager == sentinel.connection_manager
assert self.reverse_exporter.migration_environment\
.environment_config == self.mock_environment_config
assert self.reverse_exporter.precendence() == 99
assert self.reverse_exporter.suggest("value") is None
<file_sep>from behave import given, then
import os
import yaml
def set_template_path(context, stack_name, template_name):
config_path = os.path.join(
context.sceptre_dir, "config", stack_name + ".yaml"
)
template_path = os.path.join("templates", template_name)
with open(config_path) as config_file:
stack_config = yaml.safe_load(config_file)
stack_config["template_path"] = template_path
with open(config_path, 'w') as config_file:
yaml.safe_dump(stack_config, config_file, default_flow_style=False)
@given('template "{template_name}" does not exist') # noqa: F811
def step_impl(context, template_name):
filepath = os.path.join(
context.sceptre_dir, template_name
)
os.remove(filepath) if os.path.isfile(filepath) else None
@given('the template for stack "{stack_name}" ' # noqa: F811
'is "{template_name}"')
def step_impl(context, stack_name, template_name):
set_template_path(context, stack_name, template_name)
@given('template "{template_name}" exists') # noqa: F811
def step_impl(context, template_name):
filepath = os.path.join(
context.sceptre_dir, template_name
)
assert os.path.exists(
filepath
), "template '{}' not found at '{}'".format(
template_name,
filepath
)
context.template_file_mtime = os.stat(filepath).st_mtime
@then('template "{template_name}" exists') # noqa: F811
def step_impl(context, template_name):
filepath = os.path.join(
context.sceptre_dir, template_name
)
assert os.path.exists(
filepath
), "template '{}' not found at '{}'".format(
template_name,
filepath
)
@then('template "{template_name}" is unchanged') # noqa: F811
def step_impl(context, template_name):
filepath = os.path.join(
context.sceptre_dir, template_name
)
assert context.template_file_mtime == os.stat(filepath).st_mtime, \
"template '{}' has been changed.".format(template_name)
<file_sep>=======
Credits
=======
Owner
-----
* <NAME> `@omerazmon <https://github.com/omerazmon>`_
Development Leads
-----------------
* <NAME> `@omerazmon <https://github.com/omerazmon>`_
Contributors
------------
<file_sep># -*- coding: utf-8 -*-
from contextlib import contextmanager
from tempfile import mkdtemp
import shutil
import json
from mock import patch, Mock, call
import pytest
from sceptre.connection_manager import ConnectionManager
from sceptre.template import Template
from sceptre_migration_tool import config
from sceptre_migration_tool.exceptions import ImportFailureError
from sceptre_migration_tool.migration_environment import MigrationEnvironment
class TestConfig(object):
class MockConfig(dict):
pass
@contextmanager
def _create_temp_dir(self):
temp_directory = mkdtemp()
yield temp_directory
shutil.rmtree(temp_directory)
def setup_method(self, test_method):
connection_manager = Mock(spec=ConnectionManager)
environment_config = self.MockConfig()
environment_config.sceptre_dir = 'fake-spectre-dir'
environment_config["user_variables"] = {}
self.migration_environment = MigrationEnvironment(
connection_manager, environment_config)
self.migration_environment._reverse_resolver_list = []
@patch("sceptre_migration_tool.config.os.path.isfile")
def test_import_config__exists(
self, mock_isfile
):
mock_isfile.return_value = True
with pytest.raises(ImportFailureError):
config.import_config(
migration_environment=self.migration_environment,
aws_stack_name="fake-aws-stack-name",
config_path="environment-path/fake-stack",
template=Template('fake-path', [])
)
@patch("sceptre_migration_tool.config.print")
@patch("sceptre_migration_tool.config.open")
@patch("sceptre_migration_tool.config.os.path.isfile")
def test_import_config__empty_stack(
self, mock_isfile, mock_open, mock_print
):
self.migration_environment.connection_manager\
.call.return_value = {'Stacks': [
{
}
]}
mock_isfile.return_value = False
fake_template = Template('fake-path', [])
fake_template.relative_template_path = 'fake-relative-path'
config.import_config(
migration_environment=self.migration_environment,
aws_stack_name="fake-aws-stack-name",
config_path="environment-path/fake-stack",
template=fake_template
)
mock_open.assert_called_with(
"fake-spectre-dir/config/environment-path/fake-stack.yaml",
'w'
)
mock_print.assert_has_calls(
[
call(
"template_path: fake-relative-path",
file=mock_open.return_value.__enter__.return_value
),
call(
"stack_name: fake-aws-stack-name",
file=mock_open.return_value.__enter__.return_value
)
],
any_order=False
)
@patch("sceptre_migration_tool.config.print")
@patch("sceptre_migration_tool.config.open")
@patch("sceptre_migration_tool.config.os.path.isfile")
def test_import_config__all_details_stack(
self, mock_isfile, mock_open, mock_print
):
mock_template = Mock()
mock_template.path = 'fake-path'
mock_template.relative_template_path = 'fake-relative-path.yaml'
mock_template.body = json.dumps({
'Parameters': {
'fake-key1': {
},
'fake-key2': {
'Default': 'wrong-value'
},
'fake-key3': {
'Default': 'match-default-value'
},
'fake-key4': {
}
}
})
self.migration_environment.connection_manager\
.call.return_value = {'Stacks': [
{
'EnableTerminationProtection': True,
'RoleARN': 'fake-role-arn',
'Parameters': [
{
'ParameterKey': 'fake-key1',
'ParameterValue': 'no-default-value'
},
{
'ParameterKey': 'fake-key2',
'ParameterValue': 'mismatch-default-value'
},
{
'ParameterKey': 'fake-key3',
'ParameterValue': 'match-default-value'
},
{
'ParameterKey': 'fake-key4',
'ParameterValue': '!Ref ref-value'
}
],
'Tags': [
{
'Key': 'fake-tag-key',
'Value': 'fake-tag-value'
}
]
}
]}
mock_isfile.return_value = False
config.import_config(
migration_environment=self.migration_environment,
aws_stack_name="fake-aws-stack-name",
config_path="environment-path/fake-stack",
template=mock_template
)
expected_calls = [
call(
"template_path: fake-relative-path.yaml",
file=mock_open.return_value.__enter__.return_value
),
call(
"stack_name: fake-aws-stack-name",
file=mock_open.return_value.__enter__.return_value
),
call(
"protect: True",
file=mock_open.return_value.__enter__.return_value
),
call(
"role_arn: fake-role-arn",
file=mock_open.return_value.__enter__.return_value
),
call(
"parameters:",
file=mock_open.return_value.__enter__.return_value
),
call(
" fake-key1: 'no-default-value'",
file=mock_open.return_value.__enter__.return_value
),
call(
" fake-key2: 'mismatch-default-value'",
file=mock_open.return_value.__enter__.return_value
),
call(
" #fake-key3: 'match-default-value'",
file=mock_open.return_value.__enter__.return_value
),
call(
" fake-key4: '!Ref ref-value'",
file=mock_open.return_value.__enter__.return_value
),
call(
"stack_tags:",
file=mock_open.return_value.__enter__.return_value
),
call(
" \"fake-tag-key\": \"fake-tag-value\"",
file=mock_open.return_value.__enter__.return_value
)
]
mock_print.assert_has_calls(
expected_calls,
any_order=False
)
<file_sep># -*- coding: utf-8 -*-
import os
from mock import sentinel, Mock, patch
from sceptre_migration_tool.reverse_resolvers import ReverseResolver
from sceptre_migration_tool.migrator import MigrationEnvironment
class TestMigrationEnvironment_import_stack_list(object):
def test__parse_import_stack_item1(self):
assert MigrationEnvironment._parse_import_stack_item('') is None
def test__parse_import_stack_item2(self):
assert MigrationEnvironment._parse_import_stack_item(' ') is None
def test__parse_import_stack_item3(self):
assert MigrationEnvironment._parse_import_stack_item(
'# 1 2 3 4 '
) is None
def test__parse_import_stack_item4(self):
assert MigrationEnvironment._parse_import_stack_item(
'1 2 3 4 '
) == ('1', '2', '3', '4')
def test__parse_import_stack_item5(self):
assert MigrationEnvironment._parse_import_stack_item(
'1 2 3'
) == ('1', '2', '3', 'templates/aws-import/3.yaml')
def test_read_import_stack_list__empty(self):
mock_fobj = Mock()
mock_fobj.readlines.return_value = []
result = MigrationEnvironment.read_import_stack_list(mock_fobj)
assert result == []
def test_read_import_stack_list__data(self):
mock_fobj = Mock()
mock_fobj.readlines.return_value = ["1 2 3 4"]
result = MigrationEnvironment.read_import_stack_list(mock_fobj)
assert result == [('1', '2', '3', '4')]
class TestMigrationEnvironment(object):
class MockConfig(dict):
pass
def setup_method(self):
self.mock_config = self.MockConfig()
self.mock_config['user_variables'] = {}
self.migration_environment = MigrationEnvironment(
connection_manager=sentinel.connection_manager,
environment_config=self.mock_config
)
def test_config_correctly_initialised(self):
assert self.migration_environment.connection_manager == \
sentinel.connection_manager
assert self.migration_environment.environment_config == \
self.mock_config
assert self.migration_environment._reversed_env_config == {}
assert self.migration_environment._config_re_pattern == ''
assert self.migration_environment._reverse_resolver_list is None
@patch("sceptre_migration_tool.migration_environment.get_subclasses")
def test__add_reverse_resolvers__no_classes(self, mock_get_subclasses):
mock_get_subclasses.return_value = {}
self.migration_environment._add_reverse_resolvers('fake-dir')
mock_get_subclasses.assert_called_once_with(
directory='fake-dir',
class_type=ReverseResolver
)
@patch("sceptre_migration_tool.migration_environment.get_subclasses")
def test__add_reverse_resolvers(self, mock_get_subclasses):
mock_class = Mock()
mock_get_subclasses.return_value = {'key': mock_class}
self.migration_environment._reverse_resolver_list = []
self.migration_environment._add_reverse_resolvers('fake-dir')
mock_get_subclasses.assert_called_once_with(
directory='fake-dir',
class_type=ReverseResolver
)
mock_class.assert_called_once_with(
self.migration_environment
)
def test_suggest__no_resolvers(self):
self.migration_environment._reverse_resolver_list = []
result = self.migration_environment.suggest('value')
assert result == "'value'"
def test_suggest(self):
def _make_reverse_resolver(return_value):
reverse_resolver = Mock()
reverse_resolver.suggest.return_value = return_value
return reverse_resolver
self.migration_environment._reverse_resolver_list = [
_make_reverse_resolver(None),
_make_reverse_resolver("suggest2"),
_make_reverse_resolver("suggest3")
]
result = self.migration_environment.suggest('value')
assert result == 'suggest2'
def test_suggest__match_env_config(self):
self.migration_environment._reversed_env_config['value'] = \
'fake-reversal'
self.migration_environment._reverse_resolver_list = []
result = self.migration_environment.suggest('value')
assert result == "'fake-reversal'"
def test_reverse_resolver_list__pre_defined(self):
self.migration_environment._reverse_resolver_list = 'fake-list'
result = self.migration_environment.reverse_resolver_list
assert 'fake-list' == result
@patch("sceptre_migration_tool.migration_environment.MigrationEnvironment"
"._add_reverse_resolvers")
def test_reverse_resolver_list__search(self, mock__add_reverse_resolvers):
self.migration_environment.environment_config.sceptre_dir = \
'fake-sceptre-dir'
result = self.migration_environment.reverse_resolver_list
assert [] == result
assert 2 == mock__add_reverse_resolvers.call_count
mock__add_reverse_resolvers.assert_any_call(
os.path.join(
os.path.dirname(os.path.dirname(__file__)),
"sceptre_migration_tool",
"reverse_resolvers"
)
)
mock__add_reverse_resolvers.assert_any_call(
'fake-sceptre-dir/reverse_resolvers'
)
def test_get_internal_stack__not_found(self):
result = \
self.migration_environment.get_internal_stack("fake-stack-name")
assert result is None
def test_get_internal_stack__found(self):
self.migration_environment.import_stack_list = [
(
"fake-env-path",
"fake-sceptre-name",
"fake-stack-name",
"template/fake-stack-name.yaml"
)
]
result = \
self.migration_environment.get_internal_stack("fake-stack-name")
assert result == 'fake-env-path/fake-sceptre-name'
class TestMigrationEnvironment__reverse_env_config(object):
class MockConfig(dict):
pass
def setup_method(self):
self.mock_config = self.MockConfig()
self.mock_config['user_variables'] = {
'preprod_aws_profile': 'my-special-profile',
'preprod_region': 'us-west-2',
'preprod_vpc_id': 'vpc-abc123'
}
self.migration_environment = MigrationEnvironment(
connection_manager=sentinel.connection_manager,
environment_config=self.mock_config
)
def test_config_correctly_initialised(self):
assert self.migration_environment.connection_manager == \
sentinel.connection_manager
assert self.migration_environment.environment_config == \
self.mock_config
assert self.migration_environment._reversed_env_config == {
'my-special-profile': '{{ var.preprod_aws_profile }}',
'us-west-2': '{{ var.preprod_region }}',
'vpc-abc123': '{{ var.preprod_vpc_id }}'
}
assert self.migration_environment._config_re_pattern\
.split('|').sort() == \
'us\\-west\\-2|vpc\\-abc123|my\\-special\\-profile'\
.split('|').sort()
assert self.migration_environment._reverse_resolver_list is None
def test__multi_subst(self):
result = self.migration_environment._reverse_env_config(
'my-bucket-vpc-abc123-us-west-2'
)
assert result ==\
'my-bucket-{{ var.preprod_vpc_id }}-{{ var.preprod_region }}'
<file_sep>======================
Sceptre Migration Tool
======================
.. image:: https://circleci.com/gh/intuit/sceptre_migration_tool.png?style=shield
About
-----
Sceptre Migration Tool is a tool to assist importing from AWS `CloudFormation <https://aws.amazon.com/cloudformation/>`_ into a Sceptre environment. It automates away some of the more mundane, repetitive and error-prone migration tasks.
Features:
- Import single or a set of AWS Cloudformation from AWS into a sceptre environment
Example
-------
Give how Sceptre organises stacks into environments. Here, we have an empty environment named ``dev``::
$ tree
.
├── config
│ └── dev
│ └── config.yaml
└── templates
We can create a import a stack with the ``import-stack`` command. Assuming an existing stack named 'aws-vpc'
$ sceptre import-stack dev vpc aws-vpc.yaml
dev/vpc - Importing stack
dev/vpc - Imported AWS CloudFormation template 'aws-vpc' into 'templates/aws-vpc.yaml'
dev/vpc - Imported stack config from AWS CloudFormation stack 'aws-vpc'
dev/vpc - Stack imported
We can create a import a complete environment. Assuming two stacks in AWS named 'aws-vpc' and 'aws-subnets'
$ sceptre import-env dev
dev - Importing environment
dev/aws-vpc - Imported AWS CloudFormation template into 'templates/aws-import/aws-vpc.yaml'
dev/aws-subnets - Imported AWS CloudFormation template into 'templates/aws-import/aws-subnets.yaml'
dev - Environment imported
Usage
-----
Sceptre Migration Tools can be used from the CLI, or imported as a Python package.
CLI::
Usage: sceptre_migration_tool [OPTIONS] COMMAND [ARGS]...
Implements sceptre_migration_tool's CLI.
Options:
--version Show the version and exit.
--debug Turn on debug logging.
--dir TEXT Specify sceptre_migration_tool directory.
--output [yaml|json] The formatting style for command output.
--no-colour Turn off output colouring.
--var TEXT A variable to template into config files.
--var-file FILENAME A YAML file of variables to template into config
files.
--help Show this message and exit.
Commands:
generate-import-list Generate import a list of Sceptre stack from...
import-env Import a Sceptre environment from a set of...
import-list Import a list of Sceptre stack from AWS...
import-stack Import a Sceptre stack from AWS...
Python:
.. code-block:: python
from sceptre.environment import Environment
from sceptre_migration_tool import migrator
env = Environment("/path/to/sceptre_dir", "environment_name")
migrator.import_stack(
env,
"aws_stack_name",
"target_sceptre_stack_name",
"target_template_path"
)
A full API description of the sceptre migration tool package can be found in the `Documentation <docs/index.html>`__.
Install
-------
::
$ pip install sceptre_migration_tool
More information on installing sceptre migration tool can be found in our `Installation Guide <docs/install.html>`_.
Tutorial and Documentation
--------------------------
- `Get Started <docs/get_started.html>`_
- `Documentation <docs/index.html>`__
Contributions
-------------
See our `Contributing Guide <CONTRIBUTING.rst>`_.
| 9674e85122df4bad36b28374358113a811ff3e94 | [
"reStructuredText",
"Markdown",
"Makefile",
"Python",
"Text",
"Shell"
] | 42 | Makefile | oazmon/sceptre-migration-tool | 9727cf69297c28bc59fa0217edec914d2b69e702 | a7e798783bd57d11d01a4b31feabce333ec99ad0 |
refs/heads/master | <file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align="center"> Build Your Classroom </h1>
<div class="row">
<?php
$message = $this->Session->flash();
if($message !=''){
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<div class='row'>
<fieldset>
<legend>Classroom Title</legend>
<?php
echo $this->Form->create('Classroom', array('controller'=>'classrooms','action' => 'process_create_classroom'));
echo $this->Form->input('title', array('type' => 'text', 'id' => 'title', 'label' => '','placeholder'=>'Give a title to your classroom'));
?>
<br>
Note: Give a name to your classroom i.e classroom is talking about soccer. Then title will be soccer.
<br>
</fieldset>
</div>
<br>
<div class='row' align='right'>
<ul class="button-group" width='100%'>
<?php
echo $this->Form->input('category', array('type' => 'hidden', 'value' => $category));
echo $this->Form->input('created_by', array('type' => 'hidden', 'value' => $login_id));
echo '<li>' . $this->Form->button('Create', array('class' => 'button', 'width' => '33%')) . '</li>';
echo $this->Html->link('Back', array('controller' => 'classrooms', 'action' => 'classroom_category'),array('class' => 'button', 'width' => '33%'));
echo $this->Form->end();
?>
</ul>
</div>
<file_sep><?php
App::uses('AppController', 'Controller');
class ProfilesController extends AppController {
Function index() {
$this->layout = 'profileTemplate';
}
Function addNewsFeed() {
$statusFeed = $this->request->data;
$userID = $this->Session->read('User.id');
$userGroupID = 0;
;
$this->loadModel('Post');
$wallOwner = $statusFeed['NewWallPost']['wallOwner'];
$this->loadModel('User');
$selectedUser = $this->User->Query('SELECT id FROM users WHERE username="' . $wallOwner . '"');
$newPostFeed = $statusFeed['NewWallPost']['newPost'];
//pr($selectedUser[0]['users']['id']);die();
$this->Post->Query('Insert into posts (posted_by, to_who, group_id, post_content) values ("' . $userID . '", "' . $selectedUser[0]['users']['id'] . '", "' . $userGroupID . '","' . $newPostFeed . '")');
$location = $statusFeed['NewWallPost']['location'];
if ($location == 0) {
$this->redirect(array('controller' => 'users', 'action' => 'success'));
} else {
$this->redirect(array('controller' => 'profiles', 'action' => 'viewProfile', $wallOwner));
}
}
Function viewProfile($username = '') {
$currentUsername = $this->Session->read('User.username');
if ($currentUsername == $username) {
$this->redirect(array('controller' => 'profiles', 'action' => 'myProfile', $username));
} else {
$this->redirect(array('controller' => 'profiles', 'action' => 'otherProfiles', $username));
}
}
Function myProfile($username = '') {
$this->layout = 'profileTemplate';
$this->loadModel('User');
$userArray = $this->User->Query('SELECT * FROM users WHERE id="' . $this->Session->read('User.id') . '"');
$this->set('userArray', $userArray);
$otherUsers = $this->User->Query('SELECT * FROM users');
$this->set('otherUsers', $otherUsers);
$this->loadModel('Post');
$userId = $this->Session->read('User.id');
$notificationArray = $this->Post->Query('SELECT * FROM posts WHERE to_who="' . $userId . '" ORDER BY timestamp DESC');
$this->set('notificationArray', $notificationArray);
$this->loadModel('Challenge');
$challengesToOthers = $this->Challenge->Query('SELECT * FROM challenges WHERE formed_by="' . $this->Session->read('User.id') . '"');
$this->set('challengesToOthers', $challengesToOthers);
$this->loadModel('School');
$allSchools = $this->User->Query('SELECT * FROM schools');
$this->set('allSchools', $allSchools);
//pass array of class to view
$this->loadModel('Class');
$allClasses = $this->User->Query('SELECT * FROM classes');
$this->set('allClasses', $allClasses);
$this->loadModel('Friend');
$allMyFriends = $this->Friend->Query('SELECT * FROM friends WHERE owner_id="' . $userId . '"');
$this->set('allMyFriends', $allMyFriends);
}
Function otherProfiles($username = '') {
$this->layout = 'profileTemplate';
$this->set('username', $username);
$this->loadModel('User');
$userArray = $this->User->Query('SELECT * FROM users WHERE username="' . $username . '"');
$this->set('userArray', $userArray);
$otherUsers = $this->User->Query('SELECT * FROM users');
$this->set('otherUsers', $otherUsers);
$this->loadModel('Post');
$userFound = $this->User->Query('SELECT id FROM users WHERE username="' . $username . '"');
$userId = $userFound[0]['users']['id'];
$notificationArray = $this->Post->Query('SELECT * FROM posts WHERE to_who="' . $userId . '" ORDER BY timestamp DESC');
$this->set('notificationArray', $notificationArray);
$this->loadModel('Challenge');
$challengesToOthers = $this->Challenge->Query('SELECT * FROM challenges WHERE formed_by="' . $userId . '"');
$this->set('challengesToOthers', $challengesToOthers);
$this->loadModel('School');
$allSchools = $this->User->Query('SELECT * FROM schools');
$this->set('allSchools', $allSchools);
//pass array of class to view
$this->loadModel('Class');
$allClasses = $this->User->Query('SELECT * FROM classes');
$this->set('allClasses', $allClasses);
$this->loadModel('Friend');
$allMyFriends = $this->Friend->Query('SELECT * FROM friends WHERE owner_id="' . $userId . '"');
$this->set('allMyFriends', $allMyFriends);
}
Function findFriends() {
$searchData = $this->request->data;
$targetUser = $searchData['SearchFriends']['enterFriends'];
$currentUser = $this->Session->read('User.username');
if ($currentUser == $targetUser) {
$this->redirect(array('controller' => 'profiles', 'action' => 'myProfile', $currentUser));
} else {
$this->loadModel('User');
$userArray = $this->User->Query('SELECT * FROM users WHERE username="' . $targetUser . '"');
if (empty($userArray)) {
$this->Session->setFlash('No such user found! Please try again.');
$this->redirect(array('controller' => 'profiles', 'action' => 'myProfile', $currentUser));
} else {
$this->redirect(array('controller' => 'profiles', 'action' => 'otherProfiles', $targetUser));
//pr($userArray);die();
}
}
}
Function addFriend($username = '') {
$this->loadModel('Friend');
$currentUser = $this->Session->read('User.id');
$this->loadModel('User');
$potentialFriend = $this->User->Query('SELECT id FROM users WHERE username ="' . $username . '"');
$potentialFriendId = $potentialFriend[0]['users']['id'];
$this->Friend->Query('INSERT INTO friends (owner_id, friend_id) VALUES ("' . $currentUser . '","' . $potentialFriendId . '")');
$this->Friend->Query('INSERT INTO friends (owner_id, friend_id) VALUES ("' . $potentialFriendId . '","' . $currentUser . '")');
$content = $this->Session->read('User.username').' has just added '.$username.' as friends!';
$this->loadModel('Post');
$this->Post->Query('INSERT INTO posts (posted_by, to_who, post_content) VALUES ("' . $currentUser . '","' . $potentialFriendId . '","'.$content .'")');
$this->Post->Query('INSERT INTO posts (posted_by, to_who, post_content) VALUES ("' . $potentialFriendId . '","' . $currentUser . '","'.$content .'")');
$this->Session->setFlash('You have successfully added ' . $username);
$this->redirect(array('controller'=>'profiles','action' => 'viewProfile', $username));
}
Function deleteFriend($username = '') {
$this->loadModel('Friend');
$currentUser = $this->Session->read("User.id");
$this->loadModel('User');
$currentFriend = $this->User->Query('SELECT id FROM users WHERE username ="' . $username . '"');
$currentFriendId = $currentFriend[0]['users']['id'];
$this->Friend->Query('Delete from friends where owner_id=' . $currentUser . ' and friend_id=' . $currentFriendId);
$this->Friend->Query('Delete from friends where owner_id=' . $currentFriendId . ' and friend_id=' . $currentUser);
$this->Session->setFlash('You have just unfriend ' . $username);
$this->redirect(array('controller'=>'profiles','action' => 'viewProfile', $username));
}
}
?>
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align='center'>Choose Your Question</h1>
<div class="row">
<?php
$message = $this->Session->flash();
if($message !=''){
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<div class='row'>
<table width='100%'>
<thead>
<th>Available Questions</th>
<th>Option A</th>
<th>Option B</th>
<th>Option C</th>
<th>Choose?</th>
</thead>
<?php
$count = 0;
$chosen_qns = explode(';', $chosen_qns);
foreach ($questions as $question):
?>
<tr>
<?php echo $this->Form->create('Challenge', array('action' => 'add_many_to_many/' . $challenge_id)); ?>
<td><?php echo $question['Question']['question_body'] ?>
<td><?php echo $question['Question']['answer_a'] ?>
<td><?php echo $question['Question']['answer_b'] ?>
<td><?php echo $question['Question']['answer_c'] ?>
<?php
$checked = false;
$qn_id = $question['Question']['question_id'];
foreach ($chosen_qns as $temp):
if ($temp === $qn_id) {
$checked = true;
break;
}
endforeach;
?>
<td><?php
if ($checked) {
echo $this->form->checkbox($count, array('checked' => 'checked'));
} else {
echo $this->form->checkbox($count);
}
?></td>
</tr>
<?php
$count++;
endforeach
?>
</table>
</div>
<div class='row'>
<ul class="button-group" width='100%'>
<?php
//echo $this->Form->end();
echo $this->Form->button('Form Challenge', array('controller' => 'challenge'), array('class' => 'button alert', 'width' => '33%'));
echo $this->Html->link("Back", array('controller' => 'challenges', 'action' => 'many_to_many'), array('class' => 'button', 'width' => '34%'));
?>
</ul>
</div><file_sep><?php
class AcceptChallenge extends AppModel{
var $name = 'AcceptChallenge';
}
?>
<file_sep><?php
class Challenge extends AppModel{
var $name = 'Challenge';
}
?>
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align='center'>Suggest A Question</h1>
<div class="row">
<?php
$message = $this->Session->flash();
if($message !=''){
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<br>
<?php
echo $this->Form->create('Question');
?>
<?php echo $this->Form->input('raised_by', array('type' => 'hidden', 'value' => $login_id)); ?>
<div class="row">
<fieldset>
<?php echo $this->Form->input('question_body', array('label' => 'Your Question')); ?>
<br>
<div class="row collapse">
<div class="large-2 columns">
<span class="prefix radius">Option A</span>
</div>
<div class="large-10 columns">
<span>
<?php echo $this->Form->input('answer_a', array('label' => FALSE)); ?>
</span>
</div>
</div>
<div class="row collapse">
<div class="large-2 columns">
<span class="prefix radius">Option B</span>
</div>
<div class="large-10 columns">
<span>
<?php echo $this->Form->input('answer_b', array('label' => FALSE)); ?>
</span>
</div>
</div>
<div class="row collapse">
<div class="large-2 columns">
<span class="prefix radius">Option C</span>
</div>
<div class="large-10 columns">
<span>
<?php echo $this->Form->input('answer_c', array('label' => FALSE)); ?>
</span>
</div>
</div>
</fieldset>
</div>
<br>
<div class="row collapse" algin='right'>
<ul class="button-group" width='100%'>
<?php
echo $this->Form->button('Suggest Now!', array('challenges' => 'suggest'), array('class' => 'button alert', 'width' => '33%', 'align' => 'right'));
echo $this->Form->end();
?>
</ul>
</div>
<file_sep><h1 align="center" >Knowledge Challenge Arena</h1>
<div class="row">
<?php
$message = $this->Session->flash();
if($message !=''){
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<br>
<!--individual Challenge-->
<?php $individualCount = 0 ?>
<div class='row'>
<fieldset>
<br>
<h3 align='center'>Your Challenge</h3>
<br>
<table width='100%'>
<thead>
<th width="70%">Challenge Title</th>
<th>Action</th>
</thead>
<tbody>
<?php
if (empty($individual)) {
echo '<td colspan="2">';
echo 'You do not have individual challenge yet.';
echo '</td>';
} else {
foreach ($individual as $challenge):
echo '<tr>';
echo '<td>';
echo $challenge['Challenge']['challenge_title'];
echo '</td>';
echo '<td width="30%">';
echo $this->Html->link("Accept", array('action' => 'accept_challenge', $challenge['Challenge']['challenge_id']), array('style' => 'background:#00CC00', 'class' => 'button alert', 'width' => '50%'));
echo ' ';
echo $this->Html->link('Reject', array('controller' => 'challenges', 'action' => 'reject_challenge', $challenge['Challenge']['challenge_id']), array('style' => 'background:#CC0000', 'class' => 'button', 'width' => '50%'));
$individualCount++;
echo '</tr>';
endforeach;
}
?>
</tbody>
</table>
</fieldset>
</div>
<br>
<div class='row'>
<fieldset>
<br>
<h3 align='center'>Your Class Challenge</h3>
<br>
<!-- Class Challenge -->
<?php $classCount = 0 ?>
<table width='100%'>
<thead>
<th width="70%">Challenge Title</th>
<th>Action</th>
</thead>
<tbody>
<?php
if (empty($class)) {
echo '<td colspan="2">';
echo 'You do not have class challenge yet.';
echo '</td>';
} else {
foreach ($class as $challenge):
echo '<tr>';
echo '<td>';
echo $challenge['Challenge']['challenge_title'];
echo '</td>';
echo '<td width="30%">';
echo $this->Html->link("Accept", array('action' => 'accept_challenge', $challenge['Challenge']['challenge_id']), array('style' => 'background:#00CC00', 'class' => 'button alert', 'width' => '50%'));
echo ' ';
echo $this->Html->link('Reject', array('controller' => 'challenges', 'action' => 'reject_challenge', $challenge['Challenge']['challenge_id']), array('style' => 'background:#CC0000', 'class' => 'button', 'width' => '50%'));
$classCount++;
echo '</tr>';
endforeach;
}
?>
</tbody>
</table>
</fieldset>
</div>
<br>
<div class='row'>
<!-- School Challenge-->
<fieldset>
<br>
<h3 align='center'>Your School Challenge</h3>
<br>
<?php $schoolCount = 0 ?>
<table width='100%'>
<thead>
<th width="70%">Challenge Title</th>
<th>Action</th>
</thead>
<tbody>
<tr>
<?php
if (empty($school)) {
echo '<td colspan="2">';
echo 'You do not have school challenge yet.';
echo '</td>';
} else {
foreach ($school as $challenge):
echo '<tr>';
echo '<td>';
echo $challenge['Challenge']['challenge_title'];
echo '</td>';
echo '<td width="30%">';
echo $this->Html->link("Accept", array('action' => 'accept_challenge', $challenge['Challenge']['challenge_id']), array('style' => 'background:#00CC00', 'class' => 'button alert', 'width' => '50%'));
echo ' ';
echo $this->Html->link('Reject', array('controller' => 'challenges', 'action' => 'reject_challenge', $challenge['Challenge']['challenge_id']), array('style' => 'background:#CC0000', 'class' => 'button', 'width' => '50%'));
$schoolCount++;
echo '</tr>';
endforeach;
}
?>
</tr>
</tbody>
</table>
</fieldset>
</div>
<file_sep><?php
App::uses('AppController', 'Controller');
class ClassroomsController extends AppController {
//Homepage of little classroom
Function little_classroom() {
$this->layout='classroomTemplate';
$login_id = $this->Session->read('User.id');
$my_classroom = $this->Classroom->Query('select * from classrooms, classroom_collaborators where classrooms.classroom_id = classroom_collaborators.classroom_id and collaborator = ' . $login_id);
$this->set('my_classroom', $my_classroom);
$other_published_classroom = $this->Classroom->Query('select * from classrooms where published = 1 and classroom_id not in(select classroom_id from classroom_collaborators where collaborator = ' . $login_id . ')');
$this->set('other_classroom', $other_published_classroom);
}
//create new classroom
Function classroom_category() {
$this->layout='classroomTemplate';
}
Function classroom_title($category = NULL) {
$this->layout='classroomTemplate';
$this->set('category', $category);
$this->set('login_id', $this->Session->read('User.id'));
}
Function process_create_classroom() {
if (empty($this->data['Classroom']['title'])) {
$this->Session->setFlash('Please enter a title for the classroom!');
$this->redirect(array('action' => 'classroom_title', $this->data['Classroom']['category']));
} else {
$this->Classroom->save($this->data);
$classroom = $this->Classroom->find('all', array('conditions' => array('title' => $this->data['Classroom']['title'])));
$classroom_id = $classroom[0]['Classroom']['classroom_id'];
$login_id = $this->Session->read('User.id');
$this->Classroom->Query('insert into classroom_collaborators (classroom_id, collaborator) values (' . $classroom_id . ',' . $login_id . ')');
$this->redirect(array('action' => 'create_classroom', $this->data['Classroom']['title'], $classroom_id));
}
}
Function create_classroom($title = NULL, $classroom_id = NULL) {
$this->layout='classroomTemplate';
$this->set('title', $title);
$this->set('classroom_id', $classroom_id);
}
Function process_paragraph_conversion(){
$contentData = $this->request->data;
pr($contentData);die();
}
//$content should be an array
Function process_save_new_classroom() {
//there should be an array passing in (the content should be stored according to it position
$contentData = $this->request->data;
$content = array($contentData['Content']['intro'], $contentData['Content']['p1'], $contentData['Content']['p2'],$contentData['Content']['p3'],$contentData['Content']['conclusion']);
if (array_key_exists('back', $this->data)) {
$this->redirect(array('action' => 'little_classroom'));
}
$login_id = $this->Session->read('User.id');
$classroom_id = $this->data['Content']['classroom_id'];
$this->loadModel('Content');
$this->Content->Query('insert into history (classroom_id, edited_by, version_number) values (' . $classroom_id . ',' . $login_id . ',1)');
$count = 1;
foreach ($content as $temp) {
$this->Content->Query('insert into contents (classroom_id, version_number, content, position) values (' . $classroom_id . ',1,"' . $temp . '",' . $count . ')');
$count++;
}
if (array_key_exists('publish', $this->data)) {
$this->Classroom->Query('update classrooms set published=1 where classroom_id = ' . $classroom_id);
$this->Session->setFlash('You have successfully save and publish your classroom!');
} else {
$this->Session->setFlash('You have successfully save your classroom!');
}
$this->redirect(array('controller'=>'classrooms','action' => 'little_classroom'));
//$this->redirect(array('action' => 'edit', $classroom_id));
}
Function edit($classroom_id) {
$this->layout='classroomTemplate';
$version = $this->Classroom->Query('select max(version_number) from history where classroom_id=' . $classroom_id);
$version = $version[0][0]['max(version_number)'];
$content_array = array();
if (empty($version)) {
$version = 0;
} else {
$content = $this->Classroom->Query('select * from contents where classroom_id=' . $classroom_id . ' and version_number=' . $version . ' order by position');
foreach ($content as $temp) {
$content_array[$temp['contents']['position'] - 1] = $temp['contents']['content'];
}
}
$classroom = $this->Classroom->find('all', array('conditions' => array('classroom_id' => $classroom_id)));
$this->set('title', $classroom[0]['Classroom']['title']);
$this->set('version', $version);
$this->set('content', $content_array);
$this->set('classroom_id', $classroom_id);
$this->set('published', $classroom[0]['Classroom']['published']);
}
Function process_save_edited_classroom() {
//supposed to pass in the edited content
//$this->request->data;
$contentData = $this->request->data;
$content = array($contentData['Content']['intro'], $contentData['Content']['p1'], $contentData['Content']['p2'],$contentData['Content']['p3'],$contentData['Content']['conclusion']);
//pr($content);die();
if (array_key_exists('back', $this->data)) {
$this->redirect(array('action' => 'edit', $this->data['Content']['classroom_id']));
}
$login_id = $this->Session->read('User.id');
$classroom_id = $this->data['Content']['classroom_id'];
$this->loadModel('Content');
$this->Content->Query('insert into history (classroom_id, edited_by, version_number) values (' . $classroom_id . ',' . $login_id . ',' . $this->data['Content']['version_number'] . ')');
$count = 1;
foreach ($content as $temp) {
$this->Content->Query('insert into contents (classroom_id, version_number, content, position) values (' . $classroom_id . ',' . $this->data['Content']['version_number'] . ',"' . $temp . '",' . $count . ')');
$count++;
}
if (array_key_exists('publish', $this->data)) {
$this->Classroom->Query('update classrooms set published=1 where classroom_id = ' . $classroom_id);
$this->Session->setFlash('You have successfully save and publish your classroom!');
} else {
$this->Session->setFlash('You have successfully save your classroom!');
}
$this->redirect(array('controller'=>'classrooms','action' => 'little_classroom'));
}
Function delete($classroom_id = NULL) {
$this->Classroom->Query('delete from classrooms where classroom_id=' . $classroom_id);
$this->Classroom->Query('delete from classroom_collaborators where classroom_id=' . $classroom_id);
$this->Classroom->Query('delete from history where classroom_id=' . $classroom_id);
$this->Classroom->Query('delete from contents where classroom_id=' . $classroom_id);
$this->redirect(array('action' => 'little_classroom'));
}
Function view_collaborator($classroom_id) {
$this->layout='classroomTemplate';
$collaborator_id = $this->Classroom->Query('select collaborator from classroom_collaborators where classroom_id=' . $classroom_id);
$collaborator = array();
$this->loadModel('User');
$count = 0;
foreach ($collaborator_id as $temp) {
$user = $this->User->find('all', array('conditions' => array('id' => $temp['classroom_collaborators']['collaborator'])));
$collaborator[$count] = $user[0]['User']['username'];
$count++;
}
$this->set('collaborator', $collaborator);
$classroom = $this->Classroom->find('all', array('conditions' => array('classroom_id' => $classroom_id)));
$title = $classroom[0]['Classroom']['title'];
$this->set('classroom_id', $classroom_id);
$this->set('title', $title);
}
Function add_collaborator($classroom_id = NULL) {
$this->layout='classroomTemplate';
$classroom = $this->Classroom->find('all', array('conditions' => array('classroom_id' => $classroom_id)));
$title = $classroom[0]['Classroom']['title'];
$this->set('classroom_id', $classroom_id);
$this->set('title', $title);
$collaborator_id = $this->Classroom->Query('select collaborator from classroom_collaborators where classroom_id=' . $classroom_id);
$collaborator = array();
$this->loadModel('User');
$count = 0;
foreach ($collaborator_id as $temp) {
$user = $this->User->find('all', array('conditions' => array('id' => $temp['classroom_collaborators']['collaborator'])));
$collaborator[$count] = $user[0]['User']['username'];
$count++;
}
$this->set('collaborator', $collaborator);
}
Function process_add_collaborator() {
$classroom_id = $this->data['ClassroomCollaborator']['classroom_id'];
if (array_key_exists('cancel', $this->data)) {
$this->redirect(array('action' => 'view_collaborator', $classroom_id));
}
$this->loadModel('User');
if (array_key_exists('add', $this->data)) {
$user = $this->User->find('all', array('conditions' => array('username' => $this->data['ClassroomCollaborator']['collaborator'])));
if (empty($user)) {
$this->Session->setFlash('Please enter a valid username!');
$this->redirect(array('action' => 'add_collaborator', $classroom_id));
} else {
$user_id = $user[0]['User']['id'];
$this->loadModel('ClassroomCollaborator');
$existing = $this->ClassroomCollaborator->find('all', array('conditions' => array('classroom_id' => $classroom_id)));
$not_exist = true;
foreach ($existing as $temp) {
if ($user_id === $temp['ClassroomCollaborator']['collaborator']) {
$not_exist = false;
break;
}
}
if (!$not_exist) {
$this->Session->setFlash($this->data['ClassroomCollaborator']['collaborator'] . ' is an existing collaborator!');
$this->redirect(array('action' => 'add_collaborator', $classroom_id));
}
$this->ClassroomCollaborator->Query('insert into classroom_collaborators (classroom_id, collaborator) values (' . $this->data['ClassroomCollaborator']['classroom_id'] . ',' . $user_id . ')');
$this->Session->setFlash($this->data['ClassroomCollaborator']['collaborator'] . ' has been successfully added!');
$this->redirect(array('controller'=>'classrooms','action' => 'add_collaborator', $classroom_id));
}
}
}
}
?>
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<?php
App::uses('AppController', 'Controller');
class DesksController extends AppController {
Function little_desk(){
$this->layout=('deskTemplate');
}
Function my_desk(){
$this->layout=('deskTemplate');
}
Function my_tutee_desk(){
$this->layout=('deskTemplate');
}
Function display_all() {
$this->layout=('navigation');
$this->loadModel('LittleDeskQuestion');
$this->set('displayall', $this->LittleDeskQuestion->find('all'));
}
Function category_questions($categoryType =''){
$this->layout=('deskTemplate');
$this->set('categoryType',$categoryType);
//Retrieve all question related to category from database
$this->loadModel('DeskQuestion');
$allQuestions = $this->DeskQuestion->Query('SELECT * from desk_questions WHERE category="'.$categoryType.'"');
$this->loadModel('DeskQuestionsReplies');
$allResponse = $this->DeskQuestionsReplies->Query('SELECT * FROM desk_questions_replies');
$this->set('allQuestions',$allQuestions);
$this->set('allResponse',$allResponse);
//pr($allQuestions);die();
}
Function process_add_new_thread($categoryType=''){
$questionData = $this->request->data;
$question_content = $questionData['NewDeskQuestion']['newQuestion'];
$asked_by_user = $questionData['NewDeskQuestion']['askedBy'];
$this->loadModel('DeskQuestion');
$this->DeskQuestion->Query('INSERT INTO desk_questions (asked_by, qns_content, category) VALUES ("'.$asked_by_user.'","'.$question_content.'","'.$categoryType.'")');
$this->Session->setFlash('You have successfully posted a question!');
$this->redirect(array('controller'=>'desks','action'=>'category_questions',$categoryType));
}
Function viewQuestion($qnsId=''){
$this->layout=('deskTemplate');
$this->loadModel('DeskQuestion');
$foundQnsArray=$this->DeskQuestion->Query('SELECT * FROM desk_questions WHERE qns_id="'.$qnsId.'"');
$this->set('foundQnsArray',$foundQnsArray);
//pr($foundQnsArray);die();
$this->loadModel('DeskQuestionsReplies');
$qnsReplies = $this->DeskQuestionsReplies->Query('SELECT * FROM desk_questions_replies WHERE qns_id="'.$qnsId.'" ORDER BY timestamp DESC');
$this->set('qnsReplies',$qnsReplies);
}
Function process_add_new_reply($qnsId=''){
$replyData = $this->request->data;
$repliedBy = $replyData['NewDeskReply']['repliedBy'];
$replyContent = $replyData['NewDeskReply']['newReply'];
$this->loadModel('DeskQuestionsReplies');
$this->DeskQuestionsReplies->Query('INSERT INTO desk_questions_replies (qns_id, replied_by, reply_content) VALUES("'.$qnsId.'","'.$repliedBy.'","'.$replyContent.'")');
$this->Session->setFlash('Replied successfully! Thank you!');
$this->redirect(array('controller'=>'desks','action'=>'viewQuestion',$qnsId));
pr($replyData);die();
}
Function post_question() {
if (!empty($this->data)) {
$this->loadModel('LittleDeskQuestion');
if ($this->LittleDeskQuestion->save($this->data)) {
$this->loadModel('LittleDeskQuestion');
$lastPost = $this->LittleDeskQuestion->Query('SELECT MAX(desk_id) AS lastNum FROM little_desk_questions');
$tempLast = $lastPost[0][0]['lastNum'];
$this->loadModel('User');
$maxId = $this->User->Query('SELECT MAX(id) AS HighestNum FROM users');
$minId = $this->User->Query('SELECT MIN(id) AS LowestNum FROM users');
$randomNumber1 = rand($maxId[0][0]['HighestNum'], $minId[0][0]['LowestNum']);
$findAllId = $this->User->find('all');
$temp = 0;
$getRandomCollaborator1 = $this->generate($randomNumber1);
$tempCollaborator1 = $getRandomCollaborator1;
while ($tempCollaborator1 == 0) {
$getRandomCollaborator1 = $this->generate($randomNumber1);
}
$randomNumber2 = rand($maxId[0][0]['HighestNum'], $minId[0][0]['LowestNum']);
$getRandomCollaborator2 = $this->generate($randomNumber2);
$tempCollaborator2 = $getRandomCollaborator2;
while ($tempCollaborator2 == 0 || $randomNumber1 == $randomNumber2) {
$randomNumber2 = rand($maxId[0][0]['HighestNum'], $minId[0][0]['LowestNum']);
$getRandomCollaborator2 = $this->generate($randomNumber2);
}
$this->loadModel('DeskCollaborator');
$retriveUserName1 = $this->LittleDeskQuestion->Query('SELECT username from users where id = ' . $randomNumber1);
$retriveUserName2 = $this->LittleDeskQuestion->Query('SELECT username from users where id = ' . $randomNumber2);
$saveCollaborators = array('DeskCollaborator' => array('desk_id' => $tempLast, 'requested_by' => 'Michael', 'collaborator1' => $retriveUserName1[0]['users']['username'], 'collaborator2' => $retriveUserName2[0]['users']['username']));
$this->DeskCollaborator->save($saveCollaborators);
} else {
$this->Session->setFlash('The question was not saved, please try again');
}
}
}
Function generate($random) {
$temp = 0;
$count = 0;
$this->loadModel('User');
$maxId = $this->User->Query('SELECT MAX(id) AS HighestNum FROM users');
$minId = $this->User->Query('SELECT MIN(id) AS LowestNum FROM users');
$randomNumber = rand($maxId[0][0]['HighestNum'], $minId[0][0]['LowestNum']);
$findAllId = $this->User->find('all');
foreach ($findAllId as $getIdValue) {
if ($getIdValue['User']['id'] == $random) {
$temp++;
}
$count++;
}
return $temp;
}
function reply_post($desk_id = NULL) {
//$this->loadModel('LittleDeskQuestion');
//$this->Post->setSource('vote');
if (empty($this->data)) {
$this->loadModel('LittleDeskQuestion');
//$this->set('turtle', $this->LittleDeskQuestion->read(NULL, $desk_id));
//$this->data = $this->LittleDeskQuestion->read(NULL, $desk_id);
$result = $this->LittleDeskQuestion->Query('SELECT * from little_desk_questions where desk_id = ' . $desk_id);
$retrieveQuestion = $result[0]['little_desk_questions']['question'];
//$this->set('id', $this->LittleDeskQuestion->read(NULL, $result));
$this->set('retrieveQuestion', $retrieveQuestion);
} else {
$this->loadModel('LittleDeskReplie');
//$this->LittleDeskQuestion->save($this->data);
$id = $desk_id;
$replied_by = 'John';
$replied_body = $this->data['LittleDeskReplie']['reply_body'];
$datas = array('LittleDeskReplie' => array('reply_id' => '', 'desk_id' => $id, 'replied_by' => $replied_by, 'timestamp' => '', 'reply_body' => $replied_body));
$this->LittleDeskReplie->save($datas);
$this->Session->setFlash('The post has been updated.');
$this->redirect(array('controller' => 'HelpDesk', 'action' => 'display_all'));
}
}
Function rate_questions($difficulty = NULL, $chosen_qns = NULL, $username = '') {
//login user
$login_id = $this->Session->read('User.id');
$this->loadModel('Question');
$questions = $this->Question->find('all', array('conditions' => array('raised_by' => $login_id, 'status' => 'accept')));
if (empty($this->data)) {
$this->set('questions', $questions);
$this->set('difficulty', $difficulty);
if ($chosen_qns === 'NULL') {
$chosen_qns = NULL;
}
$this->set('chosen_qns', $chosen_qns);
$this->set('username', $username);
} else {
$questions_id = '';
$count = 0;
foreach ($this->data as $temp) {
if ($temp === '1') {
$qn = $questions[$count];
$questions_id = $questions_id . $qn['Question']['question_id'] . ';';
}
$count++;
}
$questions_id = substr($questions_id, 0, -1);
$this->redirect(array('action' => 'choose_target', $difficulty, $questions_id, 'NULL', $username));
}
}
Function questions_reply() {
$this->loadModel('LittleDeskQuestion');
$this->set('displayallquestion', $this->LittleDeskQuestion->find('all'));
$this->loadModel('LittleDeskReplie');
$this->set('displayallreplies', $this->LittleDeskReplie->find('all'));
}
Function rate_replie($reply_id = NULL) {
$this->loadModel('LittleDeskReplie');
if (empty($this->data)) {
$this->set('reply', $this->LittleDeskReplie->find('all', array('conditions' => array('reply_id = ' => $reply_id))));
} else {
$this->loadModel('Rate');
$retriveVoteValue = $this->data['Rate']['VotedReply'];
$this->Session->setFlash($reply_id);
$replied_by = '1';
$datas = array('Rate' => array('reply_id' => $reply_id, 'rated_by' => $replied_by, 'rate' => $retriveVoteValue, 'timestamp' => ''));
$this->Rate->save($datas);
$this->redirect(array('controller' => 'HelpDesk', 'action' => 'questions_reply'));
}
}
}
?><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align="center" >Accept Challenge</h1>
<div class="row">
<div class="large-2 columns">
<p>
Challenge Difficulty Level
<br>
<?php
if ($info['difficulty'] == 'easy') {
echo $this->Html->image('challengeImg/easy.jpg', array('height' => '10px', 'width' => '200px'));
} elseif ($info['difficulty'] == 'medium') {
echo $this->Html->image('challengeImg/medium.jpg', array('width' => '200px'));
} else {
echo $this->Html->image('challengeImg/hard.jpg', array('width' => '200px'));
}
?>
</p>
<!-- Question Progress display -->
<p>Question Attempted:    <?php echo $info['current'] . '  /  ' . $info['required']; ?></p>
</div>
<div class="large-10 columns">
<fieldset>
<legend>Your Questions</legend>
<!-- Options display -->
<p>
<?php
if ($info['current'] + 1 != $info['required']) {
echo $this->Form->create('Challenge', array('url' => '/challenges/view_question/' . $info['challenge_id'] . '/' . $info['questions'] . '/' . $info['difficulty'] . '/' . $info['required'] . '/' . ($info['current'] + 1) . '/' . $info['answers']));
} else {
echo $this->Form->create('Challenge', array('url' => '/challenges/challenge_result/' . $info['challenge_id'] . '/' . $info['difficulty'] . '/' . $info['questions'] . '/' . $info['answers']));
}
?>
<br>
<?php
$options = array('a' => 'Answer: ' . $question[0]['Question']['answer_a'], 'b' => 'Answer: ' . $question[0]['Question']['answer_b'], 'c' => 'Answer: ' . $question[0]['Question']['answer_c']);
?>
<table width='100%'>
<th colspan="2">
<?php
echo 'Question Number ' . ($info['current'] + 1) . ' : ' . $question[0]['Question']['question_body'];
?>
</th>
</table>
<p>
<?php
//echo 'Question Number ' . ($info['current'] + 1) . ' : ' . $question[0]['Question']['question_body'];
echo $this->Form->radio('selected_answer', $options, array('legend' => false, 'separator' => '<br>', 'style' => 'background:#FFF'));
?>
</p>
<div align='right'>
<ul class="button-group" width='100%'>
<?php
$option1 = array(
'label' => 'Next',
'class' => 'button',
);
$option2 = array(
'label' => 'Finish',
'class' => 'button',
);
if ($info['current'] + 1 != $info['required']) {
echo $this->Form->end($option1);
} else {
echo $this->Form->end($option2);
}
?>
</ul>
</div>
</fieldset>
</div>
</div>
<file_sep><?php
class Question extends AppModel{
var $name = 'Question';
var $validate = array(
'question_body'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Missing question body!'
)
),
'answer_a'=>array(
'answer_a_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Missing answer A!'
)
),
'answer_b'=>array(
'answer_b_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Missing answer B!'
)
),
'answer_c'=>array(
'answer_c_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Missing answer C!'
)
)
);
}
?>
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align="center" >Little Classroom</h1>
<div class="row">
<?php
$message = $this->Session->flash();
if($message !=''){
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<!--My Classroom-->
<div class='row'>
<?php echo $this->Html->link('Create New Classroom', array('controller' => 'classrooms', 'action' => 'classroom_category'), array('class' => 'button')); ?>
</div>
<div class='row' style='border-width: 2px; border-style: solid; border-color: black; '>
<h1 align='center'><font size='6'>My Classroom</font></h1>
<table width='100%'>
<thead>
<th width="60%">Classroom</th>
<th>Action</th>
</thead>
<tbody>
<?php
if (empty($my_classroom)) {
echo '<td colspan="2">';
echo 'You do not own any classroom yet.';
echo '</td>';
} else {
foreach ($my_classroom as $classroom):
echo '<tr>';
echo '<td>';
echo $classroom['classrooms']['title'];
echo '</td>';
echo '<td>';
echo $this->Html->link('Edit', array('controller' => 'classrooms', 'action' => 'edit', $classroom['classrooms']['classroom_id']), array('style' => 'background:#00CC00','class' => 'button'));
echo ' ';
echo $this->Html->link('Delete', array('controller' => 'classrooms', 'action' => 'delete', $classroom['classrooms']['classroom_id']), array('style' => 'background:#CC0000','class' => 'button'));
echo ' ';
echo $this->Html->link('View Editors', array('controller' => 'classrooms', 'action' => 'view_collaborator', $classroom['classrooms']['classroom_id']), array('class' => 'button'));
echo '</td>';
echo '</tr>';
endforeach;
}
?>
</tbody>
</table>
</div>
<br>
<div class='row' style='border-width: 2px; border-style: solid; border-color: black;'>
<!-- Other Available Classroom -->
<h1 align='center'><font size='6'>My Collaborative Classroom</font></h1>
<table width='100%'>
<thead>
<th width="60%">Classroom</th>
<th>Action</th>
</thead>
<tbody>
<?php
if (empty($other_classroom)) {
echo '<td colspan="2">';
echo 'There does not have any other classroom yet.';
echo '</td>';
} else {
foreach ($other_classroom as $classroom):
echo '<tr>';
echo '<td>';
echo $classroom['classrooms']['title'];
echo '</td>';
echo '<td>';
echo $this->Html->link('Edit', array('controller' => 'classrooms', 'action' => 'edit', $classroom['classrooms']['classroom_id']), array('style' => 'background:#00CC00','class' => 'button'));
echo ' ';
echo $this->Html->link('Delete', array('controller' => 'classrooms', 'action' => 'delete', $classroom['classrooms']['classroom_id']), array('style' => 'background:#CC0000','class' => 'button'));
echo '</td>';
echo '</tr>';
endforeach;
}
?>
</tbody>
</table>
</div>
</div><file_sep><?php
class Classroom extends AppModel{
var $name = 'Classroom';
}
?><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align='center'>Forming Collaborative Challenge</h1>
<div class="row">
<?php
$message = $this->Session->flash();
if($message !=''){
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<p></p>
<div class ='row'>
<ul class="button-group" width='100%'>
<?php
echo $this->Html->link('Start New Challenge', array('controller' => 'challenges', 'action' => 'choose_difficulty_many_to_many'), array('class' => 'button', 'width' => '33%'));
?>
</ul>
<p></p>
</div>
<div class ='row'>
<fieldset>
<legend>Form Class Challenge</legend>
<table width='100%'>
<thead>
<th width="60%">Challenge Title</th>
<th width="20%">Action</th>
<th width="20%">Remarks</th>
</thead>
<tbody>
<?php
$classCount = 0;
if (empty($class)) {
echo '<td colspan="3">';
echo 'You do not have class challenge need to be formed.';
echo '</td>';
} else {
foreach ($class as $temp):
$formed_by = $temp['form_challenges']['formed_by'];
$formed_by_array = explode(';', $formed_by);
$has_formed = false;
$login_id = $this->Session->read('User.id');
//Count how many users have formed the challenge
$sizeOfArray = count($formed_by_array);
//Check how many users required
$requiredNumUser = '';
$challengeDiff = $temp['form_challenges']['difficulty_level'];
if($challengeDiff=='easy'){
$requiredNumUser=5;
}elseif($challengeDiff=='medium'){
$requiredNumUser=10;
}else{
$requiredNumUser=15;
}
$userNeeded = $requiredNumUser-$sizeOfArray;
foreach ($formed_by_array as $temp_id) {
if ($temp_id === $login_id) {
$has_formed = true;
break;
}
}
echo '<tr>';
echo '<td width="60%">';
echo $temp['form_challenges']['challenge_title'];
echo '</td>';
echo '<td width="20%" align=\'center\'>';
if ($has_formed) {
echo "Formed";
} else {
//echo $this->Html->link('Start New Challenge', array('controller' => 'challenges', 'action' => 'add_many_to_many', $temp['form_challenges']['id']), array('style' => 'background:#00CC00', 'class' => 'custom buttony'));
echo $this->Html->link('Form Challenge', array('action' => 'add_many_to_many', $temp['form_challenges']['id']), array('style' => 'background:#00CC00', 'class' => 'button alert'));
}
echo '</td>';
echo '<td width="20%">';
if($userNeeded==0){
echo 'No more collaborators required!';
} else {
echo $userNeeded.' more collaborators required!';
}
echo '</td>';
$classCount++;
echo '</tr>';
endforeach;
}
?>
</tbody>
</table>
</fieldset>
</div>
<br>
<div class='row'>
<fieldset>
<legend>Form School Challenge</legend>
<table width='100%'>
<thead>
<th width="60%">Challenge Title</th>
<th width="20%">Action</th>
<th width="20%">Remarks</th>
</thead>
<tbody>
<?php
$schoolCount = 0;
if (empty($school)) {
echo '<td colspan="3">';
echo 'You do not have school challenge need to be formed.';
echo '</td>';
} else {
foreach ($school as $temp):
$formed_by = $temp['form_challenges']['formed_by'];
$formed_by_array = explode(';', $formed_by);
$has_formed = false;
$login_id = $this->Session->read('User.id');
//Count how many users have formed the challenge
$sizeOfArray = count($formed_by_array);
//Check how many users required
$requiredNumUser = '';
$challengeDiff = $temp['form_challenges']['difficulty_level'];
if($challengeDiff=='easy'){
$requiredNumUser=5;
}elseif($challengeDiff=='medium'){
$requiredNumUser=10;
}else{
$requiredNumUser=15;
}
$userNeeded = $requiredNumUser-$sizeOfArray;
foreach ($formed_by_array as $temp_id) {
if ($temp_id === $login_id) {
$has_formed = true;
break;
}
}
echo '<tr>';
echo '<td width="60%">';
echo $temp['form_challenges']['challenge_title'];
echo '</td>';
echo '<td width="20%" align=\'center\'>';
if ($has_formed) {
echo "Formed";
} else {
//echo $this->Html->link('Form Challenge', array('action' => 'add_many_to_many', $temp['form_challenges']['id']), array('style' => 'background:#00CC00', 'class' => 'custom buttony'));
echo $this->Html->link('Form Challenge', array('action' => 'add_many_to_many', $temp['form_challenges']['id']), array('style' => 'background:#00CC00', 'class' => 'button'));
}
//echo $this->Html->link('Accept Challenge', array('action' => 'accept_challenge', $challenge['Challenge']['challenge_id']), array('style' => 'background:#00CC00', 'class' => 'custom buttony'));
echo '</td>';
//echo $this->Html->link('Reject Challenge', array('action' => 'reject_challenge', $challenge['Challenge']['challenge_id']), array('style' => 'background:#CC0000', 'class' => 'custom buttony'));
//echo '<a style="background:#CC0000" class="custom buttony" href="#">Reject Challenge</a></td>';
echo '<td width="20%">';
if($userNeeded==0){
echo 'No more collaborators required!';
} else {
echo $userNeeded.' more collaborators required!';
}
echo '</td>';
$schoolCount++;
echo '</tr>';
endforeach;
}
?>
</tbody>
</table>
</fieldset>
</div><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align='center'>My Questions Bank</h1>
<div class='row'>
<div align="center">
<?php
$count = 0;
$chosen_qns_array = explode(';', $chosen_qns);
if (empty($questions)) {
echo '<h2><font color="black">Please suggest a question first!</font></h2>';
} else {
?>
</div>
<table width='100%'>
<thead>
<th>Available Questions</th>
<th>Option A</th>
<th>Option B</th>
<th>Option C</th>
<th>Choose?</th>
</thead>
<?php foreach ($questions as $question):
?>
<tr>
<?php echo $this->Form->create('Challenge', array('action' => 'choose_questions_many_to_many/' . $difficulty . '/NULL/' . $username . '/' . $title)); ?>
<td><?php echo $question['Question']['question_body'] ?>
<td><?php echo $question['Question']['answer_a'] ?>
<td><?php echo $question['Question']['answer_b'] ?>
<td><?php echo $question['Question']['answer_c'] ?>
<?php
$checked = false;
$qn_id = $question['Question']['question_id'];
foreach ($chosen_qns_array as $temp):
if ($temp === $qn_id) {
$checked = true;
break;
}
endforeach;
?>
<td><?php
if ($checked) {
echo $this->form->checkbox($count, array('checked' => 'checked'));
} else {
echo $this->form->checkbox($count);
}
?></td>
</tr>
<?php
$count++;
endforeach
?>
</table>
<?php }; ?>
</div>
<div class='row'>
<ul class="button-group" width='100%'>
<?php
//echo $this->Form->end();
echo $this->Form->button('Add to Challenge', array('controller' => 'send_challenge_many_to_many'), array('class' => 'button alert', 'width' => '33%'));
if ($chosen_qns === NULL) {
$chosen_qns = 'NULL';
}
echo $this->Html->link("Back", array('controller' => 'challenges', 'action' => 'choose_target_many_to_many', $difficulty, $chosen_qns, 'NULL', $username, $title), array('class' => 'button', 'width' => '34%'));
?>
</ul>
</div><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align="center" >Vote an Answer</h1>
<div class='row'>
<fieldset>
<table width='100%'>
<thead>
<th>Question</th>
<th>Response A</th>
<th>Response B</th>
<th>Response C</th>
<th>Response D</th>
<th>Actions</th>
</thead>
<?php foreach ($question_for_vote as $qn): ?>
<tr>
<td><?php echo $qn['questions']['question_body'] ?></td>
<td><?php echo $qn['questions']['answer_a'] ?></td>
<td><?php echo $qn['questions']['answer_b'] ?></td>
<td><?php echo $qn['questions']['answer_c'] ?></td>
<td>I don't understand this question.</td>
<td>
<?php
$voted = $this->requestAction(array('controller' => 'challenges', 'action' => 'voted', $qn['questions']['question_id']));
if (!$voted) {
echo $this->Html->link('Vote', array('controller' => 'challenges', 'action' => 'vote', $qn['questions']['question_id']), array('style' => 'background:#00CC00','class' => 'button', 'width' => '50%'));
} else {
echo 'Voted';
}
?>
</td>
</tr>
<?php endforeach; ?>
</table>
</fieldset>
</div><file_sep><?php
class Classes extends AppModel{
var $name = 'Class';
}
?>
<file_sep><div class="row">
<?php
$message = $this->Session->flash();
if($message !=''){
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<div class='row'>
<h1 align='center'> Little Desk </h1>
<fieldset style='border-width: 2px; border-style: solid; border-color: black;'>
<legend align='center'>Choose a Category</legend>
<ul class="small-block-grid-3">
<li><?php echo $this->Html->image('categoryImg/english.jpg', array('url'=>array('controller'=>'desks','action'=>'category_questions', 'English')));?></li>
<li><?php echo $this->Html->image('categoryImg/maths.jpg', array('url'=>array('controller'=>'desks','action'=>'category_questions', 'Maths')));?></li>
<li><?php echo $this->Html->image('categoryImg/science.jpg', array('url'=>array('controller'=>'desks','action'=>'category_questions', 'Science')));?></li>
<li><?php echo $this->Html->image('categoryImg/geography.jpg', array('url'=>array('controller'=>'desks','action'=>'category_questions', 'Geography')));?></li>
<li><?php echo $this->Html->image('categoryImg/fashion.jpg', array('url'=>array('controller'=>'desks','action'=>'category_questions', 'Fashion')));?></li>
<li><?php echo $this->Html->image('categoryImg/games.jpg', array('url'=>array('controller'=>'desks','action'=>'category_questions', 'Games')));?></li>
<li><?php echo $this->Html->image('categoryImg/sports.jpg', array('url'=>array('controller'=>'desks','action'=>'category_questions', 'Sports')));?></li>
</ul>
</fieldset>
</div><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align='center'>The <?php echo $categoryType ?> Desk</h1>
<div class='row'>
<?php echo $this->Html->link('Back', array('controller' => 'desks', 'action' => 'little_desk'), array('class' => 'button')); ?>
</div>
<div class="row">
<?php
$message = $this->Session->flash();
if ($message != '') {
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<div class="row">
<fieldset>
<legend>Post a Question</legend>
<?php
echo $this->Form->create('NewDeskQuestion', array('url' => array('controller' => 'desks', 'action' => 'process_add_new_thread', $categoryType)));
echo $this->Form->textarea('newQuestion', array('placeholder' => 'What\'s your question?', 'label' => false));
echo $this->Form->input('askedBy', array('type' => 'hidden', 'value' => $this->Session->read('User.username')));
echo $this->Form->button('Ask Now!', array('controller' => 'profiles', 'action' => 'process_add_new_thread', $categoryType), array('class' => 'button', 'align' => 'right', 'width' => '33%'));
echo $this->Form->end();
?>
</fieldset>
</div>
<div class="row">
<h1 align='center'><font size='6'>All <?php echo $categoryType ?> Questions</font></h1>
<?php if (empty($allQuestions)) { ?>
<fieldset style='border-width: 2px; border-style: solid; border-color: black; background-color: #FFFFCC'>
<div align='center'>There are no questions yet! Be the first one to ask! </div>
</fieldset>
<?php
}
foreach ($allQuestions as $temp) {
$title = $temp['desk_questions']['qns_content'];
$questionId = $temp['desk_questions']['qns_id'];
$askedBy = $temp['desk_questions']['asked_by'];
$askTime = $temp['desk_questions']['timestamp'];
//pr($askTime);die();
$lastUpdatedTime='';
foreach($allResponse as $tempResponse){
$responseQnsId = $tempResponse['desk_questions_replies']['qns_id'];
if($responseQnsId==$questionId){
$lastUpdatedTime=$tempResponse['desk_questions_replies']['timestamp'];
}
}
?>
<fieldset style='border-width: 2px; border-style: solid; border-color: black; background-color: #FFFFCC'>
<font size='4' color='#FF6633'><u><?php echo $this->Html->link($askedBy, array('controller' => 'profiles', 'action' => 'viewProfile', $askedBy), array('style' => 'color:#000000')); ?></u> has a Little Question...</font>
<br>
<br>
<div align='center'>
<fieldset style='border-width: 2px; border-style: solid; border-color: black;'>
<u><?php echo $this->Html->link($title, array('controller' => 'desks', 'action' => 'viewQuestion', $questionId), array('style' => 'color:#000000')) ?></u>
</fieldset>
</div>
<br>
<br>
<div align='right'>
<!-- Add Condition Loop here. If no last updated. display posted on else display last updated -->
<div align='left'><font size='4' color='#3366FF'><?php if(empty($lastUpdatedTime)){echo 'Posted on: '.$askTime;}else{ echo 'Last Updated On: '.$lastUpdatedTime;}; ?></font></div>
<font size='4' color='#CC0066'>(Number) Answers </font>
<font size='4' color='#FF6633'>(Number) Likes </font>
</div>
</fieldset>
<?php }
?>
</div> <file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$qnsId = $foundQnsArray[0]['desk_questions']['qns_id'];
$qnsAskedBy = $foundQnsArray[0]['desk_questions']['asked_by'];
$qnsPostedTime = $foundQnsArray[0]['desk_questions']['timestamp'];
$qns = $foundQnsArray[0]['desk_questions']['qns_content'];
$qnsCategory = $foundQnsArray[0]['desk_questions']['category'];
?>
<h1 align='center'>The <?php echo $qnsCategory ?> Desk</h1>
<div class='row'>
<?php echo $this->Html->link('Back', array('controller' => 'desks', 'action' => 'category_questions', $qnsCategory), array('class' => 'button')); ?>
</div>
<div class="row">
<?php
$message = $this->Session->flash();
if ($message != '') {
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<div class="row">
<fieldset style='border-width: 2px; border-style: solid; border-color: black; background-color: #B0E0E6'>
<font size='4' color='#FF6633'><u><?php echo $this->Html->link($qnsAskedBy, array('controller' => 'profiles', 'action' => 'viewProfile', $qnsAskedBy), array('style' => 'color:#000000')); ?></u> asked a Little Question...</font>
<br>
<br>
<div align='center'>
<fieldset style='border-width: 2px; border-style: solid; border-color: black;'>
<?php echo $qns; ?>
</fieldset>
</div>
<br>
<br>
<div align='right'>
<!-- Add Condition Loop here. If no last updated. display posted on else display last updated -->
<div align='left'><font size='4' color='#3366FF'>Posted on: <?php echo $qnsPostedTime ?></font></div>
<u><?php echo $this->Html->link('Like', array('controller' => 'profiles', 'action' => 'viewProfile', $qnsAskedBy), array('style' => 'color:#FF6633')); ?></u>
</div>
</fieldset>
</div>
<div class="row">
<fieldset>
<legend>Your Answer</legend>
<?php
echo $this->Form->create('NewDeskReply', array('url' => array('controller' => 'desks', 'action' => 'process_add_new_reply', $qnsId)));
echo $this->Form->textarea('newReply', array('placeholder' => 'Your answer here...', 'label' => false));
echo $this->Form->input('repliedBy', array('type' => 'hidden', 'value' => $this->Session->read('User.username')));
echo $this->Form->button('Reply!', array('controller' => 'desks', 'action' => 'process_add_new_reply', $qnsId), array('class' => 'button', 'align' => 'right', 'width' => '33%'));
echo $this->Form->end();
?>
</fieldset>
</div>
<div class="row">
<?php if (empty($qnsReplies)) { ?>
<fieldset style='border-width: 0px; border-style: solid; border-color: black; background-color: #D3D3D3'>
<div align='center'>There are no answers yet! Be the first one to help! </div>
</fieldset>
<?php
}
foreach ($qnsReplies as $temp) {
$qnsReplyId = $temp['desk_questions_replies']['qns_id'];
$answeredBy = $temp['desk_questions_replies']['replied_by'];
$replyContent = $temp['desk_questions_replies']['reply_content'];
$answeredTime = $temp['desk_questions_replies']['timestamp'];
?>
<fieldset align='left' style='border-width: 2px; border-style: solid; border-color: black; background-color: #D0D0D0'>
<font size='4' color='#FF6633'><u><?php echo $this->Html->link($answeredBy, array('controller' => 'profiles', 'action' => 'viewProfile', $answeredBy), array('style' => 'color:#000000')); ?></u> has replied...</font>
<br>
<br>
<div align='left'>
<fieldset style='border-width: 1px; border-style: solid; border-color: black;'>
<?php echo $replyContent; ?>
</fieldset>
</div>
<br>
<br>
<div align='right'>
<!-- Add Condition Loop here. If no last updated. display posted on else display last updated -->
<div align='left'><font size='4' color='#3366FF'>Posted on: <?php echo $answeredTime ?></font></div>
<u><?php echo $this->Html->link('Like', array('controller' => 'profiles', 'action' => 'viewProfile', $qnsAskedBy), array('style' => 'color:#FF6633')); ?></u>
</div>
</fieldset>
<?php }
?>
</div>
<file_sep><div class="form_wrapper">
<div class="wrapper-body">
<h3>Forgot your password?</h3>
<div class="error-message" align="center">
<?php
$errorMsg = $this->Session->flash();
if ($errorMsg != '') {
?>
<span class="round alert label"><?php echo $errorMsg ?></span>
<?php }
?>
</div>
<p align="center">Fret not! Just enter your email or username associated with your LittleLives account.</p>
<div>
<?php echo $this->Form->create('User', array('action' => 'process_forgetPassword')); ?>
</div>
<div>
<?php echo $this->Form->input('Enter your Username',array('id'=>'username')); ?>
</div>
<div>
<?php echo $this->Form->input('Enter your ID Number',array('id'=>'userNRIC')); ?>
</div>
<div class="bottom">
<input id="submit" type="submit" value="Reset My Password!" />
<div class="clear"></div>
<div class="forget-password-wrapper">
<?php
echo $this->Html->link('Suddenly remembered?', array(
'controller' => 'users',
'action' => 'index'
)
);
?>
</div>
</div>
<div class="clear"></div>
</div>
</div><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of choose_challenge_type
*
* @author Zee
*/
?>
<h1 align="center" >Choose Challenge Type</h1>
<div class="row">
<div class="large-6 columns" align='center'>
<?php echo $this->Html->image("challengeImg/Individual.jpg", array('url' => array('controller' => 'challenges', 'action' => 'choose_difficulty')));?>
</div>
<div class="large-6 columns" align='center'>
<?php echo $this->Html->image("challengeImg/collaborative.jpg", array('url' => array('controller' => 'challenges', 'action' => 'many_to_many')));?>
</div>
</div><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align='Center'>
<?php echo $title ?>
</h1>
<?php
echo $this->Form->create('Content', array('url' => array('controller' => 'Classrooms', 'action' => 'process_save_new_classroom')));
?>
<br>
<p>
Introduction
</p>
<?php
echo $this->Form->input('intro', array('type' => 'textarea', 'label' => false, 'placeholder' => 'Write Your Introduction Here'));
?>
<p>
Paragraph 1
</p>
<?php
echo $this->Form->input('p1', array('type' => 'textarea', 'label' => false, 'placeholder' => 'Write Your Content for Paragraph 1 Here'));
?>
<p>
Paragraph 2
</p>
<?php
echo $this->Form->input('p2', array('type' => 'textarea', 'label' => false, 'placeholder' => 'Write Your Content for Paragraph 2 Here'));
?>
<p>
Paragraph 3
</p>
<?php
echo $this->Form->input('p3', array('type' => 'textarea', 'label' => false, 'placeholder' => 'Write Your Content for Paragraph 3 Here'));
?>
<p>
Conclusion
</p>
<?php
echo $this->Form->input('conclusion', array('type' => 'textarea', 'label' => false, 'placeholder' => 'Write Your Content for Paragraph 3 Here'));
?>
<?php
echo $this->Form->input('classroom_id', array('type' => 'hidden', 'value' => $classroom_id));
echo $this->Form->button('Save', array('name' => 'save', 'value' => 'yes'));
echo $this->Form->button('Save & Publish', array('name' => 'publish', 'value' => 'yes'));
echo $this->Form->button('Cancel', array('name' => 'back', 'value' => 'yes'));
echo $this->Form->end();
?><file_sep><!DOCTYPE html>
<?php echo $this->Html->charset(); ?>
<head>
<?php
echo $this->Html->meta(
'viewport', 'width=device-width');
?>
<title>Knowledge Challenge</title>
<link rel="shortcut icon" type="image/x-icon" href="<?php echo $this->webroot; ?>img/favicon.ico">
<?php echo $this->Html->css('foundation.css'); ?>
<?php echo $this->Html->css('style.css'); ?>
<?php echo $this->Html->css('sidebar/demo.css'); ?>
<?php echo $this->Html->css('sidebar/icons.css'); ?>
<?php echo $this->Html->css('sidebar/sideBarNormalize.css'); ?>
<?php echo $this->Html->css('sidebar/style3.css'); ?>
<?php echo $this->Html->css('foundation-icons/foundation-icons.css'); ?>
<?php echo $this->Html->css('autocompletecss/select2.css'); ?>
<style type="text/css">
body {
background: white no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
color: black;
font-family: mingler-bold;
}
h3 {
line-height: 0;
font-size: 20px;
font-family: mingler-bold;
}
h1,h2,h4 {
font-family: mingler-bold;
}
table tr.even, table tr.alt, table tr:nth-of-type(even) {
}
table thead tr th,
table thead tr td,
table tfoot tr th,
table tfoot tr td {
background-color: gainsboro;
}
table tr th, table tr td {
background: #F5ECCE;
font-size: 16px;
}
</style>
<?php echo $this->Html->script('http://code.jquery.com/ui/1.10.3/jquery-ui.js'); ?>
<?php echo $this->Html->script('sidebar/modernizr.custom.js'); ?>
</head>
<body>
<nav class="top-bar" data-topbar>
<ul class="title-area">
<li class="name">
<a href=""><?php echo $this->Html->image('logo_1.png', array('width' => 80, 'url' => array('controller' => 'users', 'action' => 'success'))); ?> </a>
</li>
</ul>
<section class="top-bar-section">
<!-- Left Nav Section -->
<ul class="left">
<li>
<?php
echo $this->Html->link(' Knowledge Challenge', array('controller' => 'challenges', 'action' => 'scoreboard'), array('class' => 'fi-crown', 'id' => 'knowledgechallenge'));
?>
</li>
<li>
<?php
echo $this->Html->link(' Little Classroom', array('controller' => 'classrooms', 'action' => 'little_classroom'), array('class' => 'fi-clipboard-pencil', 'id' => 'littleclassroom'));
?>
</li>
<li class="has-dropdown">
<?php
echo $this->Html->link(' Little Desk', array('controller' => 'desks', 'action' => 'little_desk'), array('id' => 'littledesk'));
?>
<ul class="dropdown">
<li>
<?php
echo $this->Html->link(' My Questions', array('controller' => 'desks', 'action' => 'my_desk'), array('id' => 'littledesk'));
?>
</li>
<li><?php
echo $this->Html->link(' My Tutees Questions', array('controller' => 'desks', 'action' => 'my_tutee_desk'), array('id' => 'littledesk'));
?></li>
<li><?php
echo $this->Html->link(' See All', array('controller' => 'desks', 'action' => 'display_all'), array( 'id' => 'littledesk'));
?></li>
</ul>
</li>
</ul>
<!-- Right Nav Section -->
<ul class="right">
<li><a class="fi-web" id="notifications" href="#"></a></li>
<li><a class="fi-torsos-female-male" id="friendrequest" href="#"></a></li>
<li><a class="fi-info" id="opentour" href="#"></a></li>
<li class = "has-dropdown"><a href = "#"><?php echo $this->Session->read('User.username'); ?></a>
<ul class = "dropdown">
<li>
<?php
echo $this->Html->link('Search Friends', array('controller' => 'profiles', 'action' => 'viewProfile',$this->Session->read('User.username')));
?>
</li>
<li><a id = "settings" href = "#">Account Settings</a></li>
<li> <?php
echo $this->Html->link('Logout', array('controller' => 'users', 'action' => 'process_logout'));
?></li>
</ul>
</li>
</ul>
</section>
</nav>
<!--Main Content Section-->
<!--This has been source ordered to come first in the markup (and on small devices) but to be to the right of the nav on larger screens-->
<div class ="large-12 columns">
<div id = "content">
<?php echo $content_for_layout;
?>
</div>
</div>
<footer>
<div class="large-12 columns">
<hr />
<p>© LitteLives Inc. Powered by LittleTeam.</p>
<nav id="bt-menu" class="bt-menu">
<a href="#" class="bt-menu-trigger"><span>Menu</span></a>
<ul>
<li><?php
echo $this->Html->link('Scoreboard', array('controller' => 'challenges', 'action' => 'scoreboard'), array('class' => 'fi-clipboard-pencil', 'id' => 'knowledgechallenge'));
?></li>
<li><?php
echo $this->Html->link('Challenge Status', array('controller' => 'challenges', 'action' => 'view_outstanding_challenges'), array('class' => '.fi-info', 'id' => 'knowledgechallenge'));
?></li>
<li><?php
echo $this->Html->link('Send Challenge', array('controller' => 'challenges', 'action' => 'chooseChallengeType'), array('class' => 'fi-flag', 'id' => 'knowledgechallenge'));
?></li>
<li><?php
echo $this->Html->link('Accept Challenge', array('controller' => 'challenges', 'action' => 'view_challenges'), array('class' => 'fi-target 21', 'id' => 'knowledgechallenge'));
?></li>
<li><?php
echo $this->Html->link('Suggest Question', array('controller' => 'challenges', 'action' => 'suggest_question'), array('class' => 'fi-comment-quotes', 'id' => 'knowledgechallenge'));
?></li>
<li><?php
echo $this->Html->link('Vote Answer', array('controller' => 'challenges', 'action' => 'vote_answer'), array('class' => 'fi-magnifying-glass', 'id' => 'knowledgechallenge'));
?></li>
</ul>
</nav>
</div>
</footer>
<!-- Other JS plugins can be included here -->
<?php echo $this->Html->script('jquery.js'); ?>
<?php echo $this->Html->script('foundation/foundation.js'); ?>
<?php echo $this->Html->script('foundation/foundation.abide.js'); ?>
<?php echo $this->Html->script('foundation/foundation.accordion.js'); ?>
<?php echo $this->Html->script('foundation/foundation.alert.js'); ?>
<?php echo $this->Html->script('foundation/foundation.clearing.js'); ?>
<?php echo $this->Html->script('foundation/foundation.dropdown.js'); ?>
<?php echo $this->Html->script('foundation/foundation.interchange.js'); ?>
<?php echo $this->Html->script('foundation/foundation.joyride.js'); ?>
<?php echo $this->Html->script('foundation/foundation.magellan.js'); ?>
<?php echo $this->Html->script('foundation/foundation.offcanvas.js'); ?>
<?php echo $this->Html->script('foundation/foundation.orbit.js'); ?>
<?php echo $this->Html->script('foundation/foundation.reveal.js'); ?>
<?php echo $this->Html->script('foundation/foundation.tab.js'); ?>
<?php echo $this->Html->script('foundation/foundation.tooltip.js'); ?>
<?php echo $this->Html->script('foundation/foundation.topbar.js'); ?>
<?php echo $this->Html->script('foundation/jquery.cookie.js'); ?>
<?php echo $this->Html->script('sidebar/modernizr.custom.js'); ?>
<?php echo $this->Html->script('sidebar/classie.js'); ?>
<?php echo $this->Html->script('sidebar/borderMenu.js'); ?>
<script>
$(document).foundation();
</script>
</body>
</html><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align="center" >Choose Your Category</h1>
<div class="row">
<?php
$message = $this->Session->flash();
if($message !=''){
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<div class='row'>
<ul class="small-block-grid-3">
<li><?php echo $this->Html->image('categoryImg/english.jpg', array('url'=>array('action'=>'classroom_title', 'English')));?></li>
<li><?php echo $this->Html->image('categoryImg/maths.jpg', array('url'=>array('action'=>'classroom_title', 'Maths')));?></li>
<li><?php echo $this->Html->image('categoryImg/science.jpg', array('url'=>array('action'=>'classroom_title', 'Science')));?></li>
<li><?php echo $this->Html->image('categoryImg/geography.jpg', array('url'=>array('action'=>'classroom_title', 'Geography')));?></li>
<li><?php echo $this->Html->image('categoryImg/fashion.jpg', array('url'=>array('action'=>'classroom_title', 'Fashion')));?></li>
<li><?php echo $this->Html->image('categoryImg/games.jpg', array('url'=>array('action'=>'classroom_title', 'Games')));?></li>
<li><?php echo $this->Html->image('categoryImg/sports.jpg', array('url'=>array('action'=>'classroom_title', 'Sports')));?></li>
</ul>
</div>
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<div class="form_wrapper">
<div class="wrapper-body">
<h3>Welcome!</h3>
<div class="error-message" align="center">
<?php
$errorMsg = $this->Session->flash();
if ($errorMsg != '') {
?>
<span class="round alert label"><?php echo $errorMsg ?></span>
<?php }
?>
</div>
<div>
<?php echo $this->Form->create('User', array('action' => 'process_login')); ?>
</div>
<div>
<?php echo $this->Form->input('username'); ?>
</div>
<div>
<?php echo $this->Form->input('password'); ?>
</div>
<div class="bottom">
<div class="remember"><input type="checkbox" /><span>Keep me logged in</span></div>
<input id="submit" type="submit" value="Login" />
<div class="clear"></div>
<div class="forget-password-wrapper">
<?php
echo $this->Html->link('Forget Password?', array(
'controller' => 'users',
'action' => 'forgetPassword'
)
);
?>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align="center" >Your Challenge Result</h1>
<div class='row'>
<p align='center'>
<?php
$countValues = array_count_values($correct_wrong);
$total = count($correct_wrong);
if($countValues['Correct!!']==$total){
echo $this->Html->image('challengeImg/wonchallenge.jpg',array('width'=>'70%','height'=>'80%'));
} else {
echo $this->Html->image('challengeImg/lostchallenge.jpg',array('width'=>'70%','height'=>'80%'));
};
?>
</p>
</div>
<div class="row">
<div class="medium-3 columns">
<p>
Challenge Difficulty Level
<br>
<?php
if ($difficulty == 'easy') {
echo $this->Html->image('challengeImg/easy.jpg', array('width' => '200px'));
} elseif ($difficulty == 'medium') {
echo $this->Html->image('challengeImg/medium.jpg', array('width' => '200px'));
} else {
echo $this->Html->image('challengeImg/hard.jpg', array('width' => '200px'));
}
?>
</p>
</div>
<div class="medium-9 columns">
<fieldset>
<legend>Your Result</legend>
<table border='2' width='100%'>
<thead>
<th>S/N</th>
<th>Questions</th>
<th>Status</th>
</thead>
<?php
$count = 0;
foreach ($body as $temp) {
?>
<tr>
<td width='5%'>
<?php echo $count + 1 ?>
</td>
<td width='80%'>
<?php echo $temp ?>
</td>
<td width='15%'>
<?php
if ($correct_wrong[$count] == 'Wrong!!') {
echo $this->Html->image('challengeImg/Wrong.JPG', array('width' => '100%', 'height' => '100%', 'align' => 'center'));
} else {
echo $this->Html->image('challengeImg/Correct.JPG', array('width' => '100%', 'height' => '100%', 'align' => 'center'));
}
?>
</td>
</tr>
<?php
$count++;
}
?>
</table>
</fieldset>
</div>
</div>
<br>
<div class='row'>
<p align='right'>
<?php echo $this->Html->link('Another Challenge?', array('controller' => 'challenges', 'action' => 'view_challenges'), array('align' => 'right', 'class' => 'button')); ?>
<?php echo $this->Html->link('Home', array('controller' => 'challenges', 'action' => 'scoreboard'), array('align' => 'right', 'class' => 'button')); ?>
</p>
</div><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align='center'>My Tutee's Questions</h1><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align='center'><?php echo $title; ?></h1>
<div class='row'>
<table width='100%'>
<thead>
<th colspan='2'>Collaborative Editors</th>
</thead>
<tbody>
<?php
foreach ($collaborator as $temp){
echo '<tr>';
echo '<td width=\'30%\'>';
echo $this->Html->image('profileImg/'.$temp.'.jpg');
echo '</td>';
echo '<td align=\'center\'>';
echo $this->Html->link($temp, array('controller'=>'profiles','action'=>'viewProfile',$temp));
echo '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
<div class='row'>
<?php
echo $this->Html->link('Add New Collaborator', array('controller'=>'classrooms','action'=>'add_collaborator', $classroom_id), array('class' => 'button'));
//echo ' ';
echo $this->Html->link('Back', array('action'=>'little_classroom'), array('class' => 'button'));
?>
</div><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align="center" >Knowledge Challenge</h1>
<div class="row">
<?php
$message = $this->Session->flash();
if($message !=''){
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<div class='row'>
<table width="100%">
<tr><td align="center"><?php echo $this->Html->image('challengeImg/easy.jpg', array('url' => '/challenges/choose_target_many_to_many/easy'));?></td><td align="center"><h1 style="font-size:35px">5 Users</h1></td></tr>
<tr><td align="center"><?php echo $this->Html->image('challengeImg/medium.jpg', array('url' => '/challenges/choose_target_many_to_many/medium'));?><td align="center"><h1 style="font-size:35px">10 Users</h1></td></tr>
<tr><td align="center"><?php echo $this->Html->image('challengeImg/hard.jpg', array('url' => '/challenges/choose_target_many_to_many/hard'));?></td><td align="center"><h1 style="font-size:35px">15 Users</h1></td></tr>
</table>
</div><file_sep><?php
class DeskQuestion extends AppModel{
var $name = 'DeskQuestion';
}
?>
<file_sep><head>
<?php echo $this->Html->script('autocomplete/select2.js'); ?>
<script>
$(document).ready(function() {
$("#e1").select2();
});
</script>
</head>
<h1 align="center"> Building Your Challenge </h1>
<div class="row">
<?php
$message = $this->Session->flash();
if($message !=''){
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<div class='row'>
<br>
<fieldset>
<legend>Challenge Title</legend>
<?php
echo $this->Form->create('Challenge', array('action' => 'send_challenge'));
$default_title = $title;
$default = $username;
echo $this->Form->input('challenge_title', array('type' => 'text', 'default' => $default_title, 'id' => 'title', 'label' => ''));
?>
</fieldset>
<br>
<fieldset>
<legend>Choose Your Opponent</legend>
<?php
echo $this->Form->create('Challenge', array('action' => 'send_challenge'));
$default = $username;
//input in the username to choose opponent
echo $this->Form->input('username', array('type' => 'text', 'default' => $default, 'id' => 'username', 'label' => ''));
?>
<p>Note:
<li>
Enter Username of the person to send individual challenge i.e Michael
</li>
<li>
Enter class name to send class challenge i.e P5-A
</li>
<li>
Enter school name to send school challenge. i.e LittleLives Team 1
</li>
</p>
</fieldset>
<br>
</div>
<div class='row'>
<?php
$questions_id = '';
try {
if (!empty($chosen_questions)) {
?>
<fieldset>
<legend>Selected Questions List</legend>
<table width='100%'>
<tr>
<thead>
<th>Selected Questions</th>
<th>Answer A</th>
<th>Answer B</th>
<th>Answer C</th>
<th>Action</th></tr>
</thead>
<?php
foreach ($chosen_questions as $temp):
$questions_id = $questions_id . $temp['Question']['question_id'] . ';';
endforeach;
$questions_id = substr($questions_id, 0, -1);
foreach ($chosen_questions as $temp):
echo '<tr><td>' . $temp['Question']['question_body'] . '</td>';
echo '<td>' . $temp['Question']['answer_a'] . '</td>';
echo '<td>' . $temp['Question']['answer_b'] . '</td>';
echo '<td>' . $temp['Question']['answer_c'] . '</td>';
echo '<td>' . $this->Html->link('Remove', array('action' => 'choose_target', $difficulty, $questions_id, $temp['Question']['question_id'], $username, $title)) . '</td></tr>';
endforeach;
}
} catch (Exception $e) {
}
?>
</table>
</fieldset>
</div>
<br>
<div class='row' align='right'>
<ul class="button-group" width='100%'>
<?php
echo $this->Form->input('difficulty', array('type' => 'hidden', 'value' => $difficulty));
echo $this->Form->input('questions', array('type' => 'hidden', 'value' => $questions_id));
echo '<li>' . $this->Form->button('Select Questions', array('name' => 'add', 'value' => 'yes'), array('class' => 'button alert', 'width' => '33%')) . '</li>';
echo '<li>' . $this->Form->button('Send Challenge', array('name' => 'send', 'value' => 'yes', array('class' => 'button alert', 'width' => '33%'))) . '</li>';
echo $this->Html->link('Back', array('controller' => 'challenges', 'action' => 'choose_difficulty'), array('class' => 'button', 'width' => '33%'));
echo $this->Form->end();
?>
</ul>
</div><file_sep><?php
class ClassroomCollaborator extends AppModel{
var $name = 'ClassroomCollaborator';
}
?>
<file_sep><?php
class DeskQuestionsReplies extends AppModel{
var $name = 'DeskQuestionsReplies';
}
?>
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align='center'>Vote an Answer</h1>
<div class="row">
<?php
$message = $this->Session->flash();
if($message !=''){
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<div class='row'>
<fieldset>
<legend>The Question</legend>
<?php echo $question[0]['Question']['question_body']; ?>
</fieldset>
<br>
<fieldset>
<legend>Your Preferred Answer</legend>
<?php
echo $this->Form->create('Question');
$options = array('a' => 'Answer A: ' . $question[0]['Question']['answer_a'], 'b' => 'Answer B: ' . $question[0]['Question']['answer_b'], 'c' => 'Answer C: ' . $question[0]['Question']['answer_c'], 'd' => 'Answer D: I do not understand this question.');
$attributes = array('legend' => false);
echo $this->Form->radio('VotedAnswer', $options, array('legend' => false, 'separator' => '<br>', 'style' => 'background:#FFF'));
echo $this->Form->input('id', array('type' => 'hidden', 'value' => $question[0]['Question']['question_id']));
?>
</fieldset>
</div>
<br>
<div class='row'>
<ul class="button-group" width='100%'>
<?php
echo $this->Form->button('Vote Now!', array('controller' => 'challenges', 'action' => 'vote'), array('class' => 'button alert', 'width' => '33%'));
echo $this->Html->link('Cancel', array('controller' => 'challenges', 'action' => 'vote_answer'), array('class' => 'button', 'width' => '33%'));
echo $this->Form->end();
?>
</ul>
</div><file_sep><?php
class FormChallenge extends AppModel{
var $name = 'FormChallenge';
}
?>
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align="center" >Knowledge Challenge</h1>
<div class="row">
<?php
$message = $this->Session->flash();
if ($message != '') {
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<div class='row'>
<div class="small-6 large-5 columns">
<fieldset>
<legend>Leading Schools</legend>
<table width="100%">
<thead>
<th colspan="2">School Scoreboard</th>
</thead>
<tbody>
<tr>
<td width='50%'>School</td>
<td width='50%'>Points</td>
<tr>
<?php foreach ($school as $temp): ?>
<tr>
<td><?php echo $temp['schools']['school_name']; ?>
<td><?php echo $temp['schools']['score'] ?>
</tr>
<?php endforeach ?>
</tr>
</tbody>
</table>
</fieldset>
<br>
<fieldset>
<legend>Leading Class</legend>
<table width="100%">
<thead>
<th colspan="3">Class Scoreboard</th>
</thead>
<tbody>
<tr>
<td width='33%'>Class</td>
<td width='33%'>School</td>
<td width='34%'>Points</td>
</tr>
<tr>
<?php foreach ($class as $temp): ?>
<tr>
<td><?php echo $temp['classes']['class_name']; ?>
<td><?php echo $temp['schools']['school_name']; ?>
<td><?php echo $temp['classes']['score'] ?>
</tr>
<?php endforeach ?>
</tr>
</tbody>
</table>
</fieldset>
<br>
<fieldset>
<legend>Leading Individuals</legend>
<table width="100%">
<thead>
<th colspan="4">Individual Scoreboard</th>
</thead>
<tbody>
<tr>
<td width='25%'>Username</td>
<td width='25%'>Class</td>
<td width='25%'>School</td>
<td width='25%'>Points</td>
</tr>
<?php foreach ($user as $temp): ?>
<tr>
<td><?php echo $temp['users']['username']; ?>
<td><?php echo $temp['classes']['class_name'] ?>
<td><?php echo $temp['schools']['school_name']; ?>
<td><?php echo $temp['users']['score'] ?>
</tr>
<?php endforeach ?>
</tbody>
</table>
</fieldset>
</div>
<div class="small-6 large-7 columns">
<fieldset>
<legend>Challenge Arena</legend>
</fieldset>
</div>
</div>
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align='center'>Voting Results</h1>
<div class="row">
<?php
$message = $this->Session->flash();
if($message !=''){
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<div class="row">
<fieldset>
<legend> Voted Question </legend>
<?php echo $question; ?>
</fieldset>
</div>
<br>
<div class="row">
<fieldset>
<legend> Total Responses </legend>
<table width="100%">
<thead>
<th>
</th>
<th>
Answers
</th>
<th>
Percentage
</th>
</thead>
<tbody>
<tr>
<td>
Answer A
</td>
<td>
<?php echo $answersArray[0]['questions']['answer_a']; ?>
</td>
<td>
<?php echo $result['a']; ?>%
</td>
</tr>
<tr>
<td>
Answer B
</td>
<td>
<?php echo $answersArray[0]['questions']['answer_b']; ?>
</td>
<td>
<?php echo $result['b']; ?>%
</td>
</tr>
<tr>
<td>
Answer C
</td>
<td>
<?php echo $answersArray[0]['questions']['answer_c']; ?>
</td>
<td>
<?php echo $result['c']; ?>%
</td>
</tr>
<tr>
<td>
Answer D
</td>
<td>
<?php echo 'I do not understand this question.'; ?>
</td>
<td>
<?php echo $result['d']; ?>%
</td>
</tr>
</tbody>
</table>
</fieldset>
</div>
<br>
<div class="row">
<ul class="button-group" width='100%'>
<?php
echo $this->Html->link('Back', array('controller' => 'challenges', 'action' => 'vote_answer'), array('class' => 'button', 'width' => '33%'));
//echo $this->Html->link("Back", array('action' => 'view_questions_for_voting'), array('class' => 'button alert', 'width' => '34%'));
?>
</ul>
</div><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align='center'><?php echo $title; ?></h1>
<div class="row">
<?php
$message = $this->Session->flash();
if($message !=''){
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<div><?php
//pr($content);die();
if(count($content)!=4){
for($i=(count($content));$i<=4;$i++){
array_push($content,'');
}
}
?></div>
<?php
echo $this->Form->create('Content', array('url'=>array('controller'=>'Classrooms', 'action'=>'process_save_edited_classroom')));
?>
<br>
<p>
Introduction
</p>
<?php
$introContent = $content[0];
echo $this->Form->input('intro', array('type' => 'textarea', 'default'=>$content[0],'label' => false, 'placeholder' => 'Write Your Introduction Here'));
?>
<p>
Paragraph 1
</p>
<?php
$p1Content = $content[1];
echo $this->Form->input('p1', array('type' => 'textarea', 'default'=>$content[1],'label' => false, 'placeholder' => 'Write Your Content for Paragraph 1 Here'));
?>
<p>
Paragraph 2
</p>
<?php
$p2Content = $content[2];
echo $this->Form->input('p2', array('type' => 'textarea', 'default'=>$content[2],'label' => false, 'placeholder' => 'Write Your Content for Paragraph 2 Here'));
?>
<p>
Paragraph 3
</p>
<?php
$p3Content = $content[3];
echo $this->Form->input('p3', array('type' => 'textarea', 'default'=>$content[3],'label' => false, 'placeholder' => 'Write Your Content for Paragraph 3 Here'));
?>
<p>
Conclusion
</p>
<?php
$p4Content = $content[4];
echo $this->Form->input('conclusion', array('type' => 'textarea', 'default'=>$content[4],'label' => false, 'placeholder' => 'Write Your Content for Conclusion Here'));
?>
<?php
echo $this->Form->input('classroom_id', array('type'=>'hidden', 'value'=>$classroom_id));
echo $this->Form->input('version_number', array('type'=>'hidden', 'value'=>$version+1));
echo $this->Form->button('Save', array('name'=>'save', 'value'=>'yes'));
if($published === '0'){
echo $this->Form->button('Save & Publish', array('name'=>'publish', 'value'=>'yes'));
}
echo $this->Html->link('Cancel', array('controller' => 'classrooms', 'action' => 'little_classroom'), array('class' => 'button', 'width' => '33%'));
//echo $this->Html->link('Cancel', array(),array('name'=>'back', 'value'=>'yes','class'=>'button'));
echo $this->Form->end();
?><file_sep><?php
class Vote extends AppModel{
var $name = 'Vote';
}
?>
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align='center'><?php echo $title; ?></h1>
<div class='row'>
<table width='100%'>
<thead>
<th colspan='2'>Collaborative Editors</th>
</thead>
<tbody>
<?php
foreach ($collaborator as $temp){
echo '<tr>';
echo '<td width=\'30%\'>';
echo $this->Html->image('profileImg/'.$temp.'.jpg');
echo '</td>';
echo '<td align=\'center\'>';
echo $this->Html->link($temp, array('controller'=>'profiles','action'=>'viewProfile',$temp));
echo '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
<div class="row">
<?php
$message = $this->Session->flash();
if($message !=''){
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<?php
echo $this->Form->create('ClassroomCollaborator', array('url'=>array('controller'=>'Classrooms', 'action'=>'process_add_collaborator', NULL)));
echo $this->Form->input('collaborator', array('type'=>'text', 'label'=>'Collaborator'));
echo $this->Form->input('classroom_id', array('type'=>'hidden', 'value'=>$classroom_id));
echo $this->Form->button('Add', array('name'=>'add', 'value'=>'yes'));
echo $this->Form->button('Cancel', array('name'=>'cancel', 'value'=>'yes'));
echo $this->Form->end();
?>
<file_sep><?php
App::uses('AppController', 'Controller');
class UsersController extends AppController{
//Display the login page. Default route comes to here.
public function index(){
$this->layout='login';
}
function success(){
$this->layout='navigation';
$this->loadModel('Post');
$notificationArray = $this->Post->Query('SELECT * FROM posts ORDER BY timestamp DESC');
$this->set('notificationArray',$notificationArray);
$this->loadModel('User');
$userArray = $this->User->Query('SELECT * FROM users');
$this->set('userArray',$userArray);
}
//Function: To perform validation of login. And writing the valid user to the session object.
function process_login(){
if($this->Session->read('resetPassword')!=''){
$this->Session->delete('resetPassword');
}
if($this->Session->read('resetUsername')!=''){
$this->Session->delete('resetUsername');
}
$userData = $this->request->data;
$this->loadmodel('User');
$foundUser = $this->User->Query('select * from users where username="'.$userData['User']['username'].'"');
//pr($foundUser);die();
//Condition 1: Check if the there is such user by querying the database. If not found, login fails.
if(empty($foundUser)){
$this->Session->setFlash('Please enter a valid username / password! ');
$this->redirect(array('action' => 'index'));
}
//Condition 2: Check if the user password matches the one in the database. If match, redirect to the scoreboard page.
elseif ($userData['User']['password']==$foundUser[0]['users']['password']) {
$this->Session->write('User.username', $foundUser[0]['users']['username']);
$this->Session->write('User.id', $foundUser[0]['users']['id']);
//To be change after styling of the homepage (scoreboard)
$this->redirect(array('action' => 'success'));
}
//Condition 3: If password don't match, return back to the login page.
else {
$this->Session->setFlash('Invalid username/password. Please try again!');
$this->redirect(array('action' => 'index'));
}
}
//Display the layout to the user to let the user retrieve the password
function forgetPassword(){
//pr("Here"); die();
$this->layout='login';
}
//Function: Logic to reset and retrieve user password.
function process_forgetPassword(){
$userData = $this->request->data;
//pr($userData);die();
$enteredUsername = $userData['User']['Enter your Username']; //pr($enteredUsername);
$enteredNRIC = $userData['User']['Enter your ID Number']; //pr($enteredNRIC); die();
//Condition 1: Check for empty fields!
if(empty($enteredUsername)|| empty($enteredNRIC)){
if(empty($enteredUsername)){
$this->Session->setFlash('Please entered an username! ');
$this->redirect(array('action' => 'forgetPassword'));
}
else{
$this->Session->setFlash('Please enter your ID!');
$this->redirect(array('action' => 'forgetPassword'));
}
}
$foundUser = $this->User->Query('select * from users where username="'.$enteredUsername.'"');
$foundUserIC = $foundUser[0]['users']['nric'];
//Condition 1: No such user.
if(empty($foundUser)){
$this->Session->setFlash('You have entered an invalid username / ID !');
$this->redirect(array('action' => 'forgetPassword'));
}
//Condition 2: IC number is wrong
elseif($enteredNRIC != $foundUserIC){
$this->Session->setFlash('You have entered an invalid username / ID !');
$this->redirect(array('action' => 'forgetPassword'));
}
//Condition 3: Performing Password Reset.
else{
$randomWords = array(1=>"excited",2=>"happy",3=>"proactive",4=>"enthusiastic",5=>"elated");
$randomChosenWord = $randomWords[rand(1,5)];
$random3Numbers = rand(100,1000);
$newPassword = $randomChosenWord.$random3Numbers;
$this->Session->write('resetPassword',$newPassword);
$this->User->Query("UPDATE users SET password='".$<PASSWORD>."'WHERE nric='".$foundUserIC."'");
$this->Session->write('resetUsername',$foundUser[0]['users']['username']);
$this->redirect(array('action' => 'showNewPassword'));
}
}
function showNewPassword(){
$this->Session->setFlash('Success! Password resetted!');
$this->layout='login';
}
function process_logout(){
$this->Session->destroy();
$this->redirect(array('action' => 'index'));
}
}
?>
<file_sep><div class="form_wrapper">
<div class="wrapper-body">
<h3>Forgot your password?</h3>
<div class="error-message" align="center">
<?php
$successMsg = $this->Session->flash();
if ($successMsg != '') {
?>
<span class="success label"><?php echo $successMsg ?></span>
<?php }
?>
</div>
<div>
<p>Dear <?php echo $this->Session->read('resetUsername'); ?>,</p>
<p align="center">Your new password is <font color="red"><?php echo $this->Session->read('resetPassword'); ?> </font>! Please change them upon logging in.</p>
<p align="right">Regards, SMU LittleTeam</p>
</div>
<div class="bottom">
<div class="clear"></div>
<div class="forget-password-wrapper" align="center">
<?php
echo $this->Html->link('Click here to login!', array(
'controller' => 'users',
'action' => 'index'
)
);
?>
</div>
</div>
<div class="clear"></div>
</div>
</div><file_sep>
<html class="no-js" lang="en" >
<head>
<?php echo $this->Html->charset(); ?>
<?php
echo $this->Html->meta(
'viewport', 'width=device-width'
);
?>
<link rel="shortcut icon" type="image/x-icon" href="<?php echo $this->webroot; ?>img/favicon.ico" />
<title>SMU LittleTeam</title>
<?php echo $this->Html->css('foundation.css'); ?>
<?php echo $this->Html->css('style.css'); ?>
<style type="text/css">
body {
background: url(<?php echo $this->webroot; ?>img/cartoon-natural-landscape.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
h3 {
line-height: 0;
font-size: 20px;
font-family: mingler-bold;
}
h1,h2,h4 {
font-family: mingler-bold;
}
img {
max-width: 33%;
}
.orbit-container {
width: 100%;
}
.wrapper-body{
font-family: mingler-bold;
background-color: #FFFFFF;
}
.forget-password-wrapper{
font-family: mingler-bold;
color: #FFA500;
}
.error-message{
font-family: mingler-bold;
color: #980000;
}
</style>
</head>
<body class="row">
<!-- Main Content -->
<div class="large-12 columns">
<div class="row">
<!-- Login Form -->
<div class="large-12 columns">
<p> <?php echo $this->Html->image('logo.png'); ?></p>
</div>
<div class="large-6 columns">
<div class="content">
<?php echo $content_for_layout;
?>
</div>
</div>
<!-- Orbit Pictures -->
<div class="large-6 columns">
<ul data-orbit>
<li>
<?php echo $this->Html->image('homepageImg/knowledgechallenge.jpg'); ?>
</li>
<li>
<?php echo $this->Html->image('homepageImg/learningnetwork.jpg'); ?>
</li>
<li>
<?php echo $this->Html->image('homepageImg/littleclassroom.jpg'); ?>
</li>
<li>
<?php echo $this->Html->image('homepageImg/littledesk.jpg'); ?>
</li>
</ul>
</div>
<div class="large-2 columns"></div>
</div>
<!-- Footer -->
<footer class="row">
<div class="large-12 columns">
<hr />
<div class="row">
<div class="large-6 columns">
<p>© LitteLives Inc. Powered by LittleTeam.</p>
</div>
</div>
</div>
</footer>
<!-- The JavaScript -->
<?php echo $this->Html->script('jquery.js'); ?>
<?php echo $this->Html->script('foundation/foundation.js'); ?>
<?php echo $this->Html->script('foundation/foundation.abide.js'); ?>
<?php echo $this->Html->script('foundation/foundation.accordion.js'); ?>
<?php echo $this->Html->script('foundation/foundation.alert.js'); ?>
<?php echo $this->Html->script('foundation/foundation.clearing.js'); ?>
<?php echo $this->Html->script('foundation/foundation.dropdown.js'); ?>
<?php echo $this->Html->script('foundation/foundation.interchange.js'); ?>
<?php echo $this->Html->script('foundation/foundation.joyride.js'); ?>
<?php echo $this->Html->script('foundation/foundation.magellan.js'); ?>
<?php echo $this->Html->script('foundation/foundation.offcanvas.js'); ?>
<?php echo $this->Html->script('foundation/foundation.orbit.js'); ?>
<?php echo $this->Html->script('foundation/foundation.reveal.js'); ?>
<?php echo $this->Html->script('foundation/foundation.tab.js'); ?>
<?php echo $this->Html->script('foundation/foundation.tooltip.js'); ?>
<?php echo $this->Html->script('foundation/foundation.topbar.js'); ?>
<?php echo $this->Html->script('foundation/jquery.cookie.js'); ?>
<script>
$(document).foundation();
</script>
</body>
</html><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<h1 align='center'>My Challenges Status</h1>
<div class="row">
<?php
$message = $this->Session->flash();
if ($message != '') {
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<div class="row">
<div class="large-6 columns">
<fieldset>
<legend>Challenges to Others</legend>
<table width='100%'>
<thead>
<th width="40%">Challenge Title</th>
<th width="20%">Target</th>
<th width="20%">Challenge Difficulty</th>
<th width="20%">Status</th>
</thead>
<tbody>
<?php
if (empty($challengesToOthers)) {
echo '<td colspan="4">';
echo 'You do not have any outstanding challenges.';
echo '</td>';
} else {
//pr($challengesToOthers);die();
$count = 0;
foreach ($challengesToOthers as $myChallenge) {
echo '<tr>';
//display challenge title
echo '<td>';
echo $challengesToOthers[$count]['challenges']['challenge_title'];
echo '</td>';
//display target user
echo '<td>';
$targetUser = $challengesToOthers[$count]['challenges']['to_individual'];
$targetClass = $challengesToOthers[$count]['challenges']['to_class'];
$targetSchool = $challengesToOthers[$count]['challenges']['to_school'];
//do a check condition for Individual, class, school
//loop through each array to find the corresponding name;
//display the name
if (!empty($targetUser)) {
foreach ($allUsers as $temp) {
$tempUserId = $temp['users']['id'];
if ($tempUserId == $targetUser) {
echo $temp['users']['username'];
}
}
} elseif (!empty($targetClass)) {
foreach ($allClasses as $temp) {
//pr($temp);die();
$tempClassId = $temp['classes']['class_id'];
if ($tempClassId == $targetClass) {
echo $temp['classes']['class_name'];
}
}
} else {
foreach ($allSchools as $temp) {
//pr($temp);die();
$tempSchId = $temp['schools']['school_id'];
if ($tempSchId == $targetSchool) {
echo $temp['schools']['school_name'];
}
}
}
echo '</td>';
//display difficulty level of the challenge
echo '<td>';
echo $challengesToOthers[$count]['challenges']['difficulty_level'];
echo '</td>';
//display status of the challenge
echo '<td>';
$challengeStatus = $challengesToOthers[$count]['challenges']['challenge_status'];
if ($challengeStatus == '') {
echo 'Pending';
} else {
if ($challengeStatus == 'win') {
echo 'Challenge Lost';
} else {
echo 'Challenge Won';
}
}
echo '</td>';
echo '</tr>';
$count++;
}
}
?>
</tbody>
</table>
</fieldset>
</div>
<div class="large-6 columns">
<fieldset>
<legend>Challenges to Me</legend>
<table width='100%'>
<thead>
<th width="80%">Challenge Title</th>
<th>Challenge Type</th>
<th>Challenge Difficulty</th>
<th>Status</th>
</thead>
<tbody>
<?php
$counter = 0;
if (!empty($school)) {
echo '<td colspan="3">';
echo 'You do not have any outstanding challenges.';
echo '</td>';
} else {
foreach($challengesToMe as $temp){
//Challenge Title
//pr($temp);die();
$tempTitle = $temp['challenges']['challenge_title'];
//Challenge Type
$tempType='';
$tempInd = $temp['challenges']['to_individual'];
$tempClass = $temp['challenges']['to_class'];
$tempSchool = $temp['challenges']['to_school'];
if(!empty($tempInd)){
$tempType='Individual';
}elseif(!empty($tempClass)){
$tempType='Class';
}else{
$tempType='School';
}
//Challenge Difficulty
$tempDiff = $temp['challenges']['difficulty_level'];
//Challenge Status
$tempStatus = $temp['challenges']['challenge_status'];
if(empty($tempStatus)){
$tempStatus = 'Pending';
}
echo '<tr>';
echo '<td>';
echo $tempTitle;
echo '</td>';
echo '<td>';
echo $tempType;
echo '</td>';
echo '<td>';
echo $tempDiff;
echo '</td>';
echo '<td>';
echo $tempStatus;
echo '</td>';
echo '</tr>';
$counter++;
}
foreach($classChallengesToMe as $temp){
//Challenge Title
//pr($temp);die();
$tempTitle = $temp['challenges']['challenge_title'];
//Challenge Type
$tempType='';
$tempInd = $temp['challenges']['to_individual'];
$tempClass = $temp['challenges']['to_class'];
$tempSchool = $temp['challenges']['to_school'];
if(!empty($tempInd)){
$tempType='Individual';
}elseif(!empty($tempClass)){
$tempType='Class';
}else{
$tempType='School';
}
//Challenge Difficulty
$tempDiff = $temp['challenges']['difficulty_level'];
//Challenge Status
$tempStatus = $temp['challenges']['challenge_status'];
if(empty($tempStatus)){
$tempStatus = 'Pending';
}
echo '<tr>';
echo '<td>';
echo $tempTitle;
echo '</td>';
echo '<td>';
echo $tempType;
echo '</td>';
echo '<td>';
echo $tempDiff;
echo '</td>';
echo '<td>';
echo $tempStatus;
echo '</td>';
echo '</tr>';
$counter++;
}
foreach($schoolChallengesToMe as $temp){
//Challenge Title
//pr($temp);die();
$tempTitle = $temp['challenges']['challenge_title'];
//Challenge Type
$tempType='';
$tempInd = $temp['challenges']['to_individual'];
$tempClass = $temp['challenges']['to_class'];
$tempSchool = $temp['challenges']['to_school'];
if(!empty($tempInd)){
$tempType='Individual';
}elseif(!empty($tempClass)){
$tempType='Class';
}else{
$tempType='School';
}
//Challenge Difficulty
$tempDiff = $temp['challenges']['difficulty_level'];
//Challenge Status
$tempStatus = $temp['challenges']['challenge_status'];
if(empty($tempStatus)){
$tempStatus = 'Pending';
}
echo '<tr>';
echo '<td>';
echo $tempTitle;
echo '</td>';
echo '<td>';
echo $tempType;
echo '</td>';
echo '<td>';
echo $tempDiff;
echo '</td>';
echo '<td>';
echo $tempStatus;
echo '</td>';
echo '</tr>';
$counter++;
}
//echo '<td>';
//echo $challengesToOthers[$count]['challenges']['difficulty_level'];
//echo '</td>';
//pr('individual');
//pr($challengesToMe);
//pr('class');
//pr($classChallengesToMe);
//pr('school');
//pr($schoolChallengesToMe);
//die();
}
?>
</tbody>
</table>
</fieldset>
</div>
</div>
<br>
<file_sep>index.file=index.php
url=http://localhost/reEditFYP/
<file_sep><?php
class School extends AppModel{
var $name = 'School';
}
?>
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<div class ="large-3 columns">
<div class="row">
<br>
<div class="large-5 columns">
<?php echo $this->Html->image('profileImg/' . $this->Session->read('User.username') . '.jpg', array('height' => '100%', 'width' => '100%'), array('url' => array('controller' => 'recipes', 'action' => 'view'))); ?>
</div>
<div class="large-7 columns">
<?php
echo $this->Html->link($this->Session->read('User.username'), array('controller' => 'profiles', 'action' => 'viewProfile',$this->Session->read('User.username')));
?>
<br>
<?php
echo $this->Html->link(' Edit Profile', array('controller' => 'pages', 'action' => 'maintenance'), array('class' => 'fi-pencil', 'id' => 'editProfile'));
?>
<br>
Level: <?php
$id = $this->Session->read('User.id');
echo $userArray[$id-1]['users']['rank'];?>
Points: <?php echo $userArray[$this->Session->read('User.id')]['users']['score'];?>
</div>
</div>
<div class="row">
<ul class="side-nav">
<label class="fi-like"><b> My Interests</b></label>
<li><a href="#">Basketball</a></li>
<li><a href="#">Soccer</a></li>
<li class="divider"></li>
<label class="fi-torsos-all"><b> Groups</b></label>
<li><a href="#">Science Project Group</a></li>
<li><a href="#">Math Project Group</a></li>
<li class="divider"></li>
<label class="fi-results-demographics"><b> My Friends</b></label>
<li><a href="#">My Buddies</a></li>
<li><a href="#">My Schoolmates</a></li>
<li><a href="#">My Classmates</a></li>
<li class="divider"></li>
</ul>
</div>
</div>
<div class ="large-9 columns">
<div id = "content">
<div class="myPost">
<fieldset>
<legend>My Thoughts...</legend>
<?php
echo $this->Form->create('NewWallPost', array('url' => array('controller' => 'profiles', 'action' => 'addNewsFeed')));
echo $this->Form->textarea('newPost', array('placeholder' => 'What\'s your thought?', 'label' => false));
echo $this->Form->input('wallOwner', array('type' => 'hidden','value'=>$this->Session->read('User.username')));
echo $this->Form->input('location', array('type' => 'hidden','value'=>0));
echo $this->Form->button('Post', array('controller' => 'profiles', 'action' => 'addNewsFeed'), array('class' => 'button', 'align' => 'right', 'width' => '33%'));
echo $this->Form->end();
?>
</fieldset>
</div>
<div class="friendsUpdates">
<fieldset>
<legend>My News Feed</legend>
<?php
if(empty($notificationArray)){
echo 'No updates yet!';
}
//pr($notificationArray); die();
foreach ($notificationArray as $notification) {
$posted_by = $notification['posts']['posted_by'];
$posted_by_name = '';
foreach ($userArray as $user) {
//pr($user);die();
$tempID = $user['users']['id'];
if ($tempID == $posted_by) {
$posted_by_name = $user['users']['username'];
}
}
$posted_content = $notification['posts']['post_content'];
$posted_timing = $notification['posts']['timestamp'];
?>
<div class="post-container">
<p class="small-2 columns">
<?php echo $this->Html->image('profileImg/' . $posted_by_name . '.jpg', array('height' => '117px', 'width' => '88px'), array('url' => array('controller' => 'recipes', 'action' => 'view'))); ?>
</p>
<p class="small-10 columns">
<b><?php echo $this->Html->link($posted_by_name, array('controller'=>'profiles','action'=>'viewProfile', $posted_by_name))?></b> has posted some thoughts
<fieldset width="80%">
<?php echo $posted_content; ?>
</fieldset>
<br>
<span align="right"> Posted on <?php echo $posted_timing; ?></span>
</p>
</div>
<br>
<?php }
?>
</fieldset>
</div>
</div>
</div>
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<div class="row">
<?php
$message = $this->Session->flash();
if ($message != '') {
?>
<div align="center">
<span class="success alert secondary round radius label"><font size="4" color="black"><?php echo $message; ?></font></span></div>
<?php }
?>
</div>
<div class='row'>
<table width="100%" border='0' class='search-box'>
<tr>
<?php
echo $this->Form->create('SearchFriends', array('url' => array('controller' => 'profiles', 'action' => 'findFriends')));
?> <th width ="70%"><?php
echo $this->Form->input('enterFriends', array('placeholder' => 'Enter a username...', 'label' => 'Search User'));
?>
</th><th width="30%">
<?php
$userName = $this->Session->read('User.username');
echo $this->Form->button('Search', array('controller' => 'profiles', 'action' => 'findFriends'), array('class' => 'button', 'align' => 'right', 'width' => '33%'));
echo $this->Form->end();
?>
</th>
</tr>
</table>
</div>
<div class="row">
<div class="large-12" align="center">
<div class="profile-cover">
<?php echo $this->Html->image('profileCover/defaultCover.jpg'); ?>
</div>
</div>
</div>
<div class='row'>
<div class ="large-3 columns">
<div class="row">
<br>
<div class="large-5 columns">
<?php echo $this->Html->image('profileImg/' . $this->Session->read('User.username') . '.jpg', array('height' => '100%', 'width' => '100%'), array('url' => array('controller' => 'recipes', 'action' => 'view'))); ?>
</div>
<div class="large-7 columns">
<?php
echo $this->Html->link($this->Session->read('User.username'), array('controller' => 'profiles', 'action' => 'viewProfile', $this->Session->read('User.username')));
?>
<br>
<?php
echo $this->Html->link(' Edit Profile', array('controller' => 'pages', 'action' => 'maintenance'), array('class' => 'fi-pencil', 'id' => 'editProfile'));
?>
<br>
Level: <?php
$username = $this->Session->read('User.username');
echo $userArray[0]['users']['rank'];
?>
Points: <?php echo $userArray[0]['users']['score']; ?>
</div>
</div>
<div class="row">
<ul class="side-nav">
<label class="fi-like"><b> My Interests</b></label>
<li><a href="#">Basketball</a></li>
<li><a href="#">Soccer</a></li>
<li class="divider"></li>
<label class="fi-torsos-all"><b> Groups</b></label>
<li><a href="#">Science Project Group</a></li>
<li><a href="#">Math Project Group</a></li>
<li class="divider"></li>
<label class="fi-results-demographics"><b> My Friends</b></label>
<li><a href="#">My Buddies</a></li>
<li><a href="#">My Schoolmates</a></li>
<li><a href="#">My Classmates</a></li>
<li class="divider"></li>
</ul>
</div>
</div>
<div class ="large-9 columns">
<div class="myPost">
<fieldset>
<legend>My Thoughts...</legend>
<?php
echo $this->Form->create('NewWallPost', array('url' => array('controller' => 'profiles', 'action' => 'addNewsFeed')));
echo $this->Form->textarea('newPost', array('placeholder' => 'What\'s your thought?', 'label' => false));
echo $this->Form->input('wallOwner', array('type' => 'hidden','value'=>$username));
echo $this->Form->input('location', array('type' => 'hidden','value'=>1));
echo $this->Form->button('Post', array('controller' => 'profiles', 'action' => 'addNewsFeed'), array('class' => 'button', 'align' => 'right', 'width' => '33%'));
echo $this->Form->end();
?>
</fieldset>
</div>
<div class="friendsUpdates" width='100%'>
<dl class="tabs" data-tab width='100%'>
<dd class="active"><a href="#panel2-1">My Wall</a></dd>
<dd><a href="#panel2-2">My Activities</a></dd>
<dd><a href="#panel2-3">My Connections</a></dd>
</dl>
<div class="tabs-content" width='100%'>
<div class="content active" id="panel2-1" width='100%'>
<h1 align='center'><font size='6'>My Wall</font></h1>
<?php
if(empty($notificationArray)){
echo 'No Update from '.$username.' yet!';
}
//pr($notificationArray); die();
foreach ($notificationArray as $notification) {
//pr($notification);die();
$posted_by = $notification['posts']['posted_by'];
$posted_by_name = '';
foreach ($otherUsers as $user) {
//pr($user);die();
$tempID = $user['users']['id'];
if ($tempID == $posted_by) {
$posted_by_name = $user['users']['username'];
}
}
$posted_content = $notification['posts']['post_content'];
$posted_timing = $notification['posts']['timestamp'];
?>
<div class="post-container">
<p class="large-2 columns">
<?php echo $this->Html->image('profileImg/' . $posted_by_name . '.jpg', array('height' => '117px', 'width' => '88px'), array('url' => array('controller' => 'recipes', 'action' => 'view'))); ?>
</p>
<p class="large-10 columns">
<?php if ($posted_by_name == ($this->Session->read('User.username'))) { ?>
<b><?php echo $posted_by_name; ?></b> has posted <?php } else {
?>
<b><?php echo $this->Html->link($posted_by_name, array('controller'=>'profiles','action'=>'viewProfile', $posted_by_name))?></b> posted on <?php echo $this->Session->read('User.username'); ?>'s Wall <?php
}
?>
<fieldset width="80%">
<?php echo $posted_content; ?>
</fieldset>
<br>
<span align="right"> Posted on <?php echo $posted_timing; ?></span>
</p>
</div>
<br>
<?php }
?>
</div>
<div class="content" id="panel2-2">
<h1 align='center'><font size='6'>My Challenges to Others</font></h1>
<table width='100%'>
<thead>
<th width="40%">Challenge Title</th>
<th width="20%">Target</th>
<th width="20%">Challenge Difficulty</th>
<th width="20%">Status</th>
</thead>
<tbody>
<?php
if (empty($challengesToOthers)) {
echo '<td colspan="4">';
echo $username.' do not have any outstanding challenges.';
echo '</td>';
} else {
//pr($challengesToOthers);die();
$count = 0;
foreach ($challengesToOthers as $myChallenge) {
echo '<tr>';
//display challenge title
echo '<td>';
echo $challengesToOthers[$count]['challenges']['challenge_title'];
echo '</td>';
//display target user
echo '<td>';
$targetUser = $challengesToOthers[$count]['challenges']['to_individual'];
$targetClass = $challengesToOthers[$count]['challenges']['to_class'];
$targetSchool = $challengesToOthers[$count]['challenges']['to_school'];
//do a check condition for Individual, class, school
//loop through each array to find the corresponding name;
//display the name
if (!empty($targetUser)) {
foreach ($otherUsers as $temp) {
$tempUserId = $temp['users']['id'];
if ($tempUserId == $targetUser) {
echo $temp['users']['username'];
}
}
} elseif (!empty($targetClass)) {
foreach ($allClasses as $temp) {
//pr($temp);die();
$tempClassId = $temp['classes']['class_id'];
if ($tempClassId == $targetClass) {
echo $temp['classes']['class_name'];
}
}
} else {
foreach ($allSchools as $temp) {
//pr($temp);die();
$tempSchId = $temp['schools']['school_id'];
if ($tempSchId == $targetSchool) {
echo $temp['schools']['school_name'];
}
}
}
echo '</td>';
//display difficulty level of the challenge
echo '<td>';
echo $challengesToOthers[$count]['challenges']['difficulty_level'];
echo '</td>';
//display status of the challenge
echo '<td>';
$challengeStatus = $challengesToOthers[$count]['challenges']['challenge_status'];
if ($challengeStatus == '') {
echo 'Pending';
} else {
if ($challengeStatus == 'win') {
echo 'Challenge Lost';
} else {
echo 'Challenge Won';
}
}
echo '</td>';
echo '</tr>';
$count++;
}
}
?>
</tbody>
</table>
</fieldset>
</div>
<div class="content" id="panel2-3">
<h1 align='center'><font size='6'>My Friends</font></h1>
<table>
<?php
if(empty($allMyFriends)){
echo 'Please add friends!';
}
foreach ($allMyFriends as $temp) {
echo '<tr>';
$friendID = $temp['friends']['friend_id'];
$friendName = '';
foreach ($otherUsers as $tempUser) {
$tempUserId = $tempUser['users']['id'];
if ($tempUserId == $friendID) {
$friendName = $tempUser['users']['username'];
break;
}
}
?>
<td width='50%'><?php echo $this->Html->image('profileImg/' . $friendName . '.jpg', array('height' => '35%', 'width' => '35%','align'=>'center'), array('url' => array('controller' => 'profiles', 'action' => 'otherProfiles',$friendName))); ?></td>
<td width='50'><?php echo $this->Html->link($friendName, array('controller' => 'profiles', 'action' => 'otherProfiles',$friendName)); ?></td>
<?php
echo '<tr>';
}
?>
</table>
</div>
</div>
</div>
</div>
</div>
| 44d225a30c374b490b356c22e0c7c0fbed7b81ec | [
"PHP",
"INI"
] | 49 | PHP | spteo/FYP | 5c77c22b8b856fe6bd7315d0d8abbf85d5a40763 | 19fe354d99dc51aea0133a3a3be1de1cbbabfb95 |
refs/heads/main | <file_sep>import React, {useReducer} from 'react'
const initialState = {
firstCounter: 0
}; //this is the count value
const reducer = (currentState, action) => {
switch(action.type) {
case 'increment':
return {firstCounter: currentState.firstCounter +1}
case 'decrement':
return {firstCounter: currentState.firstCounter -1}
case 'reset':
return initialState
case 'default':
return currentState
}
}
function UseReducerCounter2() {
const [count, dispatch] = useReducer(reducer, initialState) //count is current state
return (
<div>
<div>count - {count.firstCounter}</div>
<button onClick={()=> dispatch({type: 'increment'})}>Increment</button>
<button onClick={()=> dispatch({type: 'decrement'})}>Decrement</button>
<button onClick={()=> dispatch({type: 'reset'})}>Reset</button>
</div>
)
}
export default UseReducerCounter2
<file_sep>import React, {useState} from 'react'
function CounterTwo() {
const [count, setCount] = useState(0)
const increment = () => {
setCount((prevCount) => prevCount +1)
}
const decrement = () => {
setCount((prevCount) => prevCount - 1)
}
const reset = () => {
setCount(0)
}
return (
<div>
<h2>Count {count}</h2>
<button onClick={increment}>Inc</button>
<button onClick={decrement}>Dec</button>
<button onClick={reset}>Res</button>
</div>
)
}
export default CounterTwo
<file_sep>import React, {useState} from 'react'
function HookCounter() {
const [count, setCount] = useState(0) //array destructuring
//-> const [currentVal of state var, method that can update state var] = useState(initialVal of state var)
return (
<div>
<button onClick={() => setCount(count+1)}>Count {count}</button>
</div>
)
}
export default HookCounter
<file_sep>import React, {useState, useEffect} from 'react'
import axios from 'axios'
function DataFetching() {
const [posts, setPosts] = useState({})
const [id, setId] = useState(1)
const [idFromBtn, setIdFromBtn] = useState(1)
useEffect(()=>{
axios.get(`https://jsonplaceholder.typicode.com/posts/${idFromBtn}`)
.then(res=>{
console.log(res)
setPosts(res.data)
})
.catch(err=>{
console.log(err)
})
}, [idFromBtn])
const handleClick = () => {
setIdFromBtn(id)
}
return (
<div>
<input type="text" value={id} onChange={(e)=>setId(e.target.value)}></input>
<button onClick={handleClick}>Fetch Posts</button>
<div>{posts.title}</div>
{/* <ul>
{
posts.map(post=>{
return <li key={post.id}>{post.title}</li>
})
}
</ul> */}
</div>
)
}
export default DataFetching
<file_sep>import React, {useState} from 'react'
import useCounter from '../hooks/useCounter'
function CounterOne() {
const [count, increment, decrement, reset] = useCounter()
// const [count, setCount] = useState(0)
// const increment = () => {
// setCount((prevCount) => prevCount +1)
// }
// const decrement = () => {
// setCount((prevCount) => prevCount - 1)
// }
// const reset = () => {
// setCount(0)
// }
return (
<div>
<h2>Count {count}</h2>
<button onClick={increment}>Inc</button>
<button onClick={decrement}>Dec</button>
<button onClick={reset}>Res</button>
</div>
)
}
export default CounterOne
| b5710619f8619687dba0f4d9744173561cc0a2fa | [
"JavaScript"
] | 5 | JavaScript | akshitkakkar/Hooks | 9efe488a7efb61c82c5c55d7b4c0689dc706e8d2 | e2856fd2eac2026a444a12608d3f3e16838c75f8 |
refs/heads/master | <file_sep>import React, { Component } from 'react'
class Like extends Component {
state = {}
// handleChange=()=>{}
render() {
let classes = "fa fa-heart";
if (!this.props.liked) classes += '-o';
return <i className={classes} aria-hidden="true"></i>;
}
}
export default Like;<file_sep>import React from 'react';
import _ from 'lodash'
const Pagination = (props) => {
const { itemCount, pageSize } = props;
const pagesCount = Math.ceil(itemCount / pageSize);
//if (pagesCount === 1) return null;
// console.log(pagesCount)
const pages = _.range(1, pagesCount + 1)
return <nav >
<ul className="pagination">
{pages.map(page => (<li key={page} className="page-item"><a className="page-link" >{page}</a></li>))}
</ul>
</nav>
;
}
export default Pagination; | b294ce9a8cf0a78ff21ef1f3ed5b4b763a1f543d | [
"JavaScript"
] | 2 | JavaScript | nishantvijayvargiya/Repovidly | 27ca0c39397adf53cf6bb00a5ed9f2b3ac56b8a7 | df8a11de6295c777c958895b0c8031532fee0ab0 |
refs/heads/master | <repo_name>VistaGraphicsInc/alexa_vg<file_sep>/README.md
# alexa_vg
Alexa Skill for VistaGraphics, Inc.
<file_sep>/src/src.py
"""
Simple Lambda function (runtime:python3.6) providing general information about VistaGraphics, Inc.
Intents supported:
About
Contact
Events
News
Services
ServicePublishing
ServiceDigital
ServicePromos
ServiceEventsTickets
Testimonials
howManyClients
howManyCoffees
howManyAds
howManyMagazines
GetHelp
Stop
"""
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
import random
# --------------- Helpers that build all of the responses ----------------------
def build_speechlet_response(card_title, card_content, output, reprompt_text, should_end_session):
return {
'outputSpeech': {
'type': 'SSML',
'ssml': output
},
'card': {
'type': 'Simple',
'title': card_title,
'content': card_content
},
'reprompt': {
'outputSpeech': {
'type': 'PlainText',
'text': reprompt_text
}
},
'shouldEndSession': should_end_session
}
def build_response(session_attributes, speechlet_response):
return {
'version': '1.0',
'sessionAttributes': session_attributes,
'response': speechlet_response
}
# -------------- functions to accompany intents' return functions -----------------
#def more_testimonials():
# pass
# --------------- functions to implement the intents ------------------
def about(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = True
card_output = "In addition to the more than 35 publications that VistaGraphics publishes regularly, we also offer our clients custom publishing services."
speech_output = "<speak>We excel at making connections. Vista Graphics is a leader in quality publications, targeted digital marketing and event management services. In addition to the more than 35 publications that Vista Graphics publishes regularly, they also offer our clients custom publishing services. Whether itís for a Destination Marketing Organization, a nonprofit organization, or a national corporation, VistaGraphics, Inc. provides agency-quality design and production to meet your specific needs. No job is too large, Nor, too small.</speak>"
return build_response(session_attributes, build_speechlet_response
("About", card_output, speech_output, reprompt_text, should_end_session))
def contact(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = True
card_output = "WEBSITE: VistaGraphicsInc.com | PHONE: (757) 422-8979 | EMAIL: <EMAIL>"
speech_output = "<speak>Vista Graphics Inc is located at 1-2-6-4 Perimeter Parkway, in Virginia Beach, VA. <break time=\"0.5s\"/> For information about our Publishing, Digital or Event Services, or to get a Custom Graphics, Publishing, or Advertising Quote, contact us today! You can reach Vista Graphics by phone at. <break time=\"0.25s\"/> 7-5-7. 4-2-2. 8-9-7-9. Or visit us on the web at Vista Graphics <break time=\"0.05s\"/> ink dot com.</speak>"
return build_response(session_attributes, build_speechlet_response
("Contact Details", card_output, speech_output, reprompt_text, should_end_session))
def services(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = False
card_output = "Services offered by VistaGraphics: Publishing, Digital Marketing, Vista Promos Division, Events & Ticketing."
speech_output = "<speak>Vista Graphics offers an array of services to help your business or event. Ask me about a service and I'll happily tell you a little more about what we offer our clients. For example, you can say <break time=\"0.25s\"/> Publishing. Digital Marketing. Promotions. <break time=\"0.25s\"/> or Ticketing.</speak>"
return build_response(session_attributes, build_speechlet_response
("Services", card_output, speech_output, reprompt_text, should_end_session))
services_list = [
'We now account for over 40 titles annually in the hospitality, lifestyle and specialized genres. With each publication, quality is the focus. We believe, the quality of the magazine affects the quality, and receptiveness of the message. Print creates an emotional connection and builds relationships. We know this first hand, for we have been in the business for over 30 years. <break time=\"0.25s\"/> A 2017 Marketing Sherpa study found that of all media, Internet users in the U-S trust print ads the most.',
'With an ever growing need for dedicated Internet service solutions, Vista Internet Marketing Solutions, Inc. was born to answer that call. As a division of VistaGraphics, Inc. <break time=\"0.25s\"/> Your company will receive the same top quality care, and service from our team of highly skilled professionals, which our clients have enjoyed for over 30 years. We have built a solid team of designers, developers, SEO and marketing specialists.',
'Are you looking for creative ways to market and brand your company or business? <break time=\"0.25s\"/> VistaGraphics has launched a new division for promotional products,<break time=\"0.25s\"/> VistaPromos. <break time=\"0.25s\"/> We provide a full spectrum of promotional products, which enhance your competitive presence, brand image, and exposure, to your target audience. From our experience,<break time=\"0.25s\"/> we believe Every business, should incorporate promotional products in to their ad campaigns.',
'We manage and promote dozens of events each year. Through sponsorships, these events now provide an additional platform for our clients to grow and extend their brand. As well, we offer clients a method for selling tickets and promoting their events, via our online ticket portals through <break time=\"0.15s\"/> Cova Ticks <break time=\"0.25s\"/> and Hill-City Ticks. These platforms are competitively priced, user friendly and customizable to fit the needs of each event.'
]
def publishing_services(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = True
card_output = "VistaGraphics publishes over 40 titles annually in the hospitality, lifestyle and specialized genres. With each publication, quality is the focus."
speech_output = "<speak>Here's a tid-bit about our publishing services<break time=\"0.25s\"/>. " + services_list[0] + " </speak>"
return build_response(session_attributes, build_speechlet_response
("Publishing Services", card_output, speech_output, reprompt_text, should_end_session))
def digital_marketing(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = False
card_output = "With an ever growing need for dedicated Internet service solutions, Vista Internet Marketing Solutions, Inc. was born to answer that call."
speech_output = "<speak>A little about our digital marketing<break time=\"0.25s\"/>. " + services_list[1] + " Check out our website to view our portfolio of amazing websites, and trendy mobile applications we have built for our clients. <break time=\"0.25s\"/> Ask me how many clients we serve.</speak>"
return build_response(session_attributes, build_speechlet_response
("Digital Marketing", card_output, speech_output, reprompt_text, should_end_session))
def vista_promos_div(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = True
card_output = "VistaGraphics has launched a new division for promotional products called VistaPromos to help market and brand your company."
speech_output = "<speak>" + services_list[2] + " </speak>"
return build_response(session_attributes, build_speechlet_response
("Vista Promos Division", card_output, speech_output, reprompt_text, should_end_session))
def events_ticketing_services(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = False
card_output = "Check out CoVaTIX.com and HillCityTIX.com | We manage and promote dozens of events each year and offer clients a method for selling tickets and promoting events."
speech_output = "<speak>Through our Events and Ticketing Services <break time=\"0.25s\"/> " + services_list[3] + " <break time=\"0.25s\"/> Take a look at the screen of your Alexa Device, or your Alexa app for website details.<break time=\"0.25s\"/> Don't know the next event you want to attend? Say, upcoming events. </speak>"
return build_response(session_attributes, build_speechlet_response
("Events and Ticketing Services", card_output, speech_output, reprompt_text, should_end_session))
# List of example testimonials to return when testimonials() is called
testimonials_list = [
"<voice name='Matthew'> The app has been a <prosody rate='x-slow'> game changer </prosody> for the Zoo. <break time=\"0.25s\"/> We have been able to achieve a big green initiative by eliminating paper maps completely. Plus, we have expanded our conservation and educational messaging to people of all ages, through the technology. </voice> <break time=\"1s\"/> That was a nice testimonial from <NAME>, Virginia Zoo's Executive Director. Thanks Greg. See what all the Wallabies are talking about. Download the Virginia Zoo app for free, on the Apple Store, or Google Playstore.",
"We just wanted to thank you again for having our winery there this year. You did a fabulous job!!! Everyone was so helpful and professional. Says <NAME>, from Castle Glen Estates Farm and Winery.",
"The bridal show was absolutely wonderful! I always take approximately 400-500 samples to a bridal show and I ran out!!! Says <NAME>, from Creations From the Heart.",
"The Visitor's Guide has been instrumental in success through targeted and broad marketing, to ensure our brand and products reach our potential customers. Says <NAME>, from Donutz On A Stick.",
"It reaches and attracts the right customers for our business's growth. Also, the creative resources make this truly a marketing partnership! Says, <NAME>, from Changes Hairstyling and City Spa.",
"Visitors Guide has given me the best response of any media I've advertised in! My coupon redemption was on point!. Says <NAME>, from the Sauce Shoppe."
]
def testimonials(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = True
card_output = "Sweet Words From Our Clients"
speech_output = "<speak>Here is what someone said about Vista Graphics. <break time=\"0.75s\"/> <say-as interpret-as='interjection'>ahem!</say-as> <break time=\"0.50s\"/> " + random.choice(testimonials_list) + " </speak>"
return build_response(session_attributes, build_speechlet_response
("Testimonials", card_output, speech_output, reprompt_text, should_end_session))
def news(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = True
card_output = "Our latest blog article: 'Why Should You Get Google Certified?' Read more at VistaGraphicsInc.com"
speech_output = "<speak>Here is the latest blog article title: <break time=\"0.75s\"/> Why should you get Google Certified? <break time=\"0.45s\"/> and here's a snippet from that blog: <break time=\"0.45s\"/> To be googled certified means you have the power to leverage your marketing services in the digital world. <break time=\"0.25s\"/> You can read the full article at Vista Graphics <break time=\"0.03s\"/> ink dot com.</speak>"
return build_response(session_attributes, build_speechlet_response
("VistaGraphics News", card_output, speech_output, reprompt_text, should_end_session))
def events(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = True
card_output = "Upcoming Events: COVA BURGER BATTLE"
speech_output = "<speak>Join Coastal Virginia Magazine, as we invite local restaurants, to battle it out to become Coastal Virginia's Best Burger, at the 2019 Cova Battle of the Burgers. <break time=\"0.25s\"/> Attendees will be invited to vote for their favorite Burger, after sampling super delicious sliders, drinking Virginia craft beers, and enjoying live entertainment! <break time=\"0.25s\"/> For more information and tickets, please visit <break time=\"0.25s\"/> Cova burger battle dot com.</speak>"
return build_response(session_attributes, build_speechlet_response
("Upcoming Events", card_output, speech_output, reprompt_text, should_end_session))
########### START Functions for the howMany Intents ###########
def clients(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = False
card_output = "Vista Graphics has over 2,196 active clients (and counting!)"
speech_output = "<speak>We have over 2,196 active and Happy Clients (and counting!). To hear sweet words from our clients, say, testimonials</speak>"
return build_response(session_attributes, build_speechlet_response
("How Many Clients?", card_output, speech_output, reprompt_text, should_end_session))
def coffees(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = False
card_output = "Collectively, we have 35 coffees a day!"
speech_output = "<speak>We have over 35 coffees per day <break time=\"0.50s\"/> <say-as interpret-as='interjection'>vroom!</say-as>. Now, ask me how many magazines we distribute.</speak>"
return build_response(session_attributes, build_speechlet_response
("How Many Coffees?", card_output, speech_output, reprompt_text, should_end_session))
def ads(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = False
card_output = "We design about 5,000 Ads a Year"
speech_output = "<speak>We Design over 5,000 Ads a Year. <break time=\"0.50s\"/> <say-as interpret-as='interjection'>phew</say-as>. If you think that's something. Ask me how many coffees a day we drink.</speak>"
return build_response(session_attributes, build_speechlet_response
("How Many Ads?", card_output, speech_output, reprompt_text, should_end_session))
def magazines(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = True
card_output = "6.5 Million Magazines Per Year"
speech_output = "<speak>We distribute over 65 million Magazines Per Year. <break time=\"0.50s\"/> <say-as interpret-as='interjection'>yowza</say-as>. By the way. Did I mention we recycle?</speak>"
return build_response(session_attributes, build_speechlet_response
("How Many Magazines?", card_output, speech_output, reprompt_text, should_end_session))
########### END Functions for the howMany Intents ###########
def stop(intent, session):
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = True
card_output = "Have a nice day!"
speech_output = "<speak>From all of us here at Vista Graphics Inc., thank you for checking us out on the Alexa App. <break time=\"0.25s\"/> Let us help your business get on its fast-track to growth. Until then, <break time=\"0.15s\"/><say-as interpret-as='interjection'>arrivederci!</say-as>!</speak>"
return build_response(session_attributes, build_speechlet_response
("Session Ended", card_output, speech_output, reprompt_text, should_end_session))
def get_help(intent, session):
""" Called when the user asks for help """
session_attributes = {}
reprompt_text = None
speech_output = ""
should_end_session = False
card_output = "You can ask Vista Graphics: About, Contact, Testimonials, or Services."
speech_output = "<speak>You can ask me things like, About, Contact, Testimonials, or what Services we offer.</speak>"
return build_response(session_attributes, build_speechlet_response
("Things to Ask", card_output, speech_output, reprompt_text, should_end_session))
def handle_session_end_request():
card_title = "Session Ended"
speech_output = "Thank you for checking out the Vista Graphics Alexa Skill."
should_end_session = True
return build_response({}, build_speechlet_response(
card_title, speech_output, None, should_end_session))
# --------------- Primary Events ------------------
def on_session_started(session_started_request, session):
""" Called when the session starts """
logger.info("on_session_started requestId=" + session_started_request['requestId'] +
", sessionId=" + session['sessionId'])
def on_launch(launch_request, session):
""" Called when the user launches the skill without specifying what they
want
"""
logger.info("on_launch requestId=" + launch_request['requestId'] +
", sessionId=" + session['sessionId'])
# Dispatch to skill's launch
return build_response({},build_speechlet_response(
"Vista Graphics, Inc.", "Welcome to the Amazon Alexa skill, Vista Graphics!", "<speak> <say-as interpret-as='interjection'>open sesame</say-as>. Welcome to the Vista Graphics, Inc Alexa Skill. I will give the 4-1-1 on Vista Graphics Inc. <break time=\"0.5s\"/> Just drop me a line by asking <break time=\"0.5s\"/> About, <break time=\"0.25s\"/> Contact, News, <break time=\"0.25s\"/> or ask me for help, and I'll give you more tips on what to ask.</speak>","Just drop me a line by asking: About, Contact, News, or ask me for help, and I'll give you more tips on what to ask.",False))
def on_intent(intent_request, session):
""" Called when the user specifies an intent for this skill """
logger.info("on_intent requestId=" + intent_request['requestId'] +
", sessionId=" + session['sessionId'])
intent = intent_request['intent']
intent_name = intent_request['intent']['name']
# Dispatch to skill's intent handlers
if intent_name == "About":
return about(intent, session)
elif intent_name == "Contact":
return contact(intent, session)
elif intent_name == "Services":
return services(intent, session)
elif intent_name == "ServicePublishing":
return publishing_services(intent, session)
elif intent_name == "ServiceDigital":
return digital_marketing(intent, session)
elif intent_name == "ServicePromos":
return vista_promos_div(intent, session)
elif intent_name == "ServiceEventsTickets":
return events_ticketing_services(intent, session)
elif intent_name == "Testimonials":
return testimonials(intent, session)
elif intent_name == "News":
return news(intent, session)
elif intent_name == "Events":
return events(intent, session)
elif intent_name == "howManyClients":
return clients(intent, session)
elif intent_name == "howManyCoffees":
return coffees(intent, session)
elif intent_name == "howManyAds":
return ads(intent, session)
elif intent_name == "howManyMagazines":
return magazines(intent, session)
elif intent_name == "Stop":
return stop(intent, session)
elif intent_name == "GetHelp":
return get_help(intent, session)
# elif intent_name == "AMAZON.HelpIntent":
# return get_help()
elif intent_name == "AMAZON.CancelIntent" or intent_name == "AMAZON.StopIntent":
return handle_session_end_request()
else:
raise ValueError("Invalid intent")
def on_session_ended(session_ended_request, session):
""" Called when the user ends the session.
Is not called when the skill returns should_end_session=true
"""
print("on_session_ended requestId=" + session_ended_request['requestId'] +
", sessionId=" + session['sessionId'])
# add cleanup logic here
# --------------- Main handler ------------------
def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
logger.info("event.session.application.applicationId=" +
event['session']['application']['applicationId'])
"""
Uncomment this if statement and populate with skill's application ID to
prevent someone else from configuring a skill that sends requests to this
function.
"""
# if (event['session']['application']['applicationId'] !=
# "amzn1.echo-sdk-ams.app.[unique-value-here]"):
# raise ValueError("Invalid Application ID")
if event['session']['new']:
on_session_started({'requestId': event['request']['requestId']},
event['session'])
if event['request']['type'] == "LaunchRequest":
return on_launch(event['request'], event['session'])
elif event['request']['type'] == "IntentRequest":
return on_intent(event['request'], event['session'])
else:
return on_session_ended(event['request'], event['session'])
<file_sep>/requirements.txt
# placeholder
python-dateutil==2.7.5 | 43734baad7a7eb85d5d209e69fd5efe650242d2c | [
"Markdown",
"Python",
"Text"
] | 3 | Markdown | VistaGraphicsInc/alexa_vg | 43309f7d549755f93b546c6a5b6150526456d6e6 | 6afa1bb4bef62a85ae7c617a7a87ebfba8387b57 |
refs/heads/master | <repo_name>MatthewKosloski/headless-wordpress<file_sep>/client/components/index.js
import { default as Header } from './Header';
import { default as Layout } from './Layout';
export {
Header,
Layout
};<file_sep>/README.md
# headless-wordpress
A work-in-progress starter for a headless implementation of WordPress. There are a lot of dependencies to do something like this (e.g., PhpMyAdmin, MySQL, WordPress, Express, etc.), so a Docker container seems like a good way of going about it. Data persistence and migration may be an issue, however.
This is a reverse engineering of [headless-wp-starter](https://github.com/postlight/headless-wp-starter).
## TODO
- Create a new image based off the WordPress image to automate the installation and activation of themes and plugins. Will probably need to use [WP CLI](https://wp-cli.org/).
- Figure out a good way to back up the database if the volumes are deleted.
## Usage
1. Create an environment variable file in root directory:
```
MYSQL_ROOT_PASSWORD=
MYSQL_DATABASE=
MYSQL_USER=
MYSQL_PASSWORD=
WORDPRESS_DB_USER=
WORDPRESS_DB_PASSWORD=
```
In the above, `MYSQL_USER` and `WORDPRESS_DB_USER` must be the same and `MYSQL_PASSWORD` and `WORDPRESS_DB_PASSWORD` must be the same.
2. Start the services in detached mode:
```
docker-compose up -d
```
3. Stop the services:
```
docker-compose down
```
If you want to delete the persisted data from the `db_data` volume, optionally add the `--volumes` flag:
```
docker-compose down --volumes
```<file_sep>/docker-compose.yaml
version: '3'
services:
db:
container_name: db
image: mysql:5.7
restart: always
env_file: ./.env
volumes:
- db_data:/var/lib/mysql
phpmyadmin:
container_name: phpmyadmin
image: phpmyadmin/phpmyadmin
restart: always
env_file: ./.env
environment:
PMA_HOST: db
depends_on:
- db
ports:
- '8080:80'
wordpress:
container_name: wordpress
image: wordpress:latest
restart: always
env_file: ./.env
environment:
WORDPRESS_DB_HOST: db:3306
depends_on:
- db
ports:
- '8000:80'
volumes:
- ./wordpress:/var/www/html
client:
container_name: client
command: bash -c 'npm install && npm run build && npm start'
ports:
- '3000:3000'
image: node
volumes:
- ./client:/home/node/app
working_dir: /home/node/app
volumes:
db_data:<file_sep>/client/pages/post.js
import WPAPI from 'wpapi';
import { Layout } from '../components';
import { endpoint } from '../config';
const wp = new WPAPI({ endpoint });
const Post = ({title, content}) => (
<Layout>
<h1>{title.rendered}</h1>
<div dangerouslySetInnerHTML={{
__html: content.rendered
}} />
</Layout>
);
Post.getInitialProps = async function(context) {
const { slug } = context.query;
try {
const post = await wp.posts().slug(slug);
return post[0];
} catch(err) {
console.error(err);
}
}
export default Post;<file_sep>/client/config.js
export const endpoint = 'http://192.168.99.100:8000/wp-json/'; | 8ba2f587fd3852ab06caabe000242bb2b8e284d3 | [
"JavaScript",
"YAML",
"Markdown"
] | 5 | JavaScript | MatthewKosloski/headless-wordpress | e6f4eac43eede146ee4de70ce66d9ce7c23d7688 | 0cd48a3c54053d779d447e7a76ecff25aaab9148 |
refs/heads/master | <repo_name>kginstructor/eoae_api<file_sep>/routes/cod.js
const router = require('express');
const routes = router();
const API = require('call-of-duty-api')();
API.login(process.env.COD_USERNAME, process.env.COD_PASSWORD).then(data => {
console.log("Got a valid response to login: ", data);
}).catch(err => {
console.error("LOGIN FAILED: ", err);
});
routes.all("/:endpoint/:gamerTag/:platform", function(req, res, next) {
const normalSuccess = function(data) {
res.json(data);
};
const normalError = function(err) {
console.error(err);
res.send('{ "Error":"COD API ERROR: '+err+'" }');
};
switch (req.params.endpoint.toLowerCase()) {
case 'multiplayer':
API.MWmp(req.params.gamerTag, req.params.platform).then(normalSuccess).catch(normalError);
break;
case 'multiplayer-matches':
var start = req.params.startTime ? req.params.startTime : 0;
var stop = req.params.stopTime ? req.params.stopTime : 0;
API.MWcombatmpdate(req.params.gamerTag, start, stop, req.params.platform).then(normalSuccess).catch(normalError);
break;
case 'leaderboard':
var page = req.params.page ? req.params.page : 1;
API.MWleaderboard(page, req.params.platform).then(normalSuccess).catch(normalError);
break;
case 'warzone':
API.MWwz(req.params.gamerTag, req.params.platform).then(normalSuccess).catch(normalError);
break;
case 'warzone-matches':
var start = req.params.startTime ? req.params.startTime : 0;
var stop = req.params.stopTime ? req.params.stopTime : 0;
API.MWcombatwzdate(req.params.gamerTag, start, stop, req.params.platform).then(normalSuccess).catch(normalError);
break;
case 'coldwar':
API.CWmp(req.params.gamerTag, req.params.platform).then(normalSuccess).catch(normalError);
break;
case 'coldwar-matches':
var start = req.params.startTime ? req.params.startTime : 0;
var stop = req.params.stopTime ? req.params.stopTime : 0;
API.CWcombatdate(req.params.gamerTag, start, stop, req.params.platform).then(normalSuccess).catch(normalError);
break;
case 'coldwar-fullmatchinfo':
var matchId = req.params.matchId ? req.params.matchId : 0;
API.CWFullMatchInfo(matchId, req.params.platform).then(normalSuccess).catch(normalError);
break;
case 'map-list':
API.MWMapList(req.params.platform).then(normalSuccess).catch(normalError);
break;
}
});
module.exports = routes;<file_sep>/routes/index.js
var express = require('express');
var router = express.Router();
const API = require('call-of-duty-api')({ platform: "battle" });
API.login(process.env.COD_USERNAME, process.env.COD_PASSWORD).then(data => {
console.log("Got a valid response to login: ", data);
}).catch(err => {
console.error("LOGIN FAILED: ", err);
});
/* GET home page. */
router.get('/', function(req, res, next) {
API.MWBattleData('KillingGame#1239').then(data => {
res.json(data);
}).catch(err => {
res.send("COD API ERROR: "+err);
});
});
module.exports = router;
| bbdea15c791be52496394f1b079fa5c31e7001b1 | [
"JavaScript"
] | 2 | JavaScript | kginstructor/eoae_api | 4211dfb6959b98e9933116b65eaef38deaa4b694 | 5c49cf04817f1092d08c5d4b2884741edebb8c49 |
refs/heads/master | <file_sep>function myFunction() {
var element1 = document.getElementById("1");
element1.classList.toggle("mystyle");
var element2 = document.getElementById("2");
element2.classList.toggle("mystyle");
var element3 = document.getElementById("3");
element3.classList.toggle("mystyle");
var element4 = document.getElementById("4");
element4.classList.toggle("mystyle");
var element5 = document.getElementById("5");
element5.classList.toggle("mystyle");
var element6 = document.getElementById("6");
element6.classList.toggle("mystyle");
var element7 = document.getElementById("7");
element7.classList.toggle("mystyle");
var element8 = document.getElementById("8");
element8.classList.toggle("mystyle");
var element9 = document.getElementById("9");
element9.classList.toggle("mystyle");
var element10 = document.getElementById("10");
element10.classList.toggle("mystyle");
var element11 = document.getElementById("11");
element11.classList.toggle("mystyle");
var element12 = document.getElementById("12");
element12.classList.toggle("mystyle");
var element13 = document.getElementById("13");
element13.classList.toggle("mystyle");
var element14 = document.getElementById("14");
element14.classList.toggle("mystyle");
var element15 = document.getElementById("15");
element15.classList.toggle("mystyle");
} | cf41598f4834112a3f0fcc15797d0a91095329dd | [
"JavaScript"
] | 1 | JavaScript | zaivsNoob/September-Kaleidscope | 2f92dfef86d2d7de66a07ae4a6b8f3d71a38493f | e5193d280d01c14b8157dca7f3b7c4b0613c1cbb |
refs/heads/master | <repo_name>MaciekLabedzki/RockPaperScissors<file_sep>/RockPaperScissors/Program.cs
/* ================*/
/* <NAME> */
/* =============== */
using System;
using System.Text.RegularExpressions;
using GameLoops;
public class Program
{
public static void Main()
{
Console.Clear();
int lastChose = 0;
//menu loop
while (true)
{
//Print Menu
Console.WriteLine(" Rock Paper Scissors ");
Console.WriteLine("");
Console.WriteLine("Main Menu:");
Console.WriteLine("[1] Play a new game!");
Console.WriteLine("[9] Exit Game");
//Choose option - if string is not all numbers you cant parse
string tmp = Console.ReadLine();
if (Regex.IsMatch(tmp, @"^\d+$"))
lastChose = Int32.Parse(tmp);
else
lastChose = 0;
//ClearScreen
Console.Clear();
switch (lastChose)
{
case 1:
//New Game
GameLoop loop = new GameLoop();
break;
case 9:
//exit program
return;
default:
//accept other choices
Console.WriteLine("Please choose correct option...");
Console.ReadKey();
Console.Clear();
break;
}
}
}
}<file_sep>/RockPaperScissors/Player.cs
using System;
namespace Players
{
public class Player
{
public string Name;
public int Points;
public string LastMove;
public Player(int playerNum)
{
LastMove = "";
Points = 0;
Console.Write("Please type name of player " + playerNum + ": ");
Name = Console.ReadLine();
Console.WriteLine(Name + " - points: " + Points + " has been created.");
}
}
}<file_sep>/RockPaperScissors/GameLoop.cs
using System;
using System.Collections.Generic;
using Players;
namespace GameLoops
{
public class GameLoop
{
public int WinValue;
public List<Player> Players;
public int Turn;
public bool IsGameFinished;
public void PressAnyKeyNoErease()
{
Console.WriteLine("Press any key...");
Console.ReadKey();
Console.Clear();
}
public void PressAnyKey()
{
Console.WriteLine("");
Console.WriteLine("Press any key...");
Console.ReadKey();
Console.Clear();
}
public void PressAnyKey(string s)
{
Console.WriteLine("");
Console.WriteLine("Press any key to " + s + "...");
Console.ReadKey();
Console.Clear();
}
public void PressAnyKey(string preS, string s)
{
Console.WriteLine("");
Console.WriteLine(preS + '\n' + '\n' + "Press any key to " + s + "...");
Console.ReadKey();
Console.Clear();
}
public GameLoop()
{
//initiate
Console.Clear();
Players = new List<Player>();
Turn = 0;
IsGameFinished = false;
//Ask for how much points to get to win
Console.Write("Please set winning points value: ");
WinValue = Int32.Parse(Console.ReadLine());
//add 2 players
for (int i = 1; i <= 2; i++)
Players.Add(new Player(i));
//Play
Console.Clear();
while (!IsGameFinished)
{
//increment turn
Turn++;
//Communicate begin of turn
PressAnyKey("Turn " + Turn + " begins.", "start");
//Select gesture
foreach(Player p in Players)
{
//nullify Last Move
p.LastMove = "";
PressAnyKey("Turn of " + p.Name, " starts");
//Player Choice until player choose proper string
while (p.LastMove == "")
{
Console.WriteLine(p.Name + " select one of gestures and press Enter:");
Console.WriteLine("[1] Rock");
Console.WriteLine("[2] Paper");
Console.WriteLine("[3] Scissors");
p.LastMove = Console.ReadLine();
switch (p.LastMove)
{
case "1":
p.LastMove = "Rock";
break;
case "2":
p.LastMove = "Paper";
break;
case "3":
p.LastMove = "Scissors";
break;
default:
p.LastMove = "";
break;
}
Console.Clear();
}
}
//Pause until both player see
PressAnyKey("see who won");
//Check who won turn
string tmpCommunicate = Players[0].Name + " played with " + Players[0].LastMove;
if (Players[0].LastMove == Players[1].LastMove)
tmpCommunicate += " same as " + Players[1].Name + '\n' + "It means draw. No one gets point.";
else
{
switch (Players[0].LastMove)
{
case "Rock":
///TODO - wrap those ifs with function
if (Players[1].LastMove == "Paper") //Lose Case
{
tmpCommunicate += " when " + Players[1].Name + " played with " + Players[1].LastMove + '\n'
+ "It means that " + Players[1].Name + " won and gets one point.";
Players[1].Points++;
}
else if (Players[1].LastMove == "Scissors") //Won Case
{
tmpCommunicate += " when " + Players[1].Name + " played with " + Players[1].LastMove + '\n'
+ "It means that " + Players[0].Name + " won and gets one point.";
Players[0].Points++;
}
break;
case "Paper":
if (Players[1].LastMove == "Scissors")
{
tmpCommunicate += " when " + Players[1].Name + " played with " + Players[1].LastMove + '\n'
+ "It means that " + Players[1].Name + " won and gets one point.";
Players[1].Points++;
}
else if (Players[1].LastMove == "Rock")
{
tmpCommunicate += " when " + Players[1].Name + " played with " + Players[1].LastMove + '\n'
+ "It means that " + Players[0].Name + " won and gets one point.";
Players[0].Points++;
}
break;
case "Scissors":
if (Players[1].LastMove == "Rock")
{
tmpCommunicate += " when " + Players[1].Name + " played with " + Players[1].LastMove + '\n'
+ "It means that " + Players[1].Name + " won and gets one point.";
Players[1].Points++;
}
else if (Players[1].LastMove == "Paper")
{
tmpCommunicate += " when " + Players[1].Name + " played with " + Players[1].LastMove + '\n'
+ "It means that " + Players[0].Name + " won and gets one point.";
Players[0].Points++;
}
break;
}
}
//show who won turn
Console.WriteLine(tmpCommunicate);
PressAnyKey();
//show points
Console.WriteLine("Points after turn " + Turn +":");
foreach (Player p in Players)
{
Console.WriteLine(p.Name + ": " + p.Points);
}
PressAnyKeyNoErease();
//check for winners
foreach (Player p in Players)
{
if (p.Points >= WinValue)
{
IsGameFinished = true;
//show who won the game
Console.Clear();
Console.WriteLine(p.Name + " won the game. Congratulations!");
PressAnyKey();
}
}
}
}
}
} | f7d61a145cac0e18dacaf6e970335044bb7c85c4 | [
"C#"
] | 3 | C# | MaciekLabedzki/RockPaperScissors | 8abfccbc3e5082669afebb8b09d0c035039d24bc | 033149bb25442bc3b1444fdbfdd6eb55b2366a20 |
refs/heads/master | <file_sep>import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/home',
name:"home",
meta: {
title: "首页",
index:1
},
component: resolve => require(['@/views/home/home.vue'], resolve)
},
{
path: '/category',
name:"category",
meta: {
title: "分类",
index:2
},
component: resolve => require(['@/views/category/category.vue'], resolve)
},
{
path: '/cart',
name:"cart",
meta: {
title: "购物车",
index:3
},
component: resolve => require(['@/views/cart/cart.vue'], resolve)
},
{
path: '/mine',
name:"mine",
meta: {
title: "我的",
index:4
},
component: resolve => require(['@/views/mine/mine.vue'], resolve)
},
{
path: '/proDetail',
name:"proDetail",
meta: {
title: "产品详情",
index:5
},
component: resolve => require(['@/components/home/proDetail.vue'], resolve)
},
{
path: '/search',
name:"search",
meta: {
title: "搜索",
index:6
},
component: resolve => require(['@/components/home/search.vue'], resolve)
},
{
path: '*',
redirect:"/home"
}
]
})
| 6107728a8cf4e75420e7b8fecec0974390f99918 | [
"JavaScript"
] | 1 | JavaScript | lzwmy/webapp | 75f6d4411de3a82185af194753636130242576ac | a0949326b7738abf0f37fd602c1ee8d5e3671bb6 |
refs/heads/main | <file_sep>import React from "react";
const About = () => {
return (
<section className="section about-section">
<h1 className="section-title">about us</h1>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Vel, placeat
libero nostrum aspernatur, consequatur enim in ipsa eos natus quasi
doloribus laboriosam laudantium omnis neque accusamus qui, est iusto
fuga quidem. Saepe recusandae ullam, laudantium at aperiam perferendis
suscipit tempore?
</p>
</section>
);
};
export default About;
| ce160538646fa17082e2dd2d26e74d75ef3a7942 | [
"JavaScript"
] | 1 | JavaScript | iObrovac/react-project-cocktail | f8baccb07d5c170660917539a59e2d850b3c2210 | 7b9084f11bb270ea56f6423ee38322c85fdcbc60 |
refs/heads/master | <file_sep>#include<iostream>
#include<vector>
#include<string>
#include<iomanip>
using namespace std;
class todoList{
public:
void add();
void del(int);
void print();
private:
typedef struct{
string name;
int year;
int month;
int day;
}Event;
vector<Event> list;
bool check(int, int, int);
bool leap(int);
};
void todoList::add(){
Event event;
cout<<"name: ";
cin>>event.name;
cout<<"year: ";
cin>>event.year;
cout<<"month: ";
cin>>event.month;
while(event.month>12 || event.month<1){
cout<<"retry month: ";
cin>>event.month;
}
cout<<"day: ";
cin>>event.day;
while(!check(event.year, event.month, event.day)){
cout<<"retry day: ";
cin>>event.day;
}
int size=list.size();
for(int i=0;i<list.size();i++){
if(event.year>list[i].year) continue;
if(event.year<list[i].year){
list.insert(list.begin()+i, event);
break;
}
if(event.month>list[i].month) continue;
if(event.month<list[i].month){
list.insert(list.begin()+i, event);
break;
}
if(event.day>list[i].day) continue;
list.insert(list.begin()+i, event);
break;
}
if(size==list.size()) list.push_back(event);
}
void todoList::del(const int id){
if(id>=list.size() || id<0){
cout<<"failed to delete event"<<endl;
return;
}
list.erase(list.begin()+id);
}
void todoList::print(){
int name=4;
for(int i=0;i<list.size();i++){
if(list[i].name.length()>name){
name=list[i].name.length();
}
}
cout<<"id "<<setw(name)<<"name"<<" year month day"<<endl;
for(int i=0;i<18+name;i++){
cout<<"-";
}
cout<<endl;
for(int i=0;i<list.size();i++){
cout<<setw(2)<<i<<setw(name+1)<<list[i].name<<setw(5)<<list[i].year<<setw(6)<<list[i].month<<setw(4)<<list[i].day<<endl;
}
}
bool todoList::check(const int year, const int month, const int day){
switch(month){
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if(day>=1 && day<=31) return true;
else return false;
case 4: case 6: case 9: case 11:
if(day>=1 && day<=30) return true;
else return false;
case 2:
if(leap(year)){
if(day>=1 && day<=29) return true;
else return false;
}else{
if(day>=1 && day<=28) return true;
else return false;
}
default:
return true;
}
}
bool todoList::leap(const int year){
if(year%400==0) return true;
else if(year%100==0) return false;
else if(year%4==0) return true;
else return false;
}
<file_sep>#include"todoList.h"
int main(){
cout<<"0: exit\n1: add\n2: del\n3: print\n\naction: ";
int act;
todoList todo;
while(cin>>act){
switch(act){
case 0:
return 0;
case 1:
todo.add();
break;
case 2:
cout<<"delete id(-1 to cancel): ";
int del;
cin>>del;
if(del==-1){
cout<<"delete canceled"<<endl;
break;
}
todo.del(del);
break;
case 3:
todo.print();
break;
default:
cout<<"unknown action"<<endl;
}
cout<<"\naction: ";
}
return 0;
}
| 26aff2dd143793f6a871d0fd1901c7a26bb183f9 | [
"C++"
] | 2 | C++ | andy31405/todoList | fa05477aaa961dd7e3cde5644adef6b0f5f89c31 | 8d33fe0e626382e65c99cf6e711c2eeaba21f5ab |
refs/heads/master | <repo_name>MMM95/SysProg<file_sep>/SysProg/SysProgTemplate_SS_15/Symboltable/includes/Symboltable.h
/*
* Symtable.h
*
* Created on: Sep 26, 2012
* Author: knad0001
*/
#ifndef SYMBOLTABLE_H_
#define SYMBOLTABLE_H_
#include "Hashtable.h"
#include "Stringtable.h"
class Symboltable {
private:
public:
Symboltable();
virtual ~Symboltable();
HashTable *memory;
Stringtable *stringTbl;
Item* insertLexem(char * lexem, int length);
Item* lookUp(char * lexem, int length);
};
#endif /* SYMTABLE_H_ */
<file_sep>/SysProg/SysProgTemplate_SS_15/ParseTree/makefile
HEADERDIR = includes
SRCDIR = src
OBJDIR = objs
makeParseTree: ParseTreeTarget
g++ -g $(OBJDIR)/ParseTree.o
ParseTreeTarget: $(HEADERDIR)/ParseTree.h
g++ -g -c -Wall $< -o $(OBJDIR)/ParseTree.o
# In parse_output.d.....
#parse_output.o: header.h
#%.o : %.cpp
# $(CXX) -c $(CXXFLAGS) -o $@ $<
#parse_output.o: parse_output.cpp
# $(CXX) -c $(CFLAGS) $< -o $@s
<file_sep>/SysProg/SysProgTemplate_SS_15/Automat/src/TestAutomat.cpp
#include "../includes/State.h"
#include "../../Scanner/includes/Scanner.h"
#include <iostream>
using namespace std;
int main (int argc, char* argv[]){
Scanner* scanner = new Scanner();
Automat* automat;
automat = new Automat(scanner);
automat -> readChar('a');
cout << automat -> getCurrentState() << endl;
cout << automat -> getIdentifier() << endl;
cout << automat -> getColumn() << endl;
cout << automat -> getLexemLength() << endl;
automat -> readChar(' ');
cout << automat -> getCurrentState() << endl;
cout << automat -> getStart() << endl;
cout << automat -> getColumn() << endl;
cout << automat -> getLexemLength() << endl;
cout << "---------" << endl;
automat -> readChar('\\');
cout << automat -> getCurrentState() << endl;
//cout << automat -> getBackslash() << endl;
cout << automat -> getColumn() << endl;
cout << automat -> getRow() << endl;
cout << automat -> getLexemLength() << endl;
automat -> readChar(10);
cout << automat -> getCurrentState() << endl;
cout << automat -> getStart() << endl;
cout << automat -> getColumn() << endl;
cout << automat -> getRow() << endl;
cout << automat -> getLexemLength() << endl;
cout << "---------" << endl;
automat -> readChar(' ');
cout << automat -> getCurrentState() << endl;
cout << automat -> getStart() << endl;
}
<file_sep>/SysProg/SysProgTemplate_SS_15/Symboltable/src/Symboltable.cpp
#include "../includes/Symboltable.h"
#include "../includes/Hashtable.h"
#include "../includes/Stringtable.h"
#include <cstring>
/*
* Symboltable.cpp
*
* Created on: Sep 26, 2012
* Author: knad0001
*/
Symboltable::Symboltable() {
memory = new HashTable();
stringTbl = new Stringtable();
/*
Item * init1 = new Item{ "if", NULL, memory->hash("if") };
Item * init2 = new Item { "IF", NULL, memory->hash("IF") };
Item * init3 = new Item { "while", NULL, memory->hash("while") };
Item * init4 = new Item { "WHILE", NULL, memory->hash("WHILE") };
memory -> insertItem(init1);
memory -> insertItem(init2);
memory -> insertItem(init3);
memory -> insertItem(init4);
*/
this -> insertLexem("if", 2);
this -> insertLexem("IF", 2);
this -> insertLexem("while", 5);
this -> insertLexem("WHILE", 5);
// TODO read, write, else
}
Symboltable::~Symboltable() {
// TODO Auto-generated destructor stub
}
Item* Symboltable::insertLexem(char * lexem, int length) {
int hashvalue = memory -> hash(lexem);
//if (stringTbl -> lookUpStringtable(lexem, length) == NULL) {
if (lookUp(lexem, length) == NULL) {
char* insertedLexem = stringTbl -> insert(lexem, length);
Item* entry = new Item {insertedLexem, NULL, hashvalue, length};
memory -> insertItem(entry);
cout << " HashvalueInserted: " << hashvalue << " + " << lexem << '\n';
return entry;
} else {
cout << " HashvalueItemAlreadyInList: " << hashvalue << " + " << lexem << '\n';
return lookUp(lexem, length);
}
/*
if (lookUp(entry -> key) == NULL) {
memory -> insertItem(entry);
return entry;
} else {
cout << hashvalue;
return lookUp(entry -> key);
}
*/
/*
int index = memory -> hash(lexem);
Item * entry = new Item{ lexem, NULL, index };
/*
if(lookUp(entry -> key) == NULL){
memory -> insertItem(entry);
return entry;
} else {
cout << index;
return lookUp(entry -> key);
}
*/
return 0;
}
Item* Symboltable::lookUp(char * lexem, int length) {
Item * search = memory -> getItemByKey(lexem, length);
if(search == NULL){
return NULL;
}
return search;
}
<file_sep>/SysProg/SysProgTemplate_SS_15/ParseTree/src/ParseTree.cpp
#include "../includes/ParseTree.h"
RootNode* ParseTree::getRoot()
{
return this -> root;
}
void ParseTree::setRoot(RootNode rootNode)
{
this -> root = rootNode;
}
DeclNode* RootNode::getDecl()
{
return this -> decl;
}
void RootNode::setDecl(DeclNode declarationNode)
{
this -> decl = declarationNode;
}
StatementNode* RootNode::getStatement()
{
return this -> statement;
}
void RootNode::setStatement(StatementNode statementNode)
{
this -> statement = statementNode;
}
DeclNode* DeclsNode::getDecl()
{
return this -> decl;
}
void DeclsNode::setDecl(DeclNode* decl)
{
this -> decl = decl;
}
char DeclsNode::getSemicolon()
{
return this -> semicolon;
}
void DeclsNode::setSemicolon(char semicolon)
{
this -> semicolon = semicolon;
}
DeclsNode* DeclsNode::getDecls()
{
return this -> decls;
}
void DeclsNode::setDecls(DeclsNode* decls)
{
this -> decls = decls;
}
StatementNode* StatementsNode::getStatement()
{
return this -> statement;
}
void StatementsNode::setStatement(StatementNode statementNode)
{
this -> statement = statementNode;
}
char* StatementsNode::getSemicolon()
{
return this -> semicolon;
}
void StatementsNode::setSemicolon(char semicolon)
{
this -> semicolon = ';';
}
StatementsNode * StatementsNode::getStatements()
{
return this -> statements;
}
/**
* @brief Setter method for the statements variable of a StatementsNode
* @param statementsNode The note wished to be set
*/
void StatementsNode::setStatements(StatementsNode statementsNode)
{
this -> statements = statementsNode;
}
Exp2Node* ExpressionNode::getExp2()
{
return this -> exp2;
}
void ExpressionNode::setExp2(Exp2Node expression2Node)
{
this -> exp2 = expression2Node;
}
OperatorExpressionNode* ExpressionNode::getOpExp()
{
return this -> opExp;
}
void ExpressionNode::setOpExp(OperatorExpressionNode opExp)
{
this -> opExp = opExp;
}
char ParanthesedExp2::getOpeningParanthesis()
{
return this -> openingParanthesis;
}
void ParanthesedExp2::setOpeningParanthesis(char openingParanthesis)
{
this -> openingParanthesis = openingParanthesis;
}
ExpressionNode* ParanthesedExp2::getExpression()
{
return this -> expression;
}
void ParanthesedExp2::setExpression(ExpressionNode* expression)
{
this -> expression = expression;
}
char ParanthesedExp2::getClosingParanthesis()
{
return this -> closingParanthesis;
}
void ParanthesedExp2::setClosingParanthesis(char closingParanthesis)
{
this -> closingParanthesis = closingParanthesis;
}
char* IdentifierExp2::getName()
{
return this -> name;
}
void IdentifierExp2::setName(char* name)
{
this -> name = name;
}
int IntegerExp2::getValue()
{
return this -> value;
}
void IntegerExp2::setValue(int value)
{
this -> value = value;
}
char OperatorExp2::getOperatorType()
{
return this -> operatorType;
}
void OperatorExp2::setOperatorType(char operatorType)
{
this -> operatorType = operatorType;
}
Exp2Node* OperatorExp2::getExp2()
{
return this -> exp2;
}
void OperatorExp2::setExp2(Exp2Node* exp2)
{
this -> exp2 = exp2;
}
OperatorNode* OperatorExpressionNode::getOperator()
{
return this -> op;
}
void OperatorExpressionNode::setOperator(OperatorNode operatorNode)
{
this -> op = operatorNode;
}
ExpressionNode* OperatorExpressionNode::getExpressionNode()
{
return this -> expression;
}
void OperatorExpressionNode::setExpressionNode(ExpressionNode expressionNode)
{
this -> expression = expressionNode;
}
IdentifierNode* DeclNode::getIdentifier()
{
return this -> identifier;
}
void DeclNode::setIdentifier(IdentifierNode identifierNode)
{
this -> identifier = identifierNode;
}
ArrayNode* DeclNode::getArrayNode()
{
return this -> array;
}
void DeclNode::setArrayNode(ArrayNode arrayNode)
{
this -> array = arrayNode;
}
IdentifierNode* DeclNode::getIntegerIdentifier()
{
return this -> integerIdentifier;
}
void DeclNode::setIntegerIdentifier(IdentifierNode identifierNode)
{
this -> integerIdentifier = identifierNode;
}
char ArrayNode::getOpeningBracket()
{
return this -> openingBracket;
}
void ArrayNode::setOpeningBracket(char openingBracket)
{
this -> openingBracket = openingBracket;
}
char ArrayNode::getClosingBracket()
{
return this -> closingBracket;
}
void ArrayNode::setClosingBracket(char closingBracket)
{
this -> closingBracket = closingBracket;
}
int ArrayNode::getValue()
{
return this -> value;
}
void ArrayNode::setValue(int value)
{
this -> value = value;
}
char OperatorNode::getOperatorType()
{
return this -> operatorType;
}
void OperatorNode::setOperatorType(char operatorType)
{
this ->operatorType = operatorType;
}
char* IdentifierNode::getIdentifier()
{
return this -> identifier;
}
void IdentifierNode::setIdentifier(char* name)
{
this -> identifier = name;
}
IdentifierNode* IdentifierStatementNode::getIdentifier()
{
return this -> identifier;
}
void IdentifierStatementNode::setIdentifier(IdentifierNode identifier)
{
this -> identifier = identifier;
}
IndexNode* IdentifierStatementNode::getIndex()
{
return this -> index;
}
void IdentifierStatementNode::setIndex(IndexNode index)
{
this -> index = index;
}
OperatorNode* IdentifierStatementNode::getColonEquals()
{
return this -> colonEquals;
}
void IdentifierStatementNode::setColonEquals(OperatorNode colonEquals){
this -> colonEquals = colonEquals;
}
ExpressionNode* IdentifierStatementNode::getExpression()
{
return this -> expression;
}
void IdentifierStatementNode::setExpression(ExpressionNode expressionNode)
{
this -> expression = expressionNode;
}
IdentifierNode* WriteStatementNode::getWrite()
{
return this -> write;
}
void WriteStatementNode::setWrite(IdentifierNode* write)
{
this -> write = write;
}
char* WriteStatementNode::getOpeningParenthesis()
{
return this -> openingParenthesis;
}
void WriteStatementNode::setOpeningParenthesis(char openingParanthesis)
{
this -> openingParenthesis = openingParanthesis;
}
ExpressionNode* WriteStatementNode::getExpression()
{
return this -> expression;
}
void WriteStatementNode::setExpression(ExpressionNode* expression)
{
this -> expression = expression;
}
char* WriteStatementNode::getClosingParenthesis()
{
return this -> closingParenthesis;
}
void WriteStatementNode::setClosingParenthesis(char closingParanthesis)
{
this -> closingParenthesis = closingParanthesis;
}
IdentifierNode* ReadStatementNode::getRead()
{
return this -> read;
}
void ReadStatementNode::setRead(IdentifierNode* read)
{
this -> read = read;
}
char* ReadStatementNode::getOpeningParenthesis()
{
return this -> openingParenthesis;
}
void ReadStatementNode::setOpeningParenthesis(char openingParanthesis)
{
this -> openingParenthesis = openingParanthesis;
}
IdentifierNode* ReadStatementNode::getIdentifier()
{
return this -> identifier;
}
void ReadStatementNode::setIdentifier(IdentifierNode* identifier)
{
this -> identifier = identifier;
}
IndexNode* ReadStatementNode::getIndex()
{
return this -> index;
}
void ReadStatementNode::setIndex(IndexNode* index)
{
this -> index = index;
}
char* ReadStatementNode::getClosingParenthesis()
{
return this -> closingParenthesis;
}
void ReadStatementNode::setClosingParenthesis(char closingParanthesis)
{
this -> closingParenthesis = closingParanthesis;
}
char* BracingStatementNode::getOpeningBrace()
{
return this -> openingBrace;
}
void BracingStatementNode::setOpeningBrace(char* openingBrace)
{
this -> openingBrace = openingBrace;
}
StatementsNode* BracingStatementNode::getStatements()
{
return this -> statements;
}
void BracingStatementNode::setStatements(StatementsNode* statements)
{
this -> statements = statements;
}
char* BracingStatementNode::getClosingBrace()
{
return this -> closingBrace;
}
void BracingStatementNode::setClosingBrace(char* closingBrace)
{
this -> closingBrace = closingBrace;
}
IdentifierNode* IfStatementNode::getIfIdentifier()
{
return this -> ifIdentifier;
}
void IfStatementNode::setIfIdentifier(IdentifierNode* ifIdentifier)
{
this -> ifIdentifier = ifIdentifier;
}
char IfStatementNode::getOpeningParanthesis()
{
return this -> openingParanthesis;
}
void IfStatementNode::setOpeningParanthesis(char openingParanthesis)
{
this -> openingParanthesis = openingParanthesis;
}
ExpressionNode* IfStatementNode::getExpression()
{
return this -> expression;
}
void IfStatementNode::setExpression(ExpressionNode* expression)
{
this -> expression = expression;
}
char IfStatementNode::getClosingParenthesis()
{
return this -> closingParanthesis;
}
void IfStatementNode::setClosingParenthesis(char closingParanthesis)
{
this -> closingParanthesis = closingParanthesis;
}
StatementNode* IfStatementNode::getIfStatement()
{
return this -> ifStatement;
}
void IfStatementNode::setIfStatement(StatementNode* ifStatement)
{
this -> ifStatement = ifStatement;
}
IdentifierNode* IfStatementNode::getElseIdentifier()
{
return this -> elseIdentifier;
}
void IfStatementNode::setElseIdentifier(IdentifierNode* elseIdentifier)
{
this -> elseIdentifier = elseIdentifier;
}
IdentifierNode* WhileStatementNode::getWhileIdentifier()
{
return this -> whileIdentifier;
}
void WhileStatementNode::setWhileIdentifier(IdentifierNode* whileIdentifier)
{
this -> whileIdentifier = whileIdentifier;
}
char WhileStatementNode::getOpeningParanthesis()
{
return this -> openingParanthesis;
}
void WhileStatementNode::setOpeningParanthesis(char openingParanthesis)
{
this -> openingParanthesis = openingParanthesis;
}
ExpressionNode* WhileStatementNode::getExpression()
{
return this -> expression;
}
void WhileStatementNode::setExpression(ExpressionNode* expression)
{
this -> expression = expression;
}
char WhileStatementNode::getClosingParanthesis()
{
return this -> closingParanthesis;
}
void WhileStatementNode::setClosingParanthesis(char closingParanthesis)
{
this -> closingParanthesis = closingParanthesis;
}
StatementNode* WhileStatementNode::getStatement()
{
return this -> statement;
}
void WhileStatementNode::setStatement(StatementNode* statement)
{
this -> statement = statement;
}
/*
* TODO checken ob getter mit Pointern antworten und setter keine Pointer nutzen!!! Im moment ist es mischmasch
*/
<file_sep>/SysProg/SysProgTemplate_SS_15/Parser/src/Parser.cpp
#include "../includes/Parser.h"
#include "../../Scanner/includes/Scanner.h"
#include "../../ParseTree/includes/ParseTree.h"
#include <cstdlib>
/**
* TODO Es muss geprüft werden, dass nextToken
* immer vor dem Eintritt in eine neue Methode
* aufgerufen wird und nicht darin.
*/
ParseTree* Parser::createParseTree()
{
ParseTree* pt = new ParseTree();
return pt;
}
RootNode* Parser::createRootNode()
{
RootNode* rn = new RootNode();
return rn;
}
StatementsNode* Parser::createStatementsNode()
{
StatementsNode* sn = new StatementsNode();
return sn;
}
ExpressionNode* Parser::createExpressionNode()
{
ExpressionNode* exp = new ExpressionNode();
return exp;
}
ParanthesedExp2* Parser::createParanthesedExp2Node()
{
ParanthesedExp2* exp2 = new ParanthesedExp2();
return exp2;
}
IdentifierExp2* Parser::createIdentifierExp2Node()
{
IdentifierExp2* exp2 = new IdentifierExp2();
return exp2;
}
IntegerExp2* Parser::createIntegerExp2()
{
IntegerExp2* exp2 = new IntegerExp2();
return exp2;
}
OperatorExp2* Parser::createOperatorExp2()
{
OperatorExp2* exp2 = new OperatorExp2();
return exp2;
}
OperatorExpressionNode* Parser::createOperatorExpressionNode()
{
OperatorExpressionNode* opExp = new OperatorExpressionNode();
return opExp;
}
DeclNode* Parser::createDeclNode()
{
DeclNode* dn = new DeclNode();
return dn;
}
ArrayNode* Parser::createArrayNode()
{
ArrayNode* an = new ArrayNode();
return an;
}
OperatorNode* Parser::createOperatorNode()
{
OperatorNode* operatorNode = new OperatorNode();
return operatorNode;
}
IdentifierNode* Parser::createIdentifierNode()
{
IdentifierNode* identifier = new IdentifierNode();
return identifier;
}
IdentifierStatementNode* Parser::createIdentifierStatementNode()
{
IdentifierStatementNode* identifierStatementNode = new IdentifierStatementNode();
return identifierStatementNode;
}
WriteStatementNode* Parser::createWriteStatementNode()
{
WriteStatementNode* write = new WriteStatementNode();
return write;
}
ReadStatementNode* Parser::createReadStatementNode()
{
ReadStatementNode* read = new ReadStatementNode();
return read;
}
BracingStatementNode* Parser::createBracingStatementNode()
{
BracingStatementNode* brace = new BracingStatementNode();
return brace;
}
IfStatementNode* Parser::createIfStatementNode()
{
IfStatementNode* ifStatement = new IfStatementNode();
return ifStatement;
}
WhileStatementNode* Parser::createWhileStatementNode()
{
WhileStatementNode* whileStatement = new WhileStatementNode();
return whileStatement;
}
void Parser::error(Token* token)
{
printf("Error located in line: %d, %s, %d, %s %d", token->getRow(), " , column: " , token->getColumn(), " , type: ", token->getTtype());
exit(-1);
}
void Parser::decls()
{
while(nextToken()-> getTtype() == INT)
{
DeclsNode decls; //TODO return ?
decls.setDecl(decl());
if(nextToken()->getTtype() != SEMICOLON)
{
error(getToken()); // Enters the error handling.
}
else
{
decls.setSemicolon(';');
}
}
}
DeclNode* Parser::decl()
{
nextToken(); // iterate to next list item
DeclNode* declNode = createDeclNode();
if(getToken()->getTtype() == INT)
{
declNode -> setIdentifier(createIdentifierNode(getToken()));
}
else
{
error(getToken());
}
ArrayNode* arrayNode = array();
declNode -> setArrayNode(*arrayNode);
if(getToken()->getTtype() == IDENTIFIER)
{
declNode -> setIdentifier(createIdentifierNode(getToken()));
}
else
{
//TODO
}
return declNode;
}
ArrayNode* Parser::array()
{
ArrayNode* node = createArrayNode();
if(getToken()->getTtype() == OPENINGBRACKET)
{
node->setOpeningBracket('[');
nextToken();
if(getToken()->getTtype() == NUMBER)
{
int value = ((IntType*)getToken())->getValue();
node -> setValue(value);
nextToken();
}
else
{
error(getToken()); // Enters the error handling
}
if(getToken()->getTtype() == CLOSINGBRACKET)
{
node -> setClosingBracket(']');
nextToken();
}
else
{
error(getToken()); // Enters the error handling
}
}
else
{
}
return node;
}
void Parser::statements()
{
// Beim ersten Eintritt, darf kein weiteres Token geordert werden.
while(nextToken())
{
//StatementsNode node = createStatementsNode();
statement();
if(nextToken()->getTtype() != SEMICOLON)
{
error(getToken()); // Enters the error handling
}
}
}
StatementNode* Parser::statement()
{
//TODO
switch(getToken()->getTtype())
{
case IDENTIFIER:
IdentifierStatementNode* identifierStatement = createIdentifierStatementNode();
identifierStatement -> setIdentifier(index());
//if()//:= TODO
exp();
case WRITE:
return write();
case READ:
return read();
case OPENINGBRACE:
return statements();
case IF:
return customIf();
case WHILE:
return customWhile();
default:
error(getToken()); // Enters the error handling
break;
}
}
IndexNode* Parser::index()
{
IndexNode* index = createIndexNode();
if(getToken()->getTtype() == OPENINGBRACKET)
{
index -> setExpression(exp());
}
else
{
error(getToken()); // Enters the error handling
}
return index;
}
ExpressionNode* Parser::exp()
{
ExpressionNode* exp = createExpressionNode();
exp -> setExp2(exp2());
nextToken();
exp -> setOpExp(op_exp());
return exp;
}
void Parser::exp2()
{
switch(getToken()->getTtype())
{
case OPENINGPARENTHESIS:
exp();
if(nextToken()->getTtype() == CLOSINGPARENTHESIS)
{
//TODO
}
else
{
error(getToken()); // Enters the error handling
}
break;
case IDENTIFIER:
index();
case NUMBER:
break;
case MINUS:
exp2();
break;
case EXCLAMATIONMARK:
exp2();
break;
default:
error(getToken()); // Enters the error handling
break;
}
}
/**An expression is an operator and an expression or nothing.*/
void Parser::op_exp()
{
OperatorExpressionNode* opExp = createOperatorExpressionNode();
//TODO Check if Token is epsilon
if(NULL == op())
{
}
nextToken();
//opExp -> setExpressionNode(exp()); TODO
}
OperatorNode* Parser::op()
{
OperatorNode* operatorNode = new OperatorNode();
switch(getToken()->getTtype())
{
case PLUS:
operatorNode->setOperatorType('+');
return operatorNode;
case MINUS:
operatorNode->setOperatorType('-');
return operatorNode;
case COLON:
operatorNode->setOperatorType(':');
return operatorNode;
case ASTERISK:
operatorNode->setOperatorType('*');
return operatorNode;
case LESSTHAN:
operatorNode->setOperatorType('<');
return operatorNode;
case GREATERTHEN:
operatorNode->setOperatorType('>');
return operatorNode;
case EQUALS:
operatorNode->setOperatorType('=');
return operatorNode;
case AMPERSAND:
operatorNode->setOperatorType('&');
return operatorNode;
default:
error(getToken()); // Enters the error handling
return operatorNode;
}
}
ReadStatementNode* Parser::read()
{
nextToken();
//TODO weitere Verarbeitung ?
}
WriteStatementNode* Parser::write()
{
WriteStatementNode* writeStatement = createWriteStatementNode();
if(nextToken()->getTtype() == OPENINGPARENTHESIS)
{
writeStatement -> setOpeningParenthesis('(');
writeStatement -> setExpression(exp());
if(nextToken()->getTtype() == CLOSINGPARENTHESIS)
{
writeStatement -> setClosingParenthesis(')');
}
else
{
error(getToken()); // Enters the error handling
}
}
else
{
error(getToken()); // Enters the error handling
}
return writeStatement;
}
IfStatementNode* Parser::customIf()
{
IfStatementNode* ifStatement = createIfStatementNode();
if(nextToken()->getTtype() == OPENINGPARENTHESIS)
{
ifStatement -> setOpeningParanthesis('(');
ifStatement -> setExpression(exp());
if(nextToken()->getTtype() == CLOSINGPARENTHESIS)
{
ifStatement -> setClosingParenthesis(')');
ifStatement -> setIfStatement(statement());
/*
* Else path
* TODO
*/
if(getToken()-> getTtype() == IDENTIFIER){
ifStatement -> setElseStatement(statement());
}
}
else
{
error(getToken()); // Enters the error handling
}
}
else
{
error(getToken()); // Enters the error handling
}
return ifStatement;
}
WhileStatementNode* Parser::customWhile()
{
WhileStatementNode* whileStatement = createWhileStatementNode();
if(nextToken()->getTtype() == OPENINGPARENTHESIS)
{
whileStatement -> setOpeningParanthesis('(');
whileStatement -> setExpression(exp());
if(nextToken()->getTtype() == CLOSINGPARENTHESIS)
{
whileStatement -> setClosingParanthesis(')');
whileStatement -> setStatement(statement());
}
else
{
error(getToken()); // Enters the error handling
}
}
else
{
error(getToken()); // Enters the error handling
}
return whileStatement;
}
void Parser::parse()
{
ParseTree();
decls();
statements();
}
Token* Parser::getToken()
{
return currentToken;
}
Token* Parser::nextToken()
{
Scanner scanner;
Token* t = new Token(0,0,0);
return t;
//TODO Request Token from Scanner
}
<file_sep>/SysProg/SysProgTemplate_SS_15/ParseTree/includes/ParseTree.h
/*
* ParseTree.h
*
* Created on: 13.09.2015
* Author: <NAME>
*/
#ifndef PARSETREE_INCLUDES_PARSETREE_H_
#define PARSETREE_INCLUDES_PARSETREE_H_
class DeclsNode;
class DeclNode;
class ArrayNode;
class StatementsNode;
class StatementNode;
class IdentifierStatementNode;
class WriteStatementNode;
class ReadStatementNode;
class BracingStatementNode;
class IfStatementNode;
class WhileStatementNode;
class ExpressionNode;
class Exp2Node;
class ParanthesedExp2;
class IdentifierExp2;
class IntegerExp2;
class OperatorExp2;
class IndexNode;
class OperatorExpressionNode;
class OperatorNode;
class IdentifierNode
{
public:
char* getIdentifier();
void setIdentifier(char* name);
private:
char* identifier;
};
class OperatorNode
{
public:
char getOperatorType();
void setOperatorType(char operatorType);
private:
char operatorType;
};
class ArrayNode
{
public:
char getOpeningBracket();
char getClosingBracket();
int getValue();
void setOpeningBracket(char openingBracket);
void setClosingBracket(char closingBracket);
void setValue(int value);
private:
char openingBracket;
int value;
char closingBracket;
};
class DeclNode
{
public:
IdentifierNode* getIntegerIdentifier();
ArrayNode* getArrayNode();
IdentifierNode* getIdentifier();
void setIntegerIdentifier(IdentifierNode integerIdentifier);
void setArrayNode(ArrayNode arrayNode);
void setIdentifier(IdentifierNode identifierNode);
private:
IdentifierNode* integerIdentifier;
ArrayNode* array;
IdentifierNode* identifier;
};
class DeclsNode
{
public:
DeclNode* getDecl();
char getSemicolon();
DeclsNode* getDecls();
void setDecl(DeclNode* decl);
void setSemicolon(char semicolon);
void setDecls(DeclsNode* decls);
private:
DeclNode* decl;
char semicolon;
DeclsNode* decls;
};
class OperatorExpressionNode
{
public:
OperatorNode* getOperator();
ExpressionNode* getExpressionNode();
void setOperator(OperatorNode operatorNode);
void setExpressionNode(ExpressionNode expressionNode);
private:
OperatorNode* op;
ExpressionNode* expression;
};
class Exp2Node
{
};
class ParanthesedExp2: public Exp2Node
{
public:
char getOpeningParanthesis();
ExpressionNode* getExpression();
char getClosingParanthesis();
void setOpeningParanthesis(char openingParanthesis);
void setExpression(ExpressionNode* expression);
void setClosingParanthesis(char closingParanthesis);
private:
char* openingParanthesis; // TODO char pointer oder char
ExpressionNode* expression;
char* closingParanthesis;
};
class IdentifierExp2: public Exp2Node
{
public:
char* getName();
void setName(char* name);
private:
char* name;
};
class IntegerExp2: public Exp2Node
{
public:
int getValue();
void setValue(int value);
private:
int value;
};
//Übernimmt beide Fälle, die mit einem Operator beginnen ( - und ! )
class OperatorExp2: public Exp2Node
{
public:
char getOperatorType();
Exp2Node* getExp2();
void setOperatorType(char operatorType);
void setExp2(Exp2Node* exp2);
private:
char operatorType;
Exp2Node* exp2;
};
class IndexNode
{
public:
char* getOpeningBracket();
ExpressionNode* getExpression();
char* getClosingBracket();
void setOpeningBracket(char openingBracket);
void setExpression(ExpressionNode expressionNode);
void setClosingBracket(char closingBracket);
private:
char openingBracket;
ExpressionNode* expression;
char closingBracket;
};
class ExpressionNode
{
public:
Exp2Node* getExp2();
OperatorExpressionNode* getOpExp();
void setExp2(Exp2Node expression2Node);
void setOpExp(OperatorExpressionNode operatorExpressionNode);
private:
Exp2Node* exp2;
OperatorExpressionNode* opExp;
};
class StatementNode
{
};
class IdentifierStatementNode: public StatementNode
{
public:
IdentifierNode* getIdentifier();
IndexNode* getIndex();
OperatorNode* getColonEquals();
ExpressionNode* getExpression();
void setIdentifier(IdentifierNode identifier);
void setIndex(IndexNode index);
void setColonEquals(OperatorNode colonEquals);
void setExpression(ExpressionNode expression);
private:
IdentifierNode* identifier;
IndexNode* index;
OperatorNode* colonEquals;
ExpressionNode* expression;
};
class WriteStatementNode: public StatementNode
{
public:
IdentifierNode* getWrite();
char* getOpeningParenthesis();
ExpressionNode* getExpression();
char* getClosingParenthesis();
void setWrite(IdentifierNode* write);
void setOpeningParenthesis(char openingParanthesis);
void setExpression(ExpressionNode* expressionNode);
void setClosingParenthesis(char closingParanthesis);
private:
IdentifierNode* write;
char* openingParenthesis;
ExpressionNode* expression;
char* closingParenthesis;
};
class ReadStatementNode: public StatementNode
{
public:
IdentifierNode* getRead();
char* getOpeningParenthesis();
IdentifierNode* getIdentifier();
IndexNode* getIndex();
char* getClosingParenthesis();
void setRead(IdentifierNode* read);
void setOpeningParenthesis(char openingParanthesis);
void setIdentifier(IdentifierNode* expressionNode);
void setIndex(IndexNode* indexNode);
void setClosingParenthesis(char closingParanthesis);
private:
IdentifierNode* read;
char openingParenthesis;
IdentifierNode* identifier;
IndexNode* index;
char closingParenthesis;
};
class BracingStatementNode: public StatementNode
{
public:
char* getOpeningBrace();
StatementsNode* getStatements();
char* getClosingBrace();
void setOpeningBrace(char* openingBrace);
void setStatements(StatementsNode* statements);
void setClosingBrace(char* closingBrace);
private:
char openingBrace;
StatementsNode* statements;
char closingBrace;
};
class IfStatementNode: public StatementNode
{
public:
IdentifierNode* getIfIdentifier();
char getOpeningParanthesis();
ExpressionNode* getExpression();
char getClosingParenthesis();
StatementNode* getIfStatement();
IdentifierNode* getElseIdentifier();
StatementNode* getElseStatement();
void setIfIdentifier(IdentifierNode* ifIdentifier);
void setOpeningParanthesis(char openingParanthesis);
void setExpression(ExpressionNode* expression);
void setClosingParenthesis(char closingParanthesis);
void setIfStatement(StatementNode* ifStatement);
void setElseIdentifier(IdentifierNode* elseIdentifier);
void setElseStatement(StatementNode* elseStatement);
private:
IdentifierNode* ifIdentifier;
char openingParanthesis;
ExpressionNode* expression;
char closingParanthesis;
StatementNode* ifStatement;
IdentifierNode* elseIdentifier;
StatementNode* elseStatement;
};
class WhileStatementNode: public StatementNode
{
public:
IdentifierNode* getWhileIdentifier();
char getOpeningParanthesis();
ExpressionNode* getExpression();
char getClosingParanthesis();
StatementNode* getStatement();
void setWhileIdentifier(IdentifierNode* whileIdentifier);
void setOpeningParanthesis(char openingParanthesis);
void setExpression(ExpressionNode* expression);
void setClosingParanthesis(char closingParanthesis);
void setStatement(StatementNode* Statement);
private:
IdentifierNode* whileIdentifier;
char openingParanthesis;
ExpressionNode* expression;
char closingParanthesis;
StatementNode* statement;
};
class StatementsNode
{
public:
/**
* @brief Getter method for the statement variable of a StatementsNode
* @return A reference to the statement
*/
StatementNode* getStatement();
/**
* @brief Getter method for the semicolon variable of a StatementsNode
* @return Returns a semicolon
*/
char* getSemicolon();
/**
* @brief Getter method for the statements variable of a StatementsNode
* @return A reference to the statements
*/
StatementsNode* getStatements();
/**
* @brief Setter method for the statement variable of a StatementsNode
* @param statementNode The note wished to be set
*/
void setStatement(StatementNode statementNode);
/**
* @brief Setter method for the semicolon variable of a StatementsNode
* @param semicolon This has to be a semicolon
*/
void setSemicolon(char semicolon);
void setStatements(StatementsNode furtherStatements);
private:
StatementNode* statement;
char semicolon;
StatementsNode* statements;
};
class RootNode
{
public:
/**
* @brief Getter method for the decl variable of a RootNode
* @return A reference to the declaration
*/
DeclNode* getDecl();
/**
* @brief Getter method for the statement variable of a StatementsNode
* @return A reference to the statement
*/
StatementNode* getStatement();
/**
* @brief Setter method for the decl variable of a RootNode
* @param The note wished to be set
*/
void setDecl(DeclNode declarationNode);
/**
* @brief Setter method for the statement variable of a RootNode
* @param statementNode The note wished to be set
*/
void setStatement(StatementNode statementNode);
private:
DeclNode* decl;
StatementNode* statement;
};
class ParseTree
{
public:
/**
* @brief Getter method for the root variable of a ParseTreeNode
* @return A reference to the root
*/
RootNode* getRoot();
/**
* @brief Setter method for the root variable of a ParseTreeNode
* @param rootNode The note wished to be set
*/
void setRoot(RootNode rootNode);
private:
RootNode* root;
};
#endif /* PARSETREE_INCLUDES_PARSETREE_H_ */
<file_sep>/SysProg/SysProgTemplate_SS_15/Scanner/src/Scanner.cpp
/*
* Scanner.cpp
*
* Created on: Sep 26, 2012
* Author: knad0001
*/
#include "../includes/Scanner.h"
#include "../../Automat/includes/State.h"
#include "../../Token/includes/Token.h"
#include <stdlib.h>
#include <iostream>
#include <string.h>
// Zum schreiben der Datei
#include <fstream>
// Zur Fehlerbehandlung
#include <error.h>
#include <errno.h>
#include <stdio.h>
using namespace std;
Scanner::Scanner(char* source, char* file) {
this -> file = file;
memory = new char[1024];
memset(memory,'0',1024);
this -> automat = new Automat(this);
this -> buffer = new Buffer(source);
this -> symboltable = new Symboltable();
output.open(file);
this -> stop = false;
}
Scanner::~Scanner() {
}
void Scanner::createToken(int line, int column, int tType, int length){
printMe(line,column,tType);
Token* token = NULL;
switch(tType){
case NUMBER: trim (this -> automat -> getLexemLength());
token = new IntType(1,1,stringToInt(memory));
//printMe(line,column,tType);
output << (stringToInt(memory)) << " " << endl;
memset(memory,'\0',1024);
break;
case IDENTIFIER: {
trim(this -> automat -> getLexemLength());
Item *key;
key = symboltable -> insertLexem(memory, length); //TODO Hier schlägt es momentan fehl
IdentifierType* token = new IdentifierType(1,1,key);
Item *name = symboltable -> lookUp(memory);
output << name -> key << " " << endl;
memset(memory,'\0',1024);
break;
}
case PLUS: token = new Token(1,1,2);
break;
case MINUS: token = new Token(1,1,3);
break;
case COLON: token = new Token(1,1,4);
break;
case ASTERISK: token = new Token(1,1,5);
break;
case LESSTHAN: token = new Token(1,1,6);
break;
case GREATERTHEN: token = new Token(1,1,7);
break;
case EQUALS: token = new Token(1,1,8);
break;
case COLONEQUALS: token = new Token(1,1,9);
break;
case SPECIALSIGN: token = new Token(1,1,10);
break;
case EXCLAMATIONMARK: token = new Token(1,1,11);
break;
case AMPERSAND: token = new Token(1,1,12);
break;
case SEMICOLON: token = new Token(1,1,13);
break;
case OPENINGPARENTHESIS: token = new Token(1,1,14);
break;
case CLOSINGPARENTHESIS: token = new Token(1,1,15);
break;
case OPENINGBRACE: token = new Token(1,1,16);
break;
case CLOSINGBRACE: token = new Token(1,1,17);
break;
case OPENINGBRACKET: token = new Token(1,1,18);
break;
case CLOSINGBRACKET: token = new Token(1,1,19);
break;
case BACKSLASH: token = new Token(1,1,20);
break;
case WRITE: token = new Token(1,1,21);
break;
case READ:
case IF:
case ELSE:
case INT:
//TODO Überhaupt relevant? Sind doch auch Identifier
break;
default: token = new ErrorType(1,1,22,memory[0]);
output << memory[0] << " " << endl;
fprintf(stderr," %c \n", memory[0]);
memset(memory,'0',1024);
break;
}
}
void Scanner::ungetChar(int value){
buffer -> ungetChar(value);
}
void Scanner::getChar(){
char cc = buffer -> getChar();
automat -> readChar(cc);
}
Buffer* Scanner::getBuffer(){
Buffer* b = this -> buffer;
return b;
}
bool Scanner::getStop(){
return this -> stop;
}
void Scanner::setStop(){
this -> stop = true;
output.close();
}
/** Gibt erzeugte Tokens auf der Konsole aus.*/
void Scanner::printMe(int line, int column, int tType){
char tab = 9;
switch (tType) {
case NUMBER:
output << "Token Integer " << tab << tab << "Reihe: " << line << " Spalte: " << column << " Wert: ";
break;
case IDENTIFIER:
output << "Token Identifier " << tab << "Reihe: " << line << " Spalte: " << column << " Lexem: ";
break;
case PLUS:
output << "Token Plus " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case MINUS:
output << "Token Minus " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case COLON:
output << "Token Colon " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case ASTERISK:
output << "Token Asterisk " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case LESSTHAN:
output << "Token < " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case GREATERTHEN:
output << "Token > " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case EQUALS:
output << "Token Equals " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case COLONEQUALS:
output << "Token Assign " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case SPECIALSIGN:
output << "Token <:> " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case EXCLAMATIONMARK:
output << "Token Exclamation mark " << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case AMPERSAND:
output << "Token Ampersand " << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case SEMICOLON:
output << "Token ; " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case OPENINGPARENTHESIS:
output << "Token ( " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case CLOSINGPARENTHESIS:
output << "Token ) " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case OPENINGBRACE:
output << "Token { " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case CLOSINGBRACE:
output << "Token } " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case OPENINGBRACKET:
output << "Token [ " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case CLOSINGBRACKET:
output << "Token ] " << tab << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case BACKSLASH:
output << "Token Backslash " << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
case 21:
output << "Token Slash " << tab << "Reihe: " << line << " Spalte: " << column << endl;
break;
default:
output << "Error Token " << tab << tab << "Reihe: " << line << " Spalte: " << column << " Lexem: ";
fprintf(stderr,"%s %d %s %d %s", "unknown Token Line: ", line, " Column: ", column, " Lexem: ");
break;
}
}
/**
* @param const char*
* Zu convertierender const char* (String)
* @return int
* Daraus resultierender int
*/
void Scanner::fillMemory(char toSave){
for(int i = 0; i < 1024; i++){
if(memory[i] == '\0' || memory[i] == '0'){ // Wird ein Zeichen gelesen, dass nicht \0 ist
memory[i] = toSave;
break;
}
}
}
long int Scanner::stringToInt(const char* str) {
errno = 0;
long int int1;
int1 = strtol(str, NULL, 0);
if (errno == ERANGE) {
const char* errorMessage = "stringToInt";
//printf("\n strtol() failed\n");
perror(errorMessage); // Prozess wird NICHT terminiert, wenn erster Parameter = 0
int1 = -1;
}
return int1;
}
void Scanner::trim(int length){
memory[length] = '\0';
}
int main(int argc, char* argv[]){ //char* source, char* target) {
Scanner* scanner;
if (argc < 3) return -1;
scanner = new Scanner(argv[1], argv[2]);//source,target);
// char *source = "/home/stud/lkt/fbi/klke1012/.nt/3.Semester/SysProg/Test2.txt";
// char *target = "/home/stud/lkt/fbi/klke1012/.nt/3.Semester/SysProg/out.txt";
// scanner = new Scanner(source,target);
int i = 0;
while(!( scanner -> getStop())){
if(i == 65536){
std::cout << "hi";
}
scanner -> getChar();
i++;
}
//scanner -> getSymboltable() -> memory -> printHistogram();
}
<file_sep>/SysProg/SysProgTemplate_SS_15/Parser/makefile
# Definition der Variablen
# enthaelt die Header Files
HEADERDIR = includes
# enthaelt die Source Files
SRCDIR = src
# enthaelt die Obj Files fuer das Gesamtprojekt
OBJDIR = objs
# enthaelt die Objectfiles und das ausfuehrbare File zum Testen des Teilprojekts
BINDIRTEST = debug
#
# Targets zum Bauen des Tests
#
# Linken der Object-files, abhaengig von ParserTarget und TestParserTarget
# flag:
# -g --> debug Informationen erzeugen
# -o --> name des output-files
makeTestParser: ParserTarget TestParserTarget
g++ -g $(OBJDIR)/Parser.o $(BINDIRTEST)/TestParser.o -o $(BINDIRTEST)/ParserTest
# compilieren der Source-files
# Parser.o ist abhaengig von Parser.cpp und Parser.h
# flag:
# -c --> nur compilieren
# -g --> debug Informationen erzeugen
# -Wall --> alle meldungen erzeugen (Warning all)
ParserTarget : $(SRCDIR)/Parser.cpp $(HEADERDIR)/Parser.h
g++ -g -c -Wall $(SRCDIR)/Parser.cpp -o $(OBJDIR)/Parser.o
#TestParser.o ist abhaengig von TestParser.cpp und Parser.h
TestParserTarget : $(SRCDIR)/TestParser.cpp $(HEADERDIR)/Parser.h
g++ -g -c -Wall $(SRCDIR)/TestParser.cpp -o $(BINDIRTEST)/TestParser.o
# loeschen aller files im verzeichnis $(OBJDIR) und $(BINDIRTEST) und neu compilieren
cleanParser:
rm -f $(OBJDIR)/*.o
rm -f $(BINDIRTEST)/*
$(MAKE) makeTestParser
# dieses Target wird vom makefile des Gesamtprojekts verwendet
# objs fuer GesamtProjekt loeschen und dann neu erzeugen
ParserOBJTarget:
rm -f $(OBJDIR)/*.o
$(MAKE) ParserTarget
<file_sep>/SysProg/SysProgTemplate_SS_15/Parser/includes/Parser.h
/*
* Parser.h
*
* Created on: 13.09.2015
* Author: kev
*/
#ifndef PARSER_H_
#define PARSER_H_
#include "../../Token/includes/Token.h"
#include "../../ParseTree/includes/ParseTree.h"
class Parser {
public:
void parse();
private:
Token* currentToken;
void error(Token* token);
void decls();
DeclsNode* createDeclsNode();
DeclNode* decl();
DeclNode* createDeclNode();
/**
* @brief Constructor method for a ParseTree
* @return A reference to the new ParseTree object
*/
ParseTree* createParseTree();
/**
* @brief Constructor method for a RootNode
* @return A reference to the new RootNode object
*/
RootNode* createRootNode();
IdentifierNode* createIdentifierNode();
ArrayNode* array();
ArrayNode* createArrayNode();
void statements();
/**
* @brief Constructor method for a StatementsNode
* @return A reference to the new StatementsNode object
*/
StatementsNode* createStatementsNode();
/*Es gibt kein createStatement, da Statement nur als Vorlage dient. */
StatementNode* statement();
IdentifierStatementNode* createIdentifierStatementNode();
WriteStatementNode* createWriteStatementNode();
ReadStatementNode* createReadStatementNode();
BracingStatementNode* createBracingStatementNode();
IfStatementNode* createIfStatementNode();
WhileStatementNode* createWhileStatementNode();
IndexNode* index();
IndexNode* createIndexNode();
ExpressionNode* exp();
ExpressionNode* createExpressionNode();
/* Gleicher Fall wie bei statement */
void exp2();
ParanthesedExp2* createParanthesedExp2Node();
IdentifierExp2* createIdentifierExp2Node();
IntegerExp2* createIntegerExp2();
OperatorExp2* createOperatorExp2();
void op_exp();
OperatorExpressionNode* createOperatorExpressionNode();
/** Erzeugt ein neues OperatorNode anhand des aktuellen Tokens.
* Die Variable operatorType wird abhängig vom aktuellen Token mit
* dem entsprechenden Operator beladen.
*/
OperatorNode* op();
OperatorNode* createOperatorNode();
ReadStatementNode* read();
WriteStatementNode* write();
IfStatementNode* customIf();
WhileStatementNode* customWhile();
/** Gibt das aktuelle Token zurück.*/
Token* getToken();
/** Fordert das nächste Token vom Scanner an.*/
Token* nextToken();
};
#endif /* PARSER_H_ */
<file_sep>/SysProg/SysProgTemplate_SS_15/makefile
#
# Baut das komplette Scanner Projekt
#
OBJDIR = objs
AUTOMATDIR = Automat
BUFFERDIR = Buffer
SYMBOLTABLEDIR = Symboltable
TOKENDIR = Token
SCANNERDIR = Scanner
STATEDIR = State
PARSERDIR = Parser
PARSETREEDIR = ParseTree
all: automatOBJs bufferOBJs symboltableOBJs tokenOBJs scanner parserOBJs parseTreeOBJs
@echo "target all"
# rm remove
# -f force, ohne nachfragen
clean:
rm -f $(AUTOMATDIR)/$(OBJDIR)/*.o
rm -f $(BUFFERDIR)/$(OBJDIR)/*.o
rm -f $(SYMBOLTABLEDIR)/$(OBJDIR)/*.o
rm -f $(TOKENDIR)/$(OBJDIR)/*.o
rm -f $(STATEDIR)/$(OBJDIR)/*.o
rm -f $(SCANNERDIR)/$(OBJDIR)/*.o
rm -f $(PARSERDIR)/$(OBJDIR)/*.o
rm -f $(SCANNERDIR)/debug/*
rm -f $(PARSETREEDIR)/$(OBJDIR)/*.o
automatOBJs:
$(MAKE) -C $(AUTOMATDIR) AutomatOBJTarget
bufferOBJs:
$(MAKE) -C $(BUFFERDIR) BufferOBJTarget
symboltableOBJs:
$(MAKE) -C $(SYMBOLTABLEDIR) SymboltableOBJTarget
tokenOBJs:
$(MAKE) -C $(TOKENDIR) TokenOBJTarget
scanner:
$(MAKE) -C $(SCANNERDIR) makeTestScanner
parserOBJs:
$(MAKE) -C $(PARSERDIR) ParserOBJTarget
parseTreeOBJs:
$(MAKE) -C $(PARSETREEDIR) ParseTreeTarget
#$(PARSETREEDIR)/parseTreeOBJ.o:
# $(MAKE) -C $(@D) $(@F)
#
#$(GENERATED_OBJS): %.o:
# $(MAKE) -C $(@D) $(@F)
<file_sep>/SysProg/SysProgTemplate_SS_15/Buffer/includes/Buffer.h
/*
* Buffer.h
*
* Created on: Apr 1, 2015
* Author: muma1041
*/
#ifndef Buffer_H_
#define Buffer_H_
class Buffer {
public:
Buffer(char *source);
virtual ~Buffer();
char getChar();
char ungetChar(int);
private:
char* getBuffer();
void setBuffer(char*);
void switchBuffer();
void openFile(const char*);
void readFile();
char* buffer1;
char* buffer2;
int fileDirectory;
int byteCount;
int maxSymbols;
int currentByteCounter;
bool currentBuffer;
bool ungetBufferSwitch;
bool endOfFile;
int x;
} ;
#endif /* Buffer_H_ */
<file_sep>/SysProg/SysProgTemplate_SS_15/Scanner/src/TestScanner.cpp
#include "../includes/Scanner.h"
#include <iostream>
using namespace std;
#if 0
int main(int argc, char **argv) {
Scanner* scanner;
scanner = new Scanner();
int i = 0;
while(i < 90){
scanner -> getChar();
//cout << cc << endl;
i++;
}
}
#endif
<file_sep>/SysProg/SysProgTemplate_SS_15/Buffer/src/Buffer.cpp
/*
* Buffer.cpp
*
* Created on: Apr 1, 2015
* Author: muma1041
*/
#include "../includes/Buffer.h"
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream> //Für Bufferwechsel Test
using namespace std; //Für Bufferwechsel Test
/**
* Gibt den momentan benutzen Buffer anhand des bools currentBuffer zurück.
* currentBuffer == false, bedeutet dass buffer1 aktiv ist,
* currentBuffer == true, bedeutet dass buffer2 aktiv ist.
*
* return: buffer1, wenn currentBuffer == false,
* buffer2, wenn currentBuffer == true
*/
char* Buffer::getBuffer() {
if (this -> currentBuffer == false) {
return this -> buffer1;
}
if (this -> currentBuffer == true) {
return this -> buffer2;
}
return 0;
}
/**
* Setzt den momentan benutzen Buffer anhand des bools currentBuffer.
* currentBuffer == false, bedeutet dass buffer1 mit param befüllt wird,
* currentBuffer == true, bedeutet dass buffer2 mit param befüllt wird.
*
* param: content
* Der übergebene Char-Pointer
*/
void Buffer::setBuffer(char* content) {
if (this -> currentBuffer == false) {
this -> buffer1 = content;
}
if (this -> currentBuffer == true) {
this -> buffer2 = content;
}
}
/**
* Invertiert currentBuffer um zu signalisieren,
* dass der andere Buffer verwendet werden soll.
*/
void Buffer::switchBuffer() {
this -> currentBuffer = !(this -> currentBuffer);
// std::cout << " _SWITCH_ " << endl; //Als Testausgabe ob der Buffer richtig gewechselt wird
}
/**
* Öffnet die Datei mit dem übergebenen const char* file
* und speichert den aus open() resultierenden int in fileDirectory ab.
*
* param:
* Der übergebene Speicherort der Datei auf dem System
*/
void Buffer::openFile(const char* file) {
this -> fileDirectory = open(file, O_RDONLY);// | O_DIRECT);
}
/**
* Liest für die Anzahl der maxSymbols Zeichen aus der Datei
* und speichert diese mit getBuffer() im momentanen Buffer ab.
* Der aus read() resultierende int Wert wird in byteCount abgespeichert.
*
* Wenn der byteCount nicht der maxSymbols entspricht, bedeutet das,
* dass das Ende der Datei erreicht wird und endOfFile wird auf true gesetzt.
*/
void Buffer::readFile() {
this -> byteCount = read(this -> fileDirectory, getBuffer(), this -> maxSymbols);
if (this -> byteCount != this -> maxSymbols) {
this -> endOfFile = true;
}
}
/*
* Gibt das nächste Symbol zurück.
*
* Führt die folgenden Aktionen aus:
* - holt sich den momentanen Buffer
* - wenn das aktuelle Symbol gleich maxSymbols ist,
* - wird der Buffer gewechselt und
*
* - wenn der Buffer NICHT durch ungetChar() gewechselt wurde
* - führe readFile() ganz normal aus
* - sonst ist der Buffer an dem Ende des zurückgegangenen Buffer angekommen
* - und ungetBufferSwitch wird false gesetzt.
* - holt sich den nächsten Buffer
* - setzt den momentan gezählten Symbol Zähler (currentByteCounter) zurück
*
* - wenn das Ende der Datei erlangt ist return 0
*
* - zählt den currentByteCounter hoch
* - erhöht die Position des Char Pointers
* - setzt den neuen Buffer
* - gibt den Pointer auf die eigentliche momentane Stelle zurück
*
* return 0, wenn das Ende der Datei erreicht ist
* return Char Pointer auf den momentan verlangte Char
*
*/
char Buffer::getChar() {
char* buffer = getBuffer();
if (this -> currentByteCounter == this -> maxSymbols) {
switchBuffer();
if (ungetBufferSwitch == false) {
readFile();
} else {
ungetBufferSwitch = false;
}
buffer = getBuffer();
this->currentByteCounter = 0;
}
if (this -> endOfFile == true && this -> currentByteCounter == this -> byteCount) {
return 0;
}
this -> currentByteCounter++;
*buffer++;
setBuffer(buffer);
return *--buffer;
}
/**
* Gibt das beliebige vorherige Symbol zurück.
*
* Führt die folgende Aktionen aus:
* - holt sich den momentanen Buffer
* - geht int a Schritte zurück und speichert die neue Position ab
* - wenn der Anfang des Buffers erreicht ist, wird der Buffer gewechselt
*
* return Char Pointer auf den momentan verlangte Char
*/
char Buffer::ungetChar(int a) {
char* buffer = getBuffer();
for (int i = 0; i < a + 1; i++) {
if (this -> currentByteCounter == 0) {
switchBuffer();
this -> currentByteCounter = 512;
buffer = getBuffer();
ungetBufferSwitch = true;
}
this -> currentByteCounter--;
*buffer--;
setBuffer(buffer);
}
this -> currentByteCounter++;
*buffer++;
setBuffer(buffer);
return *--buffer;
}
Buffer::Buffer(char *source) {
fileDirectory = 0;
byteCount = 0;
maxSymbols = 512;
currentByteCounter = 0;
currentBuffer = false;
ungetBufferSwitch = false;
endOfFile = false;
posix_memalign((void**)&buffer1, this -> maxSymbols, this -> maxSymbols + 1);
posix_memalign((void**)&buffer2, this -> maxSymbols, this -> maxSymbols + 1);
openFile(source);
readFile();
}
Buffer::~Buffer() {
}
<file_sep>/SysProg/SysProgTemplate_SS_15/Automat/src/Automat.cpp
/*
* Automat.cpp
*
*/
#include "../includes/State.h"
/** Konstruktor eines Automaten, der alle Zustände erzeugt und die Zähler
* für Reihe, Spalte und Lexemlänge initialisiert. */
Automat::Automat(AScanner *scanner) {
this -> scanner = scanner;
this -> start = new Start();
this -> digit = new Digit();
this -> identifier = new Identifier();
this -> comment = new Comment();
this -> endComment = new EndComment();
this -> lessThan = new LessThan();
this -> collon = new Collon();
this -> lessThanCollon = new LessThanCollon();
this -> currentState = start;
this -> row = 1;
this -> column = 0;
this -> lexemLength = 0;
}
Automat::~Automat() {
}
void Automat::stop(){
this -> scanner -> setStop();
}
void Automat::setState(State *next){
this -> currentState = next;
}
void Automat::readChar(char cc){
this -> currentState -> operation(cc, this);
}
void Automat::ungetChar(int value){
this -> scanner-> ungetChar(value);
}
void Automat::createToken(int line, int column, int tType){
this -> scanner -> createToken(line, column, tType, lexemLength);
}
void Automat::increaseRow(){
this -> row++;
}
void Automat::increaseColumn(int value){
this -> column = column + value;
}
void Automat::resetColumn(){
this -> column = 0;
}
void Automat::increaseLexemLength(){
this -> lexemLength++;
}
void Automat::resetLexemLength(){
this -> lexemLength = 0;
}
void Automat::saveCurrent(char cc){
this -> scanner -> fillMemory(cc);
}
State* Automat::getStart(){
return (this -> start);
}
State* Automat::getCurrentState(){
return this -> currentState;
}
State* Automat::getIdentifier(){
return (this -> identifier);
}
State* Automat::getDigit(){
return (this -> digit);
}
State* Automat::getComment(){
return (this -> comment);
}
State* Automat::getEndComment(){
return (this -> endComment);
}
State* Automat::getCollon(){
return this -> collon;
}
State* Automat::getLessThan(){
return this -> lessThan;
}
State* Automat::getLessThanCollon(){
return this -> lessThanCollon;
}
int Automat::getRow(){
return this -> row;
}
int Automat::getColumn(){
return this -> column;
}
int Automat::getLexemLength(){
return this -> lexemLength;
}
<file_sep>/SysProg/SysProgTemplate_SS_15/Symboltable/includes/LinkedList.h
#ifndef LinkedList_h
#define LinkedList_h
#include <iostream>
using namespace std;
//*****************************************************************
// List items are keys with pointers to the next item.
//*****************************************************************
struct Item
{
char * key;
Item * next;
int hashkey;
int lengthLexem;
};
//*****************************************************************
// Linked lists store a variable number of items.
//*****************************************************************
class LinkedList
{
private:
// Head is a reference to a list of data nodes.
Item * head;
// Length is the number of data nodes.
long length;
public:
// Constructs the empty linked list object.
// Creates the head node and sets length to zero.
LinkedList();
// Inserts an item at the end of the list.
void insertItem(Item * newItem);
// Removes an item from the list by item key.
// Returns true if the operation is successful.
bool removeItem(char * itemKey);
// Searches for an item by its key.
// Returns a reference to first match.
// Returns a NULL pointer if no match is found.
Item * getItem(char * itemKey, int length);
// Displays list contents to the console window.
void printList();
// Returns the length of the list.
long getLength();
// Compare Char Pointer
int compareCharPointer(char* a, char* b, int length);
// De-allocates list memory when the program terminates.
~LinkedList();
};
#endif
<file_sep>/SysProg/SysProgTemplate_SS_15/Automat/src/Zustaende/State.cpp
/*
* States.cpp
*
* Created on: Apr 1, 2015
* Author: klke1012
*/
#include "../../includes/State.h"
#include <iostream>
State::State() {
}
State::~State() {
}
/**
* Beschreibt den Startzustand des Automaten, sowie dessen Verhaltensweise.
*/
void Start::operation(char currentCharacter, Automat *boss){
// Behandelt den Fall, dass das gelesene Zeichen ein Buchstabe ist.
if((currentCharacter >= 65 && currentCharacter <= 90 )|| (currentCharacter >= 97 && currentCharacter <= 122)){
boss -> setState( boss -> getIdentifier() );
boss -> increaseColumn(1);
boss -> increaseLexemLength();
boss -> saveCurrent(currentCharacter);
// Behandelt den Fall, dass das gelesene Zeichen eine Zahl ist.
} else if(currentCharacter >= 48 && currentCharacter <= 57 ) {
boss -> setState ( boss -> getDigit() );
boss -> increaseColumn(1);
boss -> increaseLexemLength();
boss -> saveCurrent(currentCharacter);
} else {
switch(currentCharacter){
// ASCII 43
case '+': boss -> setState( boss -> getStart() );
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()), 2);
boss -> increaseColumn(1);
break;
// ASCII 45
case '-': boss -> setState( boss -> getStart() );
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),3);
boss -> increaseColumn(1);
break;
// ASCII 58
case ':': boss -> setState( boss -> getCollon());
boss -> increaseColumn(1);
boss -> increaseLexemLength();
break;
// ASCII 42
case '*': boss -> setState( boss -> getStart());
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),5);
break;
// ASCII 60
case '<': boss -> setState( boss -> getLessThan());
boss -> increaseColumn(1);
boss -> increaseLexemLength();
break;
// ASCII 62
case '>': boss -> setState( boss -> getStart() );
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),7);
boss -> increaseColumn(1);
break;
// ASCII 61
case '=': boss -> setState( boss -> getStart() );
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),8);
boss -> increaseColumn(1);
break;
// ASCII 33
case '!': boss -> setState( boss -> getStart() );
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),11);
boss -> increaseColumn(1);
break;
// ASCII 38
case '&': boss -> setState( boss -> getStart() );
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),12);
boss -> increaseColumn(1);
break;
// ASCII 59
case ';': boss -> setState( boss -> getStart() );
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),13);
boss -> increaseColumn(1);
break;
// ASCII 40
case '(': boss -> setState( boss -> getStart() );
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),14);
boss -> increaseColumn(1);
break;
// ASCII 41
case ')': boss -> setState( boss -> getStart() );
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),15);
boss -> increaseColumn(1);
break;
// ASCII 91
case '[': boss -> setState( boss -> getStart() );
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),18);
boss -> increaseColumn(1);
break;
// ASCII 93
case ']': boss -> setState( boss -> getStart() );
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),19);
boss -> increaseColumn(1);
break;
// ASCII 123
case '{': boss -> setState( boss -> getStart() );
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),16);
boss -> increaseColumn(1);
break;
// ASCII 125
case '}': boss -> setState( boss -> getStart() );
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),17);
boss -> increaseColumn(1);
break;
case '\n': boss -> setState( boss -> getStart());
boss -> increaseRow();
boss -> resetColumn();
boss -> resetLexemLength();
break;
case ' ': boss -> increaseColumn(1);
boss -> resetLexemLength();
break;
case '/': boss -> setState( boss -> getStart());
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),21);
boss -> increaseColumn(1);
break;
case '\0': boss -> stop();
break;
default:
boss -> setState( boss -> getStart());
boss -> saveCurrent(currentCharacter);
boss -> createToken(boss -> getRow(), boss -> getColumn(),22);
boss -> increaseColumn(1);
break;
}
}
}
void Digit::operation(char currentCharacter, Automat *boss){
if(currentCharacter >= 48 && currentCharacter <= 57){
boss -> increaseColumn(1);
boss -> increaseLexemLength();
boss -> saveCurrent(currentCharacter);
} else{
/**Setzt den nächsten Zustand auf den Startzustand.
* Signalisiert, dass das letzte gelesene Zeichen, beim nächsten Aufruf, erneut gelesen werden muss.
* Signalisiert, dass ein Token erzeugt werden soll.*/
boss -> setState( boss -> getStart() );
boss -> ungetChar(1);
int row = boss -> getRow();
int column = boss -> getColumn()- boss -> getLexemLength();
boss -> createToken(row, column, 0);
//boss -> createToken(boss -> getRow(), (boss -> getColumn()- boss -> getLexemLength()),0);
boss -> resetLexemLength();
}
}
/**
* Behandelt den Zustand der Bezeichner. Hier dürfen nur Buchstaben und Ziffern gelesen werden.
*/
void Identifier::operation(char currentCharacter, Automat *boss){
if((currentCharacter >= 65 && currentCharacter <= 90 ) || (currentCharacter >= 97 && currentCharacter <= 122)){
boss -> increaseColumn(1);
boss -> increaseLexemLength();
boss -> saveCurrent(currentCharacter);
}
else if (currentCharacter >= 48 && currentCharacter <= 57) {
boss -> increaseColumn(1);
boss -> increaseLexemLength();
boss -> saveCurrent(currentCharacter);
} else {
boss -> setState(boss -> getStart());
boss -> ungetChar(1);
boss -> createToken(boss -> getRow(), ((boss -> getColumn())- ( boss -> getLexemLength())) ,1);
boss -> resetLexemLength();
}
}
/** Behandelt den Fall, dass ein : eingelesen wurde.
* Dies benötigt besondere Aufmerksamkeit, da nach einem : sowohl ein * folgen könnte,
* was bedeuten würde, dass ein Kommentar beginnt, oder ein =, was als Zuweisung erkannt
* werden muss.
* */
void Collon::operation(char currentCharacter, Automat *boss){
if(currentCharacter == '='){
boss -> setState( boss -> getStart() );
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),9);
boss -> increaseColumn(1);
boss -> resetLexemLength();
} else if(currentCharacter == '*'){
boss -> setState( boss -> getComment());
boss -> increaseColumn(1);
boss -> increaseLexemLength();
} else {
boss -> setState(boss -> getStart());
boss -> ungetChar(1);
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),4);
//boss -> increaseColumn(1);
boss -> resetLexemLength();
}
}
void Comment::operation(char currentCharacter, Automat *boss){
if(currentCharacter == '*'){
boss -> setState(boss -> getEndComment());
boss -> increaseColumn(1);
boss -> increaseLexemLength();
} else {
boss -> increaseColumn(1);
boss -> increaseLexemLength();
}
}
/** Behandelt den Fall, dass man aus dem Zustand eines Kommentares ein : liest.
* Hierbei wird geprüft, ob das nachfolgende Zeichen ein * ist, um das Ende eines Kommentares zu erfassen.
* Ist das darauffolgende Zeichen wieder ein * wird der Zustand gehalten.
*/
void EndComment::operation(char currentCharacter, Automat *boss){
if(currentCharacter == ':'){
boss -> setState( boss -> getStart());
boss -> increaseColumn(1);
} else if(currentCharacter == '*'){
// Folgt ein *, wird der Zustand gehalten.
boss -> increaseColumn(1);
boss -> increaseLexemLength();
} else {
boss -> setState( boss -> getComment());
boss -> increaseColumn(1);
boss -> resetLexemLength();
//Folgt auf ein * ein :, werden folgende Zeichen nicht mehr als Kommentar bewertet.
}
}
void LessThan::operation(char currentCharacter, Automat *boss){
if(currentCharacter == ':'){
boss -> setState( boss -> getLessThanCollon());
boss -> increaseColumn(1);
boss -> increaseLexemLength();
} else {
boss -> setState( boss -> getStart());
boss -> ungetChar(1);
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),6);
boss -> resetLexemLength();
}
}
void LessThanCollon::operation(char currentCharacter, Automat *boss){
if(currentCharacter == '>'){
boss -> setState( boss -> getStart());
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),10);
boss -> increaseColumn(1);
boss -> resetLexemLength();
} else {
boss -> setState( boss -> getStart());
boss -> ungetChar(2);
boss -> createToken(boss -> getRow(), (boss -> getColumn())- ( boss -> getLexemLength()),6);
boss -> resetLexemLength();
}
}
<file_sep>/SysProg/SysProgTemplate_SS_15/Symboltable/src/Stringtable.cpp
/*
* Stringtable.cpp
*
* Created on: Nov 03, 2015
* Author: muma1041
*/
#include "../includes/Stringtable.h"
#include <string.h>
#include <iostream>
#include <stdio.h>
Stringtable::Stringtable() {
this -> lengthOld = 0;
this -> lenghtNew = 0;
this -> occupiedSpace = 0;
charArray = new char[0];
}
char* Stringtable::insert(char* lexem, int length) {
if (length + 1 > (this -> lengthOld - this -> occupiedSpace)) {
//Neues Array anlegen mit: ([Länge altes Array] + [Länge Lexem]) * 2
this -> lenghtNew = ((this -> lengthOld + length) * 2);
int x = this -> lenghtNew;
char *newCharArray = new char[this->lenghtNew];
memcpy(newCharArray, charArray, this -> occupiedSpace);
newCharArray[this -> occupiedSpace] = length;
this -> occupiedSpace++;
for (int i = occupiedSpace; i < occupiedSpace + length; ++i) {
newCharArray[i] = lexem[i - occupiedSpace];
}
//Lösche altes Array
delete [] charArray;
//Tausche Pointer und neue Länge
charArray = newCharArray;
this -> occupiedSpace += length;
this -> lengthOld = this -> lenghtNew;
} else {
charArray[this -> occupiedSpace] = length;
this -> occupiedSpace++;
for (int i = this -> occupiedSpace; i < this -> occupiedSpace + length; ++i) {
charArray[i] = lexem[i - this -> occupiedSpace];
}
this -> occupiedSpace += length;
}
//Pointer auf Anfang neues Wort übergeben
char *pointer = charArray;
return &pointer[this -> occupiedSpace - length];
}
/*
char* Stringtable::lookUpStringtable(char* lexem, int length) {
bool searching = true;
int index1 = 0;
int index2 = index1;
int compare;
while (searching && index1 < this -> occupiedSpace) {
compare = 0;
while (charArray[index1] != length && index1 < this -> occupiedSpace) {
index1 += (charArray[index1] + 1);
}
index2 = index1;
for (int i = 0; i < charArray[index1]; ++i) {
if (charArray[index2 + 1] == lexem[i]) {
compare++;
}
index2++;
}
if (compare == length) {
return &charArray[index1 + 1];
}
index1 += (charArray[index1] + 1);
}
return 0;
}
*/
<file_sep>/SysProg/SysProgTemplate_SS_15/Token/src/Token.cpp
/*
* Token.cpp
*
* Created on: Apr 15, 2015
* Author: klke1012
*/
#include "../includes/Token.h"
#include <iostream>
Token::Token(int row, int column, int tType){
this -> row = row;
this -> column = column;
this -> tType = tType;
}
Token::~Token() {
// TODO Auto-generated destructor stub
}
IntType::IntType(int row, int column, int value) : Token(row, column, tType){
this -> value = value;
this -> tType = 0;
}
ErrorType::ErrorType(int row, int column, int tType, char charracter) : Token(row, column, tType){
this -> tType = tType;
this -> character = charracter;
}
IdentifierType::IdentifierType(int row, int column, Item *key) : Token(row,column, tType){
this -> tType = 1;
this -> key = key;
}
<file_sep>/SysProg/SysProgTemplate_SS_15/Automat/includes/State.h
/*
* States.h
*
* Created on: Apr 1, 2015
* Author: klke1012
*/
#ifndef STATE_H_
#define STATE_H_
class Automat;
class AScanner{
public:
virtual void ungetChar(int value) = 0;
virtual void createToken(int line, int column, int tType, int length) = 0;
virtual void fillMemory(char toSave) = 0;
virtual void setStop() = 0;
};
class State {
public:
State();
virtual ~State();
virtual void operation(char currentCharacter, Automat *boss) = 0;
};
/** Behandelt den Startzustand.*/
class Start:public State{
public:
void operation(char currentCharacter, Automat *boss);
};
/** Behandelt den Zustand, wenn eine Zahl eingelesen wird.*/
class Digit:public State{
public:
void operation(char currentCharacter, Automat *boss);
};
/** Behandelt den Zustand, wenn ein Bezeichner eingelesen wird.*/
class Identifier:public State{
public:
void operation(char currentCharacter, Automat *boss);
};
/** Behandelt den Zustand, wenn ein Operator eingelesen wird.*/
class Operator:public State{
public:
void operation(char currentCharacter, Automat *boss);
};
/** Behandelt den Zustand, wenn ein Kommentar eingelesen wird.*/
class Comment:public State{
public:
void operation(char currentCharacter, Automat *boss);
};
/** Behandelt den Zustand, wenn ein Doppelpunkt eingelesen wird.*/
class Collon:public State{
public:
void operation(char currentCharacter, Automat *boss);
};
/** Behandelt den Zustand, wenn ein Kleiner-als-Doppelpunkt eingelesen wird.*/
class LessThanCollon:public State{
public:
void operation(char currentCharacter, Automat *boss);
};
/** Behandelt den Zustand, wenn ein mögliches Kommentarende eingelesen wird.*/
class EndComment:public State{
public:
void operation(char currentCharacter, Automat *boss);
};
/** Behandelt den Zustand, wenn ein Kleiner-als-Zeichen eingelesen wird.*/
class LessThan:public State{
public:
void operation(char currentCharacter, Automat* boss);
};
class Automat {
public:
Automat(AScanner *scanner);
virtual ~Automat();
// Liest das aktuelle Zeichen ein und führt die im Zustand deklarierten Aktionen aus.
void readChar(char cc);
// Setzt den aktuellen Zustand auf den übergebenen Zustand.
void setState(State *next);
// Signalisiert dem Scanner, dass die übergeben Anzahl an Zeichen erneut gelesen werden sollen.
void ungetChar(int value);
// Signalisiert dem Scanner, dass ein Token erzeugt werden soll.
void createToken(int line, int column, int tType);
State *getCurrentState();
State *getStart();
State *getDigit();
State *getIdentifier();
State *getCollon();
// Erhöht den Reihenzähler.
void increaseRow();
// Erhöht den Spaltenzähler.
void increaseColumn(int value);
// Setzt den Spaltenzähler zurück.
void resetColumn();
// Erhöht den Zähler der Lexemlänge.
void increaseLexemLength();
// Setzt den Zähler der Lexemlänge zurück.
void resetLexemLength();
// Signalisiert dem Scanner, dass das aktuelle Zeichen gespeichert werden soll.
void saveCurrent(char cc);
// Signalisiert dem Scanner, dass das Ende der Datei erreicht wurde.
void stop();
State *getComment();
State *getEndComment();
State *getLessThan();
State *getLessThanCollon();
int getRow();
int getColumn();
int getLexemLength();
private:
AScanner* scanner;
State* currentState;
int row;
int column;
int lexemLength;
Start* start;
Digit* digit;
Identifier* identifier;
Comment* comment;
EndComment* endComment;
LessThan* lessThan;
Collon* collon;
LessThanCollon* lessThanCollon;
};
#endif /* STATE_H_ */
<file_sep>/SysProg/SysProgTemplate_SS_15/Token/includes/Token.h
/*
* Token.h
*
* Created on: Apr 15, 2015
* Author: <NAME>
* @version: 1.0
*/
#ifndef TOKEN_H_
#define TOKEN_H_
#include "../../Symboltable/includes/LinkedList.h"
class Token {
public:
Token(int row, int column, int tType);
virtual ~Token();
int getRow();
int getColumn();
int getTtype();
protected:
int tType;
private:
int row;
int column;
};
class IntType: public Token {
public:
IntType(int row, int column, int value);
int getValue();
private:
int value;
int tType;
};
class IdentifierType: public Token {
public:
IdentifierType(int row, int column, Item* key);
void print();
private:
Item* key;
int tType;
};
class ErrorType: public Token {
public:
ErrorType(int row, int column, int tType, char character);
char getCharacter();
private:
char character;
};
#endif /* TOKEN_H_ */
<file_sep>/SysProg/SysProgTemplate_SS_15/Token/src/TestToken.cpp
#include "../includes/Token.h"
int main(int argc, char **argv) {
Token* token;
token = new Token(1,1,1);
}
<file_sep>/SysProg/SysProgTemplate_SS_15/Parser/src/TestParser.cpp
#include "../includes/Parser.h"
int main (int argc, char* argv[])
{
while(1)
{
}
}
<file_sep>/SysProg/SysProgTemplate_SS_15/Scanner/includes/Scanner.h
/*
* Scanner.h
*
* Created on: 07.04.2015
* Author: <NAME>
* @version: 1.1
*/
#ifndef SCANNER_H_
#define SCANNER_H_
#include "../../Automat/includes/State.h"
#include "../../Buffer/includes/Buffer.h"
#include "../../Symboltable/includes/Symboltable.h"
#include <fstream>
enum tTypes
{
NUMBER = 0,
IDENTIFIER = 1,
PLUS = 2,
MINUS = 3,
COLON = 4,
ASTERISK = 5,
LESSTHAN = 6,
GREATERTHEN = 7,
EQUALS = 8,
COLONEQUALS = 9,
SPECIALSIGN = 10,
EXCLAMATIONMARK = 11,
AMPERSAND = 12,
SEMICOLON = 13,
OPENINGPARENTHESIS = 14,
CLOSINGPARENTHESIS = 15,
OPENINGBRACE = 16,
CLOSINGBRACE = 17,
OPENINGBRACKET = 18,
CLOSINGBRACKET = 19,
BACKSLASH = 20,
WRITE = 21,
READ = 22,
WHILE = 23,
IF = 24,
ELSE = 25,
INT = 26,
};
class Scanner:public AScanner {
public:
Scanner();
Scanner(char* source, char* file);
virtual ~Scanner();
bool getStop();
void setStop();
// Signalisiert dem Buffer, dass die übergebene Anzahl an Zeichen erneut gelesen werden müssen.
void ungetChar(int value);
void createToken(int line, int column, int tType);
void getChar();
// Erzeugt ein Token mit übergebener Position, Typ und Länge.
void createToken(int line, int column, int tType, int length);
// Schreibt das übergebene Zeichen in den Zwischenspeicher des Scanners.
void fillMemory(char toSave);
Buffer* getBuffer();
Symboltable* getSymboltable();
private:
Buffer* buffer;
Automat* automat;
Symboltable* symboltable;
char* memory;
const char* file;
ofstream output;
bool stop;
/**
* Konvertiert den übergebenen const char* in ein int,
* sofern der const char* innerhalb des Wertebereiches von long int liegt.
*/
long int stringToInt(const char* str);
// Schrumpft den Zwischenspeicher des Scanners auf die benötigte Größe.
void trim(int length);
// Gibt das erzeugte Token auf der Eclipse-Console aus.
void printMe(int line, int column,int tType);
};
#endif /* SCANNER_H_ */
<file_sep>/SysProg/SysProgTemplate_SS_15/Symboltable/includes/Stringtable.h
/*
* Stringtable.h
*
* Created on: Nov 03, 2015
* Author: muma1041
*/
#ifndef Stringtable_h
#define Stringtable_h
// #include "Hashtable.h"
class Stringtable;
class Stringtable {
private:
int occupiedSpace;
int lengthOld;
int lenghtNew;
char *charArray;
public:
Stringtable();
char* insert(char* lexem, int length);
char* lookUpStringtable(char* lexem, int length);
};
#endif /* STRTable_H_ */
<file_sep>/SysProg/SysProgTemplate_SS_15/Symboltable/src/Hashtable.cpp
#include "../includes/Hashtable.h"
#include <iostream>
#include <string.h>
using namespace std;
// Constructs the empty Hash Table object.
// Array length is set to 120 by default.
HashTable::HashTable(int tableLength)
{
if (tableLength <= 0) tableLength = 120;
array = new LinkedList[tableLength];
length = tableLength;
}
// Returns an array location for a given item key.
int HashTable::hash(char * itemKey)
{
int value = 0;
int lenghtOfChar = 0;
char *str;
for (str = itemKey; *str != '\0'; str++, lenghtOfChar++) {
value += itemKey[lenghtOfChar];
}
int a = (value * lenghtOfChar) % length;
return a;
}
// Adds an item to the Hash Table.
void HashTable::insertItem(Item * newItem)
{
newItem->hashkey = hash(newItem->key);
array[newItem->hashkey].insertItem(newItem);
}
// Deletes an Item by key from the Hash Table.
// Returns true if the operation is successful.
bool HashTable::removeItem(char * itemKey)
{
int index = hash(itemKey);
return array[index].removeItem(itemKey);
}
// Returns an item from the Hash Table by key.
// If the item isn't found, a null pointer is returned.
Item * HashTable::getItemByKey(char * itemKey, int length)
{
int index = hash(itemKey);
return array[index].getItem(itemKey, length);
}
// Display the contents of the Hash Table to console window.
void HashTable::printTable()
{
cout << "nnHash Table:n";
for (int i = 0; i < length; i++)
{
cout << "Bucket " << i + 1 << ": ";
array[i].printList();
}
}
// Prints a histogram illustrating the Item distribution.
void HashTable::printHistogram()
{
cout << "nnHash Table Contains ";
cout << getNumberOfItems() << " Items total.n";
for (int i = 0; i < length; i++)
{
cout << i + 1 << ":t";
for (int j = 0; j < array[i].getLength(); j++)
cout << " X";
cout << "n";
}
}
// Returns the number of locations in the Hash Table.
int HashTable::getLength()
{
return length;
}
// Returns the number of Items in the Hash Table.
int HashTable::getNumberOfItems()
{
int itemCount = 0;
for (int i = 0; i < length; i++)
{
itemCount += array[i].getLength();
}
return itemCount;
}
// De-allocates all memory used for the Hash Table.
HashTable::~HashTable()
{
delete[] array;
}
/*
int main() {
HashTable *test = new HashTable;
LinkedList a;
char b[5] = "Kack";
Item * c = new Item;
c->key = b;
c->next = NULL;
a.insertItem(c);
a.printList();
Item * F = new Item{ "Fedora", NULL };
Item * G = new Item{ "Goosebumps", NULL };
Item * H = new Item{ "House", NULL };
Item * I = new Item{ "Insects", NULL };
Item * J = new Item{ "Jam", NULL };
Item * K = new Item{ "Kite", NULL };
a.insertItem(F);
a.insertItem(G);
a.insertItem(I);
a.insertItem(H);
a.insertItem(J);
a.insertItem(K);
a.printList();
test->insertItem(c);
test->insertItem(F);
test->insertItem(G);
test->insertItem(I);
test->insertItem(H);
test->insertItem(J);
test->insertItem(K);
test->getLength();
test->printHistogram();
test->printTable();
return 0;
}*/
<file_sep>/SysProg/SysProgTemplate_SS_15/Symboltable/src/LinkedList.cpp
#include "../includes/LinkedList.h"
#include <string.h>
// Constructs the empty linked list object.
// Creates the head node and sets length to zero.
LinkedList::LinkedList()
{
head = new Item;
head->next = NULL;
length = 0;
}
// Inserts an item at the end of the list.
void LinkedList::insertItem(Item * newItem)
{
if (!head -> next)
{
head -> next = newItem;
length++;
return;
}
Item * p = head;
Item * q = head;
while (q)
{
p = q;
q = p->next;
}
p->next = newItem;
newItem->next = NULL;
length++;
}
// Removes an item from the list by item key.
// Returns true if the operation is successful.
bool LinkedList::removeItem(char * itemKey)
{
//if (!head -> head) return false;
Item * p = head;
Item * q = head;
while (q)
{
if (q->key == itemKey)
{
p->next = q->next;
delete q;
length--;
return true;
}
p = q;
q = p->next;
}
return false;
}
// Searches for an item by its key.
// Returns a reference to first match.
// Returns a NULL pointer if no match is found.
Item * LinkedList::getItem(char * itemKey, int length)
{
Item * p = head;
Item * q = head;
int compare = 0;
while (q) {
p = q;
if (p -> lengthLexem == length) {
if (compareCharPointer(p -> key, itemKey, length) == 0) {
return p;
}
}
/*
for (int i = 0; i < p -> lengthLexem; ++i) {
if (p -> key[i] == itemKey[i]) {
compare++;
}
}
if (compare == p -> lengthLexem) {
return p;
}
*/
/*
if (strcmp(p->key, itemKey))
return p;
*/
q = p->next;
}
return NULL;
}
// Displays list contents to the console window.
void LinkedList::printList()
{
if (length == 0)
{
cout << "n{ }n";
return;
}
Item * p = head;
Item * q = head;
cout << "n{ ";
while (q)
{
p = q;
if (p != head)
{
cout << p->key;
if (p->next) cout << ", ";
else cout << " ";
}
q = p->next;
}
cout << "}n";
}
// Returns the length of the list.
long LinkedList::getLength()
{
return length;
}
int LinkedList::compareCharPointer(char* a, char* b, int length) {
int c = 0;
while (a[c] == b[c]) {
c++;
if (c == length) {
//if (a[c] == '\0' || b[c] == '\0')
return 0;
}
}
return -1;
}
// De-allocates list memory when the program terminates.
LinkedList::~LinkedList()
{
Item * p = head;
Item * q = head;
while (q)
{
p = q;
q = p->next;
if (q) delete p;
}
}
/* int main() {
LinkedList a;
char b[5] = "Kack";
Item * c = new Item;
c->key = b;
c->next = NULL;
a.insertItem(c);
a.printList();
return 0;
}*/
| d332b557843715a8c96a1283c0a77b2fe6578051 | [
"Makefile",
"C++"
] | 27 | C++ | MMM95/SysProg | eae38d7afd24e2d5fa4b37cb67563cf198be6d36 | d44545c8f888c1b0c2c2fd85a4e5e3781dfaf9c2 |
refs/heads/master | <file_sep># Project-1
title: Rock Climbing
Description: The user may find rock climbing areas near their location.
This includes outdoor rock climbing spots and in the future, indoor rock climbing gyms.
User Story:
- AS a rock climber I want to find outdoor rock climbing spots
near my location so I can rock climb.
API'S:
Rock Climbing API- https://www.mountainproject.com/data
req'd arguments
API key: <KEY>
user ID: 200818976
email: <EMAIL>
Google Maps API-
req'd arguments (potentially)
API key: <KEY>
email (if necessary): <EMAIL>
Link the our website: https://josephtorres1.github.io/Project-1/
<file_sep>$(document).ready(function () {
var userLat;
var userLong;
var markers = [];
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 39.833, lng: -98.583 },
zoom: 12,
});
infoWindow = new google.maps.InfoWindow();
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
userLat = position.coords.latitude;
userLong = position.coords.longitude;
console.log(userLat, userLong);
map.setCenter(pos);
var marker = new google.maps.Marker({
position: pos,
map: map,
title: "User Position",
icon: {
url: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png",
},
});
},
function () {
handleLocationError(true, infoWindow, map.getCenter());
}
);
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(
browserHasGeolocation
? "Error: The Geolocation service failed."
: "Error: Your browser doesn't support geolocation."
);
infoWindow.open(map);
}
function buildQueryURL() {
// this builds the queryURL for the mountain API
var maxDist = $("#maxDist").val();
var minDiff = $("#minDiff").val();
var maxDiff = $("#maxDiff").val();
var newqueryURL =
"https://www.mountainproject.com/data/get-routes-for-lat-lon?lat=" +
userLat +
"&lon=" +
userLong +
"&maxDistance=" +
maxDist +
"&minDiff=" +
minDiff +
"&maxDiff=" +
maxDiff +
"&key=<KEY>";
return newqueryURL;
}
// THIS IS FOR THE FORM WITH VARIABLE DISTANCE & ROUTE NUM
// $("#run-search").on("click", function(event) {
// event.preventDefault();
initMap();
$("#dumbbutton").on("click", function () {
var queryURL = buildQueryURL();
deleteMarkers();
$("#route-display").empty();
$.ajax({
url: queryURL,
method: "GET",
}).then((response) => {
console.log(response.routes);
var routes = response.routes;
var routenum = 0;
routes.forEach((routeinfo) => {
// lead with the routenum
console.log("Route Number:" + routenum);
routenum++;
var currLat = routeinfo.latitude;
var currLon = routeinfo.longitude;
newrouteMarker(currLat, currLon, routeinfo.name);
//
// then, each route is iterated across to log the contents of each pair
// a line is gonna be created to contain it, which will then be appended to the div
//
createroutecard(
routeinfo.name,
routeinfo.type,
routeinfo.rating,
currLat,
currLon,
routeinfo.url
);
jQuery.each(routeinfo, function (key, value) {
console.log(key + ": " + value);
});
});
});
});
function newrouteMarker(latitude, longitude, name) {
var marker = new google.maps.Marker({
position: { lat: latitude, lng: longitude },
map: map,
title: name,
icon: {
url: "http://maps.google.com/mapfiles/ms/icons/orange-dot.png",
},
});
markers.push(marker);
}
function createroutecard(name, type, rating, lat, lon, url) {
var clickability = $("<a>").attr({ href: url, target: "_blank" });
var newcard = $("<div>").addClass("route-card");
var cardcontent = $("<div>").addClass("route-card-content card-section");
var cardname = $("<p>").addClass("route-card-name");
var cardtype = $("<p>").addClass("route-card-type");
var cardrating = $("<p>").addClass("route-card-rating");
var cardloc = $("<p>").addClass("route-card-loc");
cardname.text(name);
cardtype.text(type);
cardrating.text("Difficulty: " + rating);
cardloc.text("Lat: " + lat + " Lon: " + lon);
cardcontent.append([cardname, cardtype, cardrating, cardloc]);
newcard.append(cardcontent);
clickability.append(newcard);
$("#route-display").append(clickability);
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function deleteMarkers() {
setMapOnAll(null);
markers = [];
}
});
| 1f88ab2b65eceb1cbb274c7d07894b7aee476db1 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Josephtorres1/Project-1 | e6a79ca9d23c24f8d08bd3d50d5ef4cf3410e6de | 9df94ecd82951ff5c672caad6367ab1ddde94521 |
refs/heads/master | <repo_name>comprog-cde-uinsa-2020/E1-WEEK3-MENGHITUNGKELIPATAN3<file_sep>/README.md
# E1-WEEK3-MENGHITUNGKELIPATAN3<file_sep>/prokom week 4.js
<!DOCTYPE html>
<html>
<head>
<title>prokom week 4 </title>
</head>
<body>
<h1>MENENTUKAN BANYAKNYA KELIPATAN 3 PADA BILANGAN 3-180</h1>
<h2>kelompok 2 kelas E</h2>
<button onclick="perulangan()">KLIK HERE!!!</button>
<!-- id hasil -->
<div id="hasil"></div>
<script>
function perulangan() {
var text = "";
var x;
for (x = 1; x <= 60; x++)
{
i=3*x;
text += "Bilangan" + i + "<br>";
}
document.getElementById("hasil").innerHTML = text;
}
</script>
</body>
</html> | dd05e87a300c4ec78a950903436524a8314da223 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | comprog-cde-uinsa-2020/E1-WEEK3-MENGHITUNGKELIPATAN3 | a346bb2e5707185ba2798286ea055b5e882f40f4 | 30f56979a29adc3b286eab96cc63a8a8d192c913 |
refs/heads/master | <file_sep><?php
/**
* @package SyDES
*
* @copyright 2011-2015, ArtyGrand <<EMAIL>>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
class VideoController extends DataTable{
public $name = 'video';
public $structure = array(
'title' => array(
'label' => 'video_title',
'type' => 'string',
'def' => 'TEXT NOT NULL',
'visible' => true,
'attr' => 'class="form-control"'
),
'url' => array(
'label' => 'video_url',
'type' => 'string',
'def' => 'TEXT NOT NULL',
'visible' => false,
'attr' => 'class="form-control" required'
),
'position' => array(
'label' => 'position',
'type' => 'string',
'def' => 'TEXT NOT NULL',
'visible' => true,
'attr' => 'class="form-control"'
),
);
}<file_sep># Module Videos for [SyDES](https://github.com/artygrand/SyDES)
Based on DataTable.
## How to use
* Insert a title and link to videos from YouTube or Vimeo.
* Insert token {iblock:video} into page.
* Look on automatically created thumbnails.
* Click to play videos in lightbox.
**may require additional configuration for fancybox**
$(".various").fancybox({
maxWidth: 800,
maxHeight: 600,
fitToView: false,
width: '70%',
height: '70%',
autoSize: false,
closeClick: false,
openEffect: 'none',
closeEffect: 'none'
});
## Installation
1. Download archive
2. Upload files
3. Install it!
<file_sep><div class="row">
<?php foreach ($result as $item){ ?>
<div class="col-sm-3">
<a href="<?=$item['src'];?>" title="<?=$item['title'];?>" class="various fancybox.iframe">
<img src="<?=$item['img'];?>" style="width:<?=$args['width'];?>px;height:<?=$args['height'];?>px;">
</a>
<div class="title"><?=$item['title'];?></div>
</div>
<?php } ?>
</div><file_sep><?php return array (
'module_video' => 'Видео',
'video_title' => 'Заголовок видео',
'video_url' => 'Ссылка на видео',
'position' => 'Позиция',
'active' => 'Активно?',
);<file_sep><?php return array (
'module_video' => 'Videos',
'video_title' => 'Video title',
'video_url' => 'Video url',
'position' => 'Position',
'active' => 'Active?',
);<file_sep><?php
$defaults = array(
'width' => 220,
'height' => 140,
);
$args = array_merge($defaults, $args);
$stmt = $this->db->query("SELECT * FROM video WHERE status = 1 ORDER BY 'position'");
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = array();
foreach ($data as $item){
// if vimeo
if (strpos($item['url'], 'vimeo') !== false){
preg_match('/vimeo.com\/([0-9]*?)/isU', $item['url'], $parts);
$video = unserialize(file_get_contents('http://vimeo.com/api/v2/video/' . $parts[1] . '.php'));
$result[] = array(
'title' => !empty($item['title']) ? $item['title'] : $video[0]['title'],
'src' => 'https://player.vimeo.com/video/' . $parts[1] . '?autoplay=1',
'img' => $video[0]['thumbnail_medium']
);
}
// if youtube
elseif (strpos($item['url'], 'youtu') !== false){
if (strpos($item['url'], 'youtube') !== false){
$regex = '/v=([a-zA-Z0-9_-]{11}?)/isU';
} elseif (strpos($item['url'], 'youtu.be') !== false){
$regex = '/youtu\.be\/([a-zA-Z0-9_-]{11}?)/isU';
}
preg_match($regex, $item['url'], $parts);
$result[] = array(
'title' => $item['title'],
'src' => 'https://www.youtube.com/embed/' . $parts[1] . '?wmode=transparent&rel=0&fs=1&autoplay=1',
'img' => 'http://i2.ytimg.com/vi/' . $parts[1] . '/hqdefault.jpg'
);
}
} | 613867048ed2c9867b19814184a8be67e09415ae | [
"Markdown",
"PHP"
] | 6 | PHP | artygrand/sydes-module-video | ee4f43ee281f6701aab1148acad5d032425036d4 | 4209f7b18f0bb41f87563dfbbad4834da3c38d2b |
refs/heads/master | <repo_name>RavirajWalke/C<file_sep>/qsort.c
#include<stdio.h>
#include<stdlib.h>
int comp(const void *p,const void *q)
{
const int *l=(const int*)p;
const int *r=(const int*)q;
return(*l-*r);
}
int main(int argc, char *argv[])
{
int a[argc-1];
for (int i = 1; i < argc; i++)
{
/* code */
a[i-1]=atoi(argv[i]);
//a[i-1]=argv[i];
printf("%d ",a[i-1] );
}
printf("\n");
qsort(a,sizeof(a)/sizeof(int),sizeof(int),comp);
for (int i = 1; i < argc; i++)
{
/* code */
printf("%d ",a[i-1] );
}
return 0;
}<file_sep>/sys.c
#include<stdio.h>
#include<string.h>
int main(int argc, char const *argv[])
{
char s[100];
while(1)
{
printf("Enter command to execute\n");
gets(s);
if(strcmp(s,"exit")==0)
break;
system(s);
}
return 0;
}<file_sep>/PrintSource.c
#include<stdio.h>
int main(int argc, char const *argv[])
{
//printf("%s\n",__FILE__);
FILE *fp=fopen(__FILE__,"r");
char c;
do
{
c=fgetc(fp);
putchar(c);
}
while(c!=EOF);
fclose(fp);
return 0;
}<file_sep>/matrix.c
/**
*
* @author Ravi
*/
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
/* code */
int n,m,i,j;
m=atoi(argv[1]);
n=atoi(argv[2]);
if(argc!=m*n+3)
printf("error\n");
int a[m][n];
int k=3;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=atoi(argv[k++]);
printf("%d ",a[i][j]);
}
printf("\n");
}
printf("Transpose:\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d ",a[j][i]);
}
printf("\n");
}
return 0;
}<file_sep>/String_qsort.c
/**
*
* @author Ravi
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int comp(const void *p,const void *q)
{
const char **l=(const char **)p;
const char **r=(const char **)q;
return(strcmp(*l,*r));
}
int main(int argc, char *argv[])
{
char *a[argc-1];
for (int i = 1; i < argc; ++i)
{
/* code */
a[i-1]=argv[i];
printf("%s ",a[i-1]);
}
printf("\n");
qsort(a,sizeof(a)/sizeof(char*),sizeof(char*),comp);
for (int i = 1; i < argc; ++i)
{
/* code */
printf("%s ",a[i-1]);
}
return 0;
}<file_sep>/strtok_demo.c
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
char *token;
char delim[10];
gets(str);
gets(delim);
for (token = strtok(str,delim); token != NULL; token = strtok(NULL, delim))
{
puts(token);
}
}
| fd5df5039b9193d9c954e7cd41790fd60de48438 | [
"C"
] | 6 | C | RavirajWalke/C | ecedc1145fb741a82d60b6e5adf0c63555d5a57c | 02abf1b68fe1d257d41f2de13632dcf476b38efc |
refs/heads/master | <repo_name>pjguzloz/sublime-text-2-packages<file_sep>/Open project path by shortcut/OpenFilePath.py
import sublime_plugin, open_path, os
class OpenFileFolder( sublime_plugin.WindowCommand ):
def run( self ):
if self.window.active_view() is None:
return
open_path.open( os.path.dirname( self.window.active_view().file_name() ) )<file_sep>/Open project path by shortcut/open_path.py
import sublime
from subprocess import call
def open( folder ):
settings = sublime.load_settings( "OpenPath.sublime-settings" )
file_manager = settings.get("file_manager", "explorer /e /root,\"{0}\"")
command = file_manager.format( folder )
call( command, shell=True )<file_sep>/GBK Encoding Support/sublime_gbk.py
#coding: utf8
import sublime, sublime_plugin
import os, re
import urllib
TEMP_PATH = os.path.join(os.getcwd(), 'tmp')
SEPERATOR = ' '
def gbk2utf8(view):
try:
reg_all = sublime.Region(0, view.size())
gbk = view.substr(reg_all).encode('gbk')
except:
gbk = file(view.file_name()).read()
text = gbk.decode('gbk')
file_name = view.file_name().encode('utf-8')
tmp_file_name = urllib.quote_plus(os.path.basename(file_name)) + SEPERATOR + urllib.quote_plus(file_name)
tmp_file = os.path.join(TEMP_PATH, tmp_file_name)
f = file(tmp_file, 'w')
f.write(text.encode('utf8'))
f.close()
window = sublime.active_window()
v = window.find_open_file(tmp_file)
if(not v):
window.open_file(tmp_file)
window.focus_view(view)
window.run_command('close')
window.focus_view(v)
sublime.status_message('gbk encoding detected, open with utf8.')
def saveWithEncoding(view, file_name = None, encoding = 'gbk'):
if(not file_name):
file_name = view.file_name()
reg_all = sublime.Region(0, view.size())
text = view.substr(reg_all).encode(encoding)
gbk = file(file_name, 'w')
gbk.write(text)
gbk.close()
class EventListener(sublime_plugin.EventListener):
def on_load(self, view):
gbk2utf8(view)
def on_post_save(self, view):
parts = view.file_name().split(SEPERATOR)
if(view.file_name().startswith(TEMP_PATH) and len(parts) > 1):
file_name = urllib.unquote_plus(parts[1].encode('utf-8')).decode('utf-8')
saveWithEncoding(view, file_name)
class SaveWithGbkCommand(sublime_plugin.TextCommand):
def __init__(self, view):
self.view = view
def run(self, edit):
file_name = self.view.file_name()
if(not file_name):
return
parts = file_name.split(SEPERATOR)
if(not file_name.startswith(TEMP_PATH) and len(parts) <= 1):
saveWithEncoding(self.view)
sublime.active_window().run_command('close')
sublime.active_window().open_file(self.view.file_name())
else:
sublime.active_window().run_command('save')
class SaveWithUtf8Command(sublime_plugin.TextCommand):
def __init__(self, view):
self.view = view
def run(self, edit):
file_name = self.view.file_name()
if(not file_name):
return
parts = file_name.split(SEPERATOR)
if(file_name.startswith(TEMP_PATH) and len(parts) > 1):
file_name = urllib.unquote_plus(parts[1].encode('utf-8')).decode('utf-8')
saveWithEncoding(self.view, file_name, 'utf-8')
sublime.active_window().run_command('close')
sublime.active_window().open_file(file_name)
else:
sublime.active_window().run_command('save')<file_sep>/Open project path by shortcut/README.md
Sublime open file/project folder plugin.
========================================
Sublime open-by-shortcut file/project folder plugin. Based on https://github.com/mikepfirrmann/openfolder.
Features
--------
- Open project folder in explorer by hitting shortcut
- Open current file folder in explorer by hitting shortcut
- Providing open_path python module for external plugins
Configuration
-------------
This is my preferred configuration. Add it to your ".sublime-keymap" to start using the plugin.
{
"keys": ["f10"],
"command": "open_project_folder"
},
{
"keys": ["ctrl+f10"],
"command": "open_file_folder"
}
API usage
---------
import open_path
open_path.open( '/your/path/' ) # will open path in OS's file browser<file_sep>/GBK Encoding Support/tmp/vhost.ini D%3A%5Ctools%5CAPMServ5.2.6%5Cvhost.ini
;;;;;;;;;;;;;;;;;;;;
; 关于 vhost.ini ;
;;;;;;;;;;;;;;;;;;;;
; 这个文件是APMServ的虚拟主机配置文件。
[vhost]
total=0
<file_sep>/Open project path by shortcut/OpenProjectPath.py
import sublime_plugin, open_path
class OpenProjectFolder( sublime_plugin.WindowCommand ):
def run( self ):
open_path.open( self.window.folders()[0] )<file_sep>/README.md
sublime-text-2-packages
=======================
sublime text 2 packages<file_sep>/GBK Encoding Support/tmp/APMServ.ini D%3A%5Ctools%5CAPMServ5.2.6%5CAPMServ.ini
;;;;;;;;;;;;;;;;;;;;
; 关于 APMServ.ini ;
;;;;;;;;;;;;;;;;;;;;
; 这个文件是APMServ的运行环境配置文件,请不要手工修改本配置文件中的任何数据,否则会造成SAPM无法启动。
[端口]
Apache=80
SSL=443
MySQL5.1=3306
MySQL4.0=3307
[路径]
APMServ=/:\tools\APMServ5.2.6
[状态]
APMServ=True
SSL=On
MySQL5.1=On
MySQL4.0=Off
ASP=Off
Memcached=On
Apache=On
[设置]
WindowState=Normal
AutoRun=Off
[缓存]
MySQL=0
| 7deba57860de8a0cff9452a5b39ad06ff92e45dd | [
"Markdown",
"Python",
"INI"
] | 8 | Python | pjguzloz/sublime-text-2-packages | f0664fc275e271fcefe15b4d21127fd545ad8eff | 1c2ef2859f39450d12d902d11a454dc29dad0b3e |
refs/heads/master | <repo_name>nzapata/Angularfire<file_sep>/app/scripts/controllers/post.js
/**
* Created by nathanielz on 5/14/2015.
*/
<file_sep>/app/scripts/app.js
'use strict';
/**
* @ngdoc overview
* @name firebaseApp
* @description
* # firebaseApp
*
* Main module of the application.
*/
angular
.module('firebaseApp', [
'ngAnimate',
'ngAria',
'ngCookies',
'ngMessages',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'firebase',
])
.constant('FURL', 'https://testing212.firebaseio.com/')
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/post', {
templateUrl: 'views/post.html',
controller: 'TaskController'
})
.when('/browser', {
templateUrl: 'views/browser.html',
controller:'TaskController'
})
.when('/edit/:taskId', {
templateUrl: 'views/edit.html',
controller: 'TaskController'
})
.when('nav', {
templateUrl: 'views/nav.html',
controller:'NavController'
})
.when('/register', {
templateUrl: 'views/register.html',
controller: 'AuthController'
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'AuthController'
}
)
.when('/changepass', {
templateUrl: 'views/changepass.html',
})
.otherwise({
redirectTo: '/'
});
});
<file_sep>/app/scripts/controllers/NavController.js
/**
* Created by nathanielz on 5/18/2015.
*/
'use strict';
angular.module('firebaseApp')
.controller('NavController',['$scope', '$location', 'Auth','firebaseAuth' ,function($scope, $location, Auth) {
$scope.currentUser = Auth.user;
$scope.signedIn = Auth.signedIn;
$scope.logout = function() {
Auth.logout();
toaster.pop('success', "Logged out successfully");
$location.path("/");
};
}]);
| 49b9d5adf2e86864455b8823ac858e711b451291 | [
"JavaScript"
] | 3 | JavaScript | nzapata/Angularfire | 0c668e2a535cec347d61fb3fb3aff56bec4ed6ef | 5c3ff015ff575a4d01be50c2b14a86c198d8146c |
refs/heads/master | <repo_name>wludh/frenchnewspapers<file_sep>/adjectivestems.py
import main
from nltk import FreqDist
corpus = main.Corpus()
dates = {}
for text in corpus.texts:
adjs = []
for x in text.tree_tagged_tokens:
if x.pos[0:3] == 'ADJ':
adjs.append(x.lemma)
if text.date in dates:
dates[text.date]+= adjs
else:
dates[text.date] = adjs
for key in dates.keys():
dates[key] = FreqDist(dates[key]).most_common(100)
print(dates)
<file_sep>/sort_topics_by_date.py
import argparse
import csv
import sys
def parse_args(argv=None):
"""This parses the command line."""
argv = sys.argv[1:] if argv is None else argv
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-f', '--file', dest='filename', action='store',
help='The input directory containing the training '
'corpus.')
return parser.parse_args(argv)
def main():
args = parse_args()
try:
except:
print(filename + " was not a csv file")
rows = []
if __name__ == '__main__':
main()
<file_sep>/drive.py
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import re
def read_sheet():
"""reads our spreadsheet"""
#TODO: Could be optimized so it doesn't pull all three every time depending on what we want to use it for.
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('Scandal-58e97c6d4a1a.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open_by_key('<KEY>')
articles = []
titles = []
corrections = []
common_ocr_errors = []
(articles, titles, corrections, common_ocr_errors) = wks.worksheets()
return articles, titles, corrections, common_ocr_errors
def get_article_metadata():
"""Gets the filename, date, and publication for each article.
Returns a list of dictionaries."""
article_sheet, _, _, _ = read_sheet()
results = []
for article in article_sheet.get_all_values()[1:]:
row = {}
row["date"] = article[6]
row["filename"] = re.sub(r'_clean|.txt|_clean.txt', '', article[2].lower())
row["newspaper name"] = article[7].lower()
results.append(row)
return results
def main():
articles, titles, corrections, common_ocr_errors = read_sheet()
print(get_article_metadata())
if __name__ == '__main__':
main()
<file_sep>/cluster_preprocess.py
import main
import shutil
import os
FOLDER_DIR = 'processed'
FILTER = 'ADJ'
if os.path.exists(FOLDER_DIR):
shutil.rmtree(FOLDER_DIR)
os.makedirs(FOLDER_DIR)
corpus = main.Corpus()
print([text.filename for text in corpus.texts])
corpus.group_articles_by_publication()
print([text.filename for text in corpus.texts])
for text in corpus.texts:
to_write = []
with open(FOLDER_DIR + '/' + text.filename + '.txt', 'w') as current_text:
for x in text.tree_tagged_tokens:
if x.pos == FILTER:
to_write.append(x.lemma)
current_text.write(' '.join(to_write))
<file_sep>/main.py
import nltk
from nltk import FreqDist
import treetaggerwrapper
import nltk.data
from nltk.corpus import stopwords, names
from nltk.stem.snowball import SnowballStemmer
import codecs
import os
import re
import csv
import operator
import datetime
import dateutil.parser
import matplotlib.pyplot as plt
plt.rcdefaults()
import numpy as np
from matplotlib.pyplot import figure, show
from matplotlib.ticker import MaxNLocator
import gensim
from gensim import corpora, models, similarities
# TODO: stemming. will need to follow the example
# TODO:
# below, where you have each text map onto an indexed stem.
# TODO: take those stems and then integrate that into everything below.
""" A text should have:
filename
date
journal
tokens
stem index for each token"""
CORPUS = 'clean_ocr'
STOPWORD_LIST = []
LIST_OF_NAMES = []
plt.rcdefaults()
fig, ax = plt.subplots()
class Corpus(object):
"""Takes in a list of text objects. and you can then
run things on the set as a whole."""
def __init__(self, corpus_dir=CORPUS):
self.corpus_dir = corpus_dir
self.stopwords = self.generate_stopwords()
self.names_list = self.generate_names_list()
self.texts = self.build_corpus()
self.sort_articles_by_date()
self.publications = [text.publication for text in self.texts]
def build_corpus(self):
"""given a corpus directory, make indexed text objects from it"""
texts = []
for (root, _, files) in os.walk(self.corpus_dir):
for fn in files:
if fn[0] == '.':
pass
else:
texts.append(IndexedText(os.path.join(root, fn)))
return texts
def preprocess_for_topic_modeling(self):
"""stem the corpus so that you can pre-process for topic modeling"""
if not os.path.exists('processed'):
os.makedirs('processed')
for text in self.texts:
with open('processed/' + text.filename + '.txt', 'w') as current_text:
current_text.write(' '.join(text.stems))
def tokens_by_publication_cfd(self):
cfd = nltk.ConditionalFreqDist(
(text.publication, word)
for text in self.texts
for word in text.tokens
)
return cfd
def generate_stopwords(self):
global STOPWORD_LIST
"""generates stopwords for use in tokenizing"""
nltk_stopwords = stopwords.words('french')
# stopwords from http://www.ranks.nl/stopwords/french
ranks_stopwords = []
text = codecs.open("french_stopwords.txt", "r", 'utf8').read()
text = text.replace(' ', ',')
text = text.replace('\r',',')
text = text.replace('\n',' ')
ranks_stopwords = text.split(",")
ranks_stopwords = [i.replace(' ', '') for i in ranks_stopwords]
extra_stopwords = []
punctuation = ['»', '«', ',', '-', '.', '!',
"\"", '\'' ':', ';', '?', '...']
STOPWORD_LIST = set(nltk_stopwords + ranks_stopwords +
punctuation + extra_stopwords)
print (STOPWORD_LIST)
return STOPWORD_LIST
def generate_names_list(self):
global LIST_OF_NAMES
"""puts together a list to query the corpus by"""
nltk_names = names.words()
# put custom name list here.
extra_names = ['Alexandre', 'Steinheil']
LIST_OF_NAMES = \
[w.lower() for w in nltk_names] + [w.lower() for w in extra_names]
return LIST_OF_NAMES
def read_out(self):
"""given a series of articles, print out stats for them
articles are given as a list of tuple pairs
(filename, list of tokens)"""
output = open('results.txt', 'w')
for text in self.texts:
output.write("===================\n")
output.write(text.filename + '\n')
output.write("Number of tokens: " +
str(text.length) + '\n')
output.write("Most common tokens: " +
str(text.most_common()) + '\n')
output.write("Punctuation Counts: " +
str(text.count_punctuation()) + '\n')
output.write("Names: " + str(text.find_names()) + '\n')
def sort_articles_by_date(self):
"""Takes the corpus and sorts them by date. Defaults to this method.
Calling it again will resort things by date."""
self.texts.sort(key=lambda x:
datetime.datetime.strptime(x.date, "%Y-%m-%d"))
def group_articles_by_publication(self):
"""group articles by publication. call it to sort."""
pub_index = {}
new_array = []
for text in self.texts:
key = text.publication
value = pub_index.get(key)
if value is None:
pub_index[key] = [text]
else:
pub_index[key] += [text]
for key in pub_index.keys():
pub_index[key].sort(key=lambda x:
datetime.datetime.strptime(x.date, "%Y-%m-%d"))
new_array += pub_index[key]
self.texts = new_array
def single_token_by_date(self, token):
"""Takes the list of articles and the parameter to sort by.
returns all the data needed for the CSV
returns a hash with key values of {(year, month, day):
(target token counts for
this month, total tokens)}"""
index = {}
for text in self.texts:
# for now, graph by date
key = text.date
column_values = index.get(key)
if column_values is None:
total_doc_tokens = text.length
column_values = text.token_count(token)
index[key] = (column_values, total_doc_tokens)
else:
index[key] = (index[key][0] + text.token_count(token), index[key][1] + text.length)
index['year-month-day'] = token
return index
def dict_to_list(self, a_dict):
"""takes the result dict and prepares it for writing to csv"""
rows = []
for (date_key, values) in a_dict.items():
try:
tf_idf = values[0] / values[1]
rows.append([date_key, tf_idf])
except:
# for the csv header, put it at the beginning of the list
rows.insert(0, [date_key, values])
# sorts things by date
rows.sort(key=operator.itemgetter(0))
# takes the last row and makes it first,
# since it gets shuffled to the back
rows.insert(0, rows.pop())
return rows
def csv_dump(self, results_dict):
"""writes some information to a CSV for graphing in excel."""
print(results_dict)
results_list = self.dict_to_list(results_dict)
with open('results.csv', 'w') as csv_file:
csvwriter = csv.writer(csv_file, delimiter=',')
for row in results_list:
csvwriter.writerow(row)
def list_all_filenames(self):
for text in self.texts:
print(text.filename)
def lda(self):
#This function computes the Latent Dirichlet Allocation (LDA) for topic modeling.
allthetokens = []
numberoftopics = int(input("Please enter the number of topics for the LDA."))
numberofwords = int(input("Please enter the number of words for each topic."))
nltk_stopwords = stopwords.words('french')
# stopwords from http://www.ranks.nl/stopwords/french
ranks_stopwords = []
text = codecs.open("french_stopwords.txt", "r", 'utf8').read()
text = text.replace(' ', ',')
text = text.replace('\r',',')
text = text.replace('\n',' ')
ranks_stopwords = text.split(",")
extra_stopwords = []
punctuation = ['»', '«', ',', '-', '.', '!',
"\"", '\'' ':', ';', '?', '...']
thestopwords = set(nltk_stopwords + ranks_stopwords +
punctuation + extra_stopwords)
thestopwords = list(thestopwords)
print (STOPWORD_LIST)
for text in self.texts:
currenttext = text.tokens_without_stopwords
textwithoutpunc = [word for word in currenttext if word.isalpha()]
allthetokens.append(textwithoutpunc)
for subarray in range(0, len(allthetokens)):
for word in range(0, len(allthetokens[subarray])):
if allthetokens[subarray][word] in thestopwords:
print ("yes")
allthetokens[subarray].remove(allthetokens[subarray][word])
print ("Please wait. This could take some time...")
dictionary = corpora.Dictionary(allthetokens)
doc_term_matrix = [dictionary.doc2bow(doc) for doc in allthetokens]
Lda = gensim.models.ldamodel.LdaModel
ldamodel = Lda(doc_term_matrix, num_topics=numberoftopics, id2word = dictionary, passes=50)
returnthis = ldamodel.print_topics(num_topics=numberoftopics, num_words=numberofwords)
return returnthis
def lsi(self):
#This function computes Latent Semantic Indexing (LSI) for topic modeling.
allthetokens = []
numberoftopics = int(input("Please enter the number of topics for the LSI."))
numberofwords = int(input("Please enter the number of words for each topic."))
for text in self.texts:
currenttext = text.tokens_without_stopwords
textwithoutpunc = [word for word in currenttext if word.isalpha()]
allthetokens.append(textwithoutpunc)
dictionary = corpora.Dictionary(allthetokens)
doc_term_matrix = [dictionary.doc2bow(doc) for doc in allthetokens]
lsi = models.LsiModel(doc_term_matrix, num_topics=numberoftopics, id2word=dictionary)
returnthis = lsi.print_topics(num_topics=numberoftopics, num_words = numberofwords)
return returnthis
def find_by_filename(self, name):
"""given a filename, return the text associated with it."""
for text in self.texts:
if text.filename == name:
return text
def find_percentages_on_first_page(self):
"""prints out the number of tokens on the first page of
an article as well as the percentage of total tokens"""
print("filename" + "," + "tokens on first page" + "," + "percentage on first page")
for text in self.texts:
try:
num_tokens_on_first_page = text.find_page_breaks()
total_tokens = (len(text.bigrams) + 1)
percentage_on_first_page = (num_tokens_on_first_page / total_tokens) * 100
print(text.date + "," + text.publication + "," + str(num_tokens_on_first_page) + "," + str(percentage_on_first_page))
except:
# if there are no page breaks, pass this article
pass
def find_conjunctions(self):
"""finds the number of coordinating conjunctions for each text and prints them out."""
for text in self.texts:
conjunctions = FreqDist([tag for token, tag in text.tagged_tokens])
conjunction_count = conjunctions['KON']
normalized_conjunction_count = conjunction_count/len(text.tokens)
print(text.date + ',' + text.publication + "," + str(normalized_conjunction_count))
def dispersion_plots(self, character_or_token, file_name, bin_count=500):
"""\
given a character or token and a filename to output the things to, produce a scatterplot of the output
"""
fig, axes = plt.subplots(len(self.texts), 1, squeeze=True)
fig.set_figheight(9.4)
for (text, ax) in zip(self.texts, axes):
print(text.filename)
matches = list(re.finditer(character_or_token, text.text))
locations = [m.start() for m in matches]
n, bins = np.histogram(locations, bin_count)
# fig.suptitle(text.filename, fontsize=14, fontweight='bold')
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n
XY = np.array(
[[left, left, right, right], [bottom, top, top, bottom]]
).T
barpath = path.Path.make_compound_path_from_polys(XY)
patch = patches.PathPatch(
barpath, facecolor='blue', edgecolor='gray', alpha=0.8,
)
ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
# plt.axis('off')
ax.add_patch(patch)
# ax.set_xlabel('Position in Text, Measured by Character')
# ax.set_ylabel('Number of Quotations')
output = os.path.join(file_name + '.png')
print('writing to {}'.format(output))
plt.savefig(output, transparent=True)
plt.show()
class IndexedText(object):
"""Text object"""
def __init__(self, filepath):
self.filepath = filepath
self.filename = re.sub(r'^.*/|_clean.txt|_Clean.txt', '', filepath).lower()
self.text = self.read_text()
self.sentences = self.get_text_sentences()
self.tokens = self.flatten_sentences()
self.tagger = treetaggerwrapper.TreeTagger(TAGLANG='fr', TAGDIR='tagger')
self.tree_tagged_tokens = self.get_tree_tagged_tokens()
self.tagged_tokens = [(foo.word, foo.pos) for foo in self.tree_tagged_tokens]
self.stems = [foo.lemma for foo in self.tree_tagged_tokens]
self.bigrams = list(nltk.bigrams(self.tokens))
self.trigrams = list(nltk.trigrams(self.tokens))
self.length = len(self.tokens)
self.fd = FreqDist(self.tokens)
self.date = self.parse_dates()
self.year = dateutil.parser.parse(self.date).year
self.month = dateutil.parser.parse(self.date).month
self.day = dateutil.parser.parse(self.date).day
self.publication = self.parse_publication()
self.stemmer = SnowballStemmer('french')
self.index = nltk.Index((self.stem(word), i)
for (i, word) in enumerate(self.tokens))
self.tokens_without_stopwords = self.remove_stopwords()
self.tokens_without_punctuation = [word for word in self.tokens if word.isalpha()]
def get_tree_tagged_tokens(self):
"""takes the tokens and tags them"""
tagger = self.tagger
return treetaggerwrapper.make_tags(tagger.tag_text(self.tokens))
def find_page_breaks(self):
"""take bigrams and return indexs of page breaks for a text"""
# page_breaks = []
return self.bigrams.index(('page', 'break'))
# for index, bigram in enumerate(self.bigrams):
# this will grab all indices
# if bigram == ('page', 'break'):
# page_breaks.append(index)
# return page_breaks
def get_text_sentences(self):
"""returns sentences from a text"""
tokenizer = nltk.data.load('tokenizers/punkt/french.pickle')
untokenized_sentences = [w.lower() for w in tokenizer.tokenize(self.text)]
matches = []
for sent in untokenized_sentences:
matches.append(re.findall(
r'\w+|[\'\"\/^/\,\-\:\.\;\?\!\(0-9]', sent
))
return matches
def flatten_sentences(self):
"""takes those sentences and returns tokens"""
return [item for sublist in self.sentences for item in sublist]
def read_text(self):
"""given a filename read in the text."""
with codecs.open(self.filepath, 'r', 'utf8') as f:
print(self.filename)
return f.read()
def parse_publication(self):
"""parse the filename for the publication."""
date_pattern = r'[jJ]anuary[a-zA-Z0-9_]*|[fF]ebruary[a-zA-Z0-9_]*|[mM]arch[a-zA-Z0-9_]*|[aA]pril[a-zA-Z0-9_]*|[mM]ay[a-zA-Z0-9_]*|[jJ]une[a-zA-Z0-9_]*|[jJ]uly[a-zA-Z0-9_]*|[aA]ugust[a-zA-Z0-9_]*|[sS]eptember[a-zA-Z0-9_]*|[oO]ctober[a-zA-Z0-9_]*|[nN]ovember[a-zA-Z0-9_]*|[dD]ecember[a-zA-Z0-9_]*'
# strip out date from filename and pop off the trailing underscore.
return re.sub(date_pattern, '', self.filename)[:-1]
def parse_dates(self):
"""parse the filename for the dates."""
date_pattern = r'[jJ]anuary[a-zA-Z0-9_]*|[fF]ebruary[a-zA-Z0-9_]*|[mM]arch[a-zA-Z0-9_]*|[aA]pril[a-zA-Z0-9_]*|[mM]ay[a-zA-Z0-9_]*|[jJ]une[a-zA-Z0-9_]*|[jJ]uly[a-zA-Z0-9_]*|[aA]ugust[a-zA-Z0-9_]*|[sS]eptember[a-zA-Z0-9_]*|[oO]ctober[a-zA-Z0-9_]*|[nN]ovember[a-zA-Z0-9_]*|[dD]ecember[a-zA-Z0-9_]*'
date = re.findall(date_pattern, self.filename)
# replaces the underscores with dashes
date = dateutil.parser.parse(re.sub(r'_', '-', date[0]))
return ('%s-%s-%s' % (date.year, date.month, date.day))
def stem(self, word):
return self.stemmer.stem(word).lower()
def concordance(self, word, width=40):
"""given a token, produce a word in context view of it."""
key = self.stem(word)
# words of context
wc = int(width / 4)
for i in self.index[key]:
lcontext = ' '.join(self.tokens[i - wc:i])
rcontext = ' '.join(self.tokens[i:i + wc])
ldisplay = '{:>{width}}'.format(lcontext[-width:], width=width)
rdisplay = '{:{width}}'.format(rcontext[:width], width=width)
print(ldisplay, rdisplay)
def remove_stopwords(self):
global STOPWORD_LIST
"""takes a list of tokens and strips out the stopwords"""
return [w for w in self.tokens if w.lower() not in STOPWORD_LIST]
def find_names(self):
"""creates a frequency distribution of the
most common names in the texts"""
names_list = LIST_OF_NAMES
name_tokens = [w for w in self.tokens if w in names_list]
fd = FreqDist(name_tokens)
return fd.most_common(50)
def count_punctuation(self):
"""Gives a count of the given punctuation marks for each text"""
fd = FreqDist(self.tokens)
punctuation_marks = ['»', '«', ',', '-', '.', '!',
"\"", ':', ';', '?', '...', '\'']
results = []
for mark in punctuation_marks:
count = str(fd[mark])
results.append("%(mark)s, %(count)s" % locals())
return(results)
def puncbysection_indiv(self):
## This function creates charts of the frequency of all punctuation marks in all subdivisions of the text.
## The character count of all of the subdivisions can be modified in the definition for the variable 'parts'
plt.rcdefaults()
fig, ax = plt.subplots()
punctuation_marks = ['»', '«', ',', '-', '.', '!',
"\"", ':', ';', '?', '...', '\'']
y_pos = np.arange(len(punctuation_marks))
thetext = self.text
parts = [thetext[i:i+1000] for i in range(0, len(thetext), 1000)]
for q in range(0, len(parts)):
thnumber = str(q + 1)
newthing = parts[q]
newthing = re.findall(r"[\w]+|[^\s\w]", newthing)
occur = []
for i in range(0, len(punctuation_marks)):
z=0
for x in range(0, len(newthing)):
if punctuation_marks[i] == newthing[x]:
z = z+1
occur.append(z)
y_pos = np.arange(len(punctuation_marks))
plt.barh(y_pos, occur, align='center', alpha=0.5)
plt.yticks(y_pos, punctuation_marks)
plt.xlabel('Occur')
plt.title('Punctuation marks in section #' + thnumber + " of text")
plt.show()
def puncbysection_total(self):
## This function plots the appears of a given punctuation mark over the course of an entire text.
punctuation_marks = ['»', '«', ',', '-', '.', '!',
"\"", ':', ';', '?', '...', '\'']
mark = input("Please enter the punctuation mark you want to plot: » « , - . ! : ; ? ... ' ")
for i in range (0, len(punctuation_marks)):
if mark == punctuation_marks[i]:
text = self.text
parts = [text[i:i+500] for i in range(0, len(text), 500)]
##The 500 character count can be changed depending on how long one wants the length of each
## subdivisions to be
totaltally =[]
for q in range(0, len(parts)):
newthing = parts[q]
newthing = re.findall(r"[\w]+|[^\s\w]", newthing)
z=0
for x in range(0, len(newthing)):
if punctuation_marks[i] == newthing[x]:
z = z+1
totaltally.append(z)
y_pos = np.arange(len(punctuation_marks[i]))
noofsectionsforxaxis = []
newvari = punctuation_marks[i]
for i in range (0, len(totaltally)):
addedone = i + 1
noofsectionsforxaxis.append(addedone)
##plt.rcdefaults()
##fig, ax = plt.subplots()
ax = figure().gca()
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
plt.plot(noofsectionsforxaxis, totaltally)
sortedtotaltally = totaltally
sortedtotaltally.sort(reverse=True)
heightofyaxis = sortedtotaltally[0] + 1
plt.axis([1, len(noofsectionsforxaxis), 0, heightofyaxis])
ax.set_xlabel('Chronological textual subdivision #')
ax.set_title('The Punctuation Mark ' + newvari + ' Over the Course of Text')
ax.set_ylabel('The number of occurrences of ' + newvari)
plt.legend([mark])
plt.show()
def multiple_punctuation(self):
punctuation_marks = ['»', '«', ',', '-', '.', '!',
"\"", ':', ';', '?', '...', '\'']
mark1 = input("Please enter the punctuation mark you want to plot: » « , - . ! : ; ? ... ")
mark2 = input("Enter the second punctuation mark.")
totaltally = []
newtotaltally = []
noofsectionsforxaxis = []
for i in range (0, len(punctuation_marks)):
if mark1 == punctuation_marks[i]:
y_pos = np.arange(len(punctuation_marks[i]))
text = self.text
parts = [text[i:i+500] for i in range(0, len(text), 500)]
for q in range(0, len(parts)):
thnumber = str(q + 1)
newthing = parts[q]
newthing = re.findall(r"[\w]+|[^\s\w]", newthing)
z=0
for x in range(0, len(newthing)):
if punctuation_marks[i] == newthing[x]:
z = z+1
totaltally.append(z)
y_pos = np.arange(len(punctuation_marks[i]))
newvari = punctuation_marks[i]
for i in range (0, len(totaltally)):
addedone = i + 1
noofsectionsforxaxis.append(addedone)
elif mark2 == punctuation_marks[i]:
text = self.text
parts = [text[i:i+500] for i in range(0, len(text), 500)]
for q in range(0, len(parts)):
thnumber = str(q + 1)
newthing = parts[q]
newthing = re.findall(r"[\w]+|[^\s\w]", newthing)
z=0
for x in range(0, len(newthing)):
if punctuation_marks[i] == newthing[x]:
z = z+1
newtotaltally.append(z)
print (totaltally)
print (newtotaltally)
ax = figure().gca()
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
plt.plot(noofsectionsforxaxis, totaltally)
plt.plot(noofsectionsforxaxis, newtotaltally)
totaltallysizing = totaltally
totaltallysizing.sort(reverse=True)
newtotaltallysizing = newtotaltally
newtotaltally.sort(reverse=True)
if totaltallysizing[0] > newtotaltallysizing[0]:
yaxassign = totaltallysizing[0]
yaxassign = yaxassign + 1
else:
yaxassign = newtotaltallysizing[0]
yaxassign = yaxassign + 1
plt.axis([1, len(noofsectionsforxaxis), 0, yaxassign])
ax.set_xlabel('Chronological textual subdivisions')
ax.set_title('The Punctuation Mark ' + mark1 + " & " + mark2 + ' Over the Course of Text')
ax.set_ylabel('The number of occurrences of ' + mark1 + " and " + mark2)
plt.legend([mark1, mark2])
plt.show()
def most_common(self):
"""takes a series of tokens and returns most common 50 words."""
fd = FreqDist(self.tokens_without_stopwords)
return fd.most_common(50)
def token_count(self, token):
"""takes a token and returns the counts for it in the text."""
return self.fd[token]
def stemmed_token_count(self, token):
stem = treetaggerwrapper.make_tags(self.tagger.tag_text(token))[0].lemma
return FreqDist(self.stems)[stem]
def count_conjunctions(self):
tagged_tokens = self.tagged_tokens
counter = 0
for index, (token, tag) in enumerate(tagged_tokens):
if tag == 'KON':
print(token + ": " + ' '.join(self.tokens[index-3:index+3]))
counter += 1
return counter
class GenreText(IndexedText):
def __init__(self, filepath):
self.filepath = filepath
self.filename = re.sub(r'^.*/|_clean\.txt|_Clean\.txt|\.txt', '', os.path.basename(filepath)).lower()
self.text = self.read_text()
self.genre = re.split(r'_', self.filename)[1]
self.sentences = self.get_text_sentences()
self.tokens = self.flatten_sentences()
self.tagger = treetaggerwrapper.TreeTagger(TAGLANG='fr', TAGDIR='tagger')
self.tree_tagged_tokens = self.get_tree_tagged_tokens()
self.tagged_tokens = [(foo.word, foo.pos) for foo in self.tree_tagged_tokens]
self.stems = [foo.lemma for foo in self.tree_tagged_tokens]
self.bigrams = list(nltk.bigrams(self.tokens))
self.trigrams = list(nltk.trigrams(self.tokens))
self.length = len(self.tokens)
self.fd = FreqDist(self.tokens)
self.stemmer = SnowballStemmer('french')
self.index = nltk.Index((self.stem(word), i)
for (i, word) in enumerate(self.tokens))
self.tokens_without_stopwords = self.remove_stopwords()
self.tokens_without_punctuation = [word for word in self.tokens if word.isalpha()]
class GenreCorpus(Corpus):
"""specialized object for genre texts"""
def __init__(self, genre_corpus_dir='genre_corpus'):
self.corpus_dir = genre_corpus_dir
self.stopwords = self.generate_stopwords()
self.names_list = self.generate_names_list()
self.texts = self.build_corpus()
def build_corpus(self):
"""given a corpus directory, make indexed text objects from it"""
texts = []
for (root, _, files) in os.walk(self.corpus_dir):
for fn in files:
if fn[0] == '.':
pass
else:
texts.append(GenreText(os.path.join(root, fn)))
return texts
def main():
"""Main function to be called when the script is called"""
corpus = Corpus()
corpus.read_out()
# corpus.csv_dump(corpus.single_token_by_date('crime'))
if __name__ == '__main__':
main()
<file_sep>/README.md
Collects scripts for processing texts for the C19 French Newspapers Scandal project at W&L.
Primary script for text analysis is main.py.
To begin, clone the repository and change into it.
# Setup
```bash
$ git clone https://github.com/wludh/frenchnewspapers.git
$ cd frenchnewspapers
```
The scripts are written in python 3. First, install [homebrew](http://brew.sh/) if you haven't already:
```
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
```
Then use homebrew to install python3:
```bash
$ brew install python3
```
Then install python dependencies using pip.
```bash
$ pip3 install nltk
$ pip3 install python-dateutil
$ pip3 install treetaggerwrapper
$ pip3 install matplotlib
$ pip3 install scipy
$ pip3 install sklearn
$ pip3 install gensim
```
For Part of Speech tagging, first install Tree Hugger by following the directions [here](http://www.cis.uni-muenchen.de/~schmid/tools/TreeTagger/). You will want to install it into the root of the frenchnewspapers directory. This involves downloading four files from that link, but be careful that you don't unzip anything yourself. The installation script will do that for you. This involves creating a folder called 'tagger' in the project root, switching into that folder, and then running the install commands. Like so:
```bash
$ mkdir tagger
$ cd tagger
$ sh install-tagger.sh
$ echo 'Hello world!' | cmd/tree-tagger-french
reading parameters ...
tagging ...
Hello INT hello
world NOM <unknown>
! SENT !
finished.
```
If you get results like this from the third command it was successful. You should be set up for things.
# Usage
Individual scripts can be created for a particular purpose by modifying the main() function in main.py. By default, it outputs a series of basic statistics about the corpus to the file results.txt when run as a program.
A more flexible way to interact with the corpus is by importing the main script in the python interpreter. First, fire up your python interpreter and import your main.py package.
```bash
$ python3
>>> import main
>>> corpus = main.Corpus()
```
The third line here loads the corpus from a given directory. By default, it reads in from a folder called "clean_ocr". If you don't have such a folder, you will have to create one and populate it with plain text files available from our WLU Box folder.
Once read in, the script prepares your corpus as a list of individual texts (organize by date by default) that can be accessed like this:
```python
>>> corpus.texts
[<main.IndexedText object at 0x10d87b550>, <main.IndexedText object at 0x10da060b8>, <main.IndexedText object at 0x10dbb11d0>, <main.IndexedText object at 0x10dc60dd8>, <main.IndexedText object at 0x10deef1d0>, <main.IndexedText object at 0x10e451710>, <main.IndexedText object at 0x10e680080>, <main.IndexedText object at 0x10e9cfa58>, <main.IndexedText object at 0x10eb57cf8>, <main.IndexedText object at 0x10d867898>, <main.IndexedText object at 0x10d9b84e0>, <main.IndexedText object at 0x10db7c5c0>, <main.IndexedText object at 0x10dbef048>, <main.IndexedText object at 0x10dd6a6a0>, <main.IndexedText object at 0x10e3a12e8>, <main.IndexedText object at 0x10e60ef98>, <main.IndexedText object at 0x10e88a978>, <main.IndexedText object at 0x10ea31978>, <main.IndexedText object at 0x10ec87e48>, <main.IndexedText object at 0x10d6a40f0>, <main.IndexedText object at 0x10d6a4630>, <main.IndexedText object at 0x10d8f4e80>, <main.IndexedText object at 0x10dabbcf8>, <main.IndexedText object at 0x10dcde278>, <main.IndexedText object at 0x10e1f2eb8>, <main.IndexedText object at 0x10e4ae940>, <main.IndexedText object at 0x10e721048>, <main.IndexedText object at 0x10ea1ab00>, <main.IndexedText object at 0x10ebccb38>]
```
You can then access any individual text by selecting it from the list:
```python
>>> corpus.texts[0]
<main.IndexedText object at 0x10d87b550>
>>> corpus.texts[0].filename
'figaro_june_1_1908'
>>> corpus.texts[0].tokens
['assassinat', 'du', 'peintre', 'steinheil', 'et', 'de', 'sa', 'belle-mère', 'mme', 'veuve', 'japy', 'mme', 'steinheil', 'échappe', 'a', 'la', 'mort', 'un', 'crime', 'épouvantable', ',', 'un', 'triple', 'assassinat', ',', 'a', 'été', 'commis', 'à', 'paris', 'dans', 'la', 'nuit', 'de', 'samedi', 'à', 'dimanche', '.', 'dans', 'la', 'série', 'des', 'meurtres', "qu'il", 'faut', 'enregistrer', 'chaque', 'jour', ',', 'celui-là', 'prend', 'une', 'place', 'à', 'part', '.',...
```
I've baked in a variety of methods, some tied to the corpus itself:
* corpus.corpus_dir
* give name of the corpus directory
* corpus.stopwords
* give the list of stopwords currently being used.
* corpus.names_list
* give the list of proper names used for querying by proper names
* corpus.texts
* give the list of all the texts
* corpus.sort_articles_by_date()
* sort the articles by date.
* corpus.read_out()
* output to a file called 'results.txt' a variety of stats about the texts in the corpus.
* corpus.group_articles_by_publication()
* orders the texts by publication and then each of these groupings by date.
* corpus.csv_dump(corpus.single_token_by_date('token'))
* Actually two methods in one - csv_dump and single_token_by_date. The latter charts the usage of a single token across the corpus and the former writes it to a csv file for graphing in excel.
* corpus.list_all_filenames()
* prints out all filenames in the corpus folder
* corpus.find_by_filename('an_example_filename_here')
* take the filename (note the quotation marks) and return the text object associated with it. So you could do something like to store a text as a variable and then manipulate it for the future:
```python
>>> corpus.list_all_filenames
croix_june_2_1908
croix_november_14_1909
croix_november_26_1908
croix_november_27_1908
>>> my_text = corpus.find_by_filename('croix_november_26_1908')
>>> my_text.filename
croix_november_26_1908
>>> my_text.tokens
['l', "'", 'affaire', 'steinheil', 'les', 'découvertes', 'd', "'", 'hier', 'nous', 'ne', 'nous', 'trompions', 'pas', 'en', 'annonçant', 'que', 'la', 'perquisition', ...
```
* corpus.preprocess_for_topic_modeling():
* creates a new folder containing copies of the texts, but all the tokens are stemmed. in case we want to try topic modeling those instead.
* corpus.lsi()
* performs Latent Semantic Indexing (LSI) for topic modeling on the corpus.
* corpus.lda()
* performs Latent Dirichlet Allocation (LDA) for topic modeling on the corpus. This takes significantly longer to run than LSI.
Others are tied to the individual texts:
* text.filename
* give filename of text
* text.text
* give unprocessed text (includes line breaks, etc.)
* text.tokens
* give tokenized version of a text
* text.tree_tagged_tokens
* gives a list of tag objects according to tree tagger, which contains word, pos, and lemma. Using this to create the tagged_tokens and stems attributes.
* text.tagged_tokens
* gives a list of tuple pairs with (token, part of speech tag)
* text.stems
* gives a list of the text's tokens converted to stems
* text.length
* give the length of a text (number of tokens)
* text.fd
* give a frequency distribution of the text (number of uses of each individual token)
* text.date
* give date of a text. Can be further broken down with text.year, text.month, and text.day
* text.publication
* give the name of the journal that published the text.
* text.puncbysection_total
* shows the distribution of punctuation marks over the course of a text.
* text.multiple_punctuation
* does the same as puncbysection_total, except for two punctuation marks at once
* text.stemmer
* produces a French stemmer for the text (not fully implemented yet)
* text.token_count('token')
* gives you the number of times that exact token occurs in the text. will not catch plural forms or alternative verb conjugations.
* text.stemmed_token_count('token')
* stems the token and then gets the number of times that stem occurs in the text. So it will catch plural vs singular and verb conjugations.
* text.index
* produces a stemmed index for the text. (mostly deprecated, since we're using a different stemmer now.)
* text.tokens_without_stopwords
* produces a list of tokens in the text with stopwords excluded.
* text.bigrams
* produces a list of word pairs or bigrams for the text as a list of tuples. Ex. [‘this’, ‘is’, ‘a’, ‘sentence’] becomes [(‘this’, ‘is’), (‘is’, ‘a’), (‘a’, ‘sentence’)].
* Keep in mind that each tuple is a unit, denoted by the (). You can access them as a unit: text.trigrams.count(('mme', 'steinheil')) will give you the number of times the bigram 'mme steinheil' occurs in a text.
* Or you can break apart the tuple and manipulate each unit of the tuple separately. The following will loop over all bigrams by assigning variable names to first and second element in each tuple, check to see if the second word in the pair is 'steinheil' and, if so, print the pair to the console. It effectively gives a list of all the different words that Steinheil follows:
```python
for first, second in my_text.bigrams:
if second == 'steinheil':
print(first + " " second)
```
* text.trigrams
* produces a list of consecutive three-word phrases. Can be manipulated in the same way as text.bigrams.
So to do a lot of the more complicated analyses, you will need to move back and forth between corpus methods and text methods:
```bash
>> average = 0
>> for text in corpus.texts:
... average += text.length
...
>> average / len(corpus.texts)
6106.3448275862065
```
Here I loop across the whole corpus, finding the length of each individual text. Adding up all those lengths, I then divide that number by the number of texts in the corpus. This gives me the average number of tokens in the corpus.
You should have everything you need for the basic building blocks of text analysis here. Let me know if anything else comes up.
And a final note: be sure to re-sync your computer's copy of the repository with the master version here on GitHub when you get ready to work each day by running
```bash
$ git pull
```
## Clustering
To preform cluster analysis, type:
```bash
$ python3 cluster_process.py -t 'VER'
```
Where 'VER' will do verbs, you can insert any part of speech tag abbreviation.
<file_sep>/cluster_process.py
import os
import matplotlib.pyplot as plt
import codecs
import re
import argparse
import main as french_main
import shutil
import sys
import pandas as pd
from matplotlib.font_manager import FontProperties
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from collections import namedtuple
# CORPUS = 'processed'
MetaData = namedtuple('MetaData',
['publication', 'month', 'day', 'year'])
GenreMetaData = namedtuple('GenreMetaData',
['title', 'genre'])
ParsedMetaData = namedtuple('ParsedMetaData',
['journal_key', 'date_key'])
ParsedGenreMetaData = namedtuple('ParsedGenreMetaData',
['title', 'genre'])
def parse_args(argv=None):
"""This parses the command line."""
argv = sys.argv[1:] if argv is None else argv
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-t', '--tag', dest='tag_filter', action='store',
default='ADJ',
help='The tag to filter on')
parser.add_argument('-o', '--output', dest='processed_dir',
action='store',
default='processed',
help="""output directory to print
the processed materials too.""")
parser.add_argument('-r', '--results', dest='results_folder',
action='store',
default='clustering_results',
help='The destination for clustering results.')
parser.add_argument('-gc', '--genre_corpus', dest='genre_corpus',
action='store', default='genre_corpus',
help="""the folder containing a corpus of
other texts tagged for genre.""")
parser.add_argument('-g', '--genre_compare', dest='genre_compare',
action='store', default="True",
help="""true/false - whether you are
comparing against a genre corpus.""")
return parser.parse_args(argv)
ARGS = parse_args()
print(ARGS.genre_compare)
class ProcCorpus:
"""the object for the processed text"""
def __init__(self):
args = ARGS
print(args.genre_compare)
self.process_corpus(args)
self.filenames = self.generate_filenames(args)
self.texts = self.read_texts()
def process_corpus(self, args):
processed_dir = args.processed_dir
tag_filter = args.tag_filter
if os.path.exists(processed_dir):
shutil.rmtree(processed_dir)
os.makedirs(processed_dir)
corpus = french_main.Corpus()
# if args.genre_compare == "True" and os.path.exists('genre_corpus'):
genre_corpus = french_main.GenreCorpus()
# elif args.genre_compare == "True":
# raise ValueError("""Error: specified genre clustering but
# genre_corpus/ directory does not exist.""")
# else:
# pass
#These lines commented out because of error being raised
corpus.group_articles_by_publication()
for text in corpus.texts:
self.filter_tags(processed_dir, tag_filter, text)
if args.genre_compare == "True":
for text in genre_corpus.texts:
self.filter_tags(processed_dir, tag_filter,
text, genre_text=True)
def filter_text(self, processed_dir, tag_filter, text, genre_text=False):
"""filters a single text based on part of speech"""
to_write = []
# your if statement here is a bit wonky
for x in text.tree_tagged_tokens:
if tag_filter == 'VER':
if x.pos[0:3] == tag_filter:
to_write.append(x.lemma)
elif tag_filter == 'PRO':
if x.pos[0:3] == tag_filter:
to_write.append(x.lemma)
# if working on punctuation only, sub
elif tag_filter == '!?' or tag_filter == '?!':
mappings = {'!': 'exclamation', '?': 'question'}
if x.lemma in mappings:
to_write.append(mappings[x.lemma])
elif (tag_filter == 'PUN' or tag_filter == 'SENT') and \
(x.pos == 'PUN' or x.pos == 'SENT'):
mappings = {',': 'comma', '(': 'open_paren',
':': 'colon', '\'': 'apostrophe', '-': 'dash',
';': 'semi-colon', '/': 'forward_slash',
'!': 'exclamation', '?': 'question',
'.': 'period'}
if x.lemma in mappings:
to_write.append(mappings[x.lemma])
else:
to_write.append(x.lemma)
elif x.pos == tag_filter:
to_write.append(x.lemma)
else:
pass
return to_write
def filter_tags(self, processed_dir, tag_filter, text, genre_text=False):
"""filters parts of speech"""
print('processing ' + text.filename)
to_write = self.filter_text(processed_dir, tag_filter, text)
chunk_size = 2000
if genre_text:
i = 1
total_tokens = len(to_write)
while (i * chunk_size) < total_tokens:
start = (i - 1) * chunk_size
end = i * chunk_size
with open(processed_dir + '/' + text.filename + '_chunk_' +
str(i) + '.txt', 'w') as current_text:
current_text.write(' '.join(to_write[start:end]))
i += 1
with open(processed_dir + '/' + text.filename + '_chunk_' +
str(i) + '.txt', 'w') as current_text:
current_text.write(' '.join(to_write[(i - 1) *
chunk_size:total_tokens]))
else:
with open(processed_dir + '/' + text.filename + '.txt',
'w') as current_text:
current_text.write(' '.join(to_write))
def generate_filenames(self, args):
filenames = []
for (root, _, files) in os.walk(args.processed_dir):
for fn in files:
if fn[0] == '.' or fn[-4:] == '.png':
pass
else:
print(fn)
filenames.append(os.path.join(root, fn))
return filenames
def read_texts(self):
texts = {}
for fn in self.filenames:
with codecs.open(fn, 'r', 'utf8') as f:
texts[fn] = f.read()
return texts
# def produce_tfidfs(self):
# tfidf = TfidfVectorizer()
# tfs = tfidf.fit_transform(self.texts.values())
# return tfs
# Added the above lines to the graph_clusters function to make scope a little
#easier to deal with
def graph_clusters(self, args=ARGS):
## Added lines:
tfidf = TfidfVectorizer()
tfs = tfidf.fit_transform(self.texts.values())
numclusters = 5
## end of added
labels = self.parse_names()
# tfs = self.produce_tfidfs()
#Deleted the above line after adding produce_tfidfs lines
# will try and slot them into the nclusters
try:
fitted = KMeans(n_clusters=numclusters).fit(tfs)
except ValueError:
fitted = KMeans(n_clusters=2).fit(tfs)
classes = fitted.predict(tfs)
##Print the data regarding words found in each cluster.
centroids = fitted.cluster_centers_
print (labels)
labelsnoarrow = [x[7:] for x in labels if x[0] == ' ']
labelsnoletter = [x[2:] for x in labels if x[0] != ' ']
newlabels = labelsnoarrow + labelsnoletter
thedict = {'Cluster':classes, 'Journal and Date':newlabels}
usethis = pd.DataFrame(thedict)
order_centroids = fitted.cluster_centers_.argsort()[:, ::-1]
terms = tfidf.get_feature_names()
for i in range(numclusters):
print("Cluster %d words:" % i, end='')
for ind in order_centroids[i, :6]: #replace 6 with n words per cluster
print(" %s" % terms[ind], end = "")
print() #add whitespace
current = usethis["Cluster"] == i
showthis = usethis[current]
print (showthis)
print ()
try:
sklearn = PCA(n_components=5)
except ValueError:
sklearn = PCA(n_components=2)
try:
sklearn_transf = sklearn.fit_transform(tfs.toarray())
except:
sklearn_transf = PCA(n_components=2).fit_transform(tfs.toarray())
plt.scatter(sklearn_transf[:, 0],
sklearn_transf[:, 1], c=classes, s=75)
for i in range(len(classes)):
plt.text(sklearn_transf[i, 0], sklearn_transf[i, 1], s=labels[i], size = 'xx-small')
# plt.show()
if not os.path.exists(ARGS.results_folder):
os.makedirs(ARGS.results_folder)
if ARGS.genre_compare == "True":
plt.savefig(ARGS.results_folder + '/' + ARGS.tag_filter +
'_with_genre_corpus' + '.png')
else:
plt.savefig(ARGS.results_folder + '/' + ARGS.tag_filter + '.png')
def parse_names(self):
keys = []
for key in self.texts.keys():
print (key)
clean_key = re.sub(r'processed\/|\.txt|_chunk_[0-9]+\.txt',
'', key)
split_key = re.split(r'_', clean_key)
if split_key[1] in ['sex', 'crime', 'corruption','morality']:
split_key = re.split(r'_', clean_key)
parsed_key = GenreMetaData(split_key[0], split_key[1])
pub_mapping_dict = {'sex': 'x', 'crime': 'y',
'corruption': 'z', 'morality': 'm', 'prostitution':'p'}
result = pub_mapping_dict[parsed_key.genre] + ' ' + split_key[0]
# ['journal_key', 'date_key']
keys.append(result)
else:
split_key = re.split(r'_', clean_key)
parsed_key = MetaData(' '.join(split_key[:-3]), split_key[-3],
split_key[-2], split_key[-1])
pub_mapping_dict = {'croix': 'c', 'figaro': 'f',
'humanite': 'h', 'intransigeant': 'i',
'journal': 'j',
'matin': 'm', 'petit journal': 'pj',
'petit parisien': 'pp', 'radical': 'r',
'temps': 't'}
datekey = "-" + parsed_key.month + " " + parsed_key.day + "," + parsed_key.year
result = ParsedMetaData(pub_mapping_dict[parsed_key.publication], datekey)
# 1: June 1908
# 2: Nov. 1908
# 3: and Nov 1909
# if parsed_key.month == 'june' and parsed_key.year == '1908':
# result = ParsedMetaData(pub_mapping_dict[
# parsed_key.publication], '1')
# elif parsed_key.year == '1908' and \
# parsed_key.month == 'november':
# result = ParsedMetaData(pub_mapping_dict[
# parsed_key.publication], '2')
# elif parsed_key.year == '1909':
# result = ParsedMetaData(pub_mapping_dict[
# parsed_key.publication], '3')
# else:
# print(keys)
# print(split_key)
# print(parsed_key)
# result = 'SOMETHING HAS GONE WRONG'
# ['journal_key', 'date_key']
keys.append(" <-- " + result.journal_key + result.date_key)
return keys
def parse_shapes(self):
pass
def main():
"""Main function to be called when the script is called"""
corpus = ProcCorpus()
corpus.graph_clusters()
if __name__ == '__main__':
main()
<file_sep>/post-process.py
#!/usr/bin/env python3
# post-processing dirty OCR for C19 french newspapers project
# assumes a series of .txt files in a 'to_clean' directory at the
# same level as this script.
# import modules
import os
from os import remove
import re
import codecs
from shutil import move
# the name of the directories containing the dirty OCR'd text
CORPUS = 'to_clean'
#
patterns = [
(r'111+', 'll'),
(r'mére', 'mère'),
(r'pére', 'père'),
(r'c\b', 'e'),
(r'ct', 'et'),
(r'cn', 'en'),
(r'\.\.\b', '«'),
(r'\b\.\.', '»')
]
def all_file_names(dirname=CORPUS):
"""Reads in the files"""
for (root, _, files) in os.walk(dirname):
for fn in files:
yield os.path.join(root, fn)
def do_the_replacing(filenames):
"""takes the files in and replaces everything"""
for file in filenames:
with codecs.open(file, 'r+', 'utf8') as f:
with codecs.open(file + '_temp', 'w', 'utf8') as new_f:
for line in f.readlines():
for pattern in patterns:
line = re.sub(*pattern, line)
line = re.sub('change', 'obama', line)
new_f.write(line)
remove(file)
move(file + '_temp', file)
def main():
filenames = list(all_file_names())
do_the_replacing(filenames)
print('Some stuff was cleaned!')
if __name__ == '__main__':
main()
<file_sep>/publications.py
import main
from nltk import FreqDist
corpus = main.Corpus()
publications = {}
for text in corpus.texts:
this_publication = []
for token,tag in text.tagged_tokens:
if tag == 'ADJ':
this_publication.append(token)
if text.publication in publications:
publications[text.publication]+= this_publication
else:
publications[text.publication] = this_publication
print(publications)
for key in publications.keys():
publications[key] = FreqDist(publications[key]).most_common(50)
print(publications)
<file_sep>/stemmed_adverbs_by_publication.py
import main
from nltk import FreqDist
corpus = main.Corpus()
publications = {}
for text in corpus.texts:
this_publication = []
for token, tag in text.tagged_tokens:
if tag == 'ADV':
this_publication.append(token)
if text.month in publications:
publications[text.publication] += this_publication
else:
publications[text.publication] = this_publication
print(publications)
for key in publications.keys():
publications[key] = FreqDist(publications[key]).most_common(100)
print(publications)<file_sep>/graphing.py
import main
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
# from bokeh.plotting import figure, output_file, show
corpus = main.Corpus()
token_dict = {}
# common_lemmas = [FreqDist(text.stems).most_common(3000)
# for text in corpus.texts]
for text in corpus.texts:
token_dict[text.filename] = text.text
tfidf = TfidfVectorizer()
tfs = tfidf.fit_transform(token_dict.values())
names = [text.filename for text in corpus.texts]
# fit and then predict will try and slot them into the nclusters
fitted = KMeans(n_clusters=5).fit(tfs)
classes = fitted.predict(tfs)
sklearn = PCA(n_components=5)
sklearn_transf = sklearn.fit_transform(tfs.toarray())
plt.scatter(sklearn_transf[:,0], sklearn_transf[:,1] ,c=classes, s=500)
for i in range(len(classes)):
plt.text(sklearn_transf[i,0], sklearn_transf[i,1] , s=names[i])
plt.show()
savefig('clustering.png')<file_sep>/most_common_stemmed_nouns_by_pub.py
import main
from nltk import FreqDist
corpus = main.Corpus()
dates = {}
for text in corpus.texts:
this_date = []
current_month=str(text.year) + '-' + str(text.month)
for token, tag in text.tagged_tokens:
if tag == 'NOM':
this_date.append(token)
if text.month in dates:
dates[current_month] += this_date
else:
dates[current_month] = this_date
print(dates)
for key in dates.keys():
dates[key] = FreqDist(dates[key]).most_common(100)
print(dates) | cf30cc76395c651bf3da808a8533878c62c72232 | [
"Markdown",
"Python"
] | 12 | Python | wludh/frenchnewspapers | db9f92d39d3f6ebf7f7dd4cbdc459717c2f6c126 | 48714f27d5db676ee785e0faa53a1ba90b59c46e |
refs/heads/master | <repo_name>bleolb/Proyecto-Integrador-Defensa<file_sep>/Vista/src/app/components/form-ponente/form-ponente.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Ponentes } from 'src/app/models/ponentes';
import { environment } from 'src/environments/environment';
import { Router } from '@angular/router';
import Swal from 'sweetalert2';
@Component({
selector: 'app-form-ponente',
templateUrl: './form-ponente.component.html',
styleUrls: ['./form-ponente.component.scss']
})
export class FormPonenteComponent implements OnInit {
data: any
tabla: string
ponente: Ponentes
title: 'sweetalert'
selectedValue = null
constructor(private http: HttpClient, private router:Router) { }
ngOnInit() {
this.ponente = {
id: 0,
nombres: '',
apellidos: '',
email: '',
categoria: ['Tecnológico','Cientifico','Social','Económico'],
tema: '',
resumen: '',
institucion: '',
fecha: '',
hora: ''
};
this.tabla = 'ponentes';
}
postData = () => {
this.data = {
tabla: this.tabla,
datos: this.ponente
};
this.http.post(environment.API_URL + 'post', this.data).subscribe(resultado => {
console.log(resultado);
Swal.fire({
position: 'top-end',
type: 'success',
title: 'Registro Exitoso',
showConfirmButton: false,
timer: 1500
})
this.router.navigate(['ponencias'])
})
}
}
<file_sep>/Vista/src/app/models/ponentes.ts
export class Ponentes{
id:number;
nombres: string;
apellidos: string;
email: string;
categoria:any [];
tema: string;
resumen: string;
institucion: string;
fecha: any;
hora: any;
}<file_sep>/Vista/src/app/components/admin/editar-asistente/editar-asistente.component.ts
import { Component, OnInit } from '@angular/core';
import { environment } from 'src/environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
import { Asistentes } from 'src/app/models/asistentes';
@Component({
selector: 'app-editar-asistente',
templateUrl: './editar-asistente.component.html',
styleUrls: ['./editar-asistente.component.scss']
})
export class EditarAsistenteComponent implements OnInit {
data: any;
tabla: string;
asistente: Asistentes;
constructor(private http: HttpClient, private router: Router) { }
ngOnInit() {
this.tabla = 'asistentes';
this.asistente = {
id: 0,
nombres: '',
apellidos: '',
email: '',
};
this.actualizar();
}
editData = () => {
this.data = {
tabla: this.tabla,
datoId: [this.asistente]
};
if (this.data === null) {
console.log('no gracias');
} else {
this.http.put(environment.API_URL + 'put', this.data).subscribe(resultado => {
console.log(resultado);
alert('datos editados');
this.router.navigate(['gestion']);
});
}
}
actualizar() {
const id = localStorage.getItem('id');
console.log(id);
}
}
<file_sep>/Vista/src/app/components/ponencias/ponencias.component.ts
import { Component, OnInit } from '@angular/core';
import { environment } from 'src/environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
import Swal from 'sweetalert2';
@Component({
selector: 'app-ponencias',
templateUrl: './ponencias.component.html',
styleUrls: ['./ponencias.component.scss']
})
export class PonenciasComponent implements OnInit {
respuesta: any[];
table_ponencias: any[];
contador: number = 0
keepAsistencia: any[]
respuesta_gestion: any[];
constructor(private http: HttpClient, private router: Router) { }
ngOnInit() {
this.getData()
this.table_ponencias = [
{
id: 'Id',
nombres: 'Nombres',
apellidos: 'Apellidos',
email: 'Email',
categoria: 'Categoria',
tema: 'Tema',
resumen: 'Resumen',
institucion: 'Institución'
}]
}
getData = () => {
const tabla = 'ponentes';
this.http.get<any>(environment.API_URL + `get?tabla=${tabla}`).subscribe(data => {
this.respuesta = data.datos;
console.log(this.respuesta);
});
const tablaGestion = 'gestion'
this.http.get<any>(environment.API_URL + `get?tabla=${tablaGestion}`).subscribe(data => {
this.respuesta_gestion = data.datos;
console.log(this.respuesta_gestion);
});
}
cambiar() {
if (this.contador <= 19) {
this.contador++
Swal.fire({
position: 'top-end',
type: 'success',
title: 'Asistencia Programada',
showConfirmButton: false,
timer: 1500
})
this.router.navigate(['home'])
console.log(this.contador)
} else {
alert('Congreso Lleno')
}
}
}
<file_sep>/Servidor/migrations/20190716222205_cronograma.js
exports.up = function(knex, Promise) {
return Promise.all([
knex.schema.createTable('cronograma', function(t) {
t.bigIncrements('id').primary();
t.string('temaPonencia').notNullable();
t.date('fecha').notNullable();
t.time('hora').notNullable();
t.string('autor').notNullable();
t.integer('idCongreso').references('id').inTable('congreso');
})
]);
};
exports.down = function(knex, Promise) {
return Promise.all([
knex.schema.dropTable('cronograma'),
]);
};<file_sep>/Vista/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { NgxPaginationModule } from 'ngx-pagination';
import { ReactiveFormsModule } from '@angular/forms'
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';
import { MenuComponent } from './components/menu/menu.component';
import { FormPonenteComponent } from './components/form-ponente/form-ponente.component';
import { PonenciasComponent } from './components/ponencias/ponencias.component';
import { FormAsistenteComponent } from './components/form-asistente/form-asistente.component';
import { InformacionComponent } from './components/informacion/informacion.component';
import { GestionGeneralComponent } from './components/admin/gestion-general/gestion-general.component';
import { EditarPonenteComponent } from './components/admin/editar-ponente/editar-ponente.component';
import { EditarAsistenteComponent } from './components/admin/editar-asistente/editar-asistente.component';
import { HeaderComponent } from './components/header/header.component';
import { LoginComponent } from './components/admin/login/login.component';
import { ContactFormComponent } from './components/contact-form/contact-form.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
MenuComponent,
FormPonenteComponent,
PonenciasComponent,
FormAsistenteComponent,
InformacionComponent,
GestionGeneralComponent,
EditarPonenteComponent,
EditarAsistenteComponent,
HeaderComponent,
LoginComponent,
ContactFormComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule,
NgxPaginationModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/Vista/src/app/components/form-asistente/form-asistente.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Asistentes } from 'src/app/models/asistentes';
import { environment } from 'src/environments/environment';
import { Router } from '@angular/router';
import Swal from 'sweetalert2'
@Component({
selector: 'app-form-asistente',
templateUrl: './form-asistente.component.html',
styleUrls: ['./form-asistente.component.scss']
})
export class FormAsistenteComponent implements OnInit {
data: any
tabla: string
asistente: Asistentes
title: 'sweetalert'
constructor(private http: HttpClient, private router:Router) { }
ngOnInit() {
this.asistente = {
id:0,
nombres: '',
apellidos: '',
email: ''
};
this.tabla = 'asistentes';
}
postData = () => {
this.data = {
tabla: this.tabla,
datos: this.asistente
};
this.http.post(environment.API_URL + 'post', this.data).subscribe(resultado => {
console.log(resultado);
Swal.fire({
position: 'top-end',
type: 'success',
title: 'Registro Exitoso',
showConfirmButton: false,
timer: 1500
})
this.router.navigate(['ponencias'])
})
}
}
<file_sep>/Vista/src/app/components/admin/editar-ponente/editar-ponente.component.ts
import { Component, OnInit } from '@angular/core';
import { environment } from 'src/environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
import { Ponentes } from 'src/app/models/ponentes';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-editar-ponente',
templateUrl: './editar-ponente.component.html',
styleUrls: ['./editar-ponente.component.scss']
})
export class EditarPonenteComponent implements OnInit {
data: any;
tabla: string;
ponente: Ponentes;
respuesta: any[];
editarForm: FormGroup;
nombres: string;
apellidos: string;
email: string;
categoria: string;
tema: string;
resumen: string;
institucion: string;
fecha: any;
hora: any;
constructor(private http: HttpClient, private router: Router, private fb: FormBuilder) { }
ngOnInit() {
this.tabla = 'ponentes';
this.actualizar();
this.formularioEdit();
}
formularioEdit() {
this.editarForm = this.fb.group({
nombres: ['', [Validators.required]],
apellidos: ['', [Validators.required]],
email: ['', [Validators.required]],
categoria: ['', [Validators.required]],
tema: ['', [Validators.required]],
resumen: ['', [Validators.required]],
institucion: ['', [Validators.required]],
fecha: ['', [Validators.required]],
hora: ['', [Validators.required]],
});
}
editData = (id) => {
console.log(id);
const nombres = this.editarForm.get('nombres').value;
const apellidos = this.editarForm.get('apellidos').value;
const email = this.editarForm.get('email').value;
const categoria = this.editarForm.get('categoria').value;
const tema = this.editarForm.get('tema').value;
const resumen = this.editarForm.get('resumen').value;
const institucion = this.editarForm.get('institucion').value;
const fecha = this.editarForm.get('fecha').value;
const hora = this.editarForm.get('hora').value;
this.data = {
tabla: this.tabla,
datoId: [{
id: id,
nombres: nombres,
apellidos: apellidos,
email: email,
categoria: categoria,
tema: tema,
resumen: resumen,
institucion: institucion,
fecha: fecha,
hora: hora
}]
};
if (this.data === null) {
console.log('datos no encontrados');
} else {
console.log(this.data);
this.http.put(environment.API_URL + 'put', this.data).subscribe(resultado => {
console.log(resultado);
alert('datos editados');
this.router.navigate(['gestion']);
});
}
}
actualizar() {
const id = localStorage.getItem('id');
console.log(localStorage);
const tabla = 'ponentes';
this.http.get<any>(environment.API_URL + `routebyid?tabla=${tabla}&id=` + id).subscribe(data => {
this.respuesta = data.datos;
console.log(this.respuesta);
console.log(id);
console.log(data);
});
}
}<file_sep>/Vista/src/app/models/images.ts
export class Images{
id: number
}<file_sep>/Servidor/migrations/20190804194240_users.js
exports.up = function (knex, Promise) {
return Promise.all([
knex.schema.createTable('users', function (t) {
t.bigIncrements('id').primary();
t.string('user');
t.string('password');
})
]);
};
exports.down = function (knex, Promise) {
return Promise.all([
knex.schema.dropTable('users')
]);
};<file_sep>/Vista/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { FormPonenteComponent } from './components/form-ponente/form-ponente.component';
import { PonenciasComponent } from './components/ponencias/ponencias.component';
import { InformacionComponent } from './components/informacion/informacion.component';
import { FormAsistenteComponent } from './components/form-asistente/form-asistente.component';
import { GestionGeneralComponent } from './components/admin/gestion-general/gestion-general.component';
import { EditarPonenteComponent } from './components/admin/editar-ponente/editar-ponente.component';
import { HeaderComponent } from './components/header/header.component';
import { LoginComponent } from './components/admin/login/login.component';
import { ContactFormComponent } from './components/contact-form/contact-form.component';
import { EditarAsistenteComponent } from './components/admin/editar-asistente/editar-asistente.component';
const routes: Routes = [
{path: 'home', component:HomeComponent},
{path: 'form-ponente', component:FormPonenteComponent},
{path: 'ponencias', component:PonenciasComponent},
{path: 'informacion', component:InformacionComponent},
{path: 'form-asistente', component:FormAsistenteComponent},
{path: 'gestion', component:GestionGeneralComponent},
{path: 'editar-ponente', component:EditarPonenteComponent},
{path: 'editar-asistente', component:EditarAsistenteComponent},
{path: 'hd', component:HeaderComponent},
{path: 'login', component:LoginComponent},
{path: 'contact', component:ContactFormComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/Vista/src/app/components/contact-form/contact-form.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['./contact-form.component.scss']
})
export class ContactFormComponent implements OnInit {
respuesta_gestion: any[];
constructor(private http:HttpClient) { }
ngOnInit() {
this.getData()
}
getData = () => {
const tablaGestion = 'gestion'
this.http.get<any>(environment.API_URL + `get?tabla=${tablaGestion}`).subscribe(data => {
this.respuesta_gestion = data.datos;
console.log(this.respuesta_gestion);
});
}
}
<file_sep>/Servidor/seeds/ponencias.js
exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('gyba.ponencias').del()
.then(function () {
// Inserts seed entries
return knex('gyba.ponencias').insert([
{
tema: 'Debate',
idPonente: 1,
idCongreso: 1,
idAsistente: 1
}
]);
});
};
<file_sep>/Vista/src/app/components/admin/gestion-general/gestion-general.component.ts
import { Component, OnInit } from '@angular/core';
import { environment } from 'src/environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
import { Ponentes } from 'src/app/models/ponentes';
import { Asistentes } from 'src/app/models/asistentes';
import { Gestion } from 'src/app/models/gestionParametros';
import { DomSanitizer } from '@angular/platform-browser';
import Swal from 'sweetalert2';
import jsPDF from 'jspdf';
import { Images } from 'src/app/models/images';
@Component({
selector: 'app-gestion-general',
templateUrl: './gestion-general.component.html',
styleUrls: ['./gestion-general.component.scss']
})
export class GestionGeneralComponent implements OnInit {
base64textString: String = "";
ponente: Ponentes;
deletePonentes: any;
tablaPonentes: string;
asistente: Asistentes;
deleteAsistentes: any;
tablaAsistentes: string;
data: any;
datoEliminar: any;
table_ponentes: any[];
respuesta_ponentes: any[];
table_asistentes: any[];
respuesta_asistentes: any[];
/*======================== GESTION PARAMETROS =======================*/
dataGestion: any
gestion: Gestion;
tablaGestion: string;
imagen: Images
/*======================== FIN GESTION PARAMETROS =======================*/
constructor(
private http: HttpClient,
private router: Router,
private _sanitizer: DomSanitizer) {
// this.files = [];
}
ngOnInit() {
this.getData();
this.table_ponentes = [
{
id: 'Id',
nombres: 'Nombres',
apellidos: 'Apellidos',
email: 'Email',
categoria: 'Categoria',
tema: 'Tema',
resumen: 'Resumen',
institucion: 'Institución',
fecha: 'Fecha',
hora: 'Hora'
}]
this.table_asistentes = [
{
id: 'Id',
nombres: 'Nombres',
apellidos: 'Apellidos',
email: 'Email'
}]
this.tablaPonentes = 'ponentes';
this.tablaAsistentes = 'asistentes'
this.deletePonentes = {
tabla: this.tablaPonentes,
id: this.datoEliminar
};
this.deleteAsistentes = {
tabla: this.tablaAsistentes,
id: this.datoEliminar
};
/*======================== GESTION PARAMETROS =======================*/
this.gestion = {
id: 0,
tituloCongreso: '',
direccionCorreo: '',
paginaWeb: '',
informacion: '',
tituloCronograma: '',
telefono: '',
correoUno: '',
correoDos: '',
};
this.tablaGestion = 'gestion';
/*======================== FIN GESTION PARAMETROS =======================*/
this.imagen = {
id: 0
};
}
getData = () => {
const tablaPonente = 'ponentes';
const tablaAsistente = 'asistentes';
this.http.get<any>(environment.API_URL + `get?tabla=${tablaPonente}`).subscribe(data => {
this.respuesta_ponentes = data.datos;
console.log(this.respuesta_ponentes);
});
this.http.get<any>(environment.API_URL + `get?tabla=${tablaAsistente}`).subscribe(data => {
this.respuesta_asistentes = data.datos;
console.log(this.respuesta_asistentes);
});
}
editarPonente = (id: any) => {
this.data = {
tabla: this.tablaPonentes,
idPonente: id
};
console.log(this.data);
localStorage.removeItem('id');
localStorage.setItem('id', this.data.idPonente.toString());
this.router.navigate(['editar-ponente']);
}
editarAsistente = (id: any) => {
this.data = {
tabla: this.tablaAsistentes,
idAsistente: id
};
console.log(this.data);
localStorage.removeItem('id');
localStorage.setItem('id', this.data.idAsistente.toString());
this.router.navigate(['editar-asistente']);
}
borrarPonente = (id: number) => {
console.log(id);
this.data = {
tabla: this.tablaPonentes,
datoId: id
};
const httpOptions = {
headers: new HttpHeaders({ 'Content-type': 'aplication/json' })
};
console.log(this.data);
if (this.data !== undefined) {
this.http.post(environment.API_URL + 'delete', this.data).subscribe(resultado => {
console.log(resultado);
window.location.reload()
});
}
}
borrarAsistente = (id: number) => {
console.log(id);
this.data = {
tabla: this.tablaAsistentes,
datoId: id
};
const httpOptions = {
headers: new HttpHeaders({ 'Content-type': 'aplication/json' })
};
console.log(this.data);
if (this.data !== undefined) {
this.http.post(environment.API_URL + 'delete', this.data).subscribe(resultado => {
console.log(resultado);
window.location.reload()
});
}
}
handleFileSelect(evt) {
var files = evt.target.files;
var file = files[0];
if (files && file) {
var reader = new FileReader();
reader.onload = this._handleReaderLoaded.bind(this);
reader.readAsBinaryString(file);
}
}
_handleReaderLoaded(readerEvt) {
var binaryString = readerEvt.target.result;
this.base64textString = btoa(binaryString);
}
addImage = (id: number) => {
console.log(id);
const tabla = 'images';
const data = {tabla: tabla, datos: [{id: this.imagen.id, nombre: this.base64textString
}]
};
this.http.post(environment.API_URL + 'post', data).subscribe(resultado => {
console.log(resultado);
this.router.navigate(['gestion']);
});
}
crearPDF() {
const doc = new jsPDF({
orientation: 'L',
unit: 'mm',
format: 'a2',
putOnlyUsedFonts: true,
compress: true
});
var elementHandler = {
'#ignorePDF': function (element, renderer) {
return true;
}
};
var source = window.document.getElementsByTagName("body")[0];
doc.fromHTML(
source,
15,
15,
{
'width': 180, 'elementHandlers': elementHandler
});
doc.output("dataurlnewwindow");
}
/*======================== GESTION PARAMETROS =======================*/
postDataGestion = () => {
this.dataGestion = {
tabla: this.tablaGestion,
datos: this.gestion
};
this.http.post(environment.API_URL + 'post', this.dataGestion).subscribe(resultado => {
console.log(resultado);
window.location.reload()
})
}
/*======================== FIN GESTION PARAMETROS =======================*/
}
<file_sep>/Servidor/migrations/20190716222255_inscripcion.js
exports.up = function(knex, Promise) {
return Promise.all([
knex.schema.createTable('inscripcion', function(t) {
t.bigIncrements('id').primary();
t.integer('idAsistente').references('id').inTable('asistentes');
t.integer('idPonente').references('id').inTable('ponentes');
t.integer('idCongreso').references('id').inTable('congreso');
})
]);
};
exports.down = function(knex, Promise) {
return Promise.all([
knex.schema.dropTable('inscripcion'),
]);
};<file_sep>/Servidor/seeds/ponentes.js
exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('gyba.ponentes').del()
.then(function () {
// Inserts seed entries
return knex('gyba.ponentes').insert([
{
id: 1,
numIdentificacion: '1723538581',
nombres: '<NAME>',
apellidos: '<NAME>',
telefono: '0958758883',
email: '<EMAIL>'
}
]);
});
};
<file_sep>/Servidor/migrations/20190716221428_congreso.js
exports.up = function(knex, Promise) {
return Promise.all([
knex.schema.createTable('congreso', function(t) {
t.bigIncrements('id').primary();
t.string('nombre');
t.string('direccion');
})
]);
};
exports.down = function(knex, Promise) {
return Promise.all([
knex.schema.dropTable('congreso')
]);
};<file_sep>/Vista/src/app/components/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
public titulo: string
respuesta: any[];
imagen: any
respuesta_imagenes: any[];
respuesta_gestion: any[];
constructor(private http: HttpClient) {
this.titulo = "Primer Congreso Institucional Yavirac"
}
ngOnInit() {
this.getData()
}
getData = () => {
const tabla = 'images';
this.http.get<any>(environment.API_URL + `getorderbyid?tabla=${tabla}`).subscribe(data => {
this.respuesta_imagenes = data.datos;
console.log(this.respuesta_imagenes);
});
const tablaGestion = 'gestion'
this.http.get<any>(environment.API_URL + `get?tabla=${tablaGestion}`).subscribe(data => {
this.respuesta_gestion = data.datos;
console.log(this.respuesta_gestion);
});
}
}
<file_sep>/Servidor/seeds/congreso.js
exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('gyba.congreso').del()
.then(function () {
// Inserts seed entries
return knex('gyba.congreso').insert([
{
nombre: 'Yavirac',
direccion: '<NAME>'
}
]);
});
};
<file_sep>/Servidor/migrations/20190806223723_gestion.js
exports.up = function(knex, Promise) {
return Promise.all([
knex.schema.createTable('gestion', function(t) {
t.bigIncrements('id');
t.text('tituloCongreso').notNullable();
t.text('direccionCorreo').notNullable();
t.text('paginaWeb').notNullable().unique();
t.text('informacion').notNullable();
t.text('tituloCronograma').notNullable();
t.text('telefono').notNullable();
t.text('correoUno').notNullable();
t.text('correoDos').notNullable();
})
]);
};
exports.down = function(knex, Promise) {
return Promise.all([
knex.schema.dropTable('gestion'),
]);
};<file_sep>/Vista/src/app/models/gestionParametros.ts
export class Gestion{
id: number;
tituloCongreso: string;
direccionCorreo: string;
paginaWeb: string;
informacion: string;
tituloCronograma: string;
telefono: string;
correoUno: string;
correoDos: string;
} | 4a6e9c15e7224c3fecb56b771c395cd94557846a | [
"JavaScript",
"TypeScript"
] | 21 | TypeScript | bleolb/Proyecto-Integrador-Defensa | beed491f215efcdbaf2db026facaadaba1f3413c | 7c0c61b84981d03d38d17d700eb341d5d39df08c |
refs/heads/master | <repo_name>mochi-x/template-cli-python<file_sep>/setup.py
from setuptools import setup
setup(entry_points={'console_scripts': ['cliname = app:main']})
<file_sep>/README.md
# template-cli-python<file_sep>/app.py
import os
import sys
import argparse
def main():
parser = createParseSetting()
args = parser.parse_args()
if args.COMMAND:
print('--- args.COMMAND ---')
print(args.COMMAND)
print('--------------------')
else:
if parser.print_help() != None:
print('------- Help -------')
showHelp(parser)
print('--------------------')
def showHelp(parser):
print(parser.print_help())
def createParseSetting():
p = argparse.ArgumentParser()
p.add_argument('COMMAND', help='')
return p | 5694685580acc7a70ba7ec49e730b06c4944393b | [
"Markdown",
"Python"
] | 3 | Python | mochi-x/template-cli-python | 4b8da645f384c63c60f096beecbd92edf7b1d616 | 01b2f21768128ac31c64af9d3440021c0062fbcc |
refs/heads/master | <file_sep>package com.everis.ideaton.controller;
import com.everis.ideaton.service.types.TypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@Slf4j
@RequestMapping("/types")
@RestController
@Api(value = "type", description = "types operations")
public class EnumController {
private final TypeService typeService;
@Autowired
public EnumController(TypeService typeService) {
this.typeService = typeService;
}
@ApiOperation("Returns all social platform types")
@RequestMapping(value = "/socialPlatform", method = RequestMethod.GET)
public List<String> getSocialPlatformTypes() throws RuntimeException{
return typeService.getSocialPlatformTypes();
}
@ApiOperation("Returns all state types")
@RequestMapping(value = "/state}", method = RequestMethod.GET)
public List<String> getStateTypes() throws RuntimeException{
return typeService.getStateTypeTypes();
}
@ApiOperation("Returns all category types")
@RequestMapping(value = "/category", method = RequestMethod.GET)
public List<String> getCategoryTypes() throws RuntimeException{
return typeService.getCategoryTypes();
}
@ApiOperation("Returns all role types")
@RequestMapping(value = "/role", method = RequestMethod.GET)
public List<String> getRoleTypes() throws RuntimeException{
return typeService.getRoleTypes();
}
}
<file_sep>package com.everis.ideaton.service.types;
import java.util.List;
public interface TypeService {
List<String> getCategoryTypes();
List<String> getRoleTypes();
List<String> getStateTypeTypes();
List<String> getSocialPlatformTypes();
}
<file_sep>package com.everis.ideaton.repository;
import com.everis.ideaton.domain.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface MongoUserRepository extends MongoRepository<User, String> {}
<file_sep>package com.everis.ideaton.controller;
import com.everis.ideaton.domain.User;
import com.everis.ideaton.domain.dto.UserDto;
import com.everis.ideaton.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@RequestMapping("/user")
@RestController
@Api(value = "user", description = "user operations")
@Slf4j
public class UserController {
@Autowired
private UserService userService;
@ApiOperation("Returns all the users")
@RequestMapping(method = RequestMethod.GET)
public List<User> getUsers() throws RuntimeException{
return userService.getAllUsers();
}
@ApiOperation("Find User by Id")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User getUserById(@PathVariable("id") String id) throws RuntimeException{
return userService.getUserById(id);
}
@ApiOperation("Add a new User")
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(method = RequestMethod.POST)
public User saveUser(@RequestBody UserDto userDto, HttpServletResponse response) throws RuntimeException {
return userService.saveUser(userDto);
}
@ApiOperation("Updates a User")
@RequestMapping(method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.NO_CONTENT)
public User updateUser(@RequestBody UserDto userDto, HttpServletResponse response) throws RuntimeException {
return userService.updateUser(userDto);
}
@ApiOperation("Deletes an existing User")
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public void deleteUser(@PathVariable("id") String id) throws RuntimeException {
userService.deleteUser(id);
}
}
<file_sep>package com.everis.ideaton.repository;
import com.everis.ideaton.domain.Idea;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface MongoIdeaRepository extends MongoRepository<Idea, String> {
}
<file_sep>mongo.url=localhost
mongo.port=27017
mongo.dbname=ideaton<file_sep>package com.everis.ideaton.domain;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public enum Category {
ENTRETENCION("Entretencion"), EDUCACION("Educacion"), TRNSPORTE_Y_ACCESIBILIDAD("Transporte y accesibilidad"),
TRABAJO("Trabajo"), COMUNICACIONES("Comunicaciones"), VIDA_DIARIA("Vida diaria");
private final String categoryType;
Category(String categoryType) {
this.categoryType = categoryType;
}
public String getCategoryType() {
return this.categoryType;
}
}
<file_sep>package com.everis.ideaton.domain;
import lombok.Builder;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@Builder
public final class Like {
@Id
private final String id;
private final User user;
private final SocialPlatform votedWith;
public Like() {
this.id = null;
this.user = null;
this.votedWith = null;
}
private Like(String id, User user, SocialPlatform votedWith) {
this.id = id;
this.user = user;
this.votedWith = votedWith;
}
public static Like createLikeInstance(String id, User user, SocialPlatform votedWith){
return new Like(id, user, votedWith);
}
public String getId() {
return id;
}
public User getUser() {
return user;
}
public SocialPlatform getVotedWith() {
return votedWith;
}
}
<file_sep>package com.everis.ideaton.domain;
import lombok.Builder;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@Builder
public final class Video {
@Id
private final String id;
private final String link;
public Video() {
this.id = null;
this.link = null;
}
private Video(String id, String link) {
this.id = id;
this.link = link;
}
public static Video createVideoInstance(String id, String link){
return new Video(id, link);
}
public String getId() {
return id;
}
public String getLink() {
return link;
}
}
<file_sep>package com.everis.ideaton.domain;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public enum StateType {
APPROVED("Approved"), REJECTED("Rejected"), PENDING("Pending");
private final String stateTipe;
StateType(String stateTipe) {
this.stateTipe = stateTipe;
}
public String getStateTipe() {
return stateTipe;
}
}
<file_sep>package com.everis.ideaton.service;
import com.everis.ideaton.domain.*;
import com.everis.ideaton.domain.dto.*;
import com.everis.ideaton.repository.MongoIdeaRepository;
import com.everis.ideaton.repository.MongoUserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.List;
@Service
@Transactional
@Slf4j
public class IdeaServiceImpl implements IdeaService {
private final MongoIdeaRepository mongoIdeaRepository;
private final MongoUserRepository mongoUserRepository;
@Autowired
public IdeaServiceImpl(MongoIdeaRepository mongoIdeaRepository, MongoUserRepository mongoUserRepository) {
this.mongoIdeaRepository = mongoIdeaRepository;
this.mongoUserRepository = mongoUserRepository;
}
@Override
public List<Idea> getAllIdeas() throws RuntimeException {
return mongoIdeaRepository.findAll();
}
@Override
public Idea getIdeaById(String id) throws RuntimeException {
return mongoIdeaRepository.findOne(id);
}
@Override
public Idea saveIdea(IdeaDto ideaDto) throws RuntimeException {
User user = new User();
try {
user = mongoUserRepository.findOne(ideaDto.getUploadedById());
} catch (Exception e) {
log.error(e.getMessage());
}
Idea idea = Idea.builder().title(ideaDto.getTitle()).description(ideaDto.getDescription())
.category(ideaDto.getCategory()).uploadedBy(user).build();
return mongoIdeaRepository.save(idea);
}
@Override
public boolean deleteIdea(String id) throws RuntimeException {
mongoIdeaRepository.delete(id);
return true;
}
@Override
public Idea updateIdea(IdeaDto ideaDto) throws RuntimeException {
return saveIdea(ideaDto);
}
@Override
public Idea addImage(ImageDto imageDto, String ideaId) throws RuntimeException {
// validate the amount of images. Put a limit
Idea idea = mongoIdeaRepository.findOne(ideaId);
List<Image> images = idea.getImages();
Image image = Image.builder().link(imageDto.getLink()).build();
images.add(image);
Idea ideaToSave = getIdea(idea, images, null, null, null, 0);
return mongoIdeaRepository.save(ideaToSave);
}
@Override
public Idea addVideo(VideoDto videoDtoeo, String ideaId) {
// validate the amount of images. Put a limit
Idea idea = mongoIdeaRepository.findOne(ideaId);
Video video = Video.builder().link(videoDtoeo.getLink()).build();
Idea ideaToSave = getIdea(idea, null, video, null, null, 0);
return mongoIdeaRepository.save(ideaToSave);
}
@Override
public Idea giveALike(LikeDto likeDto, String ideaId) {
Idea idea = mongoIdeaRepository.findOne(ideaId);
User user = mongoUserRepository.findOne(likeDto.getUserId());
List<Like> likes = idea.getLikes();
Like like = Like.builder().user(user).votedWith(likeDto.getVotedWith()).build();
likes.add(like);
Idea ideaToSave = getIdea(idea, null, null, likes, null, idea.getTotalVotes() + 1);
return mongoIdeaRepository.save(ideaToSave);
}
@Override
public Idea postCommentary(CommentaryDto commentaryDto, String ideaId) {
Idea idea = mongoIdeaRepository.findOne(ideaId);
User user = mongoUserRepository.findOne(commentaryDto.getPostedByUserId());
List<Commentary> comments = idea.getComments();
Commentary commentary = Commentary.builder().date(new SimpleDateFormat().toString()).postedBy(user)
.text(commentaryDto.getText()).build();
comments.add(commentary);
Idea ideaToSave = getIdea(idea, null, null, null, comments, 0);
return mongoIdeaRepository.save(ideaToSave);
}
@Override
public int getTotalAmountLikes(String ideaId) {
return mongoIdeaRepository.findOne(ideaId).getTotalVotes();
}
private Idea getIdea(Idea idea, List<Image> images, Video video, List<Like> likes, List<Commentary> commentaries,int totalVotes) {
if(images == null) images = idea.getImages();
if(video == null) video = idea.getVideo();
if(likes == null) likes = idea.getLikes();
if(commentaries == null) commentaries = idea.getComments();
if(totalVotes == 0) totalVotes = idea.getTotalVotes();
return Idea.builder().id(idea.getId()).title(idea.getTitle()).description(idea.getDescription())
.category(idea.getCategory()).uploadedBy(idea.getUploadedBy()).video(video).images(images)
.likes(likes).state(idea.getState()).date(idea.getDate()).comments(commentaries)
.totalVotes(totalVotes).build();
}
}
<file_sep>package com.everis.ideaton.repository;
import com.everis.ideaton.domain.Like;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface MongoLikeRepository extends MongoRepository<Like, String> {
}
<file_sep>package com.everis.ideaton.domain.dto;
public final class CommentaryDto {
private final String postedByUserId;
private final String text;
private CommentaryDto(String postedByUserId, String text) {
this.postedByUserId = postedByUserId;
this.text = text;
}
public static CommentaryDto createCommentaryDtoInstance(String postedByUserId, String text){
return new CommentaryDto(postedByUserId, text);
}
public String getPostedByUserId() {
return postedByUserId;
}
public String getText() {
return text;
}
}
<file_sep>package com.everis.ideaton.service;
import com.everis.ideaton.domain.User;
import com.everis.ideaton.domain.dto.UserDto;
import java.util.List;
public interface UserService {
List<User> getAllUsers() throws RuntimeException;
User getUserById(String id) throws RuntimeException;
User saveUser(UserDto userDto) throws RuntimeException;
boolean deleteUser(String id) throws RuntimeException;
User updateUser(UserDto userDto) throws RuntimeException;
}
<file_sep>package com.everis.ideaton.domain;
import lombok.Builder;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@Builder
public final class Commentary {
@Id
private final String id;
private final User postedBy;
private final User approvedBy;
private final String text;
private final String date;
public Commentary() {
this.id = null;
this.postedBy = null;
this.approvedBy = null;
this.text = null;
this.date = null;
}
private Commentary(String id, User postedBy, User approvedBy, String text, String date) {
this.id = id;
this.postedBy = postedBy;
this.approvedBy = approvedBy;
this.text = text;
this.date = date;
}
public static Commentary createCommentaryInstance(String id, User postedBy, User approvedBy, String text, String date){
return new Commentary(id, postedBy, approvedBy, text, date);
}
public String getId() {
return id;
}
public User getPostedBy() {
return postedBy;
}
public User getApprovedBy() {
return approvedBy;
}
public String getText() {
return text;
}
public String getDate() {
return date;
}
}
<file_sep>package com.everis.ideaton.configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.context.annotation.*;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.config.annotation.*;
import javax.xml.transform.Source;
import java.util.List;
@Configuration
@EnableWebMvc
@Import({SwaggerConfiguration.class, MongoConfiguration.class/*, SecurityConfig.class*/})
/*@ComponentScan({ "com.everis.ideaton.controller", "com.everis.ideaton.repository",
"com.everis.ideaton.service"})*/
@ComponentScan(
basePackages = { "com.everis.ideaton" },
useDefaultFilters = false,
includeFilters = { @ComponentScan.Filter(
type = FilterType.ANNOTATION,
value = { Configuration.class, Controller.class,
Component.class, Service.class, Repository.class }) })
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false).
favorParameter(true).
parameterName("mediaType").
ignoreAcceptHeader(true).
useJaf(false).
defaultContentType(MediaType.APPLICATION_JSON).
mediaType("xml", MediaType.APPLICATION_XML).
mediaType("json", MediaType.APPLICATION_JSON);
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setWriteAcceptCharset(false);
converters.add(new ByteArrayHttpMessageConverter());
converters.add(stringConverter);
converters.add(new ResourceHttpMessageConverter());
converters.add(new SourceHttpMessageConverter<Source>());
converters.add(new AllEncompassingFormHttpMessageConverter());
converters.add(jackson2Converter());
}
@Bean
public MappingJackson2HttpMessageConverter jackson2Converter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper());
return converter;
}
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
return objectMapper;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
<file_sep>package com.everis.ideaton.service.types;
import com.everis.ideaton.domain.Video;
import com.everis.ideaton.domain.dto.VideoDto;
import java.util.List;
public interface VideoService {
public List<Video> getAllVideos() throws RuntimeException;
public Video getVideoById(String id) throws RuntimeException;
public Video saveVideo(VideoDto videoDto) throws RuntimeException;
public boolean deleteVideo(String id) throws RuntimeException;
public Video updateVideo(VideoDto videoDto) throws RuntimeException;
}
<file_sep># digital-architecture
This is a Gradle based project that uses Spring MVC for exposing a Rest api and Spring Data for integrate with a MongoDB database.
For setting your enviroment you need the following:
* Java 8
* Install gradle
* Install MongoDB. You can follow the instructions given on the Wiki of this repository
* Tomcat
For runing the project:
* Gradle build
* Deploy the .war file that is in \build\libs some web container like Tomcat or use any embedded container like Jetty.
See the documentation and test the API
* http://localhost:8080/swagger-ui.html
<file_sep>package com.everis.ideaton.domain;
import lombok.Builder;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.List;
@Document
@Builder
public final class Idea {
@Id
private final String id;
private final String title;
private final String description;
private final Category category;
private final User uploadedBy;
private final Video video;
private final List<Image> images;
private final List<Like> likes;
private final State state;
private final String date;
private final List<Commentary> comments;
private final int totalVotes;
public Idea() {
this.totalVotes = 0;
this.state = null;
this.date = null;
this.comments = null;
this.id = null;
this.title = null;
this.description = null;
this.category = null;
this.uploadedBy = null;
this.video = null;
this.images = null;
this.likes = null;
}
private Idea(String id, String title, String description, Category category, User uploadedBy,
Video video, List<Image> images, List<Like> likes, State state, String date, List<Commentary> comments, int totalVotes) {
this.id = id;
this.title = title;
this.description = description;
this.category = category;
this.uploadedBy = uploadedBy;
this.video = video;
this.images = images;
this.likes = likes;
this.state = state;
this.date = date;
this.comments = comments;
this.totalVotes = totalVotes;
}
public static Idea createIdeaInstance(String id, String title, String description, Category category,
User uploadedBy, Video video, List<Image> images,
List<Like> likes, State state, String date, List<Commentary> comments, int totalVotes){
return new Idea(id, title, description, category, uploadedBy, video, images, likes, state, date, comments, totalVotes);
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public User getUploadedBy() {
return uploadedBy;
}
public Category getCategory() {
return category;
}
public Video getVideo() {
return video;
}
public List<Image> getImages() {
return images;
}
public List<Like> getLikes() {
return likes;
}
public State getState() {
return state;
}
public String getDate() {
return date;
}
public List<Commentary> getComments() {
return comments;
}
public int getTotalVotes() {
return totalVotes;
}
}
<file_sep>package com.everis.ideaton.configuration;
import com.mongodb.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
//@Configuration
//@Profile("openshift")
//@EnableMongoRepositories(mongoTemplateRef = "getMongoTemplate", basePackages = "com.everis.ideaton.repository")
public class MongoConfigurationProduction {
public
@Bean
MongoDbFactory getMongoDbFactory() throws Exception {
String openshiftMongoDbHost = System.getenv("OPENSHIFT_MONGODB_DB_HOST");
int openshiftMongoDbPort = Integer.parseInt(System.getenv("OPENSHIFT_MONGODB_DB_PORT"));
String username = System.getenv("OPENSHIFT_MONGODB_DB_USERNAME");
String password = System.getenv("OPENSHIFT_MONGODB_DB_PASSWORD");
MongoClient mongo = new MongoClient(openshiftMongoDbHost, openshiftMongoDbPort);
UserCredentials userCredentials = new UserCredentials(username, password);
String databaseName = System.getenv("OPENSHIFT_APP_NAME");
return new SimpleMongoDbFactory(mongo, databaseName, userCredentials);
}
public
@Bean
MongoTemplate getMongoTemplate() throws Exception {
return new MongoTemplate(getMongoDbFactory());
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
<file_sep>group 'spring-5'
//version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'org.akhikhl.gretty'
apply plugin: 'war'
//apply plugin: 'jetty'
//sourceCompatibility = 1.8
task wrapper(type: Wrapper) {
gradleVersion = '2.13' //we want gradle 2.13 to run this project
}
//Gretty Embedded Jetty
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'org.akhikhl.gretty:gretty:+'
}
}
gretty {
port = 8081
contextPath = 'spring4'
servletContainer = 'jetty9' //tomcat7 or tomcat8
}
repositories {
mavenLocal()
mavenCentral()
jcenter()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile group: 'org.mockito', name: 'mockito-all', version: '1.10.19'
compileOnly "org.projectlombok:lombok:1.16.10"
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.21'
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.6.2'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.6.2'
compile group: 'org.hibernate', name: 'hibernate-validator', version: '5.2.4.Final'
compile group: 'org.springframework', name: 'spring-core', version: '4.2.6.RELEASE'
compile group: 'org.springframework', name: 'spring-webmvc', version: '4.2.6.RELEASE'
compile group: 'org.springframework.data', name: 'spring-data-mongodb', version: '1.9.2.RELEASE'
compile group: 'org.springframework.hateoas', name: 'spring-hateoas', version: '0.21.0.RELEASE'
compile group: 'org.springframework.security', name: 'spring-security-web', version: '4.1.1.RELEASE'
compile group: 'org.springframework.security', name: 'spring-security-config', version: '4.1.1.RELEASE'
compile group: 'org.springframework.security', name: 'spring-security-core', version: '4.1.1.RELEASE'
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.7.4'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.7.4'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.7.4'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.2.2'
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.2.2'
}
| 057b4bd2d14648a86e00f06a3c5db995ec45c468 | [
"Markdown",
"Java",
"INI",
"Gradle"
] | 21 | Java | everischile/digital-architecture | acd3f17e7a00f70b1610e8418aa5e3039b6f0298 | 6415cea99f7c4675362278c52b5e39bae1be4c5d |
refs/heads/master | <file_sep>import random
import Item
class Room:
descriptions = ["big, with massive paintings hung on the wall", "cramped, with barely any space to move at all", "smelly, like old oatmeal"]
def __init__(self, roomdescription, items):
self.description = roomdescription
self.items = []
for i in items:
self.items.append(Item.Item(i))
def StartRoom(self):
self.description = "Welcome to the ship"
self.items = [Item.Item()]
def RandomRoom(self):
self.description = random.choice(Room.descriptions)
self.items = [Item.Item("test").RandomItem()]
return self
<file_sep>import urllib2
import json
import Player
def lambda_handler(event, context):
if event["session"]["new"]:
on_session_started({"requestId": event["request"]["requestId"]}, event["session"])
if event["request"]["type"] == "LaunchRequest":
return on_launch(event["request"], event["session"])
elif event["request"]["type"] == "IntentRequest":
return on_intent(event["request"], event["session"])
elif event["request"]["type"] == "SessionEndedRequest":
return on_session_ended(event["request"], event["session"])
def on_session_started(session_started_request, session):
print "Starting new session."
def on_session_ended(session_ended_request, session):
print "Ending session."
# Cleanup goes here...
def on_launch(launch_request, session):
return get_welcome_response()
def on_intent(intent_request, session):
intent = intent_request["intent"]
intent_name = intent_request["intent"]["name"]
if intent_name == "StartGame":
return startgame(session)
if intent_name == "EndGame":
return endgame(session)
if intent_name == "SaveGame":
return savegame(session)
if intent_name == "Move":
return move(session)
if intent_name == "Pickup":
return pickup(session)
if intent_name == "Inventory":
return inventory(session)
if intent_name == "Description":
return description(session)
else:
raise ValueError("Invalid intent")
def get_welcome_response():
p = Player.Player("Welcome room", ['exampleroomitem'], [])
card_title = "Ship"
speech_output = str(p.room.description) + ". In the corner you see "
for i in p.room.items:
speech_output += i.name
reprompt_text = "I didn't get that."
should_end_session = False
session_attributes = {"RoomDescription": p.room.description,
"RoomItems": json.dumps(p.room.items, default=lambda x: x.name),
"PlayerItems": json.dumps(p.items, default=lambda x: x.name)
}
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
def startgame():
session_attributes = {}
card_title = "start"
speech_output = "New game started. As the computer, I control the ship. Luckily for you I am programmed to abide by your every command." \
"Tell me where to go by saying 'Go North', for example"
reprompt_text = "I didn't get that."
should_end_session = False
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
def move(session):
p = Player.Player(session['attributes']['RoomDescription'], session['attributes']['RoomItems'], session['attributes']['PlayerItems'])
#p = Player.Player('testroom', ["testroomitem"], ['testplayeritem'])
p.move()
session_attributes = {}
card_title = "move"
speech_output = "The room is " + str(p.room.description) + ". In the corner you see "
for i in p.room.items:
speech_output += i.name
reprompt_text = "I didn't get that."
should_end_session = False
session_attributes = save_session(p)
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
def pickup(session):
#p = Player.Player("Welcome room", ['exampleroomitem'], ['exampleplayeritem'])
p = Player.Player(session['attributes']['RoomDescription'], session['attributes']['RoomItems'], session['attributes']['PlayerItems'])
p.pickup()
card_title = "pickup"
speech_output = "You picked up the items"
reprompt_text = "I didn't get that."
should_end_session = False
session_attributes = save_session(p)
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
def inventory(session):
p = Player.Player(session['attributes']['RoomDescription'], session['attributes']['RoomItems'], session['attributes']['PlayerItems'])
card_title = "pickup"
speech_output = "In your inventory you have "
for i in p.items:
speech_output += i.name + ", "
reprompt_text = "I didn't get that."
should_end_session = False
session_attributes = save_session(p)
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
def endgame(session):
p = Player.Player(session['attributes']['RoomDescription'], session['attributes']['RoomItems'], session['attributes']['PlayerItems'])
card_title = "end"
speech_output = "Game ended"
reprompt_text = "I didn't get that."
should_end_session = True
session_attributes = save_session(p)
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
def savegame(session):
p = Player.Player(session['attributes']['RoomDescription'], session['attributes']['RoomItems'], session['attributes']['PlayerItems'])
card_title = "save"
speech_output = "Game saved. (not really though as I am not able to do that yet)"
reprompt_text = "I didn't get that."
should_end_session = False
session_attributes = save_session(p)
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
def description(session):
p = Player.Player(session['attributes']['RoomDescription'], session['attributes']['RoomItems'], session['attributes']['PlayerItems'])
card_title = "description"
speech_output = "The room is " + str(p.room.description) + ". In the corner you see "
for i in p.room.items:
speech_output += i.name
reprompt_text = "I didn't get that."
should_end_session = False
session_attributes = save_session(p)
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
def help(session):
p = Player.Player(session['attributes']['RoomDescription'], session['attributes']['RoomItems'], session['attributes']['PlayerItems'])
card_title = "help"
speech_output = "To control the ship, the commands are help, move, pickup, description, save game, start game, end game"
for i in p.room.items:
speech_output += i.name
reprompt_text = "I didn't get that."
should_end_session = False
session_attributes = save_session(p)
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
def build_speechlet_response(title, output, reprompt_text, should_end_session):
return {
"outputSpeech": {
"type": "PlainText",
"text": output
},
"card": {
"type": "Simple",
"title": title,
"content": output
},
"reprompt": {
"outputSpeech": {
"type": "PlainText",
"text": reprompt_text
}
},
"shouldEndSession": should_end_session
}
def build_response(session_attributes, speechlet_response):
return {
"version": "1.0",
"sessionAttributes": session_attributes,
"response": speechlet_response
}
def save_session(p):
playeritems = []
for i in p.items:
playeritems.append(i.name)
roomitems = []
for i in p.room.items:
roomitems.append(i.name)
session_attributes = {"RoomDescription": p.room.description,
"RoomItems": roomitems,
"PlayerItems": playeritems
}
return session_attributes
<file_sep>import random
class Item:
items = ["a Rake", "a Spoon", "a Flashlight", "a Key", "a Gun"]
def __init__(self, name):
self.name = name
def RandomItem(self):
self.name = random.choice(Item.items)
return self
<file_sep>import Room
import Item
class Player:
def __init__(self, roomdescription, roomitems, playeritems):
self.room = Room.Room(roomdescription, roomitems)
self.items = []
for i in playeritems:
self.items.append(Item.Item(i))
def move(self):
self.room = self.room.RandomRoom()
def pickup(self):
for i in self.room.items:
self.items.append(i)
self.room.items = []
<file_sep># AlexaVoiceGame
Experimental game to test the development of Alexa apps using AWS lambda
All code has to be setup with AWS lambda, and an Alexa app must be made to communicate.
**If you wish to test this code, do the following.**
In order to run the code included in this zip:
1. Create a new AWS Lambda instance, and upload the .py code.
2. Create a new Alexa skill, and copy/paste the Intent Schema and Sample Utterances into the 'Interaction Model'
3. Connect the AWS Lambda and Alexa skill by copying the ARN from the AWS Lambda into the Alexa skill under 'Configuration'
The app can then be tested by using an Echo Dot, other compatible device,
or the inbuilt test section of the Alexa skill *(although this will not make proper use of sessions, and so there will be no progress saved between requests when tested this way)* | 3a12738ab58b770228692e0bdb0b55cfc133c759 | [
"Markdown",
"Python"
] | 5 | Python | Bolwo/AlexaVoiceGame | 56e42d99d49e76d6c00758d6593cfcd32c67021e | 7023b9bde72a2bd90e20172b57a3caa4970319b8 |
refs/heads/master | <file_sep>from numpy import argmax
from keras.applications.inception_v3 import InceptionV3
from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Embedding
from keras.layers import Dropout
from keras.layers.merge import add
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.image import load_img, img_to_array
from nltk.translate.bleu_score import corpus_bleu
from keras.models import Sequential
from keras.layers import LSTM, Embedding, TimeDistributed, Dense, RepeatVector, Merge, Activation, Flatten
from keras.optimizers import Adam, RMSprop
from keras.layers.wrappers import Bidirectional
# define the CNN model
def defineCNNmodel():
model = InceptionV3()
model.layers.pop()
model = Model(inputs=model.inputs, outputs=model.layers[-1].output)
#print(model.summary())
return model
# define the RNN model
def defineRNNmodel(vocab_size, max_len):
embedding_size = 300
# Input dimension is 2048 since we will feed it the encoded version of the image.
image_model = Sequential([
Dense(embedding_size, input_shape=(2048,), activation='relu'),
RepeatVector(max_len)
])
# Since we are going to predict the next word using the previous words(length of previous words changes with every iteration over the caption), we have to set return_sequences = True.
caption_model = Sequential([
Embedding(vocab_size, embedding_size, input_length=max_len),
LSTM(256, return_sequences=True),
TimeDistributed(Dense(300))
])
# Merging the models and creating a softmax classifier
final_model = Sequential([
Merge([image_model, caption_model], mode='concat', concat_axis=1),
Bidirectional(LSTM(256, return_sequences=False)),
Dense(vocab_size),
Activation('softmax')
])
final_model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy'])
final_model.summary()
return final_model
# map an integer to a word
def word_for_id(integer, tokenizer):
for word, index in tokenizer.word_index.items():
if index == integer:
return word
return None
# generate a description for an image, given a pre-trained model and a tokenizer to map integer back to word
def generate_desc(model, tokenizer, photo, max_length):
# seed the generation process
in_text = 'startseq'
# iterate over the whole length of the sequence
for i in range(max_length):
# integer encode input sequence
sequence = tokenizer.texts_to_sequences([in_text])[0]
# pad input
sequence = pad_sequences([sequence], maxlen=max_length)
# predict next word
yhat = model.predict([photo,sequence], verbose=0)
# convert probability to integer
yhat = argmax(yhat)
# map integer to word
word = word_for_id(yhat, tokenizer)
# stop if we cannot map the word
if word is None:
break
# append as input for generating the next word
in_text += ' ' + word
# stop if we predict the end of the sequence
if word == 'endseq':
break
return in_text
def evaluate_model(model, photos, descriptions, tokenizer, max_length):
actual, predicted = list(), list()
for key, desc_list in descriptions.items():
yhat = generate_desc(model, tokenizer, photos[key], max_length)
references = [d.split() for d in desc_list]
actual.append(references)
predicted.append(yhat.split())
print('BLEU-1: %f' % corpus_bleu(actual, predicted, weights=(1.0, 0, 0, 0)))
print('BLEU-2: %f' % corpus_bleu(actual, predicted, weights=(0.5, 0.5, 0, 0)))
print('BLEU-3: %f' % corpus_bleu(actual, predicted, weights=(0.3, 0.3, 0.3, 0)))
print('BLEU-4: %f' % corpus_bleu(actual, predicted, weights=(0.25, 0.25, 0.25, 0.25)))<file_sep>## AUTOMATIC IMAGE CAPTIONING USING CNN-LSTM DEEP NEURAL NETWORKS AND FLASK [](https://github.com/yaswanthpalaghat/Automatic-Image-Captioning-using-CNN-LSTM-deep-neural-networks-and-flask/blob/master/LICENSE)
### Description
Image caption generation has emerged as a challenging and important research area following ad-vances in statistical language modelling and image recognition. The generation of captions from images has various practical benefits, ranging from aiding the visually impaired, to enabling the automatic and cost-saving labelling of the millions of images uploaded to the Internet every day. The field also brings together state-of-the-art models in Natural Language Processing and Computer Vision, two of the major fields in Artificial Intelligence.
In this model, we has used CNN and LSTM to generate captions for the images and deployed our model using Flask.
### Deployment Procedure
## 1.Download and Install Python 3x and make sure to set the path(it is automated most of the times).
## 2.Download Anaconda IDE and Visual Studio Code.
## 3.Download Flickr8k dataset through the below link:
https://illinois.edu/fb/sec/1713398
Place the dataset files in image-captoin/train_val_data
## 4.Download the following libraries required by the project through the PIP using the following format.
## PIP INSTALL << LIBRARY NAME >>
• tensorflow
• keras
• numpy
• pandas
• opencv-python
• flask
• flask-caption
• scikit-learn
• nltk
• pytorch
• theano
• corpus
• textblob
• scipy
• matplotlib
## 5.Download the code from the following github repository.
https://github.com/yaswanthpalaghat/Automatic-Image-Captioning-using-CNN-LSTM-deep-neural-networks-and-flask
## 6.Run app.py and cap.py in the terminal.
## 7.Open browser and type Localhost:3000.
<file_sep>import numpy as np
import string
from os import listdir
from pickle import dump
from keras.applications.inception_v3 import preprocess_input
from keras.preprocessing.image import load_img, img_to_array
#The function returns a dictionary of image identifier to image features.
def extract_features(path):
model = defineCNNmodel()
# extract features from each photo
features = dict()
for name in listdir(path):
# load an image from file
filename = path + '/' + name
image = load_img(filename, target_size=(299, 299))
# convert the image pixels to a numpy array
image = img_to_array(image)
# reshape data for the model
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
# prepare the image for the VGG model
image = preprocess_input(image)
# get features
feature = model.predict(image, verbose=0)
# get image id
image_id = name.split('.')[0]
# store feature
features[image_id] = feature
return features
# extract descriptions for images
def load_descriptions(filename):
file = open(filename, 'r')
doc = file.read()
file.close()
mapping = dict()
# process lines by line
for line in doc.split('\n'):
# split line by white space
tokens = line.split()
if len(line) < 2:
continue
# take the first token as the image id, the rest as the description
image_id, image_desc = tokens[0], tokens[1:]
# remove filename from image id
image_id = image_id.split('.')[0]
# convert description tokens back to string
image_desc = ' '.join(image_desc)
# create the list if needed
if image_id not in mapping:
mapping[image_id] = list()
# store description
mapping[image_id].append(image_desc)
return mapping
def clean_descriptions(descriptions):
# prepare translation table for removing punctuation
table = str.maketrans('', '', string.punctuation)
for key, desc_list in descriptions.items():
for i in range(len(desc_list)):
desc = desc_list[i]
# tokenize
desc = desc.split()
# convert to lower case
desc = [word.lower() for word in desc]
# remove punctuation from each token
desc = [w.translate(table) for w in desc]
# remove hanging 's' and 'a'
desc = [word for word in desc if len(word)>1]
# remove tokens with numbers in them
desc = [word for word in desc if word.isalpha()]
# store as string
desc_list[i] = ' '.join(desc)
# save descriptions to file, one per line
def save_descriptions(descriptions, filename):
lines = list()
for key, desc_list in descriptions.items():
for desc in desc_list:
lines.append(key + ' ' + desc)
data = '\n'.join(lines)
file = open(filename, 'w')
file.write(data)
file.close()
def preprocessData():
# extract features from all images
path = 'Flicker8k_Dataset'
print('Generating image features...')
features = extract_features(path)
print('Completed. Saving now...')
# save to file
dump(features, open('model_data/features.pkl', 'wb'))
print("Save Complete.")
# load descriptions containing file and parse descriptions
descriptions_path = 'train_val_data/Flickr8k.token.txt'
descriptions = load_descriptions(descriptions_path)
print('Loaded Descriptions: %d ' % len(descriptions))
# clean descriptions
clean_descriptions(descriptions)
# save descriptions
save_descriptions(descriptions, 'model_data/descriptions.txt')
# Now descriptions.txt is of form :
# Example : 2252123185_487f21e336 stadium full of people watch game<file_sep>When you run the project, some files will be generated which'll be stored here
descriptions.txt : contains the saved text features
features.pkl : contains the saved image features
tokenizer.pkl : contains the saved tokenizer
model : the trained model
<file_sep>Required Libraries for python
Keras
Pillow
nltk
Matplotlib
Important: After downloading the dataset, put the reqired files in train_val_data folder
Procedure to Train Model
1)Put the required files in train_val_data Folder
2)Run train_val.py
Procedure to Test on new images
1)Put the test image in test_data folder
2)Run test.py<file_sep>from setuptools import setup
setup(name='captionbot',
version='0.1.4',
description='Simple API wrapper for https://www.captionbot.ai/',
url='http://github.com/krikunts/captionbot',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['captionbot'],
install_requires=[
'requests',
],
zip_safe=False)<file_sep># captionbot
[](https://pypi.python.org/pypi/captionbot)
Captionbot is a simple API wrapper for https://www.captionbot.ai/
## Installation
You can install captionbot using pip:
```bash
$ pip install captionbot
```
## Usage
To use, simply do:
```python
>>> from captionbot import CaptionBot
>>> c = CaptionBot()
>>> c.url_caption('your image url here')
>>> c.file_caption('your local image filename here')
```
<file_sep>import json
import mimetypes
import os
import requests
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
import logging
logger = logging.getLogger("captionbot")
class CaptionBotException(Exception):
pass
class CaptionBot:
UPLOAD_URL = "https://www.captionbot.ai/api/upload"
MESSAGES_URL = "https://captionbot.azurewebsites.net/api/messages"
@staticmethod
def _resp_error(resp):
if not resp.ok:
data = resp.json()
msg = "HTTP error: {}".format(resp.status_code)
if type(data) == dict and "Message" in data:
msg += ", " + data.get("Message")
raise CaptionBotException(msg)
def __init__(self):
self.session = requests.Session()
def _upload(self, filename):
url = self.UPLOAD_URL
mime = mimetypes.guess_type(filename)[0]
name = os.path.basename(filename)
files = {'file': (name, open(filename, 'rb'), mime)}
resp = self.session.post(url, files=files)
logger.debug("upload: {}".format(resp))
self._resp_error(resp)
res = resp.text
if res:
return res[1:-1]
def url_caption(self, image_url):
data = {
"Content": image_url,
"Type": "CaptionRequest",
}
headers = {
"Content-Type": "application/json; charset=utf-8"
}
url = self.MESSAGES_URL
resp = self.session.post(url, data=json.dumps(data), headers=headers)
logger.info("get_caption: {}".format(resp))
if not resp.ok:
return None
res = resp.text[1:-1].replace('\\"', '"').replace('\\n', '\n')
logger.info(res)
return res
def file_caption(self, filename):
upload_filename = self._upload(filename)
return self.url_caption(upload_filename)
<file_sep>from .captionbot import CaptionBot<file_sep>import numpy as np
from utils.preprocessing import *
from pickle import load, dump
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
'''
We have Flickr_8k.trainImages.txt and Flickr_8k.devImages.txt files which consist of unique identifiers which can be used to filter the images and their descriptions
'''
# load a pre-defined list of photo identifiers
def load_set(filename):
file = open(filename, 'r')
doc = file.read()
file.close()
dataset = list()
# process line by line
for line in doc.split('\n'):
# skip empty lines
if len(line) < 1:
continue
# get the image identifier
identifier = line.split('.')[0]
dataset.append(identifier)
return set(dataset)
'''
The model we will develop will generate a caption given a photo, and the caption will be generated one word at a time.
The sequence of previously generated words will be provided as input. Therefore, we will need a ‘first word’ to kick-off the generation process
and a ‘last word‘ to signal the end of the caption.
We will use the strings ‘startseq‘ and ‘endseq‘ for this purpose. These tokens are added to the loaded descriptions as they are loaded.
It is important to do this now before we encode the text so that the tokens are also encoded correctly.
'''
# load clean descriptions into memory
def load_clean_descriptions(filename, dataset):
file = open(filename, 'r')
doc = file.read()
file.close()
descriptions = dict()
for line in doc.split('\n'):
# split line by white space
tokens = line.split()
# split id from description
image_id, image_desc = tokens[0], tokens[1:]
# skip images not in the set
if image_id in dataset:
# create list
if image_id not in descriptions:
descriptions[image_id] = list()
# wrap description in tokens
desc = 'startseq ' + ' '.join(image_desc) + ' endseq'
# store
descriptions[image_id].append(desc)
return descriptions
'''
The description text will need to be encoded to numbers before it can be presented to the model as in input or compared to the model’s predictions.
The first step in encoding the data is to create a consistent mapping from words to unique integer values. Keras provides the Tokenizer class that
can learn this mapping from the loaded description data.
'''
# convert a dictionary of clean descriptions to a list of descriptions
def to_lines(descriptions):
all_desc = list()
for key in descriptions.keys():
[all_desc.append(d) for d in descriptions[key]]
return all_desc
# fit a tokenizer given caption descriptions
def create_tokenizer(descriptions):
lines = to_lines(descriptions)
tokenizer = Tokenizer()
tokenizer.fit_on_texts(lines)
return tokenizer
'''
Each description will be split into words. The model will be provided one word and the photo and generate the next word.
Then the first two words of the description will be provided to the model as input with the image to generate the next word.
This is how the model will be trained.
For example, the input sequence “little girl running in field” would be
split into 6 input-output pairs to train the model:
X1, X2 (text sequence), y (word)
photo startseq, little
photo startseq, little, girl
photo startseq, little, girl, running
photo startseq, little, girl, running, in
photo startseq, little, girl, running, in, field
photo startseq, little, girl, running, in, field, endseq
'''
# create sequences of images, input sequences and output words for an image
def create_sequences(tokenizer, max_length, desc_list, photo):
#X1 : input for photo features
#X2 : input for text features
X1, X2, y = list(), list(), list()
vocab_size = len(tokenizer.word_index) + 1
# walk through each description for the image
for desc in desc_list:
# encode the sequence
seq = tokenizer.texts_to_sequences([desc])[0]
# split one sequence into multiple X,y pairs
for i in range(1, len(seq)):
# split into input and output pair
in_seq, out_seq = seq[:i], seq[i]
# pad input sequence
in_seq = pad_sequences([in_seq], maxlen=max_length)[0]
# encode output sequence
out_seq = to_categorical([out_seq], num_classes=vocab_size)[0]
# store
X1.append(photo)
X2.append(in_seq)
y.append(out_seq)
return np.array(X1), np.array(X2), np.array(y)
# calculate the length of the description with the most words
def max_lengthcalc(descriptions):
lines = to_lines(descriptions)
return max(len(d.split()) for d in lines)
# load photo features
def load_photo_features(filename, dataset):
# load all features
all_features = load(open(filename, 'rb'))
# filter features
features = {k: all_features[k] for k in dataset}
return features
# data generator, intended to be used in a call to model.fit_generator()
def data_generator(photos, descriptions, tokenizer, max_length):
# loop for ever over images
while 1:
for key, desc_list in descriptions.items():
# retrieve the photo feature
photo = photos[key][0]
in_img, in_seq, out_word = create_sequences(tokenizer, max_length, desc_list, photo)
yield [[in_img, in_seq], out_word]
#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
def loadTrainData(path = 'train_val_data/Flickr_8k.trainImages.txt',preprocessDataReady=True):
train = load_set(path)
print('Dataset: %d' % len(train))
# check if we already have preprocessed data saved and if not, preprocess the data.
if preprocessDataReady is False:
preprocessData()
# descriptions
train_descriptions = load_clean_descriptions('model_data/descriptions.txt', train)
print('Descriptions: train=%d' % len(train_descriptions))
# photo features
train_features = load_photo_features('model_data/features.pkl', train)
print('Photos: train=%d' % len(train_features))
# prepare tokenizer
tokenizer = create_tokenizer(train_descriptions)
# save the tokenizer
dump(tokenizer, open('model_data/tokenizer.pkl', 'wb'))
# determine the maximum sequence length
max_length = max_lengthcalc(train_descriptions)
return train_features, train_descriptions, max_length
#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
def loadValData(path = 'train_val_data/Flickr_8k.devImages.txt'):
val = load_set(path)
print('Dataset: %d' % len(val))
# descriptions
val_descriptions = load_clean_descriptions('descriptions.txt', val)
print('Descriptions: val=%d' % len(val_descriptions))
# photo features
val_features = load_photo_features('features.pkl', val)
print('Photos: val=%d' % len(val_features))
return val_features, val_descriptions
#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- | 6d8028a61699f310dd25989a61ceb05a41e0c8ff | [
"Markdown",
"Python",
"Text"
] | 10 | Python | v-user1098new/Automatic-Image-Captioning-using-CNN-LSTM-deep-neural-networks-and-flask | 2dd4be83633ae827cff4818625b57312218bec1f | 20c0b079c5316366554ecbc903f813af8276f230 |
refs/heads/master | <repo_name>Jyothifr88/coffeShop-project<file_sep>/CoffeShop.Lib/CoffeeDarkRoast.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoffeShop.Lib
{
public class CoffeeDarkRoast:MenuItem
{
public CoffeeDarkRoast() : base("Coffe Dark Roast", 2.00M) { }
public override string Description { get => base.Description; set => base.Description = value; }
public override decimal BaseCost { get => base.BaseCost; set => base.BaseCost = value; }
}
}
<file_sep>/CoffeShop.Lib/OrderItem.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoffeShop.Lib
{
public class OrderItem
{
private IMenuItem Item;
public OrderItem(IMenuItem m)
{
Item = m;
}
public IMenuItem Menu
{
get { return Item; }
set { Item = value; }
}
}
}
<file_sep>/CoffeeshopRegistration/CustomerOrders.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CoffeShop.Lib;
namespace CoffeeshopRegistration
{
public partial class CustomerOrders : Form
{
MainForm mainform;
//DateTime FromDate;
//DateTime ToDate;
public CustomerOrders()
{
InitializeComponent();
}
public CustomerOrders(MainForm main)
{
InitializeComponent();
mainform = main;
}
private void CustomerOrders_Load(object sender, EventArgs e)
{
}
//public CustomerOrders(MainForm mainform,DateTime date1,DateTime date2)
//{
// InitializeComponent();
// this.mainform = mainform;
// FromDate = date1;
// ToDate = date2;
//}
public void customersNoOrderDelivered(CustomerRepository repository)
{
var cust=repository.CustomersNotDelivered();
foreach (Customer aCustomer in cust)
{
lbxcustomerNotDelivered.Items.Add(aCustomer);
}
this.ShowDialog();
}
public void OrdersWithinTime(CustomerRepository repository,DateTime begin,DateTime end)
{
var cust = repository.OrderTime(begin,end);
foreach (Customer aCustomer in cust)
{
lbxcustomerNotDelivered.Items.Add(aCustomer);
}
this.ShowDialog();
}
private void lbxcustomerNotDelivered_SelectedIndexChanged(object sender, EventArgs e)
{
if (lbxcustomerNotDelivered.SelectedIndex < 0)
{
MessageBox.Show("Please select the customer to see the order details");
return;
}
lbxOrderlist.Items.Clear();
Customer cust = lbxcustomerNotDelivered.SelectedItem as Customer;
foreach(Order od in cust.Orders)
{
lbxOrderlist.Items.Add(od.ToString());
}
}
}
}
<file_sep>/CoffeShop.Lib/Coffee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoffeShop.Lib
{
public class Coffee:MenuItem
{
private string name;
public Coffee():base("Orginal Bland Coffee", 2.0M)
{
name = "Coffe";
}
public string Name { get { return name; } set { name = value; } }
}
}
<file_sep>/CoffeShop.Lib/CustomerRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
namespace CoffeShop.Lib
{
public class CustomerRepository:RepositoryBase
{
private List<Customer> customers = new List<Customer>();
public CustomerRepository() { }
public override List<Customer> Customers
{
get { return customers; }
set { customers = Customers; }
}
public void Add(Customer aCustomer)
{
if (aCustomer != null)
{
Customers.Add(aCustomer);
}
}
public IEnumerable<Customer> CustomersNotDelivered()
{
var customersNotDelivered1 = Customers.FindAll(c=>(c.Orders.FindAll(o=>o.Delivered==false).Count())>0);
return customersNotDelivered1;
}
public IEnumerable<Customer> OrderTime(DateTime From,DateTime To)
{
var customers = (from cust in Customers
from od in cust.Orders
where od.OrderTime >= From
&& od.OrderTime <= DateTime.Now
select cust).Distinct();
return customers;
}
public bool TimeOfOrder(Customer aCustomer)
{
bool condition = false;
foreach (Order order in aCustomer.Orders)
{
if (order.Delivered == false)
{
condition = true;
}
}
return condition;
}
}
}<file_sep>/CoffeeshopRegistration/AddCustomer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CoffeShop.Lib;
namespace CoffeeshopRegistration
{
public partial class AddCustomer : Form
{
MainForm mainform;
public AddCustomer(MainForm mainform)
{
InitializeComponent();
this.mainform = mainform;
}
public void Addcustomer()
{
this.ShowDialog();
}
private void btnAdd_customer_Click(object sender, EventArgs e)
{
Address address;
address.Street = txtStreet.Text;
address.Province = txtProvince.Text;
address.PostalCode = txtPostalCode.Text;
address.City = txtCity.Text;
Customer customer = new Customer(txtName.Text, Convert.ToUInt32(txtPhoneno.Text), address);
mainform.updatelist(customer);
this.Close();
mainform.Show();
}
public void editcustomer(Customer cust)
{
txtName.Text = cust.Name;
txtStreet.Text = cust.Address.Street;
txtProvince.Text = cust.Address.Province;
txtPostalCode.Text = cust.Address.PostalCode;
txtCity.Text = cust.Address.City;
txtPhoneno.Text = Convert.ToString(cust.Phone);
this.ShowDialog();
}
//private void buttonUpdate_Click(object sender, EventArgs e)
//{
// Address address;
// address.Street = txtStreet.Text;
// address.Province = txtProvince.Text;
// address.PostalCode = txtPostalCode.Text;
// address.City = txtCity.Text;
// Customer customer = new Customer(txtName.Text, Convert.ToUInt32(txtPhoneno.Text), address);
// mainform.updatelist(customer);
// this.Close();
// mainform.Show();
//}
}
}
<file_sep>/CoffeShop.Lib/Lettuce.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoffeShop.Lib
{
public class Lettuce:MenuItemAddition
{
public Lettuce(MenuItem menu) : base(menu) { }
public override string Description
{
get { return MenuItem.Description + ", Lettuce"; }
}
public override decimal BaseCost { get => MenuItem.BaseCost + 0.30M; }
}
}
<file_sep>/CoffeShop.Lib/DelAddress.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoffeShop.Lib
{
public struct DelAddress
{
public string Street;
public string City;
public string Province;
public string PostalCode;
}
}<file_sep>/CoffeShop.Lib/Tomato.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoffeShop.Lib
{
public class Tomato:MenuItemAddition
{
public Tomato(MenuItem menu) : base(menu) { }
public override string Description
{
get { return MenuItem.Description + ", Tomato"; }
}
public override decimal BaseCost { get => MenuItem.BaseCost + 0.35M; }
}
}
<file_sep>/CoffeShop.Lib/Milk.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoffeShop.Lib
{
public class Milk:MenuItemAddition
{
public Milk(MenuItem menu) : base(menu) { }
public override string Description
{
get { return MenuItem.Description + ", Milk"; }
}
public override decimal BaseCost { get => MenuItem.BaseCost + 0.10M; }
}
}
<file_sep>/CoffeeshopRegistration/MainForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CoffeShop.Lib;
namespace CoffeeshopRegistration
{
public partial class MainForm : Form
{
int index = -1;
CustomerRepository custrep = new CustomerRepository();
Order order;
public MainForm()
{
InitializeComponent();
Customer internalCustomer = new Customer("Coffee and sandwiches", 0, Address.SHOP_ADDRESS);
CustomersList.Items.Add(internalCustomer);
}
private void btnAddCustomer_Click(object sender, EventArgs e)
{
index = -1;
AddCustomer addcustomer = new AddCustomer(this);
this.Hide();
addcustomer.Addcustomer();
}
public void updatelist(Object cust)
{
if (index >= 0)
{
CustomersList.Items.RemoveAt(index);
CustomersList.Items.Insert(index, cust);
}
else
{
CustomersList.Items.Add(cust);
}
}
public void updateorderlist(Order order,string TotalCost)
{
if (order.M_Item.Count > 0)
{
listOrder.Items.Clear();
for (int i = 0; i < order.M_Item.Count; i++)
{
if (order.M_Item[i] != null)
{
listOrder.Items.Add(order.M_Item[i].Description + ' ' +order.M_Item[i].BaseCost );
}
}
listOrder.Items.Add("Total Cost " + TotalCost);
}
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (CustomersList.SelectedIndex < 0)
{
MessageBox.Show("Please select the customer to edit");
return;
}
index = CustomersList.SelectedIndex;
AddCustomer addcustomer = new AddCustomer(this);
addcustomer.editcustomer(CustomersList.SelectedItem as Customer);
}
private void btnAddOrder_Click(object sender, EventArgs e)
{
if (CustomersList.SelectedIndex < 0)
{
MessageBox.Show("Please select the customer to add Order");
return;
;
}
Customer cust = CustomersList.SelectedItem as Customer;
if (CustomersList.SelectedIndex == 0)
{
order = new Order();
}
else
{
order = cust.CreatePhoneOrder(cust.Address);
}
AddOrder addorder = new AddOrder(this, order,cust);
addorder.Createorder();
}
private void btnsave_Click(object sender, EventArgs e)
{
if (CustomersList.SelectedIndex < 0)
{
MessageBox.Show("Please select the customer to save");
return;
}
custrep.Customers.Remove(CustomersList.SelectedItem as Customer);
custrep.Add(CustomersList.SelectedItem as Customer);
custrep.Save("Customers.json");
MessageBox.Show("Customer saved successfully");
}
private void btn_customersNotDelivered_Click(object sender, EventArgs e)
{
CustomerOrders custOrder = new CustomerOrders(this);
// this.Hide();
custOrder.customersNoOrderDelivered(custrep);
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void btn_Click(object sender, EventArgs e)
{
}
private void btnOrdersTime_Click(object sender, EventArgs e)
{
DateTime FromDate = this.dtpFrom.Value;
DateTime ToDate = this.dtpTo.Value;
//DateTime FromDate = DateTime.Parse(txtFrom.Text);
//DateTime ToDate = DateTime.Parse(txtTo.Text);
CustomerOrders custOrder = new CustomerOrders(this);
this.Hide();
custOrder.OrdersWithinTime(custrep,FromDate,ToDate);
//var cust = custrep.OrderTime(FromDate,ToDate);
//foreach (Customer aCustomer in cust)
//{
// lbxcustomerNotDelivered.Items.Add(aCustomer);
//}
//this.ShowDialog();
}
private void txtFrom_TextChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>/CoffeShop.Lib/SandwichWithEggSalad.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoffeShop.Lib
{
public class SandwichWithEggSalad:MenuItem
{
private string name;
public SandwichWithEggSalad() : base("White bread sandwich with egg salad", 4M)
{
name = "SandwichWithEggSalad";
}
public string Name { get { return name; } set { name = value; } }
}
}
<file_sep>/CoffeShop.Lib/MenuItem.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace CoffeShop.Lib
{
[Serializable()]
public class MenuItem:IMenuItem
{
protected string description;
protected decimal baseCost;
public MenuItem()
{
}
public MenuItem( string description, decimal cost)
{
this.description = description;
baseCost = cost;
}
public virtual string Description
{
get { return description; }
set { description = value; }
}
public virtual decimal BaseCost
{
get { return baseCost; }
set { baseCost = value; }
}
public override string ToString()
{
return $"Menu item:\t Description: {Description}\n \t Base cost: {BaseCost:c}";
}
}
}
<file_sep>/CoffeShop.Lib/MenuItemAddition.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace CoffeShop.Lib
{
[Serializable()]
public class MenuItemAddition:MenuItem
{
MenuItem menuitem;
public MenuItemAddition(MenuItem menuitem)
{
this.menuitem = menuitem;
}
public MenuItem MenuItem
{
get { return menuitem; }
set { menuitem = value; }
}
}
}
<file_sep>/CoffeShop.Lib/Customer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace CoffeShop.Lib
{
[Serializable()]
public class Customer
{
private static uint id;
private uint customerId;
private string name;
private Address address;
private ulong phone;
List<Order> order = new List<Order>();
public Customer() { }
public Customer(string CustName, uint PhoneNo, Address Address)
{
++id;
customerId = id;
name = CustName;
phone = PhoneNo;
address = Address;
}
public Customer(string CustName, uint PhoneNo, string SHOPADDRESS)
{
id++;
customerId = id;
name = CustName;
phone = PhoneNo;
address.Street = "1 King St";
address.City = "Toronto,";
address.Province = "ON";
address.PostalCode = " M1M 1M1";
}
public uint CustomerId
{
get { return customerId; }
set { customerId = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public Address Address
{
get { return address; }
set { address = value; }
}
public ulong Phone
{
get { return phone; }
set
{
phone = value;
}
}
public List<Order> Orders
{
get { return order; }
private set { order = value; }
}
public override string ToString()
{
string result = $"Customer Id: {CustomerId}, Name: {Name},\n \t Address: {Address.Street},{Address.City},{Address.Province}{Address.PostalCode}, Phone No: {Phone}, \n\t Orders: ";
for (int i = 0; i < Orders.Count; i++)
if (Orders[i] != null)
{
result += $"\n{Orders[i].ToString()}";
}
return result;
}
public Order CreatePhoneOrder(Address custAdd)
{
Order order = new Order(this, true) { OrderTime = DateTime.Now
};
order.Customer.Name = this.Name;
order.DAddress = new DelAddress() { Street = custAdd.Street, City = custAdd.City, Province = custAdd.Province, PostalCode = custAdd.PostalCode };
order.Delivered = false;
AddOrder(order);
return order;
}
public Order AddOrder(Order od)
{
if (od != null)
{
Orders.Add(od);
}
return od;
}
}
}
<file_sep>/CoffeShop.Lib/Order.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace CoffeShop.Lib
{
[Serializable()]
public class Order
{
private static uint id;
private uint orderId;
private Customer customer;
private DateTime orderTime;
private DateTime delTime;
private DelAddress delAddress;
private decimal cost;
private bool isPhoneOrder;
private List<MenuItem> m_items = new List<MenuItem>();
private List<OrderItem> o_items = new List<OrderItem>();
private bool delivered = false;
static Order()
{
id = 1;
}
public Order()
{
id++;
orderId = id;
customer = new Customer() { Name = "<NAME>" };
orderTime = DateTime.Now;
delTime = DateTime.Now;
cost = 0.0M;
delAddress.Street = "1 King St";
delAddress.City = "TORONTO";
delAddress.Province = "ON";
delAddress.PostalCode = "M1M 1M1";
delivered = true;
}
public Order(Customer cust, bool OrderType)
{
id++;
orderId = id;
customer = cust;
cost = 0.0M;
isPhoneOrder = OrderType;
}
public uint OrderId
{
get { return orderId; }
set { orderId = value; }
}
[JsonIgnore()]
public Customer Customer
{
get { return customer; }
set
{
if (value == this.customer)
{
customer = value;
}
else { Console.WriteLine($"Something went wrong! Customer cannot be changed once assigned"); }
}
}
public DateTime OrderTime
{
get { return orderTime; }
set { orderTime = value; }
}
public DateTime DelTime
{
get { return delTime; }
set { delTime = value; }
}
public DelAddress DAddress
{
get { return delAddress; }
set { delAddress = value; }
}
public decimal Cost
{
get { return cost; }
set { cost = value; }
}
public bool IsPhoneOrder
{
get { return isPhoneOrder; }
set { isPhoneOrder = false; }
}
public List<MenuItem> M_Item
{
get { return m_items; }
private set { m_items = value; }
}
public List<OrderItem> O_Item
{
get { return o_items; }
private set { o_items = value; }
}
public bool Delivered
{
get { return delivered; }
set { delivered = value; }
}
public void AddOrderItem(IMenuItem IItem)
{
if (IItem != null)
{
M_Item.Add((MenuItem)IItem);
Cost += IItem.BaseCost;
}
}
public override string ToString()
{
string result = $"\t Order ID: {this.OrderId}\n" +
$"\t Customer Name: {this.Customer.Name}\n" +
$"\t Order Time: {this.OrderTime.ToString("H:mm tt")}\n" +
$"\t Cost: {this.Cost:c}\n" +
$"\t Delivery Address: {this.DAddress.Street}, {this.DAddress.City}, {this.DAddress.Province}, " +
$"{this.DAddress.PostalCode}\n" + $"\t Order Time: {this.OrderTime.ToString("yyyy/MM/dd H:mm tt")}\n"+
$"\t Delivery Time: {this.DelTime.ToString("yyyy/MM/dd H:mm tt")}\n";
if (Delivered == false)
{
result += $"\t Not delivered\n";
}
result += $"\t\t Items: ";
for (int i = 0; i < M_Item.Count; i++)
if (M_Item[i] != null)
{
result += $"\n{M_Item[i].ToString()}";
}
return result;
}
public void Deliver()
{
Delivered = true;
DelTime = DateTime.Now;
}
}
}
<file_sep>/CoffeShop.Lib/Suggar.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoffeShop.Lib
{
public class Suggar:MenuItemAddition
{
//public Sugar() { }
public Suggar(MenuItem menu) : base(menu) { }
public override string Description
{
get { return MenuItem.Description+", Sugar"; }
}
public override decimal BaseCost { get => MenuItem.BaseCost+ 0.05M; }
}
}
<file_sep>/CoffeShop.Lib/SandwichWithRoastedBeef.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoffeShop.Lib
{
public class SandwichWithRoastedBeef:MenuItem
{
private string name;
public SandwichWithRoastedBeef() : base("White bread sandwich with roasted beef", 5.5M)
{
name= "SandwichWithRoastedBeef";
}
public string Name { get { return name; } set { name = value; } }
}
}
<file_sep>/CoffeeshopRegistration/AddOrder.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CoffeShop.Lib;
namespace CoffeeshopRegistration
{
public partial class AddOrder : Form
{
MainForm mainform;
CoffeShop.Lib.MenuItem menuitem;
decimal totalcost = 0;
List<CoffeShop.Lib.MenuItem> menuitems = new List<CoffeShop.Lib.MenuItem>();
Order order;
Customer cust;
public AddOrder(MainForm mainform, Order order,Customer cust)
{
InitializeComponent();
this.mainform = mainform;
this.order = order;
this.cust = cust;
}
public void Createorder()
{
Setmenuitems();
this.ShowDialog();
}
private void Setmenuitems()
{
Coffee coffee = new Coffee();
CoffeeDarkRoast coffedarkroast = new CoffeeDarkRoast();
Tea tea = new Tea();
SandwichWithBacon sandwichwithBacon = new SandwichWithBacon();
SandwichWithRoastedBeef sandwichWithRoastedBeef = new SandwichWithRoastedBeef();
SandwichWithEggSalad sandwichWithEggSalad = new SandwichWithEggSalad();
listMenu.Items.Add(coffedarkroast);
listMenu.Items.Add(tea);
listMenu.Items.Add(sandwichwithBacon);
listMenu.Items.Add(sandwichWithRoastedBeef);
listMenu.Items.Add(sandwichWithEggSalad);
}
public void btnAddItem_Click(object sender, EventArgs e)
{
if (listMenu.SelectedIndex < 0)
{
MessageBox.Show("Please select the menu item to add");
return;
}
totalcost = 0;
if (menuitem == null)
{
menuitem = listMenu.SelectedItem as CoffeShop.Lib.MenuItem;
}
menuitems.Add(menuitem);
foreach (CoffeShop.Lib.MenuItem menuItem in menuitems)
{
if (menuItem != null)
{
totalcost = totalcost + menuItem.BaseCost;
}
}
txtTotalCost.Text = Convert.ToString(totalcost);
menuitem = null;
}
private void btnAddAdditions_Click_1(object sender, EventArgs e)
{
if (menuitem == null)
{
menuitem = listMenu.SelectedItem as CoffeShop.Lib.MenuItem;
}
string text = lbxMenuAdditions.GetItemText(lbxMenuAdditions.SelectedItem);
if (text == "Milk")
{
menuitem = new Milk(menuitem);
}
if (text == "Sugar")
{
menuitem = new Suggar(menuitem);
}
if (text == "Sweetener")
{
menuitem = new Sweetener(menuitem);
}
if (text == "Cheese")
{
menuitem = new Cheese(menuitem);
}
if (text == "Lettuce")
{
menuitem = new Lettuce(menuitem);
}
if (text == "Mayo")
{
menuitem = new Mayo(menuitem);
}
if (text == "Tomato")
{
menuitem = new Tomato(menuitem);
}
}
private void btnOk_Click_1(object sender, EventArgs e)
{
for (int x = 0; x < menuitems.Count; x++)
{
order.AddOrderItem(menuitems[x]);
}
cust.Orders.Remove(order);
cust.AddOrder(order);
mainform.updateorderlist(order,txtTotalCost.Text);
}
}
}
<file_sep>/CoffeShop.Lib/Address.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoffeShop.Lib
{
public struct Address
{
public string Street;
public string City;
public string Province;
public string PostalCode;
public static string SHOP_ADDRESS;
public Address( string street, string city, string province,string postalCode)
{
Street = street;
City = city;
Province = province;
PostalCode = postalCode;
}
}
}<file_sep>/CoffeShop.Lib/Cheese.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoffeShop.Lib
{
public class Cheese:MenuItemAddition
{
public Cheese(MenuItem menu) : base(menu) { }
public override string Description
{
get { return MenuItem.Description + ", Cheese"; }
}
public override decimal BaseCost { get => MenuItem.BaseCost + 0.4M; }
}
}
| 704048bed3fa2aa7fad1001b11b9329fe9132036 | [
"C#"
] | 21 | C# | Jyothifr88/coffeShop-project | f786d69cdcbe92f2afd765f5a630ab12532fb0ce | 4067406e268f23119cb1ba41fd4f3ad82bff6b81 |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Code_97;
/**
*
* @author <NAME>
*/
public class LinkedList {
public Node head;
public Node last;
public int size;
public LinkedList() {
}
public void addFirst(int value) {
Node temp = new Node(value);
temp.next = head;
head = temp;
if (size == 0) {
head = last = temp;
size++;
} else {
head = temp;
size++;
}
}
public void removeLast() {
if (iseEmpty()) {
System.out.println("Nothing to remove");
} else {
Node temp = last;
if (last == head) {
last = head = null;
size = 0;
} else {
Node priv = head;
while (priv.next.next != null) {
priv = priv.next;
}
last = priv;
priv.next = null;
size--;
}
}
}
public void addLast(int value) {
if (iseEmpty()) {
addFirst(value);
size++;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
Node current = new Node(value);
last = current;
temp.next = current;
size++;
}
}
public int Max() {
if (iseEmpty()) {
return -1;
} else if (size == 1) {
return head.getData();
} else {
int max = Integer.MIN_VALUE;
Node temp = head;
while (temp != null) {
if (temp.getData() > max) {
max = temp.getData();
}
temp = temp.next;
}
return max;
}
}
@Override
public String toString() {
StringBuilder st = new StringBuilder();
if (iseEmpty()) {
return st.toString();
}
Node temp = head;
while (temp.next != null) {
st.append(temp.getData() + "----->");
temp = temp.next;
}
st.append(temp.getData() + "-----> Null");
return st.toString();
}
public boolean iseEmpty() {
boolean flag = false;
if (size == 0) {
flag = true;
}
return flag;
}
public void addByIndex(int val, int index) {
if (iseEmpty() || index == 1) {
addFirst(val);
} else if (index == 0) {
System.out.println("Start from Index 1 plz ");
} else {
int counter = 1;
Node temp = head;
while (temp != null && counter != index - 1) {
temp = temp.next;
counter++;
}
Node add = new Node(val);
add.next = temp.next;
temp.next = add;
}
}
public void addbySort(int value) {
Node temp = head;
Node priv = new Node(value);
if (iseEmpty()) {
addFirst(value);}
else if (head.getData() > value) {
addFirst(value);
}
else if (last.getData() < value) {
addLast(value);
}
else {
while (temp != null && temp.next.getData() < value) {
temp = temp.getNext();
}
priv.next = temp.next;
temp.next = priv;
size++;
}
}
public int getIndex(int value) {
if (iseEmpty()) {
return -1;
} else {
int index = 1;
Node temp = head;
while (temp != null) {
if (temp.getData() == value) {
return index;
}
temp = temp.next;
index++;
}
return -1;
}
}
public LinkedList Reverse() {
Node temp = head;
LinkedList l1 = new LinkedList();
while (temp != null) {
l1.addFirst(temp.getData());
temp = temp.next;
}
return l1;
}
public LinkedList Clone() {
Node temp = head;
LinkedList list = new LinkedList();
while (temp != null) {
list.addLast(temp.getData());
temp = temp.next;
}
return list;
}
public boolean Bilandrom(LinkedList list) {
LinkedList list1 = list.Reverse();
if (list1.toString().equals(list.toString())) {
return true;
} else {
return false;
}
}
public void removefirst() {
if (iseEmpty()) {
System.out.println("Nothing to remve");
} else if (size == 1) {
size--;
head = null;
} else {
head = head.next;
size--;
}
}
public void removeByIndex(int Index) {
if (iseEmpty() || size < Index) {
System.out.println("Invalid index");
} else if (size == Index) {
removeLast();
} else if (Index == 1) {
removefirst();
} else {
Node temp = head;
int counter = 1;
while (temp != null && counter != Index - 1) {
counter++;
temp = temp.next;
}
temp.next = temp.next.next;
}
}
public int get(int Index) {
if (iseEmpty() || Index > size || Index < 1) {
return -1;
} else if (Index == 1) {
return head.getData();
} else if (Index == size) {
return last.getData();
} else {
int counter = 1;
Node temp = head;
while (temp != null && counter != Index) {
temp = temp.next;
counter++;
}
return temp.getData();
}
}
public void swap(int n1, int n2) {
Node temp = head;
Node node1 = new Node();
Node node2 = new Node();
Node swap;
int counter = 0;
while (temp != null && counter != n2) {
if (counter == n1) {
node1 = temp;
}
counter++;
temp = temp.next;
}
node2 = temp;
swap = node1;
node1 = node2;
node2 = swap;
}
public static void main(String[] args) {
LinkedList list=new LinkedList();
list.addbySort(15);
list.addbySort(25);
list.addbySort(195);
list.addbySort(1);
System.out.println(list.toString());
}
}
<file_sep>This is Desktop Application represent ArrayList and LinkedList data structure from a-z.
P.S This project implemented using java .
########################
###<NAME>###
########################
| cb138464ad258e6bc0701d8384bc471b541c098a | [
"Java",
"Text"
] | 2 | Java | HuthaifaQuraini/LinkedList-ArrayList-GUI-implementation | 900c9dba17d794deb0c4c7152d338828ae32bd9f | 3ef8d2b6f8236d549c07e9dd128509c52c367726 |
refs/heads/master | <file_sep>import subprocess
from setuptools import Extension as _Extension
def _combine(list_, dict_=None):
def _reducer(x, (a, b)):
x.setdefault(a, []).append(b)
return x
return reduce(_reducer, list_, dict_ if dict_ is not None else {})
def _mapoptions(list_, map_, default):
for i in list_:
key = map_.get(i[:2])
if key:
yield key, i[2:]
else:
yield default, i
class Extension(_Extension):
def __pkgconfig(self, package, option):
return subprocess.Popen(['pkg-config', option, package],
stdout=subprocess.PIPE).communicate()[0].split()
def __libs_for_package(self, package, outdict=None):
l = {'-L': 'library_dirs',
'-l': 'libraries', } # extra_link_args
default = 'extra_link_args'
options = self.__pkgconfig(package, '--libs')
return _combine(_mapoptions(options, l, default), outdict)
def __cflags_for_package(self, package, outdict=None):
c = {'-D': 'define_macros',
'-I': 'include_dirs', } # extra_compile_flags
default = 'extra_compile_flags'
options = self.__pkgconfig(package, '--cflags')
return _combine(_mapoptions(options, c, default), outdict)
def __options_for_package(self, package, outdict=None):
out = {}
self.__cflags_for_package(package, out)
self.__libs_for_package(package, out)
out['define_macros'] = [tuple(i.split('=', 1)) if i.split('=')[1:]
else (i, None) for i in out.pop('define_macros', [])]
outdict.update(out)
return outdict
def __init__(self, *args, **kwargs):
packages = kwargs.pop('pkg_config', [])
for package in packages:
options = self.__options_for_package(package, kwargs)
_Extension.__init__(self, *args, **kwargs)
| a72d2efd4ce420290650299ad9c006b46a7e7f22 | [
"Python"
] | 1 | Python | edwardgeorge/pkgextension | 95bfc7bbf32add6c4a4731bf804c16dd9eb58599 | 13f604ef140246ccfd9a87c78b6abd1e8c6c88df |
refs/heads/master | <repo_name>niraja426/lab-dom-pizza-builder<file_sep>/starter-code/pizza.js
// Write your Pizza Builder JavaScript in this file.
// Constants
var basePrice = 10
var ingredients = {
pepperonni: {name: 'Pepperonni', price: 1},
mushrooms: {name: 'Mushrooms', price: 1},
greenPeppers: {name: 'Green Peppers', price: 1},
whiteSauce: {name: 'White sauce', price: 3},
glutenFreeCrust: {name: 'Gluten-free crust', price: 5}
}
// Initial value of the state (the state values can change over time)
var state = {
pepperonni: true,
mushrooms: true,
greenPeppers: true,
whiteSauce: false,
glutenFreeCrust: false
}
// This function takes care of rendering the pizza based on the state
// This function is triggered once at the begining and everytime the state is changed
function renderEverything() {
renderPepperonni()
renderMushrooms()
renderGreenPeppers()
renderWhiteSauce()
renderGlutenFreeCrust()
renderButtons()
renderPrice()
}
function renderPepperonni() {
document.querySelectorAll('.pep').forEach(function($pep){
if (state.pepperonni) {
$pep.style.visibility = "visible";
}
else {
$pep.style.visibility = "hidden";
}
})
}
function renderMushrooms() {
document.querySelectorAll('.mushroom').forEach(function(mush){
if(state.mushrooms){
mush.style.visibility="visible";
}
else{
mush.style.visibility="hidden";
}
})
}
function renderGreenPeppers() {
// Iteration 1: set the visibility of `<section class="green-pepper">`
document.querySelectorAll('.green-pepper').forEach(function(green){
if(state.greenPeppers){
green.style.visibility="visible"
}
else{
green.style.visibility="hidden";
}
})
}
function renderWhiteSauce() {
// Iteration 2: add/remove the class "sauce-white" of `<section class="sauce">`
document.querySelectorAll('.sauce').forEach(function(sauce){
if(state.whiteSauce){
sauce.classList.remove("sauce-white")
}
else{
sauce.classList.add("sauce-white")
}
})
}
function renderGlutenFreeCrust() {
// Iteration 2: add/remove the class "crust-gluten-free" of `<section class="crust">`
document.querySelectorAll('.crust').forEach(function(crust){
if(state.glutenFreeCrust){
crust.classList.remove("crust-gluten-free")
}
else{
crust.classList.add("crust-gluten-free")
}
})
}
function renderButtons() {
// Iteration 3: add/remove the class "active" of each `<button class="btn">`
document.querySelectorAll(".btn").forEach(function(btn){
var classes=btn.className.split(" ");
// console.log(classes);
// var i = classes.indexOf("active");
var name=classes[1];
if(name==="btn-pepperonni"){
if(state.pepperonni) btn.classList.remove("active");
else btn.classList.add("active");
}
else if(name==="btn-mushrooms"){
if(state.mushrooms) btn.classList.remove("active");
else btn.classList.add("active");
}
else if(name==="btn-green-peppers"){
if(state.greenPeppers) btn.classList.remove("active");
else btn.classList.add("active");
}
else if(name==="btn-green-peppers"){
if(state.greenPeppers) btn.classList.remove("active");
else btn.classList.add("active");
}
else if(name==="btn-sauce"){
if(state.whiteSauce) btn.classList.remove("active");
else btn.classList.add("active");
}
else if(name==="btn-crust"){
if(state.glutenFreeCrust) btn.classList.remove("active");
else btn.classList.add("active");
}
})
}
function renderPrice() {
// Iteration 4: change the HTML of `<aside class="panel price">`
var price=document.querySelector(".price");
console.log(price)
//price.innerHTML='this is text'
var newhtml="<h2>Your pizza's price</h2>\
<b>$10 cheese pizza</b>\
<ul>"
var total=10;
if(state.pepperonni) {
console.log("pep")
newhtml+="<li>$"+ingredients.pepperonni.price+" pepperonni</li>"
total+=ingredients.pepperonni.price;
}
if(state.mushrooms){
newhtml+="<li>$"+ingredients.mushrooms.price+" mushroom</li>"
total+=ingredients.mushrooms.price;
}
if(state.greenPeppers){
newhtml+="<li>$"+ingredients.greenPeppers.price+" green peppers</li>"
total+=ingredients.greenPeppers.price;
}
if(state.whiteSauce){
newhtml+="<li>$"+ingredients.whiteSauce.price+" white sauce</li>"
total+=ingredients.whiteSauce.price;
}
if(state.glutenFreeCrust){
newhtml+="<li>$"+ingredients.glutenFreeCrust.price+" gluten-free crust</li>"
total+=ingredients.glutenFreeCrust.price;
}
var footer=`</ul>\
<strong>$${total} </strong>`
newhtml+=footer;
console.log(newhtml)
price.innerHTML=newhtml;
}
// console.log(document.getElementsByClassName('price'))
// console.log(document.querySelector('.price'))
// // element = document.getElementsByClassName('price')
// element = document.querySelector('.price')
// element.innerHTML = "hello"
// // element[0].innerHTML = "this is a test"
// // console.log(element[0].innerHTML)
renderEverything()
;
// Iteration 1: Example of a click event listener on `<button class="btn btn-pepperonni">`
document.querySelector('.btn.btn-pepperonni').onclick = function() {
state.pepperonni = !state.pepperonni
renderEverything();
}
// Iteration 1: Add click event listener on `<button class="btn btn-mushrooms">`
document.querySelector('.btn.btn-mushrooms').onclick = function() {
state.mushrooms = !state.mushrooms
renderEverything()
}
// Iteration 1: Add click event listener on `<button class="btn btn-green-peppers">`
document.querySelector('.btn.btn-green-peppers').onclick = function() {
state.greenPeppers = !state.greenPeppers
renderEverything()
}
// Iteration 2: Add click event listener on `<button class="btn btn-sauce">`
document.querySelector('.btn.btn-sauce').onclick = function() {
state.whiteSauce = !state.whiteSauce
renderEverything()
}
// Iteration 2: Add click event listener on `<button class="btn btn-crust">`
document.querySelector('.btn.btn-crust').onclick = function() {
state.glutenFreeCrust = !state.glutenFreeCrust
renderEverything()
} | 52a1b0ae01c5aeb24584db3b5468d518dc31a265 | [
"JavaScript"
] | 1 | JavaScript | niraja426/lab-dom-pizza-builder | 8c5bd725f008417ad98cae08b0d2a0a543e78015 | ac98d46cf7ce1414cac3c2e25c23c679d8cccbce |
refs/heads/main | <repo_name>Edwinverheul94/solomon-monorepo<file_sep>/libs/shared/util-i18n/src/lib/simple-i18n.spec.ts
import { getArray, getRecord, getString, SimpleI18n } from './simple-i18n'
describe('simple i18n', () => {
const fallback = { test: { arr: ['1', '2', '3'], str: 'thing' } }
it('should get different types correctly', () => {
const i18n = new SimpleI18n(fallback)
expect(i18n.s('test.str')).toEqual('thing')
expect(i18n.r('test')).toEqual({ arr: ['1', '2', '3'], str: 'thing' })
expect(i18n.a('test.arr')).toEqual(['1', '2', '3'])
expect(i18n.s('test.arr.1')).toEqual('2')
})
it('helpers should get different types correctly', () => {
const i18n = new SimpleI18n(fallback)
const ts = getString(i18n)
const ta = getArray(i18n)
const tr = getRecord(i18n)
expect(ts('test.str')).toEqual('thing')
expect(tr('test')).toEqual({ arr: ['1', '2', '3'], str: 'thing' })
expect(ta('test.arr')).toEqual(['1', '2', '3'])
expect(ts('test.arr.1')).toEqual('2')
})
it('should fail to get the wrong types', () => {
const i18n = new SimpleI18n(fallback)
expect(() => i18n.a('test.str')).toThrow('Copy: expected array, found string')
expect(() => i18n.r('test.str')).toThrow('Copy: expected record, found string')
expect(() => i18n.r('test.arr')).toThrow('Copy: expected record, found array')
expect(() => i18n.s('test.arr')).toThrow('Copy: expected string, found array')
expect(() => i18n.s('test')).toThrow('Copy: expected string, found object')
})
})
<file_sep>/apps/developer-docs/docs/plugin/theming.md
# Theming
Both the Plugin and Shopping Cart include default themes that are fully customizable. When using with a bundler (such as Rollup, Webpack, etc), you may plug directly in to our [Postcss](https://postcss.org/) processing pipeline. Otherwise, it is easy enough to simply override css classes.
## Default Theme
TBD
<file_sep>/.flake8
[flake8]
# black line length (default 88)
max-line-length = 88
ignore =
# B008: Do not perform function calls in argument defaults, ignore for FastAPI Depends
B008
exclude =
migrations
# import order configuration
application-import-names = app,main
import-order-style = smarkets
<file_sep>/libs/shared/util-core/src/index.ts
export * from './lib/i-json-object'
<file_sep>/apps/blockchain-watcher/Dockerfile
# BASE IMAGE (927.6MB)
# ------------------------------------------------------------------------------------
FROM alpine:3.14 as base
ARG NODEJS_VER=14
ARG TINI_VER=0.19
ENV NODEJS_VER=$NODEJS_VER
ENV TINI_VER=$TINI_VER
ENV SHELL=/bin/sh
WORKDIR /usr/src
COPY nx.json ./
COPY subset.config.js package.json ./
COPY tools/scripts/package-subset.js ./tools/scripts/
COPY tsconfig.base.json ./
COPY workspace.json ./
RUN apk add --no-cache sqlite g++ make python3 nodejs~="$NODEJS_VER" tini~="$TINI_VER" curl~=7
RUN ln -sf python3 /usr/bin/python
RUN curl -f https://get.pnpm.io/v6.14.js | node - add --global pnpm
RUN addgroup -g 1001 -S app && adduser -u 1001 -S app -G app
COPY apps/blockchain-watcher ./apps/blockchain-watcher
COPY libs ./libs
RUN node ./tools/scripts/package-subset.js blockchain-watcher subset.config.js package.json package.json
RUN pnpm install
# WATCHER: DEV IMAGE (929.95 MB)
# ------------------------------------------------------------------------------------
FROM base as dev
ENV NODE_ENV=developemnt
ENTRYPOINT ["/sbin/tini", "-v", "--"]
CMD ["pnpm", "exec", "nx", "serve", "blockchain-watcher"]
# WATCHER: PROD IMAGE (931.99 MB)
# ------------------------------------------------------------------------------------
FROM base as production
ENV NODE_ENV=production
RUN pnpm exec nx build blockchain-watcher
ENTRYPOINT ["/sbin/tini", "-v", "--"]
CMD ["node", "./dist/apps/blockchain-watcher/main.js"]
<file_sep>/tools/scripts/generateMailTemplates.ts
import generateMailTemplates from '@solomon/blockchain-watcher/feature-templates'
let run = async () => {
await generateMailTemplates()
}
run()
<file_sep>/apps/web-evidence/src/app/router.ts
import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import SelectMethod from './views/SelectMethod.vue'
import ExternalLink from './views/ExternalLink.vue'
import SolomonLink from './views/SolomonLink.vue'
declare module 'vue-router' {
interface RouteMeta {
title?: string
}
}
const router = createRouter({
history: createWebHistory(),
scrollBehavior(to, from, savedPosition) {
if (to.hash) {
return new Promise((resolve, _reject) => {
setTimeout(() => {
resolve({ el: to.hash })
}, 500)
})
}
if (savedPosition) {
return savedPosition
}
if (to.meta.noScroll && from.meta.noScroll) {
return {}
}
return { top: 0 }
},
routes: [
{
path: '/',
name: 'home',
component: Home,
meta: { title: 'Solomon Evidence' },
},
{
path: '/select/:type(buyer|merchant)',
name: 'select',
component: SelectMethod,
meta: { title: 'Evidence Method' },
},
{
path: '/upload-external/:type(buyer|merchant)',
name: 'upload-external',
component: ExternalLink,
meta: { title: 'External Link' },
},
{
path: '/upload-solomon/:type(buyer|merchant)',
name: 'upload-solomon',
component: SolomonLink,
meta: { title: 'Solomon Link' },
},
],
})
router.afterEach((to, _from) => {
const parent = to.matched.find((record) => record.meta.title)
const parentTitle = parent ? parent.meta.title : null
document.title = to.meta.title || parentTitle || 'Solomon Evidence'
})
export default router
<file_sep>/apps/api-evidence/src/app/schemas/auth.py
from pydantic import BaseModel
from app.utils.types import EthAddress
class AddressChallengeCreate(BaseModel):
address: EthAddress
class AddressChallenge(BaseModel):
challenge: dict
<file_sep>/apps/developer-docs/docs/plugin/api.md
# Plugin API
The Solomon Plugin exports a public interface for enabling third party integrations, and bespoke implementations.
## API Documentation
TBD
<file_sep>/apps/blockchain-watcher/src/store/envStore.ts
class EnvStore {
get isTest(): boolean {
return process.env.NODE_ENV === 'test'
}
get isDev(): boolean {
return process.env.NODE_ENV === 'development'
}
get isStage(): boolean {
return process.env.NODE_ENV === 'staging'
}
get isProd(): boolean {
return process.env.NODE_ENV === 'production'
}
get envName() {
return process.env.NODE_ENV || 'unknown'
}
get infuraId(): string {
return ''
}
get ethChainUrl(): string {
if (this.isDev) {
return 'http://localhost:8545'
}
if (this.isStage) {
return `https://ropsten.infura.io/v3/${this.infuraId}`
}
if (this.isProd) {
return `https://infura.io/v3/${this.infuraId}`
}
return ''
}
get factoryAddress(): string {
return process.env.FACTORY_ADDRESS || ''
}
get mailgunApiKey(): string {
return 'foo'
}
// one of your domain names listed at your https://app.mailgun.com/app/sending/domains
get mailgunDomain(): string {
return 'foo.bar'
}
}
export default new EnvStore()
<file_sep>/apps/api-evidence/src/app/tests/test_api.py
import io
import typing
from contextlib import contextmanager
from unittest.mock import MagicMock
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from app.utils.deps import get_storage
from .utils import random_lower_string
from .utils.evidence import create_random_evidence
def test_healthcheck(client: TestClient) -> None:
rsp = client.get('/api/health/app')
assert rsp.ok
def test_get_evidence(db: Session, authed_client: TestClient) -> None:
num_evidence = 3
for _ in range(num_evidence):
create_random_evidence(db, owner_id=authed_client.user_id)
rsp = authed_client.get('/api/evidence')
assert rsp.ok
data = rsp.json()
assert len(data) == num_evidence
@contextmanager
def overrided_storage(authed_client: TestClient) -> typing.Generator:
mocked_storage = MagicMock()
authed_client.app.dependency_overrides[get_storage] = lambda: mocked_storage
yield mocked_storage
authed_client.app.dependency_overrides = {}
def test_create_evidence(authed_client: TestClient) -> None:
test_filename = 'test.jpg'
with overrided_storage(authed_client) as mocked_storage:
mocked_storage.backend.name = 's3'
mocked_storage.save.return_value = test_filename
file = io.BytesIO()
title = random_lower_string()
description = random_lower_string()
rsp = authed_client.post(
'/api/evidence',
data={'title': title, 'description': description},
files={'evidence_file': (test_filename, file)},
)
assert rsp.ok
def test_get_one_evidence(authed_client: TestClient) -> None:
test_filename = 'test.jpg'
test_file_content = b'test'
test_file = io.BytesIO()
test_file.write(test_file_content)
test_file.seek(0)
with overrided_storage(authed_client) as mocked_storage:
mocked_storage.backend.name = 's3'
mocked_storage.save.return_value = test_filename
mocked_storage.get.return_value = test_file
file = io.BytesIO()
title = random_lower_string()
description = random_lower_string()
rsp = authed_client.post(
'/api/evidence',
data={'title': title, 'description': description},
files={'evidence_file': (test_filename, file)},
)
assert rsp.ok
evidence_id = rsp.json()['id']
rsp = authed_client.get(f'/api/evidence/{evidence_id}')
assert rsp.ok
assert rsp.content == test_file_content
<file_sep>/apps/blockchain-watcher/src/util/MailgunTransport.ts
import Mailgun from 'mailgun.js'
import formData from 'form-data'
import packageData from '../../../../package.json'
const whitelist = [
['replyTo', 'h:Reply-To'],
['messageId', 'h:Message-Id'],
[/^h:/],
[/^v:/],
['from'],
['to'],
['cc'],
['bcc'],
['subject'],
['text'],
['template'],
['html'],
['attachment'],
['inline'],
['recipient-variables'],
['o:tag'],
['o:campaign'],
['o:dkim'],
['o:deliverytime'],
['o:testmode'],
['o:tracking'],
['o:tracking-clicks'],
['o:tracking-opens'],
['o:require-tls'],
['o:skip-verification'],
['X-Mailgun-Variables'],
]
export default class MailgunTransport {
options: any
messages: any
domain: string
constructor(options: any = {}) {
const mailgun = new Mailgun(formData as any)
let url = options.url
if (!options.url && options.host) {
const mailgunUrl = new URL(`https://${options.host || 'api.mailgun.net'}`)
mailgunUrl.protocol = options.protocol || 'https:'
mailgunUrl.port = options.port || 443
url = mailgunUrl.href
}
this.domain = options.auth.domain || ''
this.messages = mailgun.client({
username: 'api',
key: options.auth.api_key || options.auth.apiKey,
url,
}).messages
this.options = options
}
getPlugin() {
const self = this
const mailgunSend = (mail: any) => self.messages.create(self.domain, mail)
return {
name: 'Mailgun',
version: packageData.version,
send: this.send(mailgunSend),
messages: this.messages,
options: this.options,
}
}
applyKeyWhitelist(mail: any) {
return Object.keys(mail).reduce((acc, key) => {
const targetKey = whitelist.reduce((result, prev: any) => {
const { cond, target } = prev
if (result) {
return result
}
if ((cond.exec && cond.exec(key)) || cond === key) {
return target || key
}
return null
}, null)
if (!targetKey || !mail[key]) {
return acc
}
return { ...acc, [targetKey]: mail[key] }
}, {})
}
makeAllTextAddresses(mail: any) {
const keys = ['from', 'to', 'cc', 'bcc', 'replyTo']
const makeTextAddresses = (addresses: any) => {
const validAddresses = [].concat(addresses).filter(Boolean)
const textAddresses = validAddresses.map((item: any) =>
item.address
? item.name
? item.name + ' <' + item.address + '>'
: item.address
: typeof item === 'string'
? item
: null,
)
return textAddresses.filter(Boolean).join()
}
const result = keys.reduce((result, key) => {
const textAddresses = makeTextAddresses(mail[key])
if (!textAddresses) {
return result
}
return { ...result, [key]: textAddresses }
}, {})
return result
}
async send(mailgunSend: any) {
const self = this
return async (sendData: any, callback: any) => {
const { data } = sendData
try {
const addresses = this.makeAllTextAddresses(data)
const extendedMail = {
...data,
...addresses,
}
const whitelistedMail = self.applyKeyWhitelist(extendedMail)
const result = await mailgunSend(whitelistedMail)
callback(null, { ...result, messageId: result.id })
} catch (error) {
callback(error)
}
}
}
}
<file_sep>/apps/plugin-example-vue3/jest.config.ts
module.exports = {
displayName: 'web',
preset: '../../jest.preset.ts',
transform: {
'^.+\\.[jt]sx?$': 'ts-jest',
},
globals: {
'ts-jest': {
babelConfig: true,
},
},
testEnvironment: 'jsdom',
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
moduleFileExtensions: ['ts', 'js', 'vue'],
testTimeout: 10000,
}
<file_sep>/apps/api-evidence/src/app/schemas/evidence.py
from pydantic import BaseModel
# Shared properties
class EvidenceBase(BaseModel):
title: str
description: str
# Properties to receive on evidence creation
class EvidenceCreate(EvidenceBase):
storage_backend: str
file_key: str
media_type: str
# Properties to receive on evidence update
class EvidenceUpdate(EvidenceBase):
pass
# Properties shared by models stored in DB
class EvidenceInDBBase(EvidenceBase):
id: int
owner_id: int
class Config:
orm_mode = True
# Properties to return to client
class Evidence(EvidenceInDBBase):
pass
# Properties properties stored in DB
class EvidenceInDB(EvidenceInDBBase):
pass
<file_sep>/apps/web-evidence/README.md
# Evidence Uploader Frontend
Generated with [nx-vue3-vite](https://github.com/samatechtw/nx-vue3-vite)
<file_sep>/apps/developer-docs/docs/utilities/shortener.md
# Link Shortener
Repository: https://github.com/solomondefi/link-shortener
The link shortener is a simple utility to generate short links, and redirect requests to the shortened URL.
It has a few extra features:
- Token authentication for creating URLs
- Preferred short codes with fallback to random generation
### Usage
Solomon hosts a link shortener for the purpose of on-chain links to purchase/escrow dispute documentation. The purpose is mainly convenience and gas efficiency, but it also simplifies other optional services built around Solomon.
The intent is not to guarantee durable links, but to handle short lived pointers to off-chain data, since a dispute will never last longer than ~1 month.
### Technology
The services is written in Python. Poetry is used for dependency management, and the redirect/API server uses Flask. SQLite3 with SQLAlchemy is used for the data store, and a cache will be added when necessary.
<file_sep>/apps/blockchain-watcher/src/Entity/ScanLogEntity.ts
import { Entity, PrimaryKey, Property } from '@mikro-orm/core'
import { v4 } from 'uuid'
@Entity({
tableName: 'scan_log',
})
export class ScanLogEntity {
@PrimaryKey()
id: string = v4()
@Property()
blockHash!: string
@Property()
lastScanned!: number
}
<file_sep>/apps/developer-docs/docs/contracts/index.md
# Solomon Decom Contracts
All Solomon smart contracts are contained in the monorepo: https://github.com/solomondefi/solomon-monorepo
### Solomon Contract Factory
TODO -- updated after monorepo migration
- Package name: `@solomondefi/contract-factory`
- Source: https://github.com/solomondefi/slm-contracts/blob/main/contracts/SlmFactory.sol
- Contracts:
- `SlmFactory.sol`
A contract factory for producing chargeback, preorder, and escrow contracts with low gas cost. Depends on `SlmChargeback`, `SlmPreorder`,
`SlmEscrow`, and `SlmJudgement`.
### Solomon Contract Library
Library contracts with helper methods for chargeback, preorder, and escrow related functionality.
- Package name: `@solomondefi/contract-library`
- Source: https://github.com/solomondefi/slm-contracts/tree/main/library
- Contracts:
- `SlmPurchaseUtil.sol`
- Utility functions common to purchase contracts
- `SlmJudgement.sol`
- Mediates purchase disputes
- `SlmStaking.sol`
- Provides a mechanism for staking SLM, and distributes purchase fees to stakers
### Solomon Chargeback
Purchase/Chargeback contract that provides buyer protection for traditional ecommerce purchases.
- Package name: `@solomondefi/contract-chargebacks`
- Source: https://github.com/solomondefi/slm-contracts/blob/main/contracts/SlmChargeback.sol
- Contracts:
- `SlmChargebacks.sol`
- Chargeback functionality for ecommerce purchases
### Solomon Preorder
Preorder contract that can also be used for crowdfunding.
- Package name: `@solomondefi/contract-preorder`
- Source: https://github.com/solomondefi/slm-contracts/blob/main/contracts/SlmPreorder.sol
- Contracts:
- `SlmPreorder.sol`
- Preorder functionality for ecommerce, crowdfunding, etc
### Solomon Escrow
Escrow contract for large transactions with strict requirements.
- Package name: `@solomondefi/contract-escrow`
- Source: https://github.com/solomondefi/slm-contracts/blob/main/contracts/SlmEscrow.sol
- Contracts:
- `SlmEscrow.sol`
- Escrow functionality for personal and B2B transactions
## Contribution
SLM purchase contracts are written in Solidity. We use [Hardhat](https://hardhat.org/) for development, and future packages will be pushed
to NPM. For now, contracts are included by adding a git tag to dependencies, and importing directly from `node_modules/`
**Install** (we recommend [pnpm](https://pnpm.js.org/) if you work with many node projects):
```
npm install
```
**Compile**
```
npx hardhat compile
```
**Test**
```
npx hardhat test
```
TODO -- Include specific contribution guidelines
<file_sep>/apps/api-dispute/src/app/utils/deps.py
import hmac
import typing
from fastapi import Request
from app.config import config
from app.db.session import SessionLocal
from app.utils.security import generate_signature
def get_db() -> typing.Generator:
try:
db = SessionLocal()
yield db
finally:
db.close()
class SignatureHeader:
secret_key = config.MESSAGE_SECRET_KEY
def is_valid_signature(self, signature: str, message: bytes) -> bool:
return hmac.compare_digest(
signature, generate_signature(self.secret_key, message)
)
async def __call__(self, request: Request) -> typing.Optional[typing.Any]:
signature = request.headers[config.SIGNATURE_HEADER_NAME]
if not signature:
return None
message = await request.body()
if not self.is_valid_signature(signature, message):
return None
return await request.json()
<file_sep>/apps/db/src/app/scripts/wait-db.sh
#!/bin/sh
# Print each command and exit on error
# set -x
DB_SERVICE_HOST=${DB_SERVICE_HOST:=localhost}
DB_SERVICE_PORT=${DB_SERVICE_PORT:=5432}
DB_USER=${DB_USER:=postgres}
DB_CONNECT_OPTS="-h $DB_SERVICE_HOST -p $DB_SERVICE_PORT -U $DB_USER"
# Wait for the DB service to be up
echo "[INFO] Waiting for database service..."
wait_cmd="pg_isready $DB_CONNECT_OPTS -d postgres"
until $($wait_cmd &>/dev/null)
do
echo "[INFO] Waiting for the database service to be up..."
sleep 2
done
echo "DONE"
<file_sep>/apps/blockchain-watcher/src/service/mailService.spec.ts
import mailService from './mailService'
import { JSDOM } from 'jsdom'
import generateMailTemplates from '@solomon/blockchain-watcher/feature-templates'
describe('mailService', () => {
jest.setTimeout(60 * 1000)
beforeAll(async () => {
await generateMailTemplates()
})
test('constructor()', async () => {
expect(mailService).toBeDefined()
})
test('init()', async () => {
await expect(mailService.init()).resolves.not.toThrow()
})
test('send()', async () => {})
test('getTemplateHtml()', async () => {
let templateHtml = await mailService.getTemplateHtml('_test.html')
let finalHtml = templateHtml({
foo: 'foo',
bar: 'bar',
})
let dom = new JSDOM(finalHtml)
let r1 = dom.window.document.querySelector('#foo')?.textContent
let r2 = dom.window.document.querySelector('img')?.getAttribute('src')
expect(r1).toEqual('foo')
expect(r2).toEqual('bar')
})
test('sendChargebackCreatedEmail()', async () => {
let realSend = mailService.send
mailService.send = jest.fn()
await mailService.sendChargebackCreatedEmail('foo')
expect(mailService.send.call.length).toEqual(1)
mailService.send = realSend
})
test('sendPreorderCreatedEmail()', async () => {
let realSend = mailService.send
mailService.send = jest.fn()
await mailService.sendPreorderCreatedEmail('foo')
expect(mailService.send.call.length).toEqual(1)
mailService.send = realSend
})
test('sendEscrowCreatedEmail()', async () => {
let realSend = mailService.send
mailService.send = jest.fn()
await mailService.sendEscrowCreatedEmail('foo')
expect(mailService.send.call.length).toEqual(1)
mailService.send = realSend
})
})
<file_sep>/libs/web/ui-widgets/vite.config.ts
import path from 'path'
import { defineConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'
import VueI18n from '@intlify/vite-plugin-vue-i18n'
module.exports = defineConfig({
assetsInclude: /\.(pdf|jpg|png|svg)$/,
plugins: [Vue(), VueI18n()],
resolve: {
alias: {
'@theme/': `${path.resolve(__dirname, '../ui-theme/src')}/`,
},
},
build: {
lib: {
entry: path.resolve(__dirname, './src/index.ts'),
name: 'ui-widgets',
fileName: (format) => `ui-widgets.${format}.js`,
},
rollupOptions: {
// externalize deps that shouldn't be bundled
external: ['vue'],
output: {
// globals to use in the UMD build for externalized deps
globals: {
vue: 'Vue',
},
},
},
},
})
<file_sep>/apps/web-evidence/vite.config.ts
import path from 'path'
import { defineConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import ViteImages from 'vite-plugin-vue-images'
export default defineConfig({
assetsInclude: /\.(pdf|jpg|png|svg)$/,
resolve: {
alias: {
'@theme/': `${path.resolve(__dirname, '../../libs/web/ui-theme/src')}/`,
},
},
publicDir: path.resolve(__dirname, './src/public'),
plugins: [
Vue(),
Components({
dirs: ['src/app/components', '../../libs/web/ui-widgets'],
}),
ViteImages({ dirs: ['src/assets/img', '../../libs/web/ui-theme/src/img'] }),
],
})
<file_sep>/apps/web-evidence/src/app/store.ts
import { reactive, computed, watch } from 'vue'
const storeName = 'web-evidence-store'
// Increment to clear data on start, to avoid broken app state
const STORE_VERSION = 0
interface State {
version: number
cookiesAccepted: boolean
}
const initialState = (): State => ({
version: STORE_VERSION,
cookiesAccepted: false,
})
const saveState = (state: State) => {
localStorage.setItem(storeName, JSON.stringify(state))
}
const initialStateSetup = () => {
data = initialState()
saveState(data)
}
const raw = localStorage.getItem(storeName)
let data = null
if (raw) {
data = JSON.parse(raw)
if (data.version !== STORE_VERSION) {
console.log(`Store upgraded from ${data.version} to ${STORE_VERSION}`)
initialStateSetup()
}
} else {
initialStateSetup()
}
const state = reactive(data)
watch(state, saveState)
export const useStore = (): unknown => ({
cookiesAccepted: computed(() => state.cookiesAccepted),
setCookiesAccepted: (accepted: boolean) => {
state.cookiesAccepted = accepted
},
})
<file_sep>/libs/web/ui-widgets/src/index.ts
export { default as Checkbox } from './lib/Checkbox.vue'
export { default as ErrorMessage } from './lib/ErrorMessage.vue'
export { default as FileUpload } from './lib/FileUpload.vue'
export { default as SlmInput } from './lib/SlmInput.vue'
export { default as SlmSelect } from './lib/SlmSelect.vue'
export { default as Dropdown } from './lib/Dropdown.vue'
export { default as Caret } from './lib/Caret.vue'
export { default as Info } from './lib/svg/Info.vue'
export { default as Upload } from './lib/svg/Upload.vue'
<file_sep>/apps/api-evidence/src/app/tests/utils/evidence.py
import random
from typing import Optional
from sqlalchemy.orm import Session
from app import crud, models
from app.config import config
from app.schemas.evidence import EvidenceCreate
from app.tests.utils import random_lower_string
from app.tests.utils.user import create_random_user
def generate_content_type() -> str:
return random.choice(config.ALLOWED_FILE_TYPES)
def create_random_evidence(
db: Session, *, owner_id: Optional[int] = None
) -> models.Evidence:
if owner_id is None:
user, _ = create_random_user(db)
owner_id = user.id
title = random_lower_string()
description = random_lower_string()
evidence = EvidenceCreate(
title=title,
description=description,
storage_backend='s3',
file_key=random_lower_string(),
media_type=generate_content_type(),
)
return crud.evidence.create_with_owner(db=db, obj_in=evidence, owner_id=owner_id)
<file_sep>/README.md
# Solomon Monorepo
This monorepo contains all the main apps and libraries used in the Solomon payments ecosystem. It relies on [Nx](https://nx.dev) for generating, running, building, and testing.
We recommend [PNPM](https://pnpm.io/) over NPM for package management. In the following sections, we also make use of an `pnpx` alias, which can be added to your shell profile.
```bash
npm install -g pnpm
alias pnx="pnpm run nx --"
pnpm install
```
## Getting started
Follow these instructions to set up your local development environment. Only MacOs instructions are provided, but a similar process can be followed on other systems (replace Brew with local package manager).
**Global Dependencies**
1. **[Docker](https://www.docker.com/products/docker-desktop)** - containerization Kubernetes cluster on your desktop.
- :exclamation: **After install:** Enable local Kubernetes cluster in preferences per [these instructions](https://docs.docker.com/desktop/kubernetes/#enable-kubernetes).
It will take a few minutes to provision the cluster for the first time.
2. **[Homebrew](https://brew.sh/)** - package manager for macOS.
3. **[NodeJs (LTS)](https://nodejs.org/docs/latest-v14.x/api/index.html) and NPM** -
Follow [NVM Wiki](https://github.com/SolomonDefi/solomon-monorepo/wiki/NVM) to install
and select the correct Node/NPM versions
4. **[Helm](https://helm.sh/)** - The package manager for Kubernetes.
```sh
$ brew install helm
```
5. **[Skaffold](https://skaffold.dev/)** - build/deploy tool for local Kubernetes development.
```sh
$ brew install skaffold
```
**Start local dev environment**
```sh
$ pnpm install
$ pnpm run skaffold
```
- It may take up to 10 minutes for skaffold to run for the first time. The subsequent runs
should be much faster because artifacts are cached
- The skaffold run is usually finished when it a) settles (i.e. no more stuff is
written to the terminal log) and b) you are able to verify responses from the
apps in the next step.
**Run individual Dockerfiles**
It's possible to run apps individually, which can be useful if you're verifying package changes or debugging docker syntax:
```
docker build --progress=plain --no-cache -t blockchain-watcher:dev -f apps/blockchain-watcher/Dockerfile --target=dev .
docker build --progress=plain --no-cache -t api-evidence:dev -f apps/api-evidence/Dockerfile --target=dev .
docker build --progress=plain --no-cache -t api-dispute:dev -f apps/api-dispute/Dockerfile --target=dev .
docker build --progress=plain --no-cache -t web-evidence:dev -f apps/web-evidence/Dockerfile --target=dev .
docker build --progress=plain --no-cache -t db-api -f apps/db-api/Dockerfile .
```
## Apps
The following table outlines all the apps available. Each app is located in `apps/<app-name>`, and `<app-name>` can be substituted in the next section to serve, build, or test specific apps.
| app-name | Description |
| ------------------ | ----------------------------------------------------------------------- |
| blockchain-watcher | Watches Solomon contracts and emails relevant parties when events occur |
### App Commands
**Serve (local development)**
```bash
pnpx nx serve <app-name>
```
**Build**
```bash
pnpx nx build <app-name>
```
**Test**
```bash
pnpx nx test <app-name>
```
### Solomon Evidence Uploader
- Frontend: `apps/web-evidence`
- Backend: `apps/api-evidence`
- [Setup instructions](./apps/api-evidence)
The purpose of the uploader is to provide a simple interface for uploading evidence links to the blockchain during escrow disputes. Links must exist for the duration of the dispute (generally a maximum of 2 months). There are several methods for uploading evidence, and it is straightforward to add more.
1. User provides their own link
2. User provides files and the `backend` uploads to an S3-compatible data store
3. (TBD) Pin on an IPFS node for the duration of a dispute
Currently, only Metamask is supported as a wallet provider for posting the link to the blockchain, but WalletConnect and other methods may be added in the future.
A hosted frontend and backend will be provided by Solomon, based on this repository.
## Contribute
### Commit message
The commit message format is: `<scope> [<project>]: <short-summary> #<issue-number>`
- `scope`: Follow the [gitmoji](https://gitmoji.dev/) rule
- `project`: One of `web`, `api`, `blockchain`, `docs` and `root`
- `short-summary`: Short summary about this commit
- `issue-number`: The related issue number
All commit message header sections are required, and enforced by [husky](https://github.com/typicode/husky).
You can check the validator [here](/tools/scripts/checkCommitMsg.ts).
The following are `gitmoji` recommendations for the `scope`. These are not currently enforced, but may be in the future.
- Release/tag - :bookmark: `:bookmark:`
- Feature - :sparkles: `:sparkles:`
- Docs - :books: `:books:`
- Bugfix - :bug: `:bug:`
- Testing - :white_check_mark: `:white_check_mark:`
- Lint/format - :art: `:art:`
- Refactor - :hammer: `:hammer:`
- Code/file removal - :fire: `:fire:`
- CI/CD - :green_heart: `:green_heart:`
- Deps - :lock: `:lock:`
- Breaking changes - :boom: `:boom:`
- Config - :wrench: `:wrench:`
### Troubleshooting
- Error `**.sh: not found` when running skaffold in Windows.
- Make sure the EOL os `*.sh` files is `LF`, not `CRLF`, you can change it in your IDE. [SO ref here](https://stackoverflow.com/questions/40487747/trying-to-build-a-docker-container-start-sh-not-found).
<file_sep>/apps/blockchain-watcher/src/service/ethService.spec.ts
import ethService, { EthService } from './ethService'
describe('ethService', () => {
test('constructor()', async () => {
expect(ethService).toBeInstanceOf(EthService)
})
})
<file_sep>/apps/api-dispute/src/app/db/base_class.py
from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import as_declarative
@as_declarative()
class Base:
id = Column(Integer, primary_key=True, index=True)
<file_sep>/libs/web/data-access-state/jest.config.ts
module.exports = {
displayName: 'web-data-access-state',
preset: '../../../jest.preset.ts',
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
},
},
testEnvironment: 'jsdom',
transform: {
'^.+\\.[tj]sx?$': 'ts-jest',
},
setupFiles: ['jest-localstorage-mock'],
resetMocks: false,
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory: '../../../coverage/libs/web/data-access-state',
}
<file_sep>/apps/blockchain-watcher/src/service/mailService.ts
import path from 'path'
import nodemailer, { Transporter } from 'nodemailer'
import { readFile } from 'fs-extra'
import Handlebars from 'handlebars'
import pathStore from '@solomon/shared/util-path-store'
import MailgunTransport from '../util/MailgunTransport'
import envStore from '../store/envStore'
class MailService {
mailer: Transporter = null as any
async send(to: string | string[], subject: string, html: string, text: string) {
let info = await this.mailer.sendMail({
from: '<EMAIL>',
to: to,
subject: subject,
html: html,
text: text,
})
return info
}
async getTemplateHtml(htmlName: string): Promise<HandlebarsTemplateDelegate> {
let htmlPath = path.resolve(pathStore.watcher, 'src', 'template', htmlName)
let rawHtml = await readFile(htmlPath, 'utf-8')
let templateHtml = Handlebars.compile(rawHtml)
return templateHtml
}
async sendChargebackCreatedEmail(to: string) {
let subject = 'Chargeback created'
let templateHtml = await this.getTemplateHtml('chargebackCreated.html')
let finalHtml = templateHtml({
// TODO
})
let text = ''
await this.send(to, subject, finalHtml, text)
}
async sendPreorderCreatedEmail(to: string) {
let subject = 'Preorder created'
let templateHtml = await this.getTemplateHtml('preorderCreated.html')
let finalHtml = templateHtml({
// TODO
})
let text = ''
await this.send(to, subject, finalHtml, text)
}
async sendEscrowCreatedEmail(to: string) {
let subject = 'Escrow created'
let templateHtml = await this.getTemplateHtml('escrowCreated.html')
let finalHtml = templateHtml({
// TODO
})
let text = ''
await this.send(to, subject, finalHtml, text)
}
async init() {
const transport = new MailgunTransport({
auth: {
api_key: envStore.mailgunApiKey,
domain: envStore.mailgunDomain,
},
})
this.mailer = nodemailer.createTransport(transport.getPlugin())
}
constructor() {}
}
export default new MailService()
<file_sep>/apps/db/Dockerfile
# INIT-DB IMAGE (? MB)
# ------------------------------------------------------------------------------------
FROM alpine:3.14
ARG NODEJS_VER=14
ENV NODEJS_VER=$NODEJS_VER
ARG TINI_VER=0.19
ENV TINI_VER=$TINI_VER
ARG POSTGRES_CLIENT_VER=13
ENV POSTGRES_CLIENT_VER=$POSTGRES_CLIENT_VER
RUN apk add --no-cache \
jq~=1 \
nodejs~="$NODEJS_VER" \
postgresql-client~="$POSTGRES_CLIENT_VER" \
tini~="$TINI_VER" \
curl~=7
RUN curl -f https://get.pnpm.io/v6.14.js | node - add --global pnpm
RUN addgroup -g 1001 -S app && adduser -u 1001 -S app -G app
WORKDIR /usr/src/db/
COPY tools/scripts/package-subset.js ./tools/scripts/
COPY subset.config.js ./
COPY package.json ./
RUN node ./tools/scripts/package-subset.js db-dev subset.config.js package.json package.json
RUN pnpm install
COPY apps/db/src/app ./apps/db/src/app
COPY apps/db/src/app/scripts ./apps/db/src/app/scripts
<file_sep>/apps/api-evidence/src/app/api/__init__.py
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from app.api import auth, evidence, users
api_router = APIRouter()
api_router.include_router(auth.router, prefix='/auth', tags=['Authentication'])
api_router.include_router(users.router, prefix='/users', tags=['Users'])
api_router.include_router(evidence.router, prefix='/evidence', tags=['Evidence'])
@api_router.get('/health/app', tags=['Healthcheck'])
def healthcheck() -> JSONResponse:
return JSONResponse({'status': 'ok'})
<file_sep>/apps/api-evidence/src/app/storage/backend/__init__.py
import typing
class StorageBackendError(Exception):
pass
class StorageBackend:
name: str
def save_file(self, name: str, file: typing.IO) -> str:
raise NotImplementedError
def get_file(self, key: str) -> typing.IO:
raise NotImplementedError
<file_sep>/apps/contracts/src/tests/SlmChargebacks.ts
import { ethers } from 'hardhat'
import chai from 'chai'
const { expect } = chai
describe('SLM Chargebacks', function () {
it('Deploy SLM token', async function () {
const [owner] = await ethers.getSigners()
const TokenFactory = await ethers.getContractFactory('SlmToken')
const ChargebackFactory = await ethers.getContractFactory('SlmChargeback')
const initialSupply = ethers.utils.parseEther('100000000')
const token = await TokenFactory.deploy(
'SLMToken',
'SLM',
initialSupply,
owner.address,
)
const chargeback = await ChargebackFactory.deploy()
// Check token balances are correct
const ownerBalance = await token.balanceOf(owner.address)
expect(await token.totalSupply()).to.equal(ownerBalance)
expect(initialSupply).to.equal(ownerBalance)
})
})
<file_sep>/libs/web/data-access-state/src/lib/store.ts
import { reactive, watch } from 'vue'
export type StoreData = {
version?: number
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any
}
export interface StoreApi<DataType extends StoreData> {
// Increment to clear data on start, to avoid broken app state
initialState: () => DataType
}
export class Store<AppStoreApi extends StoreApi<DataType>, DataType extends StoreData> {
name: string
api: AppStoreApi
data!: DataType
constructor(name: string) {
this.name = name
}
private initializeState(state: DataType) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.data = reactive<any>(state)
this.save()
}
init(api: AppStoreApi) {
this.api = api
const raw = localStorage.getItem(this.name)
const defaultState = this.api.initialState()
if (!defaultState.version) {
throw new Error('Store - version must exist in top level store')
}
if (raw) {
const state = JSON.parse(raw) as DataType
if (state.version !== defaultState.version) {
console.log(`Store upgraded from ${state.version} to ${defaultState.version}`)
this.initializeState(defaultState)
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.data = reactive<any>(state)
}
} else {
this.initializeState(defaultState)
}
watch(this.data, this.save)
}
save = () => {
localStorage.setItem(this.name, JSON.stringify(this.data))
}
}
<file_sep>/apps/developer-docs/docs/guide/index.md
# Getting Started
This site contains documentation and links pertaining to all Solomon code repositories. Before contributing, make sure to review the [guidelines](/guide/contributing) relevant to the project, the [commit message format](/guide/commit-format), and read through the [code of conduct](/guide/code-of-conduct) Choose a link on the left to get started with project documentation, or check out helpful links below, organized by project type:
Solomon uses a monorepo for all apps and libraries that make up the ecosytem:
## Monorepo Root
- https://github.com/SolomonDefi/solomon-monorepo
### Plugin
- App
- TBD (monorepo migration in progress)
- Libs
- TBD (monorepo migration in progress)
- Plugin Demo: https://plugin-demo.solomondefi.com/
### Contracts
- App
- TBD (monorepo migration in progress)
- Libs
- TBD (monorepo migration in progress)
**Non-monorepo**
- https://github.com/solomondefi/presale-vesting
- The presale is over, so the repository will not be migrated to the monorepo
### Utilities
- Blockchain Watcher App
- https://github.com/SolomonDefi/solomon-monorepo/tree/main/apps/blockchain-watcher
- Link shortener
- TBD (monorepo migration in progress)
- Evidence Uploader
- TBD (monorepo migration in progress)
### Docs
- App
- https://github.com/SolomonDefi/solomon-monorepo/tree/main/apps/developer-docs
## Sites
Our documentation, marketing and presale sites are also open source:
- Repositories
- https://github.com/solomondefi/docs
- Documentation site: https://solomondefi.github.io/docs
- https://github.com/solomondefi/landing-page
- Marketing landing page: https://solomondefi.com
- https://github.com/solomondefi/presale-site
- Deprecated (sale over)
- https://github.com/solomondefi/splash
- Deprecated (replaced by landing page)
<file_sep>/apps/api-evidence/src/app/db/init_db.py
from sqlalchemy.orm import Session
from app import crud, schemas
from app.config import config
from app.db import base # noqa: F401
# Import all SQLAlchemy models (app.db.base) before initializing DB
def init_db(db: Session) -> None:
# Tables created with Alembic migrations
admin_email = config.INITIAL_ADMIN_EMAIL
user = crud.user.get_by_email(db, email=admin_email)
if not user:
user_in = schemas.UserCreate(
email=admin_email,
password=<PASSWORD>.<PASSWORD>,
is_superuser=True,
)
user = crud.user.create(db, obj_in=user_in)
<file_sep>/apps/blockchain-watcher/src/store/envStore.spec.ts
import envStore from './envStore'
describe('mailService', () => {
test('constructor()', async () => {
expect(envStore).toBeDefined()
})
})
<file_sep>/apps/web-evidence/Dockerfile
# BASE IMAGE (37.4MB)
# ------------------------------------------------------------------------------------
FROM alpine:3.14.1 AS base
ARG NODEJS_VER=14
ENV NODEJS_VER=$NODEJS_VER
ARG NPM_VER=7
ENV NPM_VER=$NPM_VER
ARG TINI_VER=0.19
ENV TINI_VER=$TINI_VER
RUN apk add --no-cache g++ make python3 nodejs~="$NODEJS_VER" tini~="$TINI_VER" curl~=7
RUN curl -f https://get.pnpm.io/v6.14.js | node - add --global pnpm
RUN addgroup -g 1001 -S app && adduser -u 1001 -S app -G app
# WEB EVIDENCE DEV APP IMAGE (214 MB)
# ------------------------------------------------------------------------------------
FROM base as dev
ENV SHELL=/bin/sh
WORKDIR /usr/src
COPY subset.config.js ./
COPY package.json ./
COPY tools/scripts/package-subset.js ./tools/scripts/
RUN node ./tools/scripts/package-subset.js web-evidence subset.config.js package.json package.json
RUN pnpm install
COPY workspace.json ./
COPY nx.json ./
COPY tsconfig*.json ./
COPY libs/web ./libs/web
COPY apps/web-evidence/cypress.json ./apps/web-evidence/
COPY apps/web-evidence/tsconfig*.json ./apps/web-evidence/
COPY apps/web-evidence/index.html ./apps/web-evidence/
COPY apps/web-evidence/vite.config.ts ./apps/web-evidence/
COPY apps/web-evidence/postcss.config.js ./apps/web-evidence/
COPY apps/web-evidence/src ./apps/web-evidence/src
ENTRYPOINT ["/sbin/tini", "-v", "--"]
CMD ["pnpm", "exec", "nx", "serve", "web-evidence"]<file_sep>/apps/api-evidence/src/app/schemas/__init__.py
# flake8: noqa
from .auth import AddressChallenge, AddressChallengeCreate
from .token import Token, TokenPayload
from .evidence import Evidence, EvidenceCreate, EvidenceInDB, EvidenceUpdate
from .user import AddressUserChallenge, User, UserCreate, UserInDB, UserUpdate
<file_sep>/apps/contracts/README.md
#
Generated via [`nx-hardhat`](https://github.com/samatechtw/nx-hardhat)
## Usage
[Hardhat](https://hardhat.org/) is used for contract development and deploy.
**Compile contracts** (see [Environment](#environment))
```bash
$ pnpx nx build contracts
```
**Run tests**
```bash
$ pnpx nx test contracts
# With coverage (TODO -- not implemented yet)
$ pnpx nx test-coverage contracts
```
**Lint**
```bash
# Tests and config files (JS/TS)
$ pnpx nx lint contracts
# Contracts
$ pnpx nx lint-solidity contracts
```
**Hardhat local blockchain node**
```bash
$ pnpx nx dev contracts
```
**Deploy**
```bash
# To local node
$ pnpx nx deploy contracts
# To Ropsten testnet (needs "ROPSTEN_X" env vars)
$ pnpx nx deploy --network testnet contracts
```
**Misc**
```sh
# Clear cache and delete all artifacts
$ pnpx nx clean contracts
```
## Environment
The repo comes with and example config in `.env.dist`. These represent the defaults; to modify them copy the file to `.env` and edit.
| Name | Default | Description |
| ----------------- | ------- | ----------------------------------------------------------------------- |
| HARDHAT_LOGGING | 1 | Logger switch |
| WALLET_MNEMONIC | - | Custom wallet mnemonic for local dev (for Metamask testing convenience) |
| ETHERSCAN_API_KEY | - | API key for etherscan. Used for deployed contract verification. |
| ROPSTEN_RPC_URL | - | RPC URL for ropsten testnet deploy |
| ROPSTEN_MNEMONIC | - | Wallet mnemonic for ropsten deploy |
| TEST_REPORT_GAS | 1 | Report gas usage after test |
<file_sep>/apps/developer-docs/docs/guide/why-solomon.md
# Why Solomon
The mission of the Solomon Project is to bring about the mainstream adoption of online cryptocurrency payments.
Solomon will achieve this by offering traditional ecommerce protections while preserving the benefits of decentralization. Our plugin
will allow any merchant to easily accept cryptocurrency and inspire consumer confidence with chargebacks, preorders, and escrow.
We call this model “decentralized ecommerce”, or DeCom for short. By combining the virtues of decentralized finance with the protections
demanded by consumers, Solomon will finally bring cryptocurrency payments into the mainstream.

## Problems for Consumers
It is telling that the biggest problem with cryptocurrency in regards to ecommerce is the fact that nearly everyone has heard of it yet
hardly anyone _uses_ it.
The advantages of cryptocurrency over credit cards are known and many: accessibility, low fees, fast transactions, unparalleled security,
globalization, and more.
The only disadvantage appears when transactions happen in the real world, such as in the delivery of goods and services. If a buyer sends
cryptocurrency to buy a product online, it is impossible today to reverse the charge if what they receive is not what was promised.
## Problems for Sellers
If this problem of consumer confidence can be solved, sellers will be eager to move away from the credit card-driven system.
In short, the current financial system is overly exclusive and centralized. Profit-driven institutions enforce onerous and often arbitrary
rules, hurting smaller sellers.
Sellers are at the mercy of these institutions, otherwise they are unable to accept payments and earn a living. In the best case scenario,
sellers put up with high fees, slow payment terms, demanding cash deposits, and chargeback penalties. Worst case, they are excluded from
banks and cannot open an account at all, or they are dropped without warning due to rules that favor larger sellers.
There are many reasons why sellers are currently excluded that have nothing to do with the value they offer consumers.
Independent sellers, especially immigrants, may not have a long credit history or the correct paperwork for traditional bank accounts. They
may be unable to afford the high “Reserve Account” deposits that banks require for new sellers, anywhere from 10–20% of monthly revenue.
They may get throttled by monthly payment processing maximums during times when banks should be supporting their growth. Or the bank may
simply not understand or like their products and cut the relationship.
Even if a seller can maintain a relationship with a bank and merchant gateway, they can fall victim to fraudulent chargebacks and associated high fees.
Credit card companies almost never side with sellers for chargebacks, no matter the evidence. Instead, they are incentivized to keep their
cardholders happy because cardholders can easily switch cards, while sellers are desperate to stay on the network and accept payments. Not
only do sellers lose out on vital revenue, banks will tack on extremely high processing fees on top.
In addition, sellers can rarely, if ever, find credit card processors willing to support self-hosted preorder campaigns. Instead, they must
turn to additional third parties who charge a high percentage of revenue on top of credit card fees. Thus, small-scale sellers have limited
options to raise early cash flow, which is when they need it the absolute most.
In today’s pandemic-ravaged world, it has never been more important to give smaller entrepreneurs a chance to earn their livelihoods online.
Hosting and helping only large-scale sellers, such as Amazon, will hurt all consumers in the long run.
## Solution
The Solomon Plugin is an easy-to-use software tool that allows entrepreneurs to accept cryptocurrency payments for their businesses. Any
business can implement the plugin on their sites with only a few lines of code, and consumers and merchants will be protected equally and
fairly.
Immediately they will be able to accept payments from around the world and at significantly lower cost than the traditional 3–5% taken by
credit card processors. The fee is further reduced if paid by the merchant in a native token called the Solomon token (SLM). Users locked
out of traditional access to major ecommerce platforms can now easily incorporate payment processing on their websites without difficulty.
In addition, Solomon introduces completely new features inspired by the Decentralized Finance (DeFi) movement, and is the pioneering project
behind the new concept of Decentralized Ecommerce (DeCom).
Decentralized ecommerce will democratize access and ownership of online commerce while simultaneously improving security and trust.
Fraudulent chargebacks will be eliminated by smart contracts that provide the benefits of traditional escrow but without the traditional
costs and exclusiveness. Escrow smart contracts also enable trustworthy crowdfunding and preorder features because funds can be released on
a schedule, and only if goods are delivered as promised.
Traditional dispute resolution usually entails high costs, bad outcomes, and unfair incentives, with credit card companies protecting their
cardholders and escrow agents protecting their profit margins. Instead, Solomon incentivizes a community of decentralized jurors with
Solomon (SLM) token to handle any disputes if they arise.
### Solomon Jurors
If chargeback or delivery disputes arise, specially elected Solomon jurors will be selected at random on the blockchain to arbitrate and
earn SLM tokens for their work. This creates a lucrative and decentralized gig economy for users. And because these jurors are both
specially elected and paid in SLM that are locked for 4 months, they are incentivized to believe in the platform and produce good work. Only
then will their tokens maintain or grow their value over time.
### Solomon Stakers
The Solomon Project is owned by a decentralized community of SLM holders who stake their tokens to long term non-trading. In return for
demonstrating long term alignment akin to traditional owners, stakers receive the fees generated by the Solomon Plugin each month minus any
payments made to jurors.
Due to their demonstrated financial investment, stakers will be trusted to elect new jurors to the system. Stakers are incentivized to elect
only high-quality, trusted jurors in order to protect their investment, and to elect as many qualified individuals as possible to make the
system robust and stable.

## Summary
Solomon ushers in a new era of decentralized commerce (DeCom) that will solve the remaining issues with accessibility and security in traditional ecommerce. The native Solomon token (SLM) ensures that ownership is decentralized and incentivizes a gig economy that maintains the quality of the system.
While at first glance this appears to taint blockchain with human intervention, the reality is that trade has and always will require cooperation between human parties. The difference is that Solomon does not rely on “good faith” or bloated, centralized institutions motivated by profits over fairness.
Instead, Solomon replaces the same features with a decentralized and efficient system where all stakeholders are personally invested in fairness and long-term success. The result will be fairness, accessibility, and the long-awaited adoption of cryptocurrency payments around the world.
<file_sep>/libs/web/plugin/vite.config.ts
import path from 'path'
import { defineConfig } from 'vite'
import Components from 'unplugin-vue-components/vite'
import ViteImages from 'vite-plugin-vue-images'
import Vue from '@vitejs/plugin-vue'
import tsconfigBase from '../../../tsconfig.base.json'
const resolve = (p: string) => path.resolve(__dirname, p)
const tsconfigBaseAliases = (rootOffset: string): Record<string, string> => {
const paths: Record<string, string[]> = tsconfigBase.compilerOptions?.paths || []
const aliases: Record<string, string> = {}
for (const [name, path] of Object.entries(paths)) {
const simplePath = path[0].replace('/*', '/')
const relative = `${rootOffset}${simplePath}`
if (name.includes('/*')) {
const resolved = `${resolve(relative)}/`
aliases[name.replace('/*', '/')] = resolved
} else {
aliases[name] = resolve(relative)
}
}
return aliases
}
module.exports = defineConfig({
assetsInclude: /\.(pdf|jpg|png|svg)$/,
resolve: {
alias: {
'@theme/': `${resolve('../../../libs/web/ui-theme/src')}/`,
...tsconfigBaseAliases('../../../'),
},
},
plugins: [Vue(), Components({ dirs: ['src/lib'] }), ViteImages()],
build: {
minify: false,
lib: {
entry: path.resolve(__dirname, './src/index.ts'),
name: 'plugin',
fileName: (format) => `plugin.${format}.js`,
},
rollupOptions: {
// externalize deps that shouldn't be bundled
external: ['vue'],
output: {
// globals to use in the UMD build for externalized deps
globals: {
vue: 'Vue',
},
},
},
},
})
<file_sep>/libs/shared/util-path-store/src/index.ts
export { default } from './lib/path-store'
<file_sep>/apps/blockchain-watcher/src/service/dbService.ts
import path from 'path'
import { MikroORM } from '@mikro-orm/core'
import { QueryOrderNumeric } from '@mikro-orm/core/enums'
import { pathExists, remove } from 'fs-extra'
import envStore from '../store/envStore'
import { ScanLogEntity } from '../Entity/ScanLogEntity'
export class DbService {
orm: MikroORM = null as any
get sqlitePath(): string {
return path.resolve(
__dirname,
'..',
'..',
`blockchain-watcher-storage.${envStore.envName}.db`,
)
}
get scanLogRepository() {
return this.orm.em.getRepository(ScanLogEntity)
}
async setLastScanned(blockHash: string) {
let newLog = this.scanLogRepository.create({
blockHash: blockHash,
lastScanned: Date.now(),
})
await this.scanLogRepository.persistAndFlush(newLog)
}
async getLastScanned() {
let lastLog = await this.scanLogRepository.find(
{},
{
orderBy: {
lastScanned: QueryOrderNumeric.DESC,
},
limit: 1,
},
)
return lastLog[0]
}
async resetForTest() {
await remove(this.sqlitePath)
await this.init()
}
async init() {
let isDbExist = await pathExists(this.sqlitePath)
let orm = await MikroORM.init({
entities: [ScanLogEntity],
dbName: this.sqlitePath,
type: 'sqlite',
})
this.orm = orm
if (!isDbExist) {
let generator = await this.orm.getSchemaGenerator()
await generator.dropSchema()
await generator.createSchema()
await generator.updateSchema()
}
}
}
export default new DbService()
<file_sep>/apps/plugin-example-vue3/src/app/utils/uid.ts
export class UidSingleton {
counter: number
constructor() {
this.counter = 0
}
next(): number {
this.counter += 1
return this.counter
}
}
export const uidSingleton = new UidSingleton()
<file_sep>/libs/web/data-access-api/src/lib/api.spec.ts
import 'jest-fetch-mock'
import { NftApi } from './api'
describe('webDataAccessApi', () => {
it('should work', () => {
const baseUrl = '/test/'
const api = new NftApi({
baseUrl,
})
expect(api.baseUrl).toEqual(baseUrl)
})
})
<file_sep>/apps/web-evidence/src/app/api.ts
import { FetchApi, FetchApiOptions } from '@sampullman/vue3-fetch-api'
import { API_URL } from './utils/config'
import { ApiResponse } from '@solomon/shared/util-api-evidence-types'
class NftApi extends FetchApi {
constructor(options: FetchApiOptions) {
super(options)
}
}
export const api = new NftApi({
baseUrl: API_URL,
responseInterceptors: [
async (res: Response): Promise<ApiResponse> => {
if (!res) {
throw new Error('NETWORK_FAILURE')
}
const { status } = res
if (status >= 500) {
throw new Error('NETWORK_FAILURE')
} else if (status === 401) {
// Permission denied
throw res
}
let data: Record<string, unknown>
try {
data = await res.json()
} catch (_e) {
// Avoid crashing on empty response
data = {}
}
if (status === 400) {
throw data
}
res.data = data
return res
},
],
})
<file_sep>/apps/db/src/app/scripts/init-db.sh
#!/bin/sh
# Print each command and exit on error
# set -x
DB_SERVICE_HOST=${DB_SERVICE_HOST:=localhost}
DB_SERVICE_PORT=${DB_SERVICE_PORT:=5432}
DB_USER=${DB_USER:=postgres}
DB_CONNECT_OPTS="-h $DB_SERVICE_HOST -p $DB_SERVICE_PORT -U $DB_USER -d postgres"
DB_PASSWORD_FILE=~/.<PASSWORD>
DB_PASSWORD_FILE_ENTRY=$DB_SERVICE_HOST:$DB_SERVICE_PORT:*:$DB_USER:$DB_PASSWORD
knex_exec=node_modules/.bin/knex
knex_dir=apps/db/src/app
# echo "[DEBUG] NODE_ENV=$NODE_ENV"
# echo "[DEBUG] DB_SERVICE_HOST=$DB_SERVICE_HOST"
# echo "[DEBUG] DB_USER=$DB_USER"
# echo "[DEBUG] DB_CONNECT_OPTS=$DB_CONNECT_OPTS"
echo "[INFO] Create PG password file if does not exist..."
echo "echo $DB_PASSWORD_FILE_ENTRY"
[ ! -f $DB_PASSWORD_FILE ] && touch $DB_PASSWORD_FILE && chmod 600 $DB_PASSWORD_FILE
grep -q -F $DB_PASSWORD_FILE_ENTRY $DB_PASSWORD_FILE || echo $DB_PASSWORD_FILE_ENTRY >> $DB_PASSWORD_FILE
db_exists=true
echo "[INFO] Check if app DB exists..."
psql $DB_CONNECT_OPTS -tc "SELECT 1 FROM pg_database WHERE datname = '$DB_NAME'" | \
grep -q 1 || db_exists=false
if [[ $NODE_ENV = "dev" && "$db_exists" = true ]]; then
echo "[INFO] Drop app and test databases in dev environment..."
# Option #1 (Dropping app database)
psql $DB_CONNECT_OPTS -c "UPDATE pg_database SET datallowconn = 'false' WHERE datname = '$DB_NAME'"
psql $DB_CONNECT_OPTS -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '$DB_NAME'"
psql $DB_CONNECT_OPTS -c "DROP DATABASE $DB_NAME"
# psql $DB_CONNECT_OPTS -c "DROP DATABASE ${DB_NAME}_test"
db_exists=false
fi
if [[ $db_exists != true ]]; then
echo "[INFO] Create app database..."
psql $DB_CONNECT_OPTS -c "CREATE DATABASE $DB_NAME"
fi
# TODO - commented out knex migrations, we may use something else
# echo "[INFO] Migrate $NODE_ENV app database..."
# NODE_ENV=$NODE_ENV $knex_exec --knexfile $knex_dir/knexfile.js migrate:latest
# # Need to do some extra steps for dev environment
# if [ "$NODE_ENV" = "dev" ]
# then
# echo "[INFO] Seeding dev database..."
# NODE_ENV=$NODE_ENV $knex_exec --knexfile $knex_dir/knexfile.js seed:run
# echo "[INFO] Create test database..."
# psql $DB_CONNECT_OPTS -tc "SELECT 1 FROM pg_database WHERE datname = '${DB_NAME}_test'" | \
# grep -q 1 || psql $DB_CONNECT_OPTS -c "CREATE DATABASE ${DB_NAME}_test"
# echo "[INFO] Migrate test database..."
# NODE_ENV=test $knex_exec --knexfile $knex_dir/knexfile.js migrate:latest
# fi
# echo "[INFO] Initializing of database is complete"
<file_sep>/apps/api-evidence/pyproject.toml
[tool.poetry]
name = "solomon-evidence-uploader-backend"
version = "0.1.0"
description = "A FastAPI (Python) app for uploading Solomon dispute evidence files to the blockchain"
authors = ["<NAME> <<EMAIL>>"]
[tool.poetry.dependencies]
python = "^3.9"
fastapi = "^0.68.1"
passlib = {extras = ["bcrypt"], version = "^1.7.2"}
uvicorn = "^0.14.0"
pydantic = "^1.8.2"
python-jose = {extras = ["cryptography"], version = "^3.1.0"}
psycopg2 = "^2.8.6"
SQLAlchemy = "^1.4.23"
starlette = "^0.14.2"
tenacity = "^8.0.1"
email-validator = "^1.1.3"
python-dotenv = "^0.19.0"
requests = "^2.26.0"
python-multipart = "^0.0.5"
eth-account = "^0.5.5"
alembic = "^1.7.3"
boto3 = "^1.18.44"
[tool.poetry.dev-dependencies]
pytest = "*"
mypy = "*"
sqlalchemy-stubs = "^0.4"
moto = {extras = ["s3"], version = "^2.2.8"}
boto3-stubs = {extras = ["s3"], version = "^1.18.49"}
black = "*"
flake8 = "*"
flake8-black = "*"
flake8-bugbear = "*"
flake8-import-order = "*"
flake8-comprehensions = "*"
[tool.mypy]
ignore_missing_imports = true
follow_imports = "skip"
show_column_numbers = true
disallow_untyped_defs = true
no_warn_no_return = true
plugins = ["sqlmypy"]
exclude = "migrations"
[tool.black]
include = '\.py$'
skip-string-normalization = true
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta:__legacy__"
<file_sep>/libs/web/data-access-api/src/index.ts
export * from './lib/api'
export { default as useCelebrityApi } from './lib/api-evidence'
export { default as useUserApi } from './lib/api-user'
<file_sep>/apps/api-evidence/src/app/tests/conftest.py
import os
import typing
import boto3
import pytest
from fastapi.testclient import TestClient
from moto import mock_s3
from mypy_boto3_s3.client import S3Client
from pydantic import PostgresDsn
from sqlalchemy import create_engine
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.orm import Session
from app.config import config
from app.db.base import Base
from app.db.session import engine, SessionLocal
from app.tests.utils import get_superuser_token_headers, random_email
from app.tests.utils.user import authentication_token_from_email
from main import app
def setup_db() -> None:
try:
conn = engine.connect()
conn.execute('commit')
conn.execute(f'drop database {config.TEST_DB}')
conn.close()
except ProgrammingError:
pass
try:
conn = engine.connect()
conn.execute('commit')
conn.execute(f'create database {config.TEST_DB}')
conn.close()
except ProgrammingError:
pass
config.SQLALCHEMY_DATABASE_URI = PostgresDsn.build(
scheme='postgresql',
user=config.POSTGRES_USER,
password=<PASSWORD>,
host=config.POSTGRES_SERVER,
path=f'/{config.TEST_DB}',
)
test_engine = create_engine(config.SQLALCHEMY_DATABASE_URI)
Base.metadata.create_all(test_engine)
SessionLocal.configure(bind=test_engine)
@pytest.fixture(scope='session')
def db() -> typing.Generator:
setup_db()
yield SessionLocal()
@pytest.fixture(scope='session')
def client() -> typing.Generator:
with TestClient(app) as c:
yield c
@pytest.fixture(scope='session')
def authed_client(
normal_user_token_headers: tuple[dict[str, str], int]
) -> typing.Generator:
with TestClient(app) as c:
headers, user_id = normal_user_token_headers
c.user_id = user_id
c.headers.update(headers)
yield c
@pytest.fixture
def aws_credentials() -> None:
"""Mocked AWS Credentials for moto."""
os.environ["AWS_ACCESS_KEY_ID"] = "testing"
os.environ["AWS_SECRET_ACCESS_KEY"] = "testing"
os.environ["AWS_SECURITY_TOKEN"] = "<PASSWORD>"
os.environ["AWS_SESSION_TOKEN"] = "testing"
@pytest.fixture
def s3_client(aws_credentials: typing.Any) -> typing.Generator[S3Client, None, None]:
with mock_s3():
if not config.S3_REGION:
config.S3_REGION = 'us-east-1'
conn = boto3.client("s3", region_name=config.S3_REGION)
yield conn
@pytest.fixture(scope='session')
def superuser_token_headers(client: TestClient) -> dict[str, str]:
return get_superuser_token_headers(client)
@pytest.fixture(scope='session')
def normal_user_token_headers(
client: TestClient, db: Session
) -> tuple[dict[str, str], int]:
return authentication_token_from_email(client=client, email=random_email(), db=db)
<file_sep>/libs/web/data-access-api/jest.config.ts
module.exports = {
displayName: 'web-data-access-api',
preset: '../../../jest.preset.ts',
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
},
},
testEnvironment: 'node',
transform: {
'^.+\\.[tj]sx?$': 'ts-jest',
},
transformIgnorePatterns: ['../../../node_modules/(?!@sampullman/*)'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory: '../../../coverage/libs/web/data-access-api',
}
<file_sep>/apps/contracts/src/scripts/deploy.ts
import { ethers } from 'hardhat'
const getFactories = async () => {
const erc20Factory = await ethers.getContractFactory('SlmToken')
return { erc20Factory }
}
const deployToken = async (factory, owner) => {
const initialSupply = '100000000000000000000000000'
const erc20 = await factory.deploy('Test ERC20', 'T20', initialSupply, owner)
return { erc20 }
}
const printContractAddresses = ({ erc20 }) => {
console.log('ERC20 address:', erc20.address)
}
async function main() {
const [deployer] = await ethers.getSigners()
const network = await ethers.provider.getNetwork()
console.log(
`Deploying contracts to ${network.name} (${network.chainId}) with account: ${deployer.address}`,
deployer.address,
)
console.log('Account balance:', (await deployer.getBalance()).toString())
const factories = await getFactories()
// Do something different for local development
if (network.chainId === 1337) {
const { erc20 } = await deployToken(factories.erc20Factory, deployer.address)
printContractAddresses({ erc20 })
} else if (network.chainId === 3) {
// Ropsten testnet
const { erc20 } = await deployToken(factories.erc20Factory, deployer.address)
printContractAddresses({ erc20 })
}
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error)
process.exit(1)
})
<file_sep>/apps/api-evidence/Dockerfile
# BASE IMAGE (37.4MB)
# ------------------------------------------------------------------------------------
FROM alpine:3.14.1 AS base
ARG NODEJS_VER=14
ENV NODEJS_VER=$NODEJS_VER
ARG TINI_VER=0.19
ENV TINI_VER=$TINI_VER
RUN apk add --no-cache nodejs~="$NODEJS_VER" tini~="$TINI_VER" curl~=7
RUN apk add --no-cache python3 py3-pip && ln -sf python3 /usr/bin/python
RUN curl -f https://get.pnpm.io/v6.14.js | node - add --global pnpm
RUN addgroup -g 1001 -S app && adduser -u 1001 -S app -G app
# Install poetry and relevant deps
RUN apk add --no-cache build-base libffi-dev openssl-dev python3-dev rust cargo postgresql-dev
RUN pip3 install --upgrade pip
RUN pip3 install poetry
# API EVIDENCE DEV APP IMAGE (? GB)
# ------------------------------------------------------------------------------------
FROM base as dev
ENV SHELL=/bin/sh
WORKDIR /usr/src
COPY subset.config.js package.json ./
COPY tools/scripts/package-subset.js ./tools/scripts/
RUN node ./tools/scripts/package-subset.js api-evidence subset.config.js package.json package.json
RUN pnpm install
COPY workspace.json nx.json tsconfig*.json ./
COPY apps/api-evidence ./apps/api-evidence
COPY apps/api-evidence/.env.dist ./apps/api-evidence/src/.env
RUN cd /usr/src/apps/api-evidence \
&& poetry config virtualenvs.in-project true \
&& poetry install --no-dev
ENTRYPOINT ["/sbin/tini", "-v", "-s", "--"]
CMD ["pnpm", "nx", "serve", "api-evidence"]
<file_sep>/libs/web/plugin/src/lib/i18n.ts
import {
I18nObject,
SimpleI18n,
getString,
getArray,
getRecord,
} from '@solomon/shared/util-i18n'
// Provide fallback English plugin text, if none is provided
const fallback: I18nObject = {
title: 'Solomon Payments',
secure: 'Protected by Solomon',
solomon: 'SOLOMON',
chargebacks: {
label: 'DIRECT CHARGE',
select: 'Select your cryptocurrency below:',
select_label: 'Select Crypto',
schedule: 'Schedule',
protection: 'Charge Protection',
price: 'Price',
usd_price: 'USD Price',
currency: {
SLM: 'Solomon (SLM)',
ETH: 'Ethereum (ETH)',
},
},
preorder: {
label: 'PREORDER',
select: 'Prepay for a future delivery:',
},
escrow: {
label: 'ESCROW',
enter: 'Place funds into escrow',
},
continue: 'CONTINUE SHOPPING',
confirm: 'CONFIRM',
}
export const i18n = new SimpleI18n(fallback)
export const ts = getString(i18n)
export const ta = getArray(i18n)
export const tr = getRecord(i18n)
<file_sep>/jest.config.ts
const { getJestProjects } = require('@nrwl/jest')
module.exports = {
projects: getJestProjects(),
maxWorkers: 1,
}
<file_sep>/apps/api-evidence/src/app/models/user.py
from typing import TYPE_CHECKING
from sqlalchemy import Boolean, Column, Integer, String
from sqlalchemy.orm import relationship
from app.db.base_class import Base
if TYPE_CHECKING:
from app.models.evidence import Evidence # noqa: F401
class User(Base):
__tablename__ = 'users'
full_name = Column(String)
email = Column(String, unique=True, index=True)
hashed_password = Column(String)
is_active = Column(Boolean, default=True)
is_superuser = Column(Boolean, default=False)
eth_address = Column(String, unique=True, index=True)
challenge_hash = Column(String)
challenge_expiry = Column(Integer, default=0)
items = relationship('Evidence', back_populates='owner')
<file_sep>/apps/api-evidence/src/app/api/auth.py
from datetime import datetime
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.encoders import jsonable_encoder
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app import crud, schemas
from app.utils import deps, security
router = APIRouter()
address_auth = security.AddressHeaderAuth()
@router.post(
'/email',
summary='Login with email and passowrd',
response_model=schemas.Token,
responses={401: {'description': 'Incorrect username or password'}},
)
def email_login(
db: Session = Depends(deps.get_db), form_data: OAuth2PasswordRequestForm = Depends()
) -> schemas.Token:
user = crud.user.authenticate(
db, email=form_data.username, password=<PASSWORD>
)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Incorrect username or password',
headers={'WWW-Authenticate': 'Bearer'},
)
return security.create_access_token(schemas.TokenPayload(sub=str(user.id)))
@router.post(
'/address-challenge',
summary='Generate a challenge for wallet address authentication',
response_model=schemas.AddressChallenge,
)
def address_challenge(
address_in: schemas.AddressChallengeCreate, db: Session = Depends(deps.get_db)
) -> schemas.AddressChallenge:
challenge = address_auth.create_challenge(db, address_in.address)
return schemas.AddressChallenge(challenge=jsonable_encoder(challenge))
@router.post(
'/address',
summary='Login with wallet address authentication',
response_model=schemas.Token,
responses={401: {'description': 'User not found / Challenge expired'}},
)
def address_login(
db: Session = Depends(deps.get_db),
address: Optional[str] = Depends(address_auth),
) -> schemas.Token:
if address is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='User not found',
headers={'WWW-Authenticate': 'Bearer'},
)
user = crud.user.get_by_eth_address(db, eth_address=address)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='User not found',
headers={'WWW-Authenticate': 'Bearer'},
)
if user.challenge_expiry < datetime.utcnow().timestamp():
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Challenge expired',
headers={'WWW-Authenticate': 'Bearer'},
)
return security.create_access_token(schemas.TokenPayload(sub=str(user.id)))
<file_sep>/libs/shared/util-path-store/src/lib/path-store.ts
import * as path from 'path'
import pkgDir = require('pkg-dir')
class PathStore {
get root(): string {
return pkgDir.sync() || ''
}
get watcher() {
return path.resolve(this.root, 'apps', 'blockchain-watcher')
}
get doc() {
return path.resolve(this.root, 'apps', 'developer-docs')
}
get scripts() {
return path.resolve(this.root, 'tools', 'scripts')
}
}
export default new PathStore()
<file_sep>/apps/developer-docs/docs/utilities/index.md
# Evidence Upload
Repository: https://github.com/solomondefi/evidence-uploader
The purpose of the uploader is to provide a simple interface for uploading evidence links to the blockchain during escrow disputes. Links must exist for the duration of the dispute (generally a maximum of 2 months). There are several methods for uploading evidence, and it is straightforward to add more.
1. User provides their own link
2. User provides files and the `backend` uploads to an S3-compatible data store
3. (TBD) Pin on an IPFS node for the duration of a dispute
Currently, only Metamask is supported as a wallet provider for posting the link to the blockchain, but WalletConnect and other methods may be added in the future.
A hosted frontend and backend are provided by Solomon, a UI demo can currently be viewed at https://evidence.solomondefi.com
## Evidence Uploader Frontend
See the `frontend` folder of the evidence uploader Github repository for more technical details including setup and deploy procedures: https://github.com/solomondefi/evidence-uploader/tree/main/frontend
A Vue3 app for uploading dispute evidence links to the blockchain. Files may be provided via external link, or uploaded directly to the hosted `backend`. Metamask is used for executing the transaction.
## Evidence Uploader Backend
See the `backend` folder of the evidence uploader Github repository for more technical details including setup and deploy procedures: https://github.com/solomondefi/evidence-uploader/tree/main/backend
A Flask (Python) app for uploading dispute evidence links to the blockchain. DigitalOcean's spaces service is used for storing data, but it
can be substituted with any S3 compatible service.
The [URL Shortener](/utilities/shortener) is used to shorten links to reduce blockchain gas fees.
<file_sep>/apps/api-dispute/src/app/utils/security.py
import base64
import hashlib
import hmac
def generate_signature(secret_key: bytes, message: bytes) -> str:
h = hmac.new(secret_key, msg=message, digestmod=hashlib.sha256)
return base64.b64encode(h.digest()).decode('utf-8')
<file_sep>/apps/api-evidence/src/app/crud/crud_user.py
from typing import Any, Optional, Union
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models import User
from app.schemas import AddressUserChallenge, UserCreate, UserUpdate
from app.utils.security import EmailPassword
class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]):
password_auth = EmailPassword()
def get_by_email(self, db: Session, *, email: str) -> Optional[User]:
return db.query(User).filter(User.email == email).first()
def get_by_eth_address(self, db: Session, *, eth_address: str) -> Optional[User]:
return db.query(User).filter(User.eth_address == eth_address).first()
def create(self, db: Session, *, obj_in: UserCreate) -> User:
db_obj = User(
email=obj_in.email,
hashed_password=self.password_auth.hash(obj_in.password),
full_name=obj_in.full_name,
is_superuser=obj_in.is_superuser,
)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def update(
self, db: Session, *, db_obj: User, obj_in: Union[UserUpdate, dict[str, Any]]
) -> User:
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.dict(exclude_unset=True)
if update_data['password']:
hashed_password = self.password_auth.hash(update_data['password'])
del update_data['password']
update_data['hashed_password'] = hashed_password
return super().update(db, db_obj=db_obj, obj_in=update_data)
def authenticate(self, db: Session, *, email: str, password: str) -> Optional[User]:
user = self.get_by_email(db, email=email)
if not user or not user.hashed_password:
return None
if not self.password_auth.verify(password, user.hashed_password):
return None
return user
def challenge_address_user(
self, db: Session, *, challenge: AddressUserChallenge
) -> User:
user = self.get_by_eth_address(db, eth_address=challenge.eth_address)
if not user:
user = User(eth_address=challenge.eth_address)
db.add(user)
user.challenge_hash = challenge.challenge_hash
user.challenge_expiry = challenge.challenge_expiry
db.commit()
db.refresh(user)
return user
user = CRUDUser(User)
<file_sep>/apps/web-evidence/src/app/i18n.ts
import { createI18n } from 'vue-i18n'
import en from './translations/en.json'
type MessageSchema = typeof en
export default createI18n<[MessageSchema], 'en'>({
legacy: false,
globalInjection: true,
locale: 'en',
fallbackLocale: import.meta.env.VITE_I18N_FALLBACK_LOCALE || 'en',
messages: { en },
})
<file_sep>/apps/api-evidence/src/main.py
from typing import Optional
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from app.api import api_router
from app.config import config
description = """
Solomon Evidence API uploads evidence files to various storages for disputes.
"""
docs_urls: dict[str, Optional[str]] = {
'openapi_url': f'{config.API_PREFIX}/openapi.json',
}
if not config.DEBUG:
docs_urls = {
'openapi_url': None,
'docs_url': None,
'redoc_url': None,
}
app = FastAPI(
debug=config.DEBUG,
title=config.PROJECT_NAME,
version='1.0',
description=description,
contact={
'name': 'Solomon',
'url': 'https://solomondefi.com/',
'email': '<EMAIL>',
},
**docs_urls,
)
# Set all CORS enabled origins
if config.CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin) for origin in config.CORS_ORIGINS],
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*'],
)
app.include_router(api_router, prefix=config.API_PREFIX)
<file_sep>/libs/blockchain-watcher/feature-templates/src/lib/generate.spec.ts
import generateMailTemplates from './generate'
describe('blockchain watcher generate templates', () => {
it('should work', async () => {
expect(await generateMailTemplates()).toBe(true)
})
})
<file_sep>/libs/blockchain-watcher/feature-templates/src/lib/generate.ts
import { readdir, readFile, writeFile } from 'fs-extra'
import * as path from 'path'
import pathStore from '@solomon/shared/util-path-store'
import mjml2html = require('mjml')
export default async (): Promise<boolean> => {
try {
const templateDirPath = path.resolve(pathStore.watcher, 'src', 'template')
const templateNames = await readdir(templateDirPath)
for (let templateName of templateNames) {
if (!templateName.endsWith('.mjml')) {
continue
}
let templatePath = path.resolve(templateDirPath, templateName)
let htmlName = templateName.replace('.mjml', '.html')
let htmlPath = path.resolve(templateDirPath, htmlName)
let template = await readFile(templatePath, 'utf-8')
let mjmlParseResults = mjml2html(template)
await writeFile(htmlPath, mjmlParseResults.html)
console.log(`${htmlName} generated`)
}
return true
} catch (_e) {
console.log(_e)
return false
}
}
<file_sep>/apps/api-dispute/src/app/db/init_db.py
from sqlalchemy.orm import Session
from app import crud, schemas # noqa: F401
from app.config import config # noqa: F401
from app.db import base # noqa: F401
# Import all SQLAlchemy models (app.db.base) before initializing DB
def init_db(db: Session) -> None:
# Tables created with Alembic migrations
pass
<file_sep>/libs/web/data-access-state/src/lib/store.spec.ts
import { Store } from './store'
describe('Store', () => {
it('should work', () => {
const name = 'store-test'
const store = new Store(name)
store.init({
initialState: () => ({
version: 1,
}),
})
expect(store.name).toEqual(name)
expect(store.data.version).toEqual(1)
})
})
<file_sep>/apps/api-dispute/src/app/tests/conftest.py
from typing import Generator
import pytest
from fastapi.testclient import TestClient
from pydantic import PostgresDsn
from sqlalchemy import create_engine
from sqlalchemy.exc import ProgrammingError
from app.config import config
from app.db.base import Base
from app.db.session import engine, SessionLocal
from main import app
def setup_db() -> None:
try:
conn = engine.connect()
conn.execute('commit')
conn.execute(f'drop database {config.TEST_DB}')
conn.close()
except ProgrammingError:
pass
try:
conn = engine.connect()
conn.execute('commit')
conn.execute(f'create database {config.TEST_DB}')
conn.close()
except ProgrammingError:
pass
config.SQLALCHEMY_DATABASE_URI = PostgresDsn.build(
scheme='postgresql',
user=config.POSTGRES_USER,
password=<PASSWORD>,
host=config.POSTGRES_SERVER,
path=f'/{config.TEST_DB}',
)
test_engine = create_engine(config.SQLALCHEMY_DATABASE_URI)
Base.metadata.create_all(test_engine)
SessionLocal.configure(bind=test_engine)
@pytest.fixture(scope='session')
def db() -> Generator:
setup_db()
yield SessionLocal()
@pytest.fixture(scope='module')
def client() -> Generator:
with TestClient(app) as c:
yield c
<file_sep>/apps/api-evidence/src/app/models/evidence.py
from datetime import datetime
from typing import TYPE_CHECKING
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship
from app.db.base_class import Base
if TYPE_CHECKING:
from app.models.user import User # noqa: F401
class Evidence(Base):
__tablename__ = 'evidence'
owner_id = Column(Integer, ForeignKey('users.id'))
owner = relationship('User', back_populates='items')
title = Column(String, nullable=False)
description = Column(Text, nullable=False)
storage_backend = Column(String, nullable=False)
file_key = Column(String, nullable=False)
media_type = Column(String, nullable=False)
created = Column(DateTime, nullable=False, default=datetime.utcnow)
<file_sep>/apps/api-dispute/src/app/api/__init__.py
import typing
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from app.api import events
api_router = APIRouter()
api_router.include_router(events.router, prefix='/events', tags=['Events'])
@api_router.get('/health/app', tags=['Healthcheck'])
def healthcheck() -> typing.Any:
return JSONResponse({'status': 'ok'})
<file_sep>/apps/contracts/hardhat.config.ts
import '@typechain/hardhat'
import '@nomiclabs/hardhat-ethers'
import '@nomiclabs/hardhat-solhint'
import '@nomiclabs/hardhat-waffle'
import '@nomiclabs/hardhat-etherscan'
import 'hardhat-deploy'
import 'hardhat-gas-reporter'
import 'hardhat-contract-sizer'
import 'solidity-coverage'
import 'tsconfig-paths/register'
import { HardhatUserConfig } from 'hardhat/types'
const walletMnemonic = process.env.WALLET_MNEMONIC || ''
const etherscanApiKey = process.env.ETHERSCAN_API_KEY || ''
const ropstenRpcUrl = process.env.ROPSTEN_RPC_URL || ''
const ropstenMnemonic = process.env.ROPSTEN_MNEMONIC || ''
const testReportGas = process.env.TEST_REPORT_GAS || '1'
const config: HardhatUserConfig = {
defaultNetwork: 'hardhat',
networks: {
// Hardhat dev Ethereum network node running on localhost
hardhat: {
chainId: 1337,
accounts: {
count: 100,
mnemonic: walletMnemonic,
},
initialBaseFeePerGas: 0,
},
// Hardhat dev Ethereum network node running in local dev Kubernetes
hardhatK8s: {
chainId: 1337,
accounts: {
count: 100,
mnemonic: walletMnemonic,
},
url: 'http://ethereum-node:8545',
},
ropsten: {
chainId: 3,
gas: 5000000,
gasPrice: 50000000000,
gasMultiplier: 1,
timeout: 90000,
url: ropstenRpcUrl,
accounts: {
mnemonic: ropstenMnemonic,
},
},
},
gasReporter: {
enabled: testReportGas === '1',
showMethodSig: true,
},
etherscan: {
apiKey: etherscanApiKey,
},
solidity: {
version: '0.8.9',
},
paths: {
root: './',
sources: 'src/contracts',
tests: 'src/tests',
cache: '../../dist/apps/contracts/cache',
artifacts: '../../dist/apps/contracts/artifacts',
},
}
export default config
<file_sep>/libs/shared/util-path-store/src/lib/path-store.spec.ts
import pathStore from './path-store'
describe('sharedUtilPathStore', () => {
it('should work', () => {
expect(pathStore.watcher).toContain('blockchain-watcher')
})
})
<file_sep>/apps/developer-docs/docs/.vitepress/config.js
const base = '/'
module.exports = {
title: 'Solomon Documentation',
description: 'Solomon Plugin and Smart Contract Documentation',
repo: 'solomondefi/solomon-monorepo',
base,
head: [['link', { rel: 'icon', type: 'image/png', href: `${base}favicon.png` }]],
themeConfig: {
logo: '/header_logo.png',
nav: [
{ text: 'Guide', link: '/guide/' },
{ text: 'Plugin', link: '/plugin/' },
{ text: 'Contracts', link: '/contracts/' },
{ text: 'Utilities', link: '/utilities/' },
{
text: 'Links',
items: [
{
text: 'Solomon Home',
link: 'https://solomondefi.com/',
},
{
text: 'Github',
link: 'https://github.com/solomondefi',
},
{
text: 'Telegram',
link: 'https://t.me/solomondefiproject',
},
{
text: 'Twitter',
link: 'https://twitter.com/solomondefi',
},
{
text: 'Facebook',
link: 'https://facebook.com/solomondefi',
},
{
text: 'Medium (Blog)',
link: 'https://medium.com/@solomondefi',
},
],
},
],
sidebar: {
// catch-all fallback
'/': [
{
text: 'Guide',
children: [
{
text: 'Why Solomon',
link: '/guide/why-solomon',
},
{
text: 'Getting Started',
link: '/guide/',
},
{
text: 'Technology',
link: '/guide/technology',
},
{
text: 'Contributing',
link: '/guide/contributing',
},
],
},
{
text: 'Plugin',
children: [
{
text: 'Usage',
link: '/plugin/',
},
{
text: 'Plugin API',
link: '/plugin/api',
},
{
text: 'Shopping Cart',
link: '/plugin/shopping',
},
{
text: 'Theming',
link: '/plugin/theming',
},
],
},
{
text: 'Smart Contracts',
children: [
{
text: 'Usage',
link: '/contracts/',
},
{
text: 'Customization',
link: '/contracts/customization',
},
{
text: 'API',
link: '/contracts/api',
},
],
},
{
text: 'Utilities',
children: [
{
text: 'Evidence Upload',
link: '/utilities/',
},
{
text: 'Link Shortener',
link: '/utilities/shortener',
},
{
text: 'Blockchain wATCHER',
link: '/utilities/watcher',
},
],
},
],
},
},
}
<file_sep>/apps/api-evidence/src/app/migrations/versions/3543c7aaeaae_rename_upload_items_table.py
"""Rename upload_items table
Revision ID: 3543c7aaeaae
Revises: <PASSWORD>
Create Date: 2021-09-23 08:27:16.177821+00:00
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
'evidence',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('owner_id', sa.Integer(), nullable=True),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=False),
sa.Column('storage_backend', sa.String(), nullable=False),
sa.Column('file_key', sa.String(), nullable=False),
sa.Column('media_type', sa.String(), nullable=False),
sa.Column('created', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['owner_id'], ['users.id']),
sa.PrimaryKeyConstraint('id'),
)
op.create_index(op.f('ix_evidence_id'), 'evidence', ['id'], unique=False)
op.drop_index('ix_upload_items_id', table_name='upload_items')
op.drop_table('upload_items')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
'upload_items',
sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),
sa.Column('owner_id', sa.INTEGER(), autoincrement=False, nullable=True),
sa.ForeignKeyConstraint(
['owner_id'], ['users.id'], name='upload_items_owner_id_fkey'
),
sa.PrimaryKeyConstraint('id', name='upload_items_pkey'),
)
op.create_index('ix_upload_items_id', 'upload_items', ['id'], unique=False)
op.drop_index(op.f('ix_evidence_id'), table_name='evidence')
op.drop_table('evidence')
# ### end Alembic commands ###
<file_sep>/apps/api-evidence/src/app/storage/security.py
import typing
from cryptography.fernet import Fernet, InvalidToken
class Encryption:
def encrypt(self, file: typing.IO) -> bytes:
raise NotImplementedError
def decrypt(self, encryted_file: typing.IO) -> typing.Optional[bytes]:
raise NotImplementedError
class FernetEncryption(Encryption):
"""
File encryption using Fernet (AES128-CBC with HMAC-SHA256)
"""
encryptor: Fernet
def __init__(self, secret_key: bytes) -> None:
self.encryptor = Fernet(secret_key)
def encrypt(self, file: typing.IO) -> bytes:
file.seek(0)
return self.encryptor.encrypt(file.read())
def decrypt(self, encryted_file: typing.IO) -> typing.Optional[bytes]:
try:
encryted_file.seek(0)
return self.encryptor.decrypt(encryted_file.read())
except InvalidToken:
pass
return None
<file_sep>/libs/web/ui-widgets/cypress/plugins/index.ts
import { startDevServer } from '@cypress/vite-dev-server'
module.exports = (on: Cypress.PluginEvents, config: Cypress.PluginConfigOptions) => {
on('dev-server:start', (options: Cypress.DevServerConfig) =>
startDevServer({
options,
}),
)
return config
}
<file_sep>/apps/api-dispute/src/main.py
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from app.api import api_router
from app.config import config
app = FastAPI(
title=config.PROJECT_NAME, openapi_url=f'{config.API_PREFIX}/openapi.json'
)
# Set all CORS enabled origins
if config.CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin) for origin in config.CORS_ORIGINS],
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*'],
)
app.include_router(api_router, prefix=config.API_PREFIX)
<file_sep>/apps/api-evidence/src/app/utils/deps.py
from typing import Generator
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt
from pydantic import ValidationError
from sqlalchemy.orm import Session
from app import crud, models, schemas
from app.config import config
from app.db.session import SessionLocal
from app.storage import Encryption, Storage, StorageBackend
token_auth = OAuth2PasswordBearer(tokenUrl="/api/auth/email")
def get_db() -> Generator:
try:
db = SessionLocal()
yield db
finally:
db.close()
def get_s3_backend() -> StorageBackend:
from app.storage.backend.s3 import S3
if config.S3_REGION is None or config.S3_KEY is None or config.S3_SECRET is None:
raise ValueError('S3 is not configured')
return S3(
config.S3_REGION,
config.S3_KEY,
config.S3_SECRET,
config.S3_BUCKET,
endpoint=config.S3_ENDPOINT,
)
def get_encryption() -> Encryption:
from app.storage.security import FernetEncryption
return FernetEncryption(config.FILE_ENCRYPTION_KEY.encode('utf-8'))
def get_storage(
backend: StorageBackend = Depends(get_s3_backend),
encryption: Encryption = Depends(get_encryption),
) -> Storage:
return Storage(backend, encryption)
def get_current_user(
db: Session = Depends(get_db), token: str = Depends(token_auth)
) -> models.User:
try:
payload = jwt.decode(token, config.SECRET_KEY)
token_data = schemas.TokenPayload(**payload)
except (jwt.JWTError, ValidationError):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
user = crud.user.get(db, id=token_data.sub)
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
return user
def get_current_active_user(
current_user: models.User = Depends(get_current_user),
) -> models.User:
if not current_user.is_active:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail="Inactive user"
)
return current_user
def get_current_active_superuser(
current_user: models.User = Depends(get_current_user),
) -> models.User:
if not current_user.is_superuser:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail="Missing privileges"
)
return current_user
<file_sep>/.github/actions/setup-python-app/create_db.sh
#!/bin/bash
set -e
set -u
echo "Creating user and database '$1'"
PGPASSWORD=$POSTGRES_PASSWORD psql -v ON_ERROR_STOP=1 -U $POSTGRES_USER -h localhost <<-EOSQL
CREATE DATABASE $1;
GRANT ALL PRIVILEGES ON DATABASE $1 TO $POSTGRES_USER;
EOSQL
<file_sep>/.husky/commit-msg
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
pnpx --no-install ts-node ./tools/scripts/checkCommitMsg.ts $1
<file_sep>/apps/plugin-example-vue3/README.md
# plugin-example-vue3 Frontend
Generated with [nx-vue3-vite](https://github.com/samatechtw/nx-vue3-vite)
<file_sep>/apps/api-evidence/src/generate_openapi.py
import argparse
import json
from pathlib import Path
from fastapi.openapi.utils import get_openapi
from main import app
def write_openapi(path: Path) -> None:
if not path.match('*.json'):
raise ValueError('Output file must be .json')
with open(path, 'w') as f:
openapi = get_openapi(
title=app.title,
version=app.version,
openapi_version=app.openapi_version,
description=app.description,
routes=app.routes,
tags=app.openapi_tags,
servers=app.servers,
terms_of_service=app.terms_of_service,
contact=app.contact,
license_info=app.license_info,
)
json.dump(openapi, f, separators=(',', ':'))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-o', dest='output', required=True, help='output file')
args = parser.parse_args()
write_openapi(Path(args.output))
<file_sep>/libs/web/data-access-api/src/lib/api-evidence.ts
import { plainToClass } from 'class-transformer'
import { EvidenceApiResponse } from '@solomon/shared/util-api-evidence-types'
import { NftApi } from './api'
export default (api: NftApi) => {
const createEvidence = async (
evidence: Record<string, unknown>,
): Promise<EvidenceApiResponse> => {
const { data } = await api.authRequest({
url: 'evidence',
method: 'POST',
data: evidence,
})
return plainToClass(EvidenceApiResponse, data)
}
return {
createEvidence,
}
}
<file_sep>/apps/api-evidence/src/app/crud/__init__.py
# flake8: noqa
from .crud_evidence import evidence
from .crud_user import user
<file_sep>/libs/web/data-access-state/src/lib/user.ts
import { computed, ComputedRef } from 'vue'
import { PrivateProfileApiResponse } from '@solomon/shared/util-api-evidence-types'
import { NftApi, useUserApi } from '@solomon/web/data-access-api'
import { StoreData, StoreApi } from './store'
export interface TxState {
id: number
}
export interface NftState {
id: number
}
export interface AuthState {
token: string | null
}
export interface UserState {
email: string | null
avatar: string | null
bio: string | null
name: string | null
joined: number | null
auth: AuthState
nfts: NftState[]
txs: TxState[]
}
export interface UserStoreData extends StoreData {
user: UserState
}
export interface UserStoreApi extends StoreApi<UserStoreData> {
// getters
token: ComputedRef<string | null>
loggedIn: ComputedRef<boolean>
avatar: ComputedRef<string | null>
raw: UserStoreData
// mutations
updateUser: (userData: PrivateProfileApiResponse) => void
// actions
getPrivate(): Promise<void>
logout(): void
}
export const useUserStoreApi = (api: NftApi, data: UserStoreData): UserStoreApi => {
const userApi = useUserApi(api)
const mutations = {
updateUser(userData: PrivateProfileApiResponse): void {
data.user = { ...data.user, ...userData }
},
}
const actions = {
async getPrivate(): Promise<void> {
const user = await userApi.getProfilePrivate()
mutations.updateUser(user)
},
logout() {
data.user = { ...userInit().user }
},
}
const getters = {
avatar: computed(() => data.user.avatar),
loggedIn: computed(() => !!data.user.auth.token),
token: computed(() => data.user.auth.token),
raw: data,
}
return {
initialState: userInit,
...getters,
...mutations,
...actions,
}
}
export const userInit = (): UserStoreData => ({
user: {
email: '',
avatar: null,
bio: '',
name: '',
joined: null,
nfts: [],
txs: [],
auth: {
token: null,
},
},
})
<file_sep>/apps/developer-docs/docs/plugin/shopping.md
# Shopping Cart
The Solomon Plugin comes bundled with a fully featured shopping cart that integrates directly with the plugin, via the [Plugin API](/plugin/api).
The shopping cart is optional, it may be extended or replaced.
<file_sep>/tools/scripts/prune-all.sh
#!/bin/sh
# Print each command and exit on error
set -e
echo "[INFO] Running system prune..."
docker system prune -a --volumes
echo "[INFO] Removing unused containers..."
docker container prune -f
echo "[INFO] Removing unused images..."
docker image prune -a -f
echo "[INFO] After cleanup:"
docker container ls
docker image ls
<file_sep>/apps/blockchain-watcher/src/service/ethService.ts
import { ethers } from 'ethers'
import envStore from '../store/envStore'
import mailService from './mailService'
export class EthService {
provider = null as any
contract = null as any
async onChargebackCreated() {
// TODO: Process event
await mailService.sendChargebackCreatedEmail('A')
await mailService.sendChargebackCreatedEmail('B')
}
async onPreorderCreated() {
// TODO: Process event
await mailService.sendPreorderCreatedEmail('A')
await mailService.sendPreorderCreatedEmail('B')
}
async onEscrowCreated() {
// TODO: Process event
await mailService.sendEscrowCreatedEmail('A')
await mailService.sendEscrowCreatedEmail('B')
}
async getChargebackCreatedLogs() {
// TODO: replace with typed method
let eventFilter = this.contract.filters['ChargebackCreated']()
let events = this.contract.queryFilter(eventFilter)
// TODO: save last event block hash
return events
}
async getPreorderCreatedLogs() {
// TODO: replace with typed method
let eventFilter = this.contract.filters['PreorderCreated']()
let events = this.contract.queryFilter(eventFilter)
// TODO: save last event block hash
return events
}
async getEscrowCreatedLogs() {
// TODO: replace with typed method
let eventFilter = this.contract.filters['EscrowCreated']()
let events = this.contract.queryFilter(eventFilter)
// TODO: save last event block hash
return events
}
async init() {
this.provider = new ethers.providers.JsonRpcProvider(envStore.ethChainUrl)
// TODO: Replace with contract factory from TypeContract
this.contract = new ethers.Contract('', '', this.provider)
this.contract.connect(this.provider)
this.contract.on('ChargebackCreated', this.onChargebackCreated)
this.contract.on('PreorderCreated', this.onPreorderCreated)
this.contract.on('EscrowCreated', this.onEscrowCreated)
}
}
export default new EthService()
<file_sep>/apps/developer-docs/docs/plugin/index.md
# Usage
## Installation
### Package Manager
```bash
npm i -S @solomondefi/plugin
```
```bash
yarn add @solomondefi/plugin
```
```bash
pnpm i -S @solomondefi/plugin
```
### Browser
It is recommended to download the distribution and copy `plugin.min.js` into your project.
For testing and prototyping, you can include it from the Unpkg CDN:
```
<script src="https://unpkg.com/@solomondefi/plugin@0.1.0/dist/plugin.min.js>
```
<file_sep>/apps/api-evidence/src/app/utils/security.py
from datetime import datetime, timedelta
from typing import Optional
from uuid import uuid4
from cryptography.hazmat.primitives import hashes, hmac
from eth_account import Account
from eth_account.messages import encode_structured_data
from eth_utils import decode_hex, to_checksum_address
from fastapi.exceptions import HTTPException
from jose import jwt
from passlib.context import CryptContext
from sqlalchemy.orm import Session
from starlette.requests import Request
from starlette.status import HTTP_401_UNAUTHORIZED
from app import crud, schemas
from app.config import config
def create_access_token(
token_payload: schemas.TokenPayload, expires_delta: timedelta = None
) -> schemas.Token:
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(
minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES
)
to_encode = {"exp": expire, "sub": token_payload.sub}
encoded_jwt = jwt.encode(to_encode, config.SECRET_KEY)
return schemas.Token(access_token=encoded_jwt)
class EmailPassword:
pwd_context: CryptContext = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify(self, password: str, hashed_password: str) -> bool:
return self.pwd_context.verify(password, hashed_password)
def hash(self, password: str) -> str:
return self.pwd_context.hash(password)
class AddressHeaderAuth:
chain_id: int = config.CHAIN_ID
def challenge_from_hash(self, hash: str) -> dict:
return {
"domain": {
"chainId": self.chain_id,
"name": "Solomon DeFi",
"version": "1",
},
"message": {
"label": "Sign this message to authenticate",
"contents": hash,
},
"primaryType": "Auth",
"types": {
"EIP712Domain": [
{"name": "name", "type": "string"},
{"name": "version", "type": "string"},
{"name": "chainId", "type": "uint256"},
],
"Auth": [
{"name": "contents", "type": "string"},
{"name": "label", "type": "string"},
],
},
}
def create_challenge(self, db: Session, eth_address: str) -> dict:
checksum_address = to_checksum_address(eth_address)
hash = hmac.HMAC(uuid4().bytes, hashes.SHA256())
hash.update(f"{checksum_address}{uuid4().hex}".encode())
challenge_hash = hash.finalize().hex()
challenge_expiry = int(datetime.utcnow().timestamp() + config.CHALLENGE_TTL)
challenge = self.challenge_from_hash(challenge_hash)
address_user_chaellenge = schemas.AddressUserChallenge(
eth_address=checksum_address,
challenge_hash=challenge_hash,
challenge_expiry=challenge_expiry,
)
crud.user.challenge_address_user(db, challenge=address_user_chaellenge)
return challenge
def is_valid_challenge(
self, address: str, challenge_hash: str, signature: str
) -> bool:
data = self.challenge_from_hash(challenge_hash)
signature_hex = decode_hex(signature)
recovered_address = Account.recover_message(
encode_structured_data(data), signature=signature_hex
)
return to_checksum_address(address) == recovered_address
def __call__(self, request: Request) -> Optional[str]:
auth_header = request.headers["authorization"]
if not auth_header:
return None
auth_data = auth_header.split()
if len(auth_data) != 4 or auth_data.pop(0) != "Challenge":
raise HTTPException(HTTP_401_UNAUTHORIZED)
address, challenge_hash, signature = auth_data
if not self.is_valid_challenge(address, challenge_hash, signature):
raise HTTPException(HTTP_401_UNAUTHORIZED)
return address
<file_sep>/apps/blockchain-watcher/src/main.ts
import 'reflect-metadata'
import dbService from './service/dbService'
import mailService from './service/mailService'
let start = async () => {
await dbService.init()
await mailService.init()
// await ethService.init()
console.log(`Blockchain watcher server start success.`)
}
start()
<file_sep>/apps/developer-docs/docs/guide/contributing.md
# Contributing
The Solomon ecosystem consists of several repositories hosted with Git/Github. Depending on the technology, there are different ways a community member can contribute. The Guidelines section below notes some common things to keep in mind, and the Links section lists the contribution guideliness for specific projects.
## General Guidelines
These are general contribution guidelines for all projects, regardless of language or libraries used. See the [Language Specific](#language-specific-guidelines) section for more fine-grained guidelines.
- Consider what you are going to code before jumping straight in. Is there already code that covers what you are going to do? What is the simplest way to code the feature without compromising maintainability?
- Add unit tests if you're implementing or changing a feature.
- Review and update documentation relevant to your changes, including these developer docs, project READMEs, and inline code comments.
- Create and keep up to date [an OpenAPI Specification](https://swagger.io/specification/) file in the form of `openapi.yaml` in the project root all web services/APIs.
- Remove debug statements
- Set up your editor or IDE to automatically lint and format on save. Code that does not pass CI lint/format/test checks will be automatically rejected.
### Pull Requests
Pull requests (PRs) represent a feature branch currently in progress, or ready to merge to `main`
There may be multiple PRs per issue, but each PR should only cover a single issue (with some exceptions).
Follow these steps to ensure a smooth process:
- Link to the corresponding issue in the description (e.g. `#117`)
- If the PR will close the issue, include e.g. `Close #117` on its own line
- If the PR is for a hotfix, mention it in the description
- Verify that status/CI checks are passing
- Squash trivial commits and edit poorly worded messages with [interactive rebase](https://thoughtbot.com/blog/git-interactive-rebase-squash-amend-rewriting-history#interactive-rebase)
### Commits
- Follow the commit message guidelines below
- Use the present tense ("fix bug", not "fixed bug")
- Use the [imperative mood](https://en.wikipedia.org/wiki/Imperative_mood) ("update packages", not "updates packages")
- No merge commits, PRs must be rebased on `main` before merging
- If there are conflicts, this must be done locally. A force push is necessary (`git push --force-with-lease`)
- One task/subtask per commit
- Push often, but avoid pushing broken code
### Dependencies
Dependencies should be discussed before they're added, and evaluated on a few points:
- Is it mature and/or actively developed?
- Is it cross platform?
- Does it pull in many sub-dependencies?
- How does it affect the build size/runtime speed?
## Licenses and Attribution
Non permissively licensed code should be avoided, as well as copy pasting from arbitrary online sources.
If a library is not included in the standard package manager (NPM, PyPI, Cargo, etc) and is non-trivial to reproduce, exceptions can be made, but should be discussed in an issue first.
## Language Specific Guidelines
This section contains detailed guidelines for specific languages and frameworks.
### Solidity
### Typescript
### Vue3
### CSS/PostCSS
#### CSS media queries
Media queries should be placed at the end of the style block/file, within the scope of the top level class.
Good:
```
.top-level-content {
.stuff {
width: 50%;
}
@media (max-width: $mobile-width) {
.stuff {
width: 100%;
}
}
```
Bad:
```
.top-level-content {
.stuff {
width: 50%;
@media (max-width: $mobile-width) {
width: 100%;
}
}
}
```
We only use max-width media queries, so mobile style is a union of mobile/tablet/desktop, tablet style is a union of tablet/desktop, and desktop is default.
#### CSS vendor prefixes
The PostCSS `autoprefixer` plugin is included, so CSS vendor extensions should never be necessary.
### Python
- Lint: `pylint`
- Configuration: `.pylintrc`
- Format: [`black`](https://github.com/psf/black)
### Rust
TBD
<file_sep>/libs/web/plugin/src/lib/defaults.ts
export const allPlugins = ['chargebacks', 'preorder', 'escrow']
<file_sep>/libs/shared/util-i18n/src/lib/simple-i18n.ts
export type I18nValue = string | I18nArray | I18nObject
export type I18nArray = Array<string | I18nObject>
export type I18nObject = { [member: string]: I18nValue }
export const getDeep = (key: string, copy: I18nObject): I18nValue => {
const path = key.split('.')
let copyValue: I18nValue = copy
for (const subkey of path) {
copyValue = copyValue[subkey]
if (!copyValue) {
console.warn(`Copy key not found: ${key}`)
return key
}
}
return copyValue
}
export class SimpleI18n {
fallback: I18nObject
constructor(fallback: I18nObject) {
this.fallback = fallback
}
s(key: string, copy?: I18nObject): string {
const val = getDeep(key, copy ?? this.fallback)
if (Array.isArray(val)) {
throw new Error('Copy: expected string, found array')
} else if (typeof val !== 'string') {
throw new Error(`Copy: expected string, found ${typeof val}`)
}
return val
}
r(key: string, copy?: I18nObject): I18nObject {
const val = getDeep(key, copy ?? this.fallback)
if (typeof val !== 'object') {
throw new Error(`Copy: expected record, found ${typeof val}`)
} else if (Array.isArray(val)) {
throw new Error('Copy: expected record, found array')
}
return val as I18nObject
}
a(key: string, copy?: I18nObject): I18nArray {
const val = getDeep(key, copy ?? this.fallback)
if (!Array.isArray(val)) {
throw new Error(`Copy: expected array, found ${typeof val}`)
}
return val
}
}
export const getString =
(i18n: SimpleI18n) =>
(key: string, copy?: I18nObject): string =>
i18n.s(key, copy)
export const getArray =
(i18n: SimpleI18n) =>
(key: string, copy?: I18nObject): I18nArray =>
i18n.a(key, copy)
export const getRecord =
(i18n: SimpleI18n) =>
(key: string, copy?: I18nObject): I18nObject =>
i18n.r(key, copy)
<file_sep>/apps/api-evidence/src/app/tests/utils/user.py
from eth_account import Account
from eth_account.messages import encode_structured_data
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from app import crud, models, schemas
from app.config import config
from app.tests.utils import random_email, random_lower_string
def user_authentication_headers(
*, client: TestClient, email: str, password: str
) -> dict[str, str]:
r = client.post(
f"{config.API_PREFIX}/auth/email",
data={"username": email, "password": password},
)
response = r.json()
auth_token = response["access_token"]
headers = {"Authorization": f"Bearer {auth_token}"}
return headers
def create_random_user(db: Session) -> tuple[models.User, str]:
email = random_email()
password = <PASSWORD>()
user_in = schemas.UserCreate(username=email, email=email, password=<PASSWORD>)
user = crud.user.create(db=db, obj_in=user_in)
return user, password
def create_random_wallet() -> tuple[str, bytes]:
account = Account.create()
return account.address, account.key
def eth_sign_data(challenge: dict, private_key: bytes) -> str:
message = encode_structured_data(challenge)
signed_message = Account.sign_message(message, private_key)
return signed_message.signature.hex()
def authentication_token_from_email(
*, client: TestClient, email: str, db: Session
) -> tuple[dict[str, str], int]:
"""
Return a valid token for the user with given email.
If the user doesn't exist it is created first.
"""
password = <PASSWORD>()
user = crud.user.get_by_email(db, email=email)
if not user:
user_in_create = schemas.UserCreate(
username=email, email=email, password=<PASSWORD>
)
user = crud.user.create(db, obj_in=user_in_create)
else:
user_in_update = schemas.UserUpdate(password=<PASSWORD>)
user = crud.user.update(db, db_obj=user, obj_in=user_in_update)
return (
user_authentication_headers(client=client, email=email, password=password),
user.id,
)
<file_sep>/apps/blockchain-watcher/src/service/dbService.spec.ts
import dbService, { DbService } from './dbService'
import * as fse from 'fs-extra'
describe('dbService', () => {
beforeEach(async () => {
await dbService.resetForTest()
})
test('constructor()', async () => {
expect(dbService).toBeInstanceOf(DbService)
})
test('init()', async () => {
expect(fse.existsSync(dbService.sqlitePath)).toBe(true)
})
test('setLastScanned()', async () => {
await dbService.setLastScanned('block1')
let r1 = await dbService.scanLogRepository.findAll()
expect(r1.length).toEqual(1)
expect(r1[0].blockHash).toEqual('block1')
expect(r1[0].lastScanned).toBeGreaterThan(0)
await dbService.setLastScanned('block2')
await dbService.setLastScanned('block3')
let r2 = await dbService.scanLogRepository.findAll()
let hashArr = r2.map((entity) => entity.blockHash).sort()
expect(r2.length).toEqual(3)
expect(hashArr).toEqual(['block1', 'block2', 'block3'])
})
test('getLastScanned()', async () => {
let log1 = dbService.scanLogRepository.create({
blockHash: 'block1',
lastScanned: 1,
})
let log2 = dbService.scanLogRepository.create({
blockHash: 'block2',
lastScanned: 2,
})
let log3 = dbService.scanLogRepository.create({
blockHash: 'block3',
lastScanned: 3,
})
await dbService.scanLogRepository.persistAndFlush([log1, log2, log3])
let r1 = await dbService.getLastScanned()
expect(r1?.id).toEqual(log3.id)
})
})
<file_sep>/apps/api-evidence/src/app/storage/__init__.py
import io
import typing
from pathlib import PurePath
from uuid import uuid4
from .backend import StorageBackend, StorageBackendError
from .security import Encryption
class StorageError(Exception):
pass
class InvalidEncryptedFile(Exception):
pass
class Storage:
backend: StorageBackend
encryption: typing.Optional[Encryption]
def __init__(self, backend: StorageBackend, encryption: Encryption = None) -> None:
self.backend = backend
self.encryption = encryption
def _file_extension(self, filename: str) -> str:
return PurePath(filename).suffix.lower()
def _stored_filename(self, filename: str) -> str:
ext = self._file_extension(filename)
if self.encryption is not None:
ext = '.enc'
return f'{uuid4().hex}{ext}'
def save(self, name: str, file: typing.IO) -> str:
try:
if self.encryption is not None:
encrypted = io.BytesIO(self.encryption.encrypt(file))
return self.backend.save_file(self._stored_filename(name), encrypted)
return self.backend.save_file(self._stored_filename(name), file)
except StorageBackendError:
raise StorageError
def get(self, file_key: str) -> typing.IO:
try:
stored_file = self.backend.get_file(file_key)
if self.encryption is not None:
decrypted = self.encryption.decrypt(stored_file)
if decrypted is None:
raise InvalidEncryptedFile
return io.BytesIO(decrypted)
except (InvalidEncryptedFile, StorageBackendError):
raise StorageError
return stored_file
<file_sep>/apps/api-evidence/src/app/tests/test_s3.py
import io
from fastapi.testclient import TestClient
from mypy_boto3_s3.client import S3Client
from app.config import config
from .utils import random_lower_string
def test_s3_create_evidence(authed_client: TestClient, s3_client: S3Client) -> None:
s3_client.create_bucket(Bucket=config.S3_BUCKET)
test_filename = 'test.jpg'
file = io.BytesIO()
title = random_lower_string()
description = random_lower_string()
rsp = authed_client.post(
'/api/evidence',
data={'title': title, 'description': description},
files={'evidence_file': (test_filename, file)},
)
assert rsp.ok
def test_s3_get_evidence(authed_client: TestClient, s3_client: S3Client) -> None:
s3_client.create_bucket(Bucket=config.S3_BUCKET)
test_filename = 'test.jpg'
test_file_content = b'test'
test_file = io.BytesIO(test_file_content)
title = random_lower_string()
description = random_lower_string()
rsp = authed_client.post(
'/api/evidence',
data={'title': title, 'description': description},
files={'evidence_file': (test_filename, test_file)},
)
assert rsp.ok
evidence_id = rsp.json()['id']
rsp = authed_client.get(f'/api/evidence/{evidence_id}')
assert rsp.ok
assert rsp.content == test_file_content
<file_sep>/apps/api-evidence/src/app/api/evidence.py
from datetime import datetime, timedelta
from typing import Any
from fastapi import APIRouter, Depends, File, Form, HTTPException, status
from fastapi.responses import StreamingResponse
from sqlalchemy.orm import Session
from app import crud, models, schemas
from app.config import config
from app.storage import Storage
from app.utils import deps, types
router = APIRouter()
@router.get('', response_model=list[schemas.Evidence])
def get_evidence_list(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Retrieve evidence.
"""
if current_user.is_superuser:
evidence = crud.evidence.get_multi(db, skip=skip, limit=limit)
else:
evidence = crud.evidence.get_by_owner(
db=db, owner_id=current_user.id, skip=skip, limit=limit
)
return evidence
@router.post('', response_model=schemas.Evidence)
def create_evidence(
db: Session = Depends(deps.get_db),
storage: Storage = Depends(deps.get_storage),
current_user: models.User = Depends(deps.get_current_active_user),
title: str = Form(...),
description: str = Form(...),
evidence_file: types.EvidenceFile = File(...),
) -> Any:
"""
Create new evidence.
"""
file_key = storage.save(evidence_file.filename, evidence_file.file)
evidence_in = schemas.EvidenceCreate(
title=title,
description=description,
storage_backend=storage.backend.name,
file_key=file_key,
media_type=evidence_file.content_type,
)
evidence = crud.evidence.create_with_owner(
db=db, obj_in=evidence_in, owner_id=current_user.id
)
return evidence
@router.get(
'/{id}',
response_class=StreamingResponse,
responses={
400: {'description': 'Evidence expired'},
403: {'description': 'Not enough permissions'},
404: {},
},
)
def get_evidence(
id: int,
db: Session = Depends(deps.get_db),
storage: Storage = Depends(deps.get_storage),
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Get evidence by ID.
"""
evidence = crud.evidence.get(db=db, id=id)
if evidence is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
if not current_user.is_superuser and evidence.owner_id != current_user.id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail='Not enough permissions'
)
if evidence.created + timedelta(days=config.MAX_FILE_TTL) < datetime.utcnow():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail='Evidence expired'
)
return StreamingResponse(
storage.get(evidence.file_key), media_type=evidence.media_type
)
<file_sep>/apps/api-evidence/src/app/utils/types.py
import zipfile
from pathlib import PurePath
from typing import Any, Callable, Generator
from eth_utils.address import is_address
from fastapi import UploadFile
from pydantic.errors import PydanticValueError
from app.config import config
class EthAddressError(PydanticValueError):
msg_template = 'value is not a valid Ethereum address'
class EthAddress(str):
@classmethod
def __get_validators__(cls) -> Generator[Callable[..., Any], None, None]:
yield cls.validate
@classmethod
def validate(cls, v: Any) -> 'EthAddress':
if is_address(v):
return cls(v)
raise EthAddressError()
class FileTooLargeError(PydanticValueError):
msg_template = 'File is too large'
class ForbiddenFileTypeError(PydanticValueError):
msg_template = 'File type is forbidden'
class InvalidZipFileError(PydanticValueError):
msg_template = 'Zip file is invalid'
class EvidenceFile(UploadFile):
@staticmethod
def _file_extension(filename: str) -> str:
return PurePath(filename).suffix.strip('.').lower()
@classmethod
def _is_valid_zip_file(cls, file: UploadFile) -> bool:
# validate zip file
if not zipfile.is_zipfile(file.file):
return False
# allow only single folder level
for dir in zipfile.Path(file.file).iterdir():
if dir.is_dir():
return False
# check files inside zip file
for info in zipfile.ZipFile(file.file).infolist():
extension = cls._file_extension(info.filename)
if extension not in config.ALLOWED_FILE_TYPES:
return False
return True
@classmethod
def __get_validators__(cls) -> Generator[Callable[..., Any], None, None]:
yield cls.validate
@classmethod
def validate(cls, v: Any) -> 'EvidenceFile':
file: UploadFile = UploadFile.validate(v)
size_in_mb = sum([len(chunk) / 1024 / 1024 for chunk in file.file])
if size_in_mb > config.MAX_FILE_SIZE:
raise FileTooLargeError
extension = cls._file_extension(file.filename)
if extension not in config.ALLOWED_FILE_TYPES:
raise ForbiddenFileTypeError
if extension == 'zip' and not cls._is_valid_zip_file(file):
raise InvalidZipFileError
return file
<file_sep>/apps/api-dispute/README.md
# api-dispute
A Python FastAPI app.
## Setup
Some software is required to run the app. These instructions have been tested on Ubuntu 20.04, but should translate well to OSX.
### Install/update `poetry`
#### Ubuntu:
Install Python 3.9 or later:
```
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt install python3.9-dev
```
Install Pip and Poetry:
```
sudo apt update
sudo apt install python3-pip
pip3 install poetry
```
#### OSX (untested)
```
brew install poetry pyenv
pyenv install 3.9.5
pyenv local 3.9.5
```
### Install python packages
```
poetry install
```
### Run the app
First you'll need to create a database (make sure Postgres is installed). Make sure to set the appropriate variables in `.env` as well.
```
createdb -U <dbuser> <dbname>
```
Then, initialize:
```
cd backend
poetry run python pre_start.py
```
Now you can run the server with live reload:
```
nx serve api-dispute
```
### Test
Run the tests
```
nx test api-dispute
```
### Format
Run black formatter
```
nx format api-dispute
```
### Migrations
TODO -- add executors
Apply migrations
```
poetry run alembic upgrade head
```
Generate a migration
```
poetry run alembic revision --autogenerate -m "Description"
```
## App configuration table
| Key | Default | Description |
| ----------------- | ------------- | ------------------------------------------------------ |
| APP_DOMAIN | | Name of the server, must match production server name. |
| APP_PORT | 5000 |
| API_PREFIX | /api | API url prefix |
| POSTGRES_USER | | Postgres database user |
| POSTGRES_PASSWORD | | Postgres database password |
| POSTGRES_SERVER | | Postgres server url |
| POSTGRES_DB | | Postgres database name |
| TEST_DB | postgres_test | Unit test database name |
<file_sep>/apps/api-evidence/src/app/crud/crud_evidence.py
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models import Evidence
from app.schemas import EvidenceCreate, EvidenceUpdate
class CRUDEvidence(CRUDBase[Evidence, EvidenceCreate, EvidenceUpdate]):
def create_with_owner(
self, db: Session, *, obj_in: EvidenceCreate, owner_id: int
) -> Evidence:
obj_in_data = jsonable_encoder(obj_in)
db_obj = Evidence(**obj_in_data, owner_id=owner_id)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def get_by_owner(
self, db: Session, *, owner_id: int, skip: int = 0, limit: int = 100
) -> list[Evidence]:
return (
db.query(Evidence)
.filter(Evidence.owner_id == owner_id)
.offset(skip)
.limit(limit)
.all()
)
evidence = CRUDEvidence(Evidence)
<file_sep>/apps/developer-docs/docs/contracts/customization.md
# Customization
Solomon Chargebacks, Preorder, and Escrow contracts can be customized by passing in options to the factory constructor. Normally this is handled directly by the frontend plugin, but apps with e.g. existing backend shopping functionality can integrate directly with the blockchain.
See the contract [API documentation](/contracts/api) for precise code generated definitions.
## Chargebacks
TBD
## Preorders
TBD
## Escrow
TBD
<file_sep>/apps/developer-docs/docs/guide/technology.md
# Technology
Solomon takes advantage an accessible and modern tech stack in order to iterate quickly and encourage community contributions.
## Ethereum
Solomon's core technology is built around Ethereum, which is still the gold standard for smart contract development, with great documentation and mature development practices. Solidity is the most widely used language for the Ethereum virtual machine.
## Frontend
Aside from blockchain contracts guaranteeing buyer protection for online transactions, Solomon's core strength is its extensible frontend plugin. Using popular, modern, and light frameworks and development practices is key for growing a developer community and having the best chance of avoiding future tech stack obsolescence.
### Vue3
[Vue3](https://github.com/vuejs/vue-next) is a significant upgrade over Vue2, which is one of the most popular javascript frameworks. It enables more convenient Typescript integration, a composition API for better code organization and reuse, native Postcss integration, and numerous speed/build size improvements.
Solomon's plugin developed as a Vue3 component, although we provide builds that work natively in the browser and other populate frameworks.
### Vite
[Vite](https://github.com/vitejs/vite) is an extremely fast and convenient development server built by the creator of Vue. It integrates cleanly with Vue3, and removes a lot of the headache and bloat of Webpack.
### VitePress
[VitePress](https://github.com/vuejs/vitepress) is a fast static site generator geared towards building documentation sites.
This site is built on VitePress.
## Services
For the various services surrounding the smart contracts and frontend plugin, Solomon evaluates requirements and tech options, and attempts to choose the best one for the job.
### Node/Typescript
We use Node with Typescript to take advantage of the wide availability of Ethereum libraries written in JS/TS.
### Python
We often use Python when speed and safety are less important than ecosystem and ease of development. We use MyPy for static type checking.
### Rust
Solomon uses Rust when possible to take advantage of its speed and safety.
<file_sep>/libs/web/data-access-api/src/lib/api-user.ts
import { plainToClass } from 'class-transformer'
import { PrivateProfileApiResponse } from '@solomon/shared/util-api-evidence-types'
import { NftApi } from './api'
export default (api: NftApi) => {
const getProfilePrivate = async () => {
const { data } = await api.authRequest({
url: 'user',
method: 'GET',
})
return plainToClass(PrivateProfileApiResponse, data)
}
return {
getProfilePrivate,
}
}
<file_sep>/libs/shared/util-api-evidence-types/src/lib/api-evidence-response.ts
import { IJsonObject } from '@solomon/shared/util-core'
export class ApiResponse extends Response {
data!: IJsonObject
}
export interface IEvidence {
id: string
}
export interface EvidenceApiResponse extends IEvidence {}
export class EvidenceApiResponse implements IEvidence {}
interface IPrivateProfile {
email: string | null
avatar: string | null
bio: string | null
name: string | null
joined: number | null
}
export interface PrivateProfileApiResponse extends IPrivateProfile {}
export class PrivateProfileApiResponse implements IPrivateProfile {}
<file_sep>/apps/api-evidence/src/app/storage/backend/s3.py
import io
import typing
import boto3
from botocore.exceptions import ClientError
from mypy_boto3_s3.client import S3Client
from . import StorageBackend, StorageBackendError
class GetObjectError(StorageBackendError):
pass
class PutObjectError(StorageBackendError):
pass
class S3(StorageBackend):
name: str = 'S3'
s3_client: S3Client
bucket_name: str
def __init__(
self,
region: str,
key: str,
secret: str,
bucket_name: str,
endpoint: typing.Optional[str] = None,
) -> None:
self.bucket_name = bucket_name
endpoint_url = None
if endpoint:
endpoint_url = f'https://{endpoint}'
self.s3_client = boto3.client(
's3',
region_name=region,
aws_access_key_id=key,
aws_secret_access_key=secret,
endpoint_url=endpoint_url,
)
def save_file(self, name: str, file: typing.IO) -> str:
try:
self.s3_client.put_object(
Bucket=self.bucket_name, Key=name, Body=file, ACL='private'
)
return name
except ClientError as e:
raise PutObjectError from e
def get_file(self, key: str) -> typing.IO:
try:
response = self.s3_client.get_object(
Bucket=self.bucket_name,
Key=key,
)
return io.BytesIO(response['Body'].read())
except ClientError as e:
raise GetObjectError from e
<file_sep>/apps/api-evidence/src/app/tests/test_auth.py
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from .utils.user import create_random_user, create_random_wallet, eth_sign_data
def test_api_without_auth(client: TestClient) -> None:
rsp = client.get('/api/users/me')
assert rsp.status_code == 401
def test_email_login(client: TestClient, db: Session) -> None:
user, password = create_random_user(db)
rsp = client.post('/api/auth/email', {'username': user.email, 'password': password})
assert rsp.ok
# check the validity of the access token
access_token = rsp.json()['access_token']
rsp = client.get(
'/api/users/me', headers={'Authorization': f'Bearer {access_token}'}
)
assert rsp.ok
def test_login_with_nonexist_email(client: TestClient) -> None:
rsp = client.post(
'/api/auth/email', {'username': '<EMAIL>', 'password': '<PASSWORD>'}
)
assert rsp.status_code == 401
def test_address_login(client: TestClient) -> None:
address, private_key = create_random_wallet()
rsp = client.post('/api/auth/address-challenge', json={'address': address})
assert rsp.ok
challenge = rsp.json()['challenge']
signature = eth_sign_data(challenge, private_key)
challenge_contents = challenge['message']['contents']
rsp = client.post(
'/api/auth/address',
headers={
'Authorization': f'Challenge {address} {challenge_contents} {signature}'
},
)
assert rsp.ok
# check the validity of the access token
access_token = rsp.json()['access_token']
rsp = client.get(
'/api/users/me', headers={'Authorization': f'Bearer {access_token}'}
)
assert rsp.ok
<file_sep>/apps/api-dispute/src/app/api/events.py
import typing
from fastapi import APIRouter, Depends, HTTPException, status
from app.utils.deps import SignatureHeader
router = APIRouter()
@router.post('/ping', status_code=status.HTTP_200_OK)
def ping(
message: typing.Optional[typing.Any] = Depends(SignatureHeader()),
) -> typing.Any:
if message is None:
raise HTTPException(status.HTTP_400_BAD_REQUEST)
return ''
<file_sep>/libs/shared/util-i18n/src/index.ts
export * from './lib/simple-i18n'
<file_sep>/tools/scripts/checkCommitMsg.ts
import * as fs from 'fs'
let msgPath = process.argv[2]
let msg = fs.readFileSync(msgPath, 'utf-8')
msg = msg.split('\n')[0]
let msgArr = msg.split(' ')
let scope = msgArr[0]
let project = msgArr[1]
let issue = msgArr[msgArr.length - 1].replace(/\n/, ``)
let summary = msg
.replace(scope, ` `)
.replace(project, ``)
.replace(issue, ``)
.replace(/ /g, ``)
let isValid = true
const projectNames = ['web', 'api', 'blockchain', 'docs', 'root']
if (!/:.+:/.test(scope)) {
console.log(`Scope ${scope} is not valid`)
isValid = false
}
let projectName: string = (/\[.+]:$/.exec(project) || [''])[0].replace(/[\[\]:]/g, '')
if (projectNames.indexOf(projectName) === -1) {
console.log(`Project ${project} is not valid`)
isValid = false
}
if (summary.length === 0) {
console.log(`Summary should not be empty`)
isValid = false
}
if (!/#[0-9]+$/.test(issue)) {
console.log(`Issue number ${issue} is not valid`)
isValid = false
}
if (!isValid) {
throw 'commit msg format should be "<scope> [<project>]: <short-summary> #<issue-number>"'
}
<file_sep>/subset.config.js
const allPython = [
// devDependencies
'@nrwl/cli',
'@nrwl/cypress',
'nx-python-fastapi',
'shelljs',
'typescript',
]
module.exports = {
'web-evidence': {
include: [
// dependencies
'vue',
'@sampullman/vue3-fetch-api',
'vue-i18n',
'vue-router',
// devDependencies
'@vitejs/plugin-vue',
'@vue/compiler-sfc',
'@samatech/postcss-basics',
'nx-vue3-vite',
'vite',
'unplugin-vue-components',
'vite-plugin-vue-images',
'@nrwl/cli',
'@nrwl/workspace',
],
},
'api-evidence': {
include: [...allPython],
},
'api-dispute': {
include: [...allPython],
},
'blockchain-watcher': {
include: [
'@nrwl/node',
'@nrwl/cli',
'@nrwl/workspace',
'mjml',
'fs-extra',
'@types/fs-extra',
'@mikro-orm/core',
'@mikro-orm/sqlite',
'uuid',
'@types/uuid',
'ethers',
'nodemailer',
'@types/nodemailer',
'mailgun.js',
'handlebars',
'form-data',
'typescript',
'tslib',
'reflect-metadata',
'pkg-dir',
],
},
'db-dev': {
include: [
// dependencies
'pg',
'dotenv',
// devDependencies
'husky',
],
},
}
<file_sep>/libs/shared/util-core/src/lib/i-json-object.ts
type AnyJson = boolean | number | string | null | IJsonArray | IJsonObject
export interface IJsonObject {
[key: string]: AnyJson
}
export interface IJsonArray extends Array<AnyJson> {}
<file_sep>/libs/web/data-access-state/src/index.ts
export * from './lib/store'
export * from './lib/user'
<file_sep>/libs/web/plugin/src/index.ts
export { default as SlmPlugin } from './lib/SlmPlugin.vue'
export { default as SlmPluginChargebacks } from './lib/SlmPluginChargebacks.vue'
export { default as SlmPluginEscrow } from './lib/SlmPluginEscrow.vue'
export { default as SlmPluginPreorder } from './lib/SlmPluginPreorder.vue'
<file_sep>/apps/api-evidence/src/app/models/__init__.py
# flake8: noqa
from .evidence import Evidence
from .user import User
<file_sep>/apps/api-evidence/README.md
# Evidence Uploader API
A Python FastAPI app.
## Setup
Some software is required to run the app. These instructions have been tested on Ubuntu 20.04, but should translate well to OSX.
### Install/update `poetry`
#### Ubuntu:
Install Python 3.9 or later:
```
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt install python3.9-dev
```
Install Pip and Poetry:
```
sudo apt update
sudo apt install python3-pip
pip3 install poetry
```
#### OSX (untested)
There will be a dependency on Postgres for poetry install. Please install Postgres first.
Reference is at [github](https://github.com/psycopg/psycopg2/issues/1200#issuecomment-776159466)
```
brew install poetry pyenv
pyenv install 3.9.5
pyenv local 3.9.5
brew install postgresql
```
### Install python packages
```
poetry install
```
### Run the app
First you'll need to create a database (make sure Postgres is installed). Make sure to set the appropriate variables in `src/.env` as well. You can copy `.env.dist` as a reference
```
createdb -U <dbuser> <dbname>
```
Then, initialize:
```
cd backend
poetry run python pre_start.py
```
Now you can run the server with live reload:
```
nx serve api-evidence
```
### Test
Run the tests
```
nx test api-evidence
```
### Format
Run black formatter
```
nx run api-evidence:format
```
### Migrations
TODO -- add executors
Apply migrations
```
poetry run alembic upgrade head
```
Generate a migration
```
poetry run alembic revision --autogenerate -m "Description"
```
## App configuration table
| Key | Default | Description |
| ---------------------- | ---------------- | ------------------------------------------ |
| MAX_FILE_TTL | 90 | Maximum lifetime of evidence files in days |
| S3_BUCKET | evidence-uploads | S3 bucket for App files |
| S3_ENDPOINT | | S3 endpoint |
| S3_KEY | | S3 client key |
| S3_SECRET | | S3 client secret |
| S3_REGION | | S3 region |
| SHORTENER_URL | | Private URL shortener for project links |
| SHORTENER_ACCESS_TOKEN | | Access token for URL shortener |
<file_sep>/apps/api-dispute/pyproject.toml
[tool.poetry]
name = "solomon-dispute-backend"
version = "0.1.0"
description = "A FastAPI (Python) app for uploading Solomon dispute evidence files to the blockchain"
authors = ["<NAME> <<EMAIL>>"]
[tool.poetry.dependencies]
python = "^3.9"
fastapi = "^0.68.1"
uvicorn = "^0.14.0"
pydantic = "^1.8.2"
psycopg2 = "^2.8.6"
SQLAlchemy = "^1.4.23"
starlette = "^0.14.2"
tenacity = "^8.0.1"
python-dotenv = "^0.19.0"
requests = "^2.26.0"
alembic = "^1.7.3"
[tool.poetry.dev-dependencies]
pytest = "*"
mypy = "*"
sqlalchemy-stubs = "^0.4"
black = "*"
flake8 = "*"
flake8-black = "*"
flake8-bugbear = "*"
flake8-import-order = "*"
flake8-comprehensions = "*"
[tool.mypy]
ignore_missing_imports = true
follow_imports = "skip"
show_column_numbers = true
disallow_untyped_defs = true
no_warn_no_return = true
plugins = ["sqlmypy"]
exclude = "migrations"
[tool.black]
include = '\.py$'
skip-string-normalization = true
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta:__legacy__"<file_sep>/apps/api-dispute/src/app/tests/test_api.py
from fastapi.testclient import TestClient
from app.config import config
from app.utils.security import generate_signature
def test_healthcheck(client: TestClient) -> None:
rsp = client.get('/api/health/app')
assert rsp.ok
def test_ping_incorrect_signature(client: TestClient) -> None:
rsp = client.post(
'/api/events/ping',
json={},
headers={config.SIGNATURE_HEADER_NAME: 'incorrect-signature'},
)
assert not rsp.ok
def test_ping(client: TestClient) -> None:
signature = generate_signature(config.MESSAGE_SECRET_KEY, b'{}')
rsp = client.post(
'/api/events/ping',
json={},
headers={config.SIGNATURE_HEADER_NAME: signature},
)
assert rsp.ok
<file_sep>/apps/developer-docs/README.md
# Solomon Defi Documentation
Solomon developer documentation.
Generated with [nx-vue3-vite](https://github.com/samatechtw/nx-vue3-vite)
## Setup
Run a local development server:
```
npx nx serve developer-docs
```
Build for production:
```
npx nx build developer-docs
```
<file_sep>/apps/developer-docs/docs/index.md
---
home: true
heroImage: /ic_logo_white.png
actionText: Get Started
actionLink: /guide/
altActionText: Learn More
altActionLink: https://medium.com/solomondefi/introducing-the-future-of-decom-1eeac25cd391
features:
- title: 🚀 eCommerce plugin
details: Fully customizable crypto-enabled frontend checkout plugin
- title: 🛒 Optional shopping cart
details: Track user purchases with our shopping cart, or provide your own
- title: 🤝 SPA Integrations
details: Use the Solomon plugin with your favorite framework
- title: 🔌 Third Party Plugins
details: Integrate easily with existing shopping platforms
- title: 💰 Smart contract suite
details: Ethereum contracts for escrow, preorders, and buyer protection
- title: 📖 Open Source
details: Solomon is committed to transparent development
footer: GPLv3 Licensed | Copyright © 2021-present <NAME>
---
<file_sep>/apps/web-evidence/src/app/utils/config.ts
const apiHost = import.meta.env.VITE_API_HOST
export const API_URL = `${apiHost}/api/`
<file_sep>/apps/blockchain-watcher/README.md
# Solomon Blockchain Watcher
A service that scans the blockchain and triggers actions based on incoming log messages. It is intended for use in the Solomon payments
ecosystem, but may be adapted for general use.
At a high level, the operation is simple:
1. Scan blocks for events from a list of contracts
2. On meeting some event condition, e.g. `CreateEscrow` emitted, trigger a list of actions
The list of scanned contracts may be dynamically updated, and actions adhere to a standard plugin interface.
Solomon implements scanners for:
- Notifying (via email) buyers, merchants, or escrow holders when a contract deploys
- Notifying both parties when a dispute is initiated
- Notifying parties when funds are withdrawn from escrow
The service is written with Typescript as a nodejs application.
<file_sep>/libs/web/data-access-api/src/lib/api.ts
import { FetchApi, FetchApiOptions, FetchRequestConfig } from '@sampullman/vue3-fetch-api'
import { ApiResponse } from '@solomon/shared/util-api-evidence-types'
import { IJsonObject } from '@solomon/shared/util-core'
const defaultResponseInterceptors = [
async (res: Response): Promise<ApiResponse> => {
if (!res) {
throw new Error('NETWORK_FAILURE')
}
const { status } = res
if (status >= 500) {
throw new Error('NETWORK_FAILURE')
} else if (status === 401) {
// Permission denied
throw res
}
let data: IJsonObject
try {
data = await res.json()
} catch (_e) {
// Avoid crashing on empty response
data = {}
}
if (status === 400) {
throw data
}
const apiRes = res as ApiResponse
apiRes.data = data
return apiRes
},
]
export class NftApi extends FetchApi {
constructor(options: FetchApiOptions) {
super({
responseInterceptors: defaultResponseInterceptors,
...options,
})
}
authRequest(config: FetchRequestConfig): Promise<ApiResponse> {
// TODO -- use real auth strategy
const token = 'test'
const { headers, ...rest } = config
return this.request({
...rest,
headers: {
...headers,
Authorization: `Bearer ${token}`,
},
}) as Promise<ApiResponse>
}
}
| ad0909d0abc54e3d045f9aa4ce5d552a716d94e2 | [
"Markdown",
"TOML",
"JavaScript",
"INI",
"Python",
"TypeScript",
"Dockerfile",
"Shell"
] | 127 | TypeScript | Edwinverheul94/solomon-monorepo | 36b44d5f5288b0ef5d6d24ae1e38c1f43a9e151d | a3bf22fa9930df6811031432889d0050d35de726 |
refs/heads/master | <repo_name>tajfunek/Whatever<file_sep>/python_stuff/coderdojo.py
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 07:33:24 2018
@author: DN
"""
import numpy as np
from skimage.io import imsave
resX = 640
resY = 480
ramka_1 = np.zeros((resX, resY, 3), dtype=np.uint8)
ramka_2 = np.zeros((resX, resY, 3), dtype=np.uint8)
ramka_3 = np.zeros((resX, resY, 3), dtype=np.uint8)
kolor_lini = 255
kanal_R = int(0)
kanal_G = int(1)
kanal_B = int(2)
kamera_1 = 1
kamera_2 = 2
kamera_3 = 3
for kat in range(182):
ramka_1[:, int(ramka_1.shape[1] / 2 - 3):int(ramka_1.shape[1] / 2 + 3), kanal_R] = kolor_lini
ramka_1[:, int(ramka_1.shape[1] / 2), kanal_G] = 0
ramka_1[:, int(ramka_1.shape[1] / 2), kanal_B] = 0
ramka_2[:, int(ramka_1.shape[1] / 2 - 3):int(ramka_1.shape[1] / 2 + 3), kanal_R] = kolor_lini
ramka_2[:, int(ramka_1.shape[1] / 2), kanal_G] = 0
ramka_2[:, int(ramka_1.shape[1] / 2), kanal_B] = 0
ramka_3[:, int(ramka_1.shape[1] / 2 - 3):int(ramka_1.shape[1] / 2 + 3), kanal_R] = kolor_lini
ramka_3[:, int(ramka_1.shape[1] / 2), kanal_G] = 0
ramka_3[:, int(ramka_1.shape[1] / 2), kanal_B] = 0
nazwa_pliku_1 = "%1i_%03i.png" % (kamera_1, kat)
nazwa_pliku_2 = "%1i_%03i.png" % (kamera_2, kat)
nazwa_pliku_3 = "%1i_%03i.png" % (kamera_3, kat)
imsave(nazwa_pliku_1, ramka_1)
imsave(nazwa_pliku_2, ramka_2)
imsave(nazwa_pliku_3, ramka_3)
<file_sep>/calculate.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Funkcje do obliczeń na danych punktach - pewnego rodzaju biblioteka."""
"""Wymagają modułu math!"""
import math
#import PNG_read
#from skimage.io import imread
import png
import time
import numpy as np
#wspólne stałe parametry kamery i skanera oraz zdjęcia:
w = 1024 # szerokość zdjęcia
h = 1280 # wysokość zdjęcia
f = 1110 # f to ogniskowa w pixelach (odległość "matryca-obiektyw")
laserDEG = 28.5 # kąt nachylenia lasera (należący do trójkąta z punktem skanowanym)
laserDIS = 100 # odległość kamera-laser w mm
k = 194 # k - odległość kamera-środek "tacki" w mm
camH = 73 # wysokość na której znajduje się kamera w mm
#odległość kamera-tacka oraaz camH jak na razie nie muszą być podane osobno
def convert(x, y, deg):
"""przygotowywuje punkty do obliczeń"""
resX = w
resY = h
x -= (resX / 2)
y = (resY / 2) - y
return x, y, deg
def cartesian(H, r, alpha):
x = r * math.cos(alpha)
y = r * math.sin(alpha)
return x, y, H
def calculate(x=0, y=0, deg=0):
"""używa układy współrzędnych o punkcie (0,0) na środku zdjęcia"""
"""do obliczeń na pomiarach kamer na bokach"""
"""teraz wywołuje też cartesian() na koniec"""
# stałe parametry kamery:
#k = 231.75 # k - odległość kamera-środek "tacki" w mm
#k = 205
#camH = 75 # wysokość na której znajduje się kamera w mm
# obliczenia:
r = laserDIS / (math.tan(math.radians(laserDEG)) + (x / f))
a = x * r / f
H = y * r / f + camH
R = math.sqrt((k - r) ** 2 + a ** 2)
if r == k:
if x != 0:
beta = 90
elif x == 0:
beta = 0
else:
beta = math.atan(a / (k - r))
if x >= 0:
Alpha = deg + beta
elif x < 0:
Alpha = deg - beta
X, Y, Z = cartesian(H, R, Alpha)
point = [X, Y, Z]
return point
def calculateTOP(x=0, y=0, deg=0):
"""Do obliczeń na pomiarach z kamery na górze"""
"""zwraca o drazu punkt w układzie kartezjańskim!!!"""
"""w przeciwieństwie do calculateTOP - działa"""
# stałe parametry kamery:
k = 315
# obliczenia:
h1 = laserDIS / (math.tan(math.radians(laserDEG)) - (x / f))
Z = k - h1
a = x * h1 / f
b = y * h1 / f
sin = math.sin(deg)
cos = math.cos(deg)
X = a * cos + b * sin
Y = -1 * a * sin + b * cos
#kartezjański układ współrzędnych!!!
point = [X, Y, Z]
return X, Y, Z
def extract(filename, folder, stepDEGR=1):
_time = time.time()
pic = []
points = []
try:
#PyPNG:
reader = png.Reader(folder + filename + '.png')
w, h, pixels, metadata = reader.read_flat()
#np.array(pixels)
# pixels = np.array(PNG_read.read(folder + filename + '.png'))
#print('Reading time:', time.time()-_time)
_time = time.time()
filename = filename.rstrip(".png")
cam_no = int(filename[0])
deg = int(filename[2:]) * stepDEGR
#deg = int(deg)
if cam_no == 2:
deg += 180
if deg >= 360: deg -= 360
deg = math.radians(deg)
for i in range(len(pixels)):
if (i % 3) == 0:
pic.append(pixels[i+1]) #zmienić na i+1 !!!!! -
for i in range(h):
row = pic[i * w: ((i + 1) * w)]
x = getpointConst(row) # należy wybrać którą funkcję wykorzystać
# x = getpointAvg(row)
if x is None:
continue
y = i
x, y, deg = convert(x, y, deg)
data = [x, y, deg]
points.append(data)
#print('getpoint time:', time.time()-_time)
return points
except:
return None
def getpointConst(row):
"""używa średniej arytmetycznej wszystkich pixeli które spełniają warunek"""
RED = 140
REDlist = []
sequences = []
for i in range(len(row)):
if row[i] >= RED:
REDlist.append(i)
i = 0
while i < len(REDlist):
if (REDlist[i] + 1 or REDlist[i] + 2) in REDlist:
condition = 1
temp = []
ii = i
while condition == 1:
temp.append(ii)
ii += 1
if (REDlist[ii] + 1 or REDlist[ii] + 2) in REDlist:
condition = 1
else:
condition = 0
temp.append(ii)
sequences.append(temp)
i = i + len(temp)
else:
i += 1
try:
if sequences[0]:
longest = max(sequences)
a = 0
for j in range(len(longest)):
a += REDlist[longest[j]]
x = a / len(longest)
else:
x = REDlist[0]
return x
except:
if len(REDlist) is 0:
#print('Something is wrong!!!')
return None
else:
x = REDlist[0]
return x
def getpointAvg(row):
"używa średniej ważonej pixeli które spełniają warunek"
"jest niedokończona względem getpointConst"
RED = 128
REDlist = []
sequences = []
for i in range(len(row)):
if row[i] >= RED:
REDlist.append(i)
i = 0
while i < len(REDlist):
if (REDlist[i] + 1) in REDlist:
condition = 1
elif (REDlist[i] + 2) in REDlist:
condition = 1
else:
condition = 0
i += 1
temp = []
ii = i
while condition == 1:
temp.append(ii)
ii += 1
if (REDlist[ii] + 1) in REDlist:
condition = 1
elif (REDlist[ii] + 2) in REDlist:
condition = 1
else:
condition = 0
temp.append(ii)
sequences.append(temp)
i = i + len(temp)
if sequences[0]:
longest = max(sequences)
a = 0
b = 0
for j in range(len(longest)):
a += REDlist[longest[j]] * row[REDlist[longest[j]]]
b += row[REDlist[longest[j]]]
x = a / b
else:
x = REDlist[0]
return x
def getpointConst2(row):
"""Ta nowa wolniejsza. W ramach optymalizacji zwiększono czas wykonywania o ok 3 sekundy"""
"""Nie przesestowana do końca - brak pewności, że działa"""
"""używa średniej arytmetycznej wszystkich pixeli które spełniają warunek"""
RED = 128
#REDlist = []
sequences = []
i = 0
while i < len(row):
if row[i] >= RED:
red = True
x = row[i]
if (row[i] + 1 or row[i] + 2) >= RED:
condition = 1
temp = []
ii = i
while condition == 1:
temp.append(ii)
ii += 1
if (row[ii] + 1 or row[ii] + 2) >= RED:
condition = 1
else:
condition = 0
temp.append(ii)
sequences.append(temp)
i = i + len(temp)
else:
i += 1
else: i += 1
if red == False:
#print('Something is wrong!!!')
return None
if sequences[0]:
longest = max(sequences)
a = 0
for j in range(len(longest)):
a += row[longest[j]]
x = a / len(longest)
return x
def calculateTOP_OLD(x=0, y=0, deg=0):
"""stara wersja, nie działa poprawnie. zostawiona just in case"""
"""Do obliczeń na pomiarach z kamery na górze"""
# stałe parametry kamery:
f = 577
k = 250
laserDEG = 30
laserDIS = 30
x, y, deg = convert(x, y, deg)
# obliczenia:
h1 = laserDIS / (math.tan(math.radians(laserDEG)) - (x / f))
H = k - h1
a = x * h1 / f
r = y * h1 / f
R = math.sqrt(a ** 2 + r ** 2)
if r != 0:
beta = math.degrees(math.atan(a / r))
# ustalenie kąta (dużo przypadków)
if y == 0:
if x > 0:
alpha = deg + 90
if x < 0:
alpha = deg - 90
elif x == 0:
alpha = 0 # 0 ale to w sumie nie ma znaczenia, jest w puncie (0,0)
else:
if y > 0:
if x >= 0:
alpha = deg - beta
if x < 0:
alpha = deg + beta
if y < 0:
if x >= 0:
alpha = deg + beta + 180
if x < 0:
alpha = deg - beta + 180
if alpha < 0:
alpha += 360
point = [H, R, alpha]
return point
<file_sep>/python_stuff/calibratetest.py
import calculate as c
import math
extracted = c.extract()
if extracted is not None:
output = []
calibration = open("calibration.txt", "r")
for point in extracted:
output.append(c.calculate(point[0], point[1], point[2]))
print(output)
<file_sep>/python_stuff/calibrate.py
import calculate as cd
import png
import math
plateR = 75
camdis = 231.75
expectedDIS = camdis - plateR
#parametry z kamery:
f = 1155
laserDIS = 100
laserDEG = 28.5
resY = 1280
expectedX = f*math.tan(math.radians(laserDEG)) - (f*laserDIS/expectedDIS)
output_old = []
output_new = []
calibration = []
errors_old = []
errors_new = []
pixels_new = []
pixels = []
AVGerror_old = 0
AVGerror_new = 0
pixels = cd.extract("1_000","testimages/", 0)
longY = resY / len(pixels)
for pixel in pixels:
output_old.append(cd.calculate(*pixel))
for pixel in pixels:
calibration.append(expectedX - pixel[0])
for i in range(len(pixels)):
pixelx = pixels[i]
pixel = [(pixelx[0] + calibration[i]) , pixelx[1], pixelx[2]]
pixels_new.append(pixel)
for pixel in pixels_new:
output_new.append(cd.calculate(*pixel))
for result in output_old:
result = math.sqrt((result[0]**2) + (result[1]**2))
errors_old.append(expectedDIS - result)
AVGerror_old += (expectedDIS - result)
for result in output_new:
result = math.sqrt((result[0]**2) + (result[1]**2))
errors_new.append(expectedDIS - result)
AVGerror_new += (expectedDIS - result)
AVGerror_old = AVGerror_old / len(output_old)
AVGerror_new = AVGerror_new / len(output_new)
print("AVGerror_old: ", AVGerror_old)
print("AVGerror_new: ", AVGerror_new)
file = open("calibration.txt", "w")
file.write(str(longY) + "\n")
for i in calibration:
file.write(str(i) + "\n")
file.close()
<file_sep>/python_stuff/calculation.py
import math
import calculateTEMP as cd
folder = "./"
filename = "testpic1000.png"
#prawdziwe wymiary:
#wspólne stałe parametry kamery i skanera oraz zdjęcia:
w = 1000 # szerokość zdjęcia
h = 1000 # wysokość zdjęcia
f = 500 # f to ogniskowa w pixelach (odległość "matryca-obiektyw")
laserDEG = 45 # kąt nachylenia lasera (należący do trójkąta z punktem skanowanym)
laserDIS = 100 # odległość kamera-laser w mm
k = 250 # k - odległość kamera-środek "tacki" w mm
camH = 50 # wysokość na której znajduje się kamera w mm
"""w = 1024 # szerokość zdjęcia
h = 1280 # wysokość zdjęcia
f = 1110 # f to ogniskowa w pixelach (odległość "matryca-obiektyw")
laserDEG = 28.5 # kąt nachylenia lasera (należący do trójkąta z punktem skanowanym)
laserDIS = 90 # odległość kamera-laser w mm
k = 206 # k - odległość kamera-środek "tacki" w mm
camH = 73 # wysokość na której znajduje się kamera w mm"""
output = open("msm.txt", "w")
i = 0
extracted = cd.extract(filename, folder, 0)
for point in extracted:
print("extracted points: ", point, "iteration: ", i)
r = laserDIS / (math.tan(math.radians(laserDEG)) + (point[0] / f))
a = point[0] * r / f
H = r * point[1] / f + camH
print(r, "\t", a, "\t", H)
msg = "point: " + str(point) + "\t" + str(r) + "\t" + str(a) + "\t" + str(H) + "\n"
output.write(msg)
i += 1
output.close()
<file_sep>/python_stuff/lasterTEST.py
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setup((21, 20, 26), GPIO.OUT)
GPIO.output(21, 0)
GPIO.output(20, 0)
GPIO.output(26, 0)
print("GPIO set: laser ON")
input("press Enter to continue")
GPIO.output(21, 1)
GPIO.output(20, 1)
GPIO.output(26, 1)
print("GPIO set: laser OFF")
while choice != "y":
GPIO.output(21, 0)
GPIO.output(20, 1)
GPIO.output(26, 1)
input("GPIO set: 21 ON")
GPIO.output(21, 1)
GPIO.output(20, 0)
GPIO.output(26, 1)
input("GPIO set: 20 ON")
GPIO.output(21, 1)
GPIO.output(20, 1)
GPIO.output(26, 0)
input("GPIO set: 26 ON")
choice = input("continue? y/n ")
<file_sep>/main.py
import driver
import os
import RPi.GPIO as GPIO
import subprocess as s
import shlex
import sys
import time as t
_t=t.time()
GPIO.setwarnings(False)
os.nice(-5)
driver.setup()
GPIO.setup((21, 20, 26), GPIO.OUT)
print("Starting...\n")
stepdeg = 4 # resolution - sth is wrong 64*8 is 360deg. not 64*64
motor_time = 10 # in ms, '10' Can be changed to lower if works
turns = int(256/stepdeg)
choice = str(input("Do you want to continue from where you left off? y/n "))
if choice == "y":
startpoint = int(input("Which iteration failed? "))
print("continuing from ", startpoint)
else:
startpoint = 0
try:
for i in range(startpoint, turns):
print("ITERATION: ", i)
GPIO.output(21, 0)
GPIO.output(20, 1)
GPIO.output(26, 1)
print("GPIO set")
print("CAM1")
error = 1
while error:
error = 0
print("PHOTO")
#print("Iteration")
cam1 = s.Popen(shlex.split("sudo fswebcam --resolution 1280x1024 --device /dev/video0 \
--no-banner --png --no-title --no-subtitle --no-timestamp --no-info \
--set brightness=5 --set contrast=255 --rotate 270 \
images/1_{}.png".format(i)), stdout = s.PIPE, stderr = s.PIPE)
try:
#print("Communication")
_, error1 = cam1.communicate(timeout = 15)
error1 = error1.decode('utf-8')
#print(error1)
if "Writing PNG image to" not in error1:
error = 1
print(error1)
except:
error = 1
"""cam1.kill()
print("ERROR")
sys.exit()"""
# Next camera
print("CAM2")
GPIO.output(21, 1)
GPIO.output(20, 1)
GPIO.output(26, 0)
error = 1
while error:
error = 0
#print("Iteration")
cam1 = s.Popen(shlex.split("sudo fswebcam --resolution 1280x1024 --device /dev/video0 \
--no-banner --png --no-title --no-subtitle --no-timestamp --no-info \
--set brightness=5 --set contrast=255 --rotate 270 \
images/2_{}.png".format(i)), stdout = s.PIPE, stderr = s.PIPE)
try:
#print("Communication")
_, error1 = cam1.communicate(timeout = 15)
error1 = error1.decode('utf-8')
#print(error1)
except:
cam1.kill()
print("ERROR")
sys.exit()
finally:
pass
#print("Done")
#error1 = error1.decode('utf-8')
if "Writing PNG image to" not in error1:
error = 1
"""print("CAM3")
GPIO.output(21, 1)
GPIO.output(20, 0)
GPIO.output(26, 1)
error = 1
while error:
error = 0
#print("Iteration")
cam1 = s.Popen(shlex.split("sudo fswebcam --resolution 1280x1024 --device /dev/video0 \
--no-banner --png --no-title --no-subtitle --no-timestamp --no-info \
--set brightness=5 --set contrast=255 --rotate 270 \
images/3_{}.png".format(i)), stdout = s.PIPE, stderr = s.PIPE)
try:
#print("Communication")
_, error1 = cam1.communicate(timeout = 15)
error1 = error1.decode('utf-8')
#print(error1)
except:
cam1.kill()
print("ERROR")
sys.exit()
finally:
pass
#print("Done")
#error1 = error1.decode('utf-8')
if "Writing PNG image to" not in error1:
error = 1"""
driver.forward(motor_time/1000, stepdeg) # '10' Can be changed to lower if works
except KeyboardInterrupt:
GPIO.cleanup()
sys.exit()
print("TIME: ", t.time() - _t)
GPIO.cleanup()
<file_sep>/README.md
# Scan & Print
this stuff can do this:
<p align="center">
<img src="miscellaneous/marszalek.png" />
</p>
<file_sep>/calculated.c
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <dirent.h>
#include <sys/types.h>
#include <signal.h>
#include <png.h>
#include <math.h>
// For comparison of two doubles in calculator()
//#define ERROR 0.0588
#define THREAD_NO 24
#define DIR_IMG "./images/"
#define IMG_NO 128
#define BUF_LEN 64
#define FILE_NO 128
#define F 1110
#define LASER_DEG 28.5
#define LASER_DIS 100
#define K 194
#define CAM_H 73
#define STEP 4
int progress;
int threads_running = 0;
struct arg_calc {
int pipefd;
char filename[16];
};
struct ret_png {
int width;
int height;
png_bytepp row_pointers;
};
struct sequence {
int start;
int end;
float avg;
int len;
};
struct point {
double x;
double y;
double z;
};
static pthread_mutex_t mutex;
pthread_t threads[IMG_NO];
/*void padding(char* str, int pad) {
int len = strlen(str);
int pad_len = pad - len;
char padding[pad_len];
for(int i = 0; i < pad_len; i++) {
padding[i] = '\0';
}
strcat(str, padding);
}*/
struct ret_png* read_png(char*);
float getpointConst(struct ret_png*, int);
struct point* calculator(struct ret_png*, double, double, double);
double radians(double);
void* calculate(void* args) {
//nice(-10);
char buf[BUF_LEN];
struct arg_calc* args_ptr = (struct arg_calc*)args;
int error = 0;
READ_START:
memset(buf, 0, BUF_LEN * sizeof(char));
strncpy(buf, DIR_IMG, BUF_LEN);
strcat(buf, args_ptr->filename);
struct ret_png* png = read_png(buf);
memset(buf, 0, BUF_LEN * sizeof(char));
int len = strlen(args_ptr->filename);
char filename[len];
strncpy(filename, args_ptr->filename, len);
filename[len - 4] = '\0';
char deg_string[strlen(filename) - 1];
strncpy(deg_string, filename + 2, strlen(filename) - 1);
if(png != NULL) {
sprintf(buf, "prtSuccecful reading: %s, deg = %s", filename, deg_string);
write(args_ptr->pipefd, buf, BUF_LEN);
memset(buf, 0, BUF_LEN * sizeof(char));
} else {
sprintf(buf, "prtFailed: %s", filename);
write(args_ptr->pipefd, buf, BUF_LEN);
error++;
if(error > 10){
sprintf(buf, "prtFailed too many times: %s", filename);
write(args_ptr->pipefd, buf, BUF_LEN);
kill(getpid(), SIGTERM);
return NULL;
}
goto READ_START;
}
float stepdeg = 180/(256/STEP);
int deg = atoi(deg_string) * stepdeg;
int i;
for(i = 0; i < png->height; i++) {
float x = getpointConst(png, i);
if(x != -1) {
struct point* point_car = calculator(png, x, i, radians(deg));
sprintf(buf, "res%f;%f;%f;",
point_car->x, point_car->y, point_car->z);
write(args_ptr->pipefd, buf, BUF_LEN);
}
free(png->row_pointers[i]);
}
pthread_mutex_lock(&mutex);
progress++;
threads_running--;
pthread_mutex_unlock(&mutex);
return NULL;
}
void* file_buffer(void* args) {
FILE* output = fopen("./output.txt", "w");
int pipe = *(int*)args;
char buf[BUF_LEN];
read(pipe, buf, BUF_LEN);
while(1) {
//printf("Received: %s\n", buf);
char cmd[4];
strncpy(cmd, buf, 3);
cmd[3] = '\0';
if(!strcmp(cmd, "prt")) {
printf("%s\n", &buf[3]);
} else if(!strcmp(cmd, "res")) {
fprintf(output, "%s\r\n", &buf[3]);
}
fflush(stdout);
read(pipe, buf, BUF_LEN);
if(!strcmp(buf, "finish")) {
break;
}
}
return NULL;
}
int main(void) {
//nice(-20);
time_t start = time(NULL);
printf("Program started\n");
int pipefd[2]; // pipefd[0] - read end / pipefd[1] - write end
if(pipe(pipefd) != 0) {
printf("ERROR: Pipe cannot be created; %i", errno);
}
if(pthread_mutex_init(&mutex, NULL)) {
printf("ERROR while mutexing\n");
return 5;
}
DIR* images_dir = opendir(DIR_IMG);
char filenames_full[FILE_NO+2][16];
struct dirent* entry = readdir(images_dir);
unsigned int i = 0;
while(entry != NULL) {
strncpy(filenames_full[i], entry->d_name, 16);
filenames_full[i][15] = '\0';
i++;
entry = readdir(images_dir);
fflush(stdout);
}
//printf("HERE1");
char filenames[IMG_NO][16];
for(int j = 0, i = 0; i < FILE_NO + 2; i++) {
//printf("WorKING\n");
if((strcmp(filenames_full[i], ".") == 0) || (strcmp(filenames_full[i], "..") == 0)) {
continue;
}
strncpy(filenames[j], filenames_full[i], 16);
printf("FILE %i: %s\n", j, filenames[j]);
j++;
}
int j;
for(j = 0, i = FILE_NO; i < IMG_NO; i++, j++) {
printf("j = %i\n", j);
if(j == FILE_NO) j = 0;
strncpy(filenames[i], filenames[j], 16);
}
printf("i = %i\n", i);
printf("Directory read\n");
fflush(stdout);
if(i < IMG_NO) {
printf("Less than IMG_NO images in directory\n");
return 4;
}
printf("Number of images is correct: %i\n", i);
//raise(SIGINT);
pthread_attr_t attributes;
pthread_attr_init(&attributes);
pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
struct arg_calc args[IMG_NO];
//threads_running = THREAD_NO;
for(i = 0; i < IMG_NO; i++) {
args[i].pipefd = pipefd[1];
strncpy(args[i].filename, filenames[i], 16);
//free(filenames[i]);
}
pthread_t buffer;
pthread_create(&buffer, NULL, &file_buffer, pipefd);
//printf("Threads launched\nThreads running: %i\n", threads_running);
i = 0;
while(1) {
int active_threads = threads_running;
//raise(SIGINT);
//printf("SPAM: %i\n", active_threads);
if(i != IMG_NO) {
if(active_threads != THREAD_NO) {
printf("Creating thread: %i\n", i);
pthread_mutex_lock(&mutex);
pthread_create(&threads[i], &attributes, &calculate, &args[i]);
threads_running++;
pthread_mutex_unlock(&mutex);
i++;
}
}
if(threads_running == 0) break;
}
//sleep(2);
printf("Thread running: %i\n", threads_running);
sleep(3);
write(pipefd[1], "finish", 64);
pthread_join(buffer, NULL);
fflush(stdout);
close(pipefd[0]);
close(pipefd[1]);
printf("Took: %li seconds\n", (time(NULL)- start));
return 0;
}
struct ret_png* read_png(char* filename) {
FILE* image = fopen(filename, "rb");
if(image == NULL) {
return NULL;
}
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(!png_ptr) {
return NULL;
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
return NULL;
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
fclose(image);
return NULL;
}
png_init_io(png_ptr, image);
png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_STRIP_ALPHA, NULL);
int width = png_get_image_width(png_ptr, info_ptr);
int height = png_get_image_height(png_ptr, info_ptr);
png_bytepp row_pointers;
row_pointers = png_get_rows(png_ptr, info_ptr);
struct ret_png* ret = malloc(sizeof(struct ret_png));
ret->width = width;
ret->height = height;
ret->row_pointers = row_pointers;
fclose(image);
return ret;
}
int compar(const void* a, const void* b) {
struct sequence* a_ = (struct sequence*)a;
struct sequence* b_ = (struct sequence*)b;
if(a_->avg > b_->avg) return 1;
if(a_->avg < b_->avg) return -1;
else return 0;
}
float getpointConst(struct ret_png* png, int row_no) {
png_bytep row = png->row_pointers[row_no];
const int RED = 140;
int REDlist[png->width];// = malloc(png->width * sizeof(int));//[png->width]
struct sequence sequences[(png->width)/4];// = malloc(50 * sizeof(struct sequence));
int red_len = 0;
int seq_len = 0;
for(int i = 0; i < png->width; i++) {
if(row[3 * i + 1] >= RED) { // 3 * i ponieważ nie usunąłem innych kolorów
REDlist[red_len] = i;
red_len++;
}
}
for(int i = 0; i < red_len;) {
if(REDlist[i] + 2 == REDlist[i + 2] || REDlist[i] + 1 == REDlist[i + 1]) {
struct sequence temp;
int condition = 1;
temp.start = i;
int j = 0;
while(condition == 1) {
if(REDlist[j] + 2 == REDlist[j + 2] || REDlist[j] + 1 == REDlist[j + 1]) {
j++;
} else {
condition = 0;
temp.end = i + j +2;
}
}
i = temp.end;
temp.len = temp.end - temp.start;
temp.avg = temp.len * (temp.start + temp.end) / 2;
memcpy(&sequences[seq_len], &temp, sizeof(struct sequence));
//free(temp);
seq_len++;
} else i++;
}
if(seq_len == 1) return sequences[0].avg;
if(seq_len > 1) {
qsort(sequences, seq_len, sizeof(struct sequence), &compar);
//free(REDlist);
struct sequence seq = sequences[0];
return seq.avg;
} else if(red_len == 0) return -1;
else return REDlist[0];
}
double radians(double deg) {
return deg * M_PI / 180;
}
struct point* calculator(struct ret_png* png, double x, double y, double deg) {
x -= png->width/2;
y = png->height/2 - y;
double r = LASER_DIS / (tan(radians(LASER_DEG)) + (x/F));
double a = x * r / F;
double H = y * r / F + CAM_H;
double R = sqrt(pow((K - r), 2) + pow(a, 2));
double alpha, beta;
if(r == K) {
if(x != 0) {
beta = 90;
} else {
beta = 0;
}
} else {
beta = atan(a / (K - r));
}
if(x >= 0) {
alpha = deg + beta;
}
else {
alpha = deg - beta;
}
struct point* point_car = malloc(sizeof(struct point));
point_car->x = R * cos(alpha);
point_car->y = R * sin(alpha);
point_car->z = H;
//point_car->x = H;
//point_car->y = r;
//point_car->z = a;
return point_car;
}
<file_sep>/python_stuff/measurement.py
import driver
import RPi.GPIO as GPIO
import subprocess as s
import shlex
import sys
import calculateTEMP as cd
GPIO.setwarnings(False)
driver.setup()
GPIO.setup((21, 20, 26), GPIO.OUT)
print("Starting...\n")
GPIO.output(21, 0)
GPIO.output(20, 0)
GPIO.output(26, 0)
print("GPIO set: laser ON")
device = input("device number (0/1/2): ")
laser = input("laser number (21/20/26): ")
if laser == 21:
GPIO.output(21, 0)
GPIO.output(20, 1)
GPIO.output(26, 1)
elif laser == 20:
GPIO.output(21, 1)
GPIO.output(20, 0)
GPIO.output(26, 1)
elif laser == 26:
GPIO.output(21, 1)
GPIO.output(20, 1)
GPIO.output(26, 0)
#zrobienie zdjęcia:
error = 1
while error:
error = 0
cam1 = s.Popen(shlex.split("sudo fswebcam --resolution 1280x1024 --device /dev/video{} \
--no-banner --png --no-title --no-subtitle --no-timestamp --no-info \
--set brightness=128 --set contrast=128 \
./msm.png".format(device)), stdout = s.PIPE, stderr = s.PIPE)#change brightness and contrast
try:
_, error1 = cam1.communicate(timeout = 15)
error1 = error1.decode('utf-8')
if "Writing PNG image to" not in error1:
error = 1
print(error1)
except:
error = 1
GPIO.output(21, 1)
GPIO.output(20, 1)
GPIO.output(26, 1)
print("GPIO set: laser OFF")
print("Picture taken, directory: Whatever/python_stuff/msm.png")
<file_sep>/python_stuff/calculated.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import calculate as c
import time
import os
import multiprocessing as mp
IMAGES_FOLDER = 'images'
output_filename = 'OUTPUT.txt'
progress = 0
step = 4
stepDEGR = 180/(256/step)
mutex = mp.Mutex()
def init():
"""Saves to array 'files' names of all photos in images subdirectory"""
files = []
for file in os.listdir(IMAGES_FOLDER):
if file.endswith('.png'):
files.append(file)
# break # Gets only first file, comment if you want more
return files
def calc_everything(tup):
""""Designed to be run in other tread. Calculates everything"""
global progress
filename = tup[0]
q = tup[1]
filename = filename.rstrip('.png')
_time = time.time()
extracted = c.extract(filename, IMAGES_FOLDER, stepDEGR)
#print('Extract time: ', time.time()-_time, ' File: ', filename)
if extracted is not None:
_time = time.time()
output = []
if filename.startswith('3'):
#pass
for point in extracted:
output.append(c.calculateTOP(point[0], point[1], point[2]))
else:
for point in extracted:
output.append(c.calculate(point[0], point[1], point[2]))
#print('Calculate time: ', time.time()-_time)
q.put(output)
mutex.lock()
progress = progress + 1
print('DONE!!!', filename, "progress: ", progress, '\n')
mutex.unlock()
else:
progress = progress + 1
print("Corrupted PNG file: ", filename, "progress: ", progress, '\n')
def main():
"""Runs init() and manages threads"""
_time = time.time()
files = init()
files.sort()
m = mp.Manager()
q = m.Queue()
tup = list(zip(files, [q] * len(files)))
print('Starting!!!')
_time = time.time()
workers = mp.Pool(processes=8) # Number of process it creates
workers.map(calc_everything, tup)
#print('Allocate time: ', time.time()-_time)
# Wait for first processes witch finish their jobs
# time.sleep(3)
file = open(output_filename, 'w')
i = 0
while i < len(files):
if not q.empty():
out = q.get()
for line in out:
file.write('{} ; {} ; {}\r\n'.format(line[0], line[1], line[2]))
i += 1
file.flush()
file.close()
workers.close()
print('Done Everything! Time:', time.time() - _time)
"""with open('OUTPUT.txt', 'a') as f:
for file in os.listdir('Outputs/'):
with open('Outputs/' + file, 'r') as f2:
f.write(f2.read())"""
if __name__ == '__main__':
main()
| 24713d34b931d12bce107fcb1d53a66436df499e | [
"Markdown",
"C",
"Python"
] | 11 | Python | tajfunek/Whatever | f63561e1867a4089b6515cec301ea84656fcfc44 | 45f8e0c3c6576413c36bb7e2f6e7aca8464a64cf |
refs/heads/main | <repo_name>00009054/WT.CW1.00009054<file_sep>/js/main.js
// Find an element with a class "site-header" by announcing it using var
var elSiteHeader = document.querySelector('.site-header');
// Find an element with a class "menu-btn" by announcing it using var
var elSiteHeaderToggler = elSiteHeader.querySelector('.menu-btn');
//Js listens to the button with "menu-btn" class and when it is clicked it toggles the "site-header--open" class of the site-header
elSiteHeaderToggler.addEventListener('click', function () {
elSiteHeader.classList.toggle('site-header--open');
});<file_sep>/js/add-review.js
function addReview () {
//new li is created in the document file
const newLi = document.createElement('LI')
// the value of the new li is equal to the value of the input with "review" id
newLi.textContent = review.value
//new li is appended to the ul list with "reviewList" id
reviewList.appendChild(newLi)
//initially the value of the input is blank
review.value = ''
//new minus button is created in the document file
const newBtn = document.createElement('BUTTON')
//it is appended to the li element
newLi.appendChild(newBtn)
//when this button is clicked the li element is removed
newBtn.onclick = function () {
newLi.remove()
newBtn.remove()
}
}
//the funcstion runs when an element with "addReview" is clicked
plusButton.onclick = addReview
//the same event happens when enter button on keyboard is clicked
review.onkeyup = function (event) {
if (event.keyCode === 13) {
//13 is the key code of "enter" button on the keyboard
const newLi = document.createElement('LI')
newLi.textContent = review.value
reviewList.appendChild(newLi)
review.value = ''
const newBtn = document.createElement('BUTTON')
newLi.appendChild(newBtn)
newBtn.onclick = function () {
newLi.remove()
newBtn.remove()
}
}
}
| 52073092fff9f25c49408e6df5a11a708a79f975 | [
"JavaScript"
] | 2 | JavaScript | 00009054/WT.CW1.00009054 | bd4c907040615e8187997444114b13e0b6d4f336 | 85fa40bd0fd78e9973dfe7475286a4815d56b609 |
refs/heads/master | <file_sep>import {
DEFAULT_VALUES,
GAME_STATUSES,
keyMoveDict,
moveConfigDict,
MOVE_DIRECTIONS,
} from "./constants"
import { getColumnCount } from "./CellsManager"
import { cellsState, gameStatusState, isLoadingState } from "./store"
import { getNewCells } from "./service"
import { getThirdAxis, logCellsMovement, logNewCells } from "./helpers"
import { pipe } from "./utils"
export const resetGame = (radius, serverUrl) => {
gameStatusState.update(() => GAME_STATUSES.playing)
cellsState.update(() => DEFAULT_VALUES.cells)
addNewCells(radius, [], serverUrl)
}
// TODO: make it with async/await instead of setTimeout
const addNewCells = (radius, cells, serverUrl) => {
setTimeout(() => {
isLoadingState.update(() => true)
getNewCells(radius, cells, serverUrl)
.then((cellsValue) => {
logNewCells(cellsValue)
cellsState.update(() => [...cells, ...cellsValue])
})
.finally(() => {
isLoadingState.update(() => false)
})
}, 150)
}
export const tryMove = (
radius,
isLoading,
gameStatus,
keyCode,
cells,
serverUrl
) => {
const isPlaying = gameStatus === GAME_STATUSES.playing
if (!!radius && !isLoading && isPlaying) {
moveCells(keyMoveDict[keyCode], radius, cells, serverUrl)
}
}
export const updateGameStatus = (radius, cells) => {
if (!radius || !cells) return
if (!isStepAvailable(radius, cells))
gameStatusState.update(() => GAME_STATUSES.game_over)
}
// Move Cells ("step")
const groupCellsByDirectionAxis = (direction, radius, cells) => {
const { axis, directAxis } = moveConfigDict[direction]
return new Array(getColumnCount(radius))
.fill([])
.map((_, index) =>
cells
.filter((cell) => cell[axis] === index - (radius - 1))
.sort((a, b) => b[directAxis] - a[directAxis])
)
}
const tryMergeCells = (cellsGroupedByDirectionAxis) =>
cellsGroupedByDirectionAxis
.reduce(
(acc, cur) =>
acc.length && acc[acc.length - 1].value === cur.value
? [
...acc.slice(0, acc.length - 1),
{ ...acc[acc.length - 1], value: cur.value * 2 },
{ ...cur, value: 0 },
]
: [...acc, cur],
[]
)
.reduce((acc, cur) => (!!cur.value ? [...acc, cur] : acc), [])
const tryShiftCells = (radius, direction) => (cellsGroupedByDirectionAxis) => {
const { axis, directAxis } = moveConfigDict[direction]
return cellsGroupedByDirectionAxis.map((cell, index) => {
const moveAxisValue = cell[axis]
const directAxisValue = radius - 1 - Math.max(moveAxisValue, 0) - index
return {
...cell,
[directAxis]: directAxisValue,
[getThirdAxis(axis, directAxis)]: -(moveAxisValue + directAxisValue),
}
})
}
const moveCells = async (direction, radius, cells, serverUrl) => {
const movedCells = groupCellsByDirectionAxis(direction, radius, cells)
.map((line) => pipe(tryMergeCells, tryShiftCells(radius, direction))(line))
.flat()
const needToRerender = !isCellsArraysEqual(cells, movedCells)
if (!needToRerender) return
cellsState.update(() => movedCells)
logCellsMovement(direction)
addNewCells(radius, movedCells, serverUrl)
}
// Game Status update
const groupCellsByEveryDirectionAxis = (radius, cells) => {
return [
MOVE_DIRECTIONS.top,
MOVE_DIRECTIONS.top_right,
MOVE_DIRECTIONS.top_left,
].map((direction) => groupCellsByDirectionAxis(direction, radius, cells))
}
const checkStepAvailability = (radius, cells) =>
groupCellsByEveryDirectionAxis(radius, cells)
.map((direction) =>
direction
.map((axis) =>
axis.some(
(cell, cellIndex, axisArray) =>
cellIndex && cell.value === axisArray[cellIndex - 1].value
)
)
.some((direcionAvaliableSteps) => direcionAvaliableSteps)
)
.some((direcionsAvaliableSteps) => direcionsAvaliableSteps)
// Game Status (step availability)
const getCellsCount = (radius) => {
const sumFromOneToN = (n) => (n * (n + 1)) / 2
const sumFromNToM = (n, m) => sumFromOneToN(m) - sumFromOneToN(n - 1)
const maxColumnCount = getColumnCount(radius)
return sumFromNToM(radius, maxColumnCount - 1) * 2 + maxColumnCount
}
const isEveryCellFilled = (radius, cells) =>
cells.length === getCellsCount(radius)
const isStepAvailable = (radius, cells) => {
if (!radius || !cells.length) return true
if (!isEveryCellFilled(radius, cells)) return true
return checkStepAvailability(radius, cells)
}
// cells comparing
const stringifyCell = (cell) => `${cell.x};${cell.y};${cell.z};${cell.value}`
const stringifyCellsArray = (cellsArray) => cellsArray.map(stringifyCell)
const isStringifiedCellsArraysEqual = (original, moved) => {
if (original.length !== moved.length) return false
return original.every((cell) => moved.includes(cell))
}
const isCellsArraysEqual = (original, moved) =>
isStringifiedCellsArraysEqual(
stringifyCellsArray(original),
stringifyCellsArray(moved)
)
<file_sep>import { writable } from "svelte/store"
import { DEFAULT_VALUES, SERVER_URLS } from "./constants"
import { getRadiusFromUrl } from "./helpers"
export const radiusState = writable(getRadiusFromUrl())
export const cellsState = writable(DEFAULT_VALUES.cells)
export const isLoadingState = writable(DEFAULT_VALUES.isLoading)
export const gameStatusState = writable(DEFAULT_VALUES.gameStatus)
export const serverUrlState = writable(
!getRadiusFromUrl() ? SERVER_URLS[0] : SERVER_URLS[1]
)
<file_sep>// TODO: Find out better filename. Controller?
import {
dataCellColors,
GAME_AREA_WIDTH,
HEXAGON_ITEM_ASPECT_RATIO,
} from "./constants.js"
// HexagonGrid
export const getColumnCount = (radius) => radius * 2 - 1
const getHexagonItemCount = (columnIndex, radius, columnCount) =>
columnIndex > radius - 1
? columnCount + (radius - 1) - columnIndex
: columnIndex + radius
const getHexagonWidthCountInContainer = (radius) =>
(radius + getColumnCount(radius)) / 2
const getHexagonItemWidth = (radius) =>
GAME_AREA_WIDTH / getHexagonWidthCountInContainer(radius)
const getHexagonItemBorderWidth = (radius) =>
0.25 *
(() =>
({
2: 2.5,
3: 1.25,
4: 0.775,
5: 0.5,
6: 0.35,
7: 0.235,
8: 0.2,
9: 0.159, // TODO: find out correlation and get rid this magic numbers
}[radius] || 0))()
export const getHexagonGridParams = (radius) => {
const columnCount = getColumnCount(radius)
const borderWidth = getHexagonItemBorderWidth(radius)
const rawWidth = getHexagonItemWidth(radius)
const width = rawWidth + borderWidth * columnCount
const rawHeight = rawWidth / HEXAGON_ITEM_ASPECT_RATIO
const height = rawHeight + borderWidth * radius
const leftShift = rawWidth * 0.75 - borderWidth
const getTopShift = (itemIndex, columnIndex) =>
(rawHeight - borderWidth) * itemIndex +
(rawHeight / 2) * Math.abs(columnIndex - (radius - 1))
return {
columnCount,
hexagon: { width, height, leftShift, borderWidth, getTopShift },
}
}
// DataCells
export const getCellColor = (value) => dataCellColors[value] || "#FFF"
const getCellCoords = (radius, columnIndex, itemIndex) => ({
x: columnIndex - (radius - 1),
y:
columnIndex < radius
? radius - 1 - itemIndex
: radius - 1 - (itemIndex + (columnIndex - radius + 1)),
z:
columnIndex < radius
? -(columnIndex - itemIndex)
: -(columnIndex - (itemIndex + (columnIndex - radius + 1))),
})
export const getCellDataAttributes = (
radius,
columnIndex,
itemIndex,
cells = []
) => {
const { x, y, z } = getCellCoords(radius, columnIndex, itemIndex)
const cellData = cells.find(
(cell) => cell.x === x && cell.y === y && cell.z === z
)
const value = cellData ? cellData.value : 0
return {
"data-x": x,
"data-y": y,
"data-z": z,
"data-value": value,
}
}
export const getDataCellsArray = (radius, cells = []) =>
new Array(getColumnCount(radius)).fill(null).map((_, columnIndex, columns) =>
new Array(getHexagonItemCount(columnIndex, radius, columns.length))
.fill(null)
.map((_, itemIndex) => {
const coords = getCellCoords(radius, columnIndex, itemIndex)
const cellData = cells.find(
(cell) =>
cell.x === coords.x && cell.y === coords.y && cell.z === coords.z
)
return cellData && cellData.value
})
)
const getCellValueFontSize = (radius) => Math.max(6.2 - radius, 1)
export const getDataCellsParams = (radius) => {
const fontSize = getCellValueFontSize(radius)
const margin = getHexagonItemBorderWidth(radius) * 3
return { fontSize, margin }
}
<file_sep># Hex2048 - Svelte
Demo: http://hex2048svelte.surge.sh/
Hexagonal 2048 game (task for TypeScript bootcamp by Evolution Gaming)
## Running in development mode
```bash
npm i
npm run dev
```
Navigate to [localhost:5000](http://localhost:5000).
## Building and running in production mode
```bash
npm run build
```
<file_sep>import {
AVALIABLE_RADIUS_VALUES,
GAME_STATUSES,
MOVE_KEYS_LIST,
} from "./constants.js"
export const getRadiusFromUrl = () => {
const url = document.location.href
const urlParts = url.split("/#test")
const radius = urlParts && urlParts[1] && parseInt(urlParts[1])
if (radius && AVALIABLE_RADIUS_VALUES.includes(radius)) return radius
return undefined
}
export const isMoveKey = (keyCode) => MOVE_KEYS_LIST.includes(keyCode)
/**
* @param {string} moveAxis "x", "y" or "z"
* @param {string} directAxis "x", "y" or "z" differ from moveAxis
* @returns "x", "y" or "z" differ from moveAxis and directAxis
*/
export const getThirdAxis = (moveAxis, directAxis) =>
["x", "y", "z"].find((axis) => axis !== moveAxis && axis !== directAxis)
export const isGameAreaVisible = (radius, gameStatus) =>
radius && gameStatus !== GAME_STATUSES.network_unavailable
// log
export const logCellsMovement = (direction) => {
console.log(
`Cells moved in %c${direction}%c direction`,
"color:red; font-weight: bold;",
""
)
}
export const logNewCells = (newCells) => {
console.log(
`%cNew cells: %c${JSON.stringify(newCells)}`,
"color:violet; font-weight: bold;",
""
)
}
<file_sep>export const SERVER_URL =
"//68f02c80-3bed-4e10-a747-4ff774ae905a.pub.instances.scw.cloud"
export const AVALIABLE_RADIUS_VALUES = [2, 3, 4, 5, 6, 7, 8, 9]
export const MOVE_KEYS_LIST = [81, 87, 69, 65, 83, 68] // ["q", "w", "e", "a", "s", "d"]
export const MOVE_DIRECTIONS = {
top: "top",
top_right: "top-right",
top_left: "top-left",
bottom: "bottom",
bottom_right: "bottom-right",
bottom_left: "bottom-left",
}
export const keyMoveDict = {
[MOVE_KEYS_LIST[0]]: MOVE_DIRECTIONS.top_left,
[MOVE_KEYS_LIST[1]]: MOVE_DIRECTIONS.top,
[MOVE_KEYS_LIST[2]]: MOVE_DIRECTIONS.top_right,
[MOVE_KEYS_LIST[3]]: MOVE_DIRECTIONS.bottom_left,
[MOVE_KEYS_LIST[4]]: MOVE_DIRECTIONS.bottom,
[MOVE_KEYS_LIST[5]]: MOVE_DIRECTIONS.bottom_right,
}
export const moveConfigDict = {
[MOVE_DIRECTIONS.top]: { axis: "x", directAxis: "y" },
[MOVE_DIRECTIONS.bottom]: { axis: "x", directAxis: "z" },
[MOVE_DIRECTIONS.top_right]: { axis: "y", directAxis: "x" },
[MOVE_DIRECTIONS.bottom_left]: { axis: "y", directAxis: "z" },
[MOVE_DIRECTIONS.top_left]: { axis: "z", directAxis: "y" },
[MOVE_DIRECTIONS.bottom_right]: { axis: "z", directAxis: "x" },
}
export const SERVER_URLS = [
{
id: "remote",
value: "//68f02c80-3bed-4e10-a747-4ff774ae905a.pub.instances.scw.cloud",
title: "Remote server",
},
{
id: "localhost",
value: "http://localhost:13337",
title: "Local server",
},
]
export const GAME_STATUSES = {
playing: "playing",
game_over: "game-over",
round_select: "round-select",
network_unavailable: "network-unavailable",
}
export const DEFAULT_VALUES = {
cells: [],
isLoading: false,
gameStatus: GAME_STATUSES.round_select,
}
export const colors = {
maximum_blue_purple: "#B2ABF2",
claret: "#89043D",
turquoise: "#2FE6DE",
gunmetal: "#1C3041",
sea_green_crayola: "18F2B2",
}
// all sizes in vim (mininal of vh/vw)
export const GAME_AREA_WIDTH = 60
export const GAME_AREA_HEIGHT = 66.5
export const HEXAGON_ITEM_ASPECT_RATIO = 130 / 114
export const HEXAGON_ITEM_SVG =
"data:image/svg+xml,%3Csvg viewBox='0 0 130 114' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M94.6132 5.70835L124.226 57L94.6132 108.292L35.3867 108.292L5.7735 57L35.3867 5.70834L94.6132 5.70835Z' stroke='black' stroke-width='10'/%3E%3C/svg%3E%0A"
export const dataCellColors = {
2: "rgb(238, 228, 218)",
4: "rgb(237, 224, 200)",
8: "rgb(242, 177, 121)",
16: "rgb(245, 149, 99)",
32: "rgb(246, 124, 95)",
64: "rgb(246, 94, 59)",
128: "rgb(237, 207, 114)",
256: "rgb(237, 204, 97)",
512: "rgb(237, 200, 80)",
1024: "rgb(237, 197, 63)",
2048: "rgb(237, 194, 46)",
4096: "red", // TODO: define more colors
8192: "red",
}
| 63a9d558bba76bd81cc18b00b75ff664bb167f8e | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | torcoste/hex2048-svelte | 54d701e875b033675ed4ab3332da1a1d4bbe9a5c | ea79b4828a4e4137ba7e4890dc7626c05c44abcc |
refs/heads/master | <repo_name>st35/frustration-biological-networks<file_sep>/Noisy_Dynamics_Methods.hpp
double CalculateEnergy(std::vector<int> state, RegNetwork R)
{
double energy = 0.0;
int J_ij, s_i, s_j;
for(int i = 0; i < R.numedges; i++)
{
s_i = state[R.interactions[i][0]];
s_j = state[R.interactions[i][1]];
J_ij = R.interactions[i][2];
if(s_i == 0)
{
s_i = -1;
}
if(s_j == 0)
{
s_j = -1;
}
if(J_ij == 2)
{
J_ij = -1;
}
energy += J_ij*s_i*s_j;
}
return(-energy);
}
void Metropolis(double T, int numsteps, std::vector<int> state, RegNetwork R, std::ofstream *f, std::ofstream *g)
{
if(state.size() != R.numnodes)
{
std::cout << "The initial state is so wrong that you should stand there in your wrongness and be wrong." << "\n";
return;
}
std::vector<int> newstate;
for(int i = 0; i < state.size(); i++)
{
newstate.push_back(state[i]);
}
int nodetoupdate, flag = 0;
double DeltaE;
for(int t = 0; t < numsteps; t++)
{
for(int i = 0; i < R.numnodes; i++)
{
nodetoupdate = (int) (distribution(generator)*R.numnodes);
for(int j = 0; j < R.numnodes; j++)
{
if(j == nodetoupdate)
{
newstate[j] = (int) (!state[j]);
}
else
{
newstate[j] = state[j];
}
}
DeltaE = CalculateEnergy(newstate, R) - CalculateEnergy(state, R);
flag = 0;
if(DeltaE < 0.0)
{
flag = 1;
}
else
{
if(distribution(generator) < std::exp(-DeltaE / T))
{
flag = 1;
}
}
if(flag == 1)
{
state[nodetoupdate] = newstate[nodetoupdate];
}
}
if(t > numsteps / 2 && t % 50 == 0)
{
(*f) << CalculateFrustration(state, R) << " ";
(*g) << Get_Phenotypic_Score(state, R) << " ";
}
}
(*f) << "\n";
(*g) << "\n";
return;
}
std::vector<int> Noisy_Asyn_Dynamics(double eta, int numsteps, std::vector<int> state, RegNetwork R, std::ofstream *f, std::ofstream *g)
{
if(state.size() != R.numnodes)
{
std::cout << "The initial state is so wrong that you should stand there in your wrongness and be wrong." << "\n";
return(std::vector<int>());
}
int errflag = 0;
int nodetoupdate, input;
int source, target, interactiontype;
for(int runcount = 0; runcount < numsteps; runcount++)
{
for(int step = 0; step < R.numnodes; step++)
{
nodetoupdate = (int) (distribution(generator)*R.numnodes);
input = 0;
for(int i = 0; i < R.numedges; i++)
{
source = R.interactions[i][0];
target = R.interactions[i][1];
if(target != nodetoupdate)
{
continue;
}
interactiontype = R.interactions[i][2];
if(interactiontype == 1)
{
if(state[source] == 0)
{
input += (1)*(-1);
}
else if(state[source] == 1)
{
input += (1)*(1);
}
else
{
errflag = 1;
}
}
else if(interactiontype == 2)
{
if(state[source] == 0)
{
input += (-1)*(-1);
}
else if(state[source] == 1)
{
input += (-1)*(1);
}
else
{
errflag = 1;
}
}
else
{
errflag = 1;
}
}
if(errflag == 1)
{
std::cout << "Wicked weird stuff going on here. Take some time and think about what you have done." << "\n";
return(std::vector<int>());
}
if(input > 0)
{
state[nodetoupdate] = 1;
}
else if(input < 0)
{
state[nodetoupdate] = 0;
}
else
{
state[nodetoupdate] = state[nodetoupdate];
}
if(distribution(generator) < eta)
{
state[nodetoupdate] = (int) (!state[nodetoupdate]);
}
}
if(runcount > numsteps / 2 && runcount % 50 == 0)
{
(*f) << CalculateFrustration(state, R) << " ";
(*g) << Get_Phenotypic_Score(state, R) << " ";
}
}
(*f) << "\n";
(*g) << "\n";
return(state);
}
<file_sep>/GRC_calculation.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <algorithm>
#include "Network_Type.hpp"
#include "Process_Topology_Methods.hpp"
#include "BFS.hpp"
void Calculate_GRC(std::string filename, int network_id, int world_rank, std::ofstream *f)
{
RegNetwork R = ReadTopologyFile(filename + "_" + std::to_string(network_id) + ".ids", filename + "_" + std::to_string(network_id) + ".topo", filename + "_" + std::to_string(network_id) + ".phs");
if(!R.isvalid)
{
std::cout << "Network input failed. Your input files disrespected Tuco Salamanca." << "\n";
return;
}
(*f) << GRC(R) << "\n";
return;
}
int main(int argc, char *argv[])
{
int world_rank = 0;
std::string filename = argv[1];
std::ofstream f("outputfiles/GRC.log");
for(int i = 0; i < 750; i++)
{
Calculate_GRC("inputfiles/" + filename, i, world_rank, &f);
}
f.close();
return(0);
}
<file_sep>/Simulate_Population_With_Selection.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <boost/unordered_map.hpp>
#include <mpi.h>
#include "Network_Type.hpp"
#include "Process_Topology_Methods.hpp"
#include "Boolean_Modeling_Methods.hpp"
#include "Mutate_Network.hpp"
#include "Population_Methods.hpp"
void Simulate_Population(std::string filename, int network_id, int world_rank, int numsteps)
{
RegNetwork R = ReadTopologyFile(filename + "_" + std::to_string(network_id) + ".ids", filename + "_" + std::to_string(network_id) + ".topo", filename + "_" + std::to_string(network_id) + ".phs");
if(!R.isvalid)
{
std::cout << "Network input failed. Your input files disrespected Tuco Salamanca." << "\n";
return;
}
std::ofstream f("outputfiles/frustration_output_" + std::to_string(world_rank) + ".log");
if(!static_cast<bool>(f))
{
std::cout << "The output file specified is AWOL. Go figure." << "\n";
return;
}
std::ofstream g("outputfiles/phenotype_output_" + std::to_string(world_rank) + ".log");
if(!static_cast<bool>(g))
{
std::cout << "The output file specified is AWOL. Go figure." << "\n";
return;
}
std::ofstream h("outputfiles/qab_output_" + std::to_string(world_rank) + ".log");
if(!static_cast<bool>(h))
{
std::cout << "The output file specified is AWOL. Go figure." << "\n";
return;
}
std::ofstream meanfile("outputfiles/meanf_output_" + std::to_string(world_rank) + ".log");
if(!static_cast<bool>(meanfile))
{
std::cout << "The output file specified is AWOL. Go figure." << "\n";
return;
}
std::vector<RegNetwork> P = Generate_Random_Network_Population(R, 500);
Simulate_With_Selection(P, 0.05, 1000, 50, &f, &g, &h, &meanfile, world_rank);
f.close();
g.close();
h.close();
meanfile.close();
return;
}
int main(int argc, char *argv[])
{
MPI_Init(NULL, NULL);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int world_rank = 0;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
InitializeRandomNumGen(std::time(NULL) + world_rank);
std::string filename = argv[1];
int network_id = std::stoi(argv[2]);
Simulate_Population("inputfiles/" + filename, network_id, world_rank, 5);
MPI_Finalize();
return(0);
}
<file_sep>/Infer_Networks_From_Data.py
import warnings
warnings.filterwarnings("ignore")
Sample_Names = []
Sample_Type = []
with open('dump/Sample_Description.log', 'r') as f:
count = 0
for line in f:
l = line.strip().split('\t')
l = l[1:]
if count == 0:
for val in l:
Sample_Names.append(val.strip())
count += 1
continue
if count == 1:
for val in l:
Sample_Type.append(val.strip())
count += 1
Normal_Samples = []
for i in range(len(Sample_Names)):
if '"tissue type: Non-tumor"' in Sample_Type[i]:
Normal_Samples.append(Sample_Names[i][1:-1])
import pandas as pd
D = pd.read_csv('dump/Terenuma_Data.log', sep = '\t')
Normal_Data = D[Normal_Samples]
avail_genes = list(D.index)
MYC_genes = []
with open('dump/MYC_genes.log', 'r') as f:
for line in f:
MYC_genes.append(line.strip())
avail_MYC_genes = [gene for gene in MYC_genes if gene in avail_genes]
genes_to_use = set()
TFs = set()
with open('dump/TRRUST_Human_Data.log', 'r') as f:
for line in f:
l = line.strip().split('\t')
source = l[0].strip()
target = l[1].strip()
TFs.add(source)
if target in avail_MYC_genes:
if source in avail_genes:
genes_to_use.add(source)
genes_to_use.add(target)
import numpy as np
from arboreto.algo import grnboost2, genie3
from sklearn.decomposition import PCA
pca = PCA(n_components = 1)
if __name__ == '__main__':
pcafile = open('pc_fraction_explained.log', 'w')
data_to_use = Normal_Data.loc[list(genes_to_use), :].T
pca.fit(data_to_use)
pca_explained = pca.explained_variance_ratio_[0]
pcafile.write(str(pca_explained) + '\n')
TFs_to_use = [gene for gene in genes_to_use if gene in TFs]
network = grnboost2(expression_data = data_to_use, tf_names = list(TFs_to_use))
print(network.head())
network.to_csv('networkfiles/biologicalnetwork.log', sep = '\t', index = False, header = False)
original_data = Normal_Data.loc[list(genes_to_use), :]
for i in range(100):
print(i)
data_to_use = original_data.copy()
for j in range(len(Normal_Samples)):
l = list(original_data.iloc[:, j])
l = list(np.random.permutation(l))
data_to_use[Normal_Samples[j]] = l
print(data_to_use.shape)
data_to_use = data_to_use.T
pca.fit(data_to_use)
pca_explained = pca.explained_variance_ratio_[0]
pcafile.write(str(pca_explained) + '\n')
TFs_to_use = [gene for gene in genes_to_use if gene in TFs]
network = grnboost2(expression_data = data_to_use, tf_names = list(TFs_to_use))
print(network.head())
network.to_csv('networkfiles/networkrandomdata_' + str(i + 1) + '.log', sep = '\t', index = False, header = False)
pcafile.close()
<file_sep>/README.md
# frustration-biological-networks
Code to probe the minimal frustration property of biological regulatory networks.
In the .topo files, Type 1 interactions are activating interactions. Type 2 interactions are inhibitory interactions.
<file_sep>/Process_Network_Inferred_From_Data.py
import sys
Sample_Names = []
Sample_Type = []
with open('dump/Sample_Description.log', 'r') as f:
count = 0
for line in f:
l = line.strip().split('\t')
l = l[1:]
if count == 0:
for val in l:
Sample_Names.append(val.strip())
count += 1
continue
if count == 1:
for val in l:
Sample_Type.append(val.strip())
count += 1
Normal_Samples = []
for i in range(len(Sample_Names)):
if '"tissue type: Non-tumor"' in Sample_Type[i]:
Normal_Samples.append(Sample_Names[i][1:-1])
import pandas as pd
import numpy as np
D = pd.read_csv('dump/Terenuma_Data.log', sep = '\t')
Normal_Data = D[Normal_Samples]
for i in range(1, 101):
Chosen_Pairs = []
with open('networkfiles/networkrandomdata_' + str(i) + '.log', 'r') as f:
count = 0
for line in f:
l = line.strip().split('\t')
Chosen_Pairs.append([])
Chosen_Pairs[count].append(l[0].strip())
Chosen_Pairs[count].append(l[1].strip())
count += 1
if count == 500:
break
Sources = set()
Targets = set()
Genes = set()
Sign = []
for j in range(len(Chosen_Pairs)):
Sources.add(Chosen_Pairs[j][0])
Targets.add(Chosen_Pairs[j][1])
Genes.add(Chosen_Pairs[j][0])
Genes.add(Chosen_Pairs[j][1])
gene1 = list(Normal_Data.loc[Chosen_Pairs[j][0]])
gene2 = list(Normal_Data.loc[Chosen_Pairs[j][1]])
c = np.corrcoef(gene1, gene2)
if c[0, 1] > 0:
Sign.append(1)
elif c[0, 1] < 0:
Sign.append(2)
To_remove = []
for gene in Genes:
if gene not in Sources or gene not in Targets:
To_remove.append(gene)
print(str(len(Chosen_Pairs)) + '\t' + str(len(Sign)))
lineswritten = 0
with open('inputfiles/networkrandomdata' + '_' + str(i) + '.topo', 'w') as f:
f.write('Source\tTarget\tType\n')
for j in range(len(Chosen_Pairs)):
source = Chosen_Pairs[j][0]
target = Chosen_Pairs[j][1]
if source in To_remove or target in To_remove:
continue
f.write(source + '\t' + target + '\t' + str(Sign[j]) + '\n')
lineswritten += 1
IDS = []
with open('inputfiles/networkrandomdata' + '_' + str(i) + '.topo', 'r') as f:
count = 0
for line in f:
if count == 0:
count += 1
continue
l = line.strip().split('\t')
source = l[0].strip()
target = l[1].strip()
if source not in IDS:
IDS.append(source)
if target not in IDS:
IDS.append(target)
with open('inputfiles/networkrandomdata' + '_' + str(i) + '.ids', 'w') as f:
for j in range(len(IDS)):
f.write(IDS[j] + '\t' + str(j) + '\n')
print(len(IDS))
with open('inputfiles/networkrandomdata' + '_' + str(i) + '.phs', 'w') as f:
f.write('0\t1\n')
<file_sep>/Generate_Random_Network_Files.py
import sys
R = []
with open('../networkfiles/' + sys.argv[1] + '.topo', 'r') as f:
count = 0
for line in f:
if count == 0:
count += 1
continue
l = line.strip().split('\t')
R.append([l[0].strip(), l[1].strip(), l[2].strip()])
from math import floor
from math import log
import random
from datetime import datetime
random.seed(datetime.now())
for i in range(750):
print i
R_new = []
for j in range(len(R)):
R_new.append([R[j][0], R[j][1], R[j][2]])
N = int(floor(log(1e7)*len(R_new) / 2))
for j in range(N):
edge1 = int(floor(random.randint(0, len(R_new) - 1)))
edge2 = edge1
while edge2 == edge1:
edge2 = int(floor(random.randint(0, len(R_new) - 1)))
target1 = R_new[edge1][1]
target2 = R_new[edge2][1]
R_new[edge1][1] = target2
R_new[edge2][1] = target1
if i == 0:
with open('inputfiles/' + sys.argv[1] + '_' + str(i) + '.topo', 'w') as f:
f.write('Source\tTarget\tType\n')
for j in range(len(R)):
f.write(R[j][0] + '\t' + R[j][1] + '\t' + R[j][2] + '\n')
else:
with open('inputfiles/' + sys.argv[1] + '_' + str(i) + '.topo', 'w') as f:
f.write('Source\tTarget\tType\n')
for j in range(len(R_new)):
f.write(R_new[j][0] + '\t' + R_new[j][1] + '\t' + R_new[j][2] + '\n')
with open('../networkfiles/' + sys.argv[1] + '.ids', 'r') as f, open('inputfiles/' + sys.argv[1] + '_' + str(i) + '.ids', 'w') as g:
for line in f:
g.write(line.strip() + '\n')
with open('../networkfiles/' + sys.argv[1] + '.phs', 'r') as f, open('inputfiles/' + sys.argv[1] + '_' + str(i) + '.phs', 'w') as g:
for line in f:
g.write(line.strip() + '\n')
<file_sep>/BFS.hpp
#include <queue>
void Print_AL(std::vector<std::vector<int>> G)
{
for(int i = 0; i < G.size(); i++)
{
std::cout << i << "-->";
for(int j = 0; j < G[i].size(); j++)
{
std::cout << G[i][j] << " ";
}
std::cout << "\n";
}
}
std::vector<std::vector<int>> Topology_To_AL(RegNetwork R)
{
std::vector<std::vector<int>> G;
int source, target;
for(int i = 0; i < R.numnodes; i++)
{
G.push_back(std::vector<int>());
}
for(int i = 0; i < R.numedges; i++)
{
source = R.interactions[i][0];
target = R.interactions[i][1];
G[source].push_back(target);
}
return(G);
}
std::vector<int> BFS(std::vector<std::vector<int>> G, int source)
{
int u, v;
std::vector<int> color, d, pi;
for(int i = 0; i < G.size(); i++)
{
color.push_back(0);
d.push_back(INFINITY);
pi.push_back(-1);
}
color[source] = 1;
d[source] = 0;
pi[source] = -1;
std::queue<int> Q;
Q.push(source);
while(Q.size() > 0)
{
u = Q.front();
Q.pop();
for(int i = 0; i < G[u].size(); i++)
{
v = G[u][i];
if(color[v] == 0)
{
color[v] = 1;
d[v] = d[u] + 1;
pi[v] = u;
Q.push(v);
}
}
color[u] = 2;
}
return(color);
}
double GRC(RegNetwork R)
{
std::vector<std::vector<int>> G = Topology_To_AL(R);
std::vector<int> color;
std::vector<double> LRC;
for(int i = 0; i < R.numnodes; i++)
{
color = BFS(G, i);
LRC.push_back(0.0);
for(int j = 0; j < color.size(); j++)
{
if(color[j] > 0 && j != i)
{
LRC[i] += 1.0;
}
}
LRC[i] = LRC[i] / ((double) (R.numnodes - 1));
}
double max_LRC = -1.0;
for(int i = 0; i < LRC.size(); i++)
{
if(LRC[i] > max_LRC)
{
max_LRC = LRC[i];
}
}
double GRC = 0.0;
for(int i = 0; i < LRC.size(); i++)
{
GRC += max_LRC - LRC[i];
}
GRC = GRC / ((double) R.numnodes - 1);
return(GRC);
}<file_sep>/Simulate_Noisy_Dynamics_Metropolis.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <boost/unordered_map.hpp>
#include <mpi.h>
#include "Network_Type.hpp"
#include "Process_Topology_Methods.hpp"
#include "Boolean_Modeling_Methods.hpp"
#include "Noisy_Dynamics_Methods.hpp"
void Sample_States(double T, int Tid, std::string filename, int network_id, int world_rank, int numsteps)
{
RegNetwork R = ReadTopologyFile(filename + "_" + std::to_string(network_id) + ".ids", filename + "_" + std::to_string(network_id) + ".topo", filename + "_" + std::to_string(network_id) + ".phs");
if(!R.isvalid)
{
std::cout << "Network input failed. Your input files disrespected Tuco Salamanca." << "\n";
return;
}
std::vector<int> state;
std::ofstream f("outputfiles/RUN" + std::to_string(Tid) + "/frustration_output_" + std::to_string(world_rank) + ".log");
if(!static_cast<bool>(f))
{
std::cout << "The output file specified is AWOL. Go figure." << "\n";
return;
}
std::ofstream g("outputfiles/RUN" + std::to_string(Tid) + "/phenotype_output_" + std::to_string(world_rank) + ".log");
if(!static_cast<bool>(g))
{
std::cout << "The output file specified is AWOL. Go figure." << "\n";
return;
}
for(int i = 0; i < numsteps; i++)
{
state = GetRandomState(R.numnodes);
Metropolis(T, 5000, state, R, &f, &g);
}
f.close();
g.close();
return;
}
int main(int argc, char *argv[])
{
MPI_Init(NULL, NULL);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int world_rank = 0;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
InitializeRandomNumGen(std::time(NULL) + world_rank);
std::string filename = argv[1];
int network_id = std::stoi(argv[2]);
double T = std::stod(argv[3]);
int Tid = std::stoi(argv[4]);
Sample_States(T, Tid, "inputfiles/" + filename, network_id, world_rank, 500);
MPI_Finalize();
return(0);
}
<file_sep>/Population_Methods.hpp
std::vector<RegNetwork> Generate_Same_Network_Population(RegNetwork R, int popusize)
{
std::vector<RegNetwork> P;
for(int i = 0; i < popusize; i++)
{
P.push_back(R);
}
return(P);
}
std::vector<RegNetwork> Generate_Random_Network_Population(RegNetwork R, int popusize)
{
std::vector<RegNetwork> P;
for(int i = 0; i < popusize; i++)
{
P.push_back(R);
for(int j = 0; j < (int) ((std::log(1e7)*R.numedges) / 2.0); j++)
{
Mutate_Network(&P[i]);
}
}
return(P);
}
void Simulate_No_Selection(std::vector<RegNetwork> P, int num_generations, int num_steps, std::ofstream *f, std::ofstream *g, std::ofstream *h, std::ofstream *meanfile, int world_rank)
{
std::ofstream networkfile;
std::vector<RegNetwork> New_P;
std::vector<std::vector<int>> F, score, states_list;
for(int i = 0; i < P.size(); i++)
{
F.push_back(std::vector<int>());
score.push_back(std::vector<int>());
for(int j = 0; j < num_steps; j++)
{
F[i].push_back(0);
score[i].push_back(0);
}
}
std::vector<int> state;
double meanf = 0.0;
for(int numgen = 0; numgen < num_generations; numgen++)
{
meanf = 0.0;
for(int i = 0; i < P.size(); i++)
{
states_list.clear();
for(int j = 0; j < num_steps; j++)
{
state = GetRandomState(P[i].numnodes);
state = TrajectoryAsynUpdate(5000, state, P[i]);
F[i][j] = CalculateFrustration(state, P[i]);
score[i][j] = Get_Phenotypic_Score(state, P[i]);
states_list.push_back(state);
if(numgen % 50 == 0)
{
(*f) << F[i][j] << " ";
(*g) << score[i][j] << " ";
}
meanf += F[i][j];
}
if(numgen % 50 == 0)
{
for(int j = 0; j < num_steps; j++)
{
for(int k = j + 1; k < num_steps; k++)
{
(*h) << StateOverlap(states_list[j], states_list[k], P[i]) << " ";
}
}
}
}
(*meanfile) << meanf / ((double) (P.size()*num_steps)) << "\n";
if(numgen % 50 == 0)
{
(*f) << "\n";
(*g) << "\n";
(*h) << "\n";
for(int netindex = 0; netindex < P.size(); netindex++)
{
networkfile.open("outputfiles/network_files" + std::to_string(world_rank) + "/network_" + std::to_string(numgen) + "_" + std::to_string(netindex) + ".topo");
Print_Network(P[netindex], &networkfile);
networkfile.close();
}
}
New_P.clear();
for(int i = 0; i < P.size(); i++)
{
New_P.push_back(P[i]);
}
for(int i = 0; i < P.size(); i++)
{
P[i] = New_P[(int) (distribution(generator)*New_P.size())];
if(distribution(generator) < 0.05)
{
Mutate_Network(&P[i]);
}
}
}
return;
}
std::vector<int> Get_Networks_Order(std::vector<std::vector<int>> F)
{
std::vector<int> index;
for(int i = 0; i < F.size(); i++)
{
index.push_back(i);
}
std::vector<double> quantity;
for(int i = 0; i < F.size(); i++)
{
quantity.push_back((double) F[i][std::min_element(F[i].begin(), F[i].end()) - F[i].begin()]);
}
std::sort(index.begin(), index.end(), [&quantity] (size_t i1, size_t i2) {return quantity[i1] < quantity[i2];});
return(index);
}
void Simulate_With_Selection(std::vector<RegNetwork> P, double selection_frac, int num_generations, int num_steps, std::ofstream *f, std::ofstream *g, std::ofstream *h, std::ofstream *meanfile, int world_rank)
{
std::ofstream networkfile;
std::vector<RegNetwork> New_P;
std::vector<std::vector<int>> F, score, states_list;
for(int i = 0; i < P.size(); i++)
{
F.push_back(std::vector<int>());
score.push_back(std::vector<int>());
for(int j = 0; j < num_steps; j++)
{
F[i].push_back(0);
score[i].push_back(0);
}
}
std::vector<int> state, index;
double meanf = 0.0;
for(int numgen = 0; numgen < num_generations; numgen++)
{
for(int i = 0; i < P.size(); i++)
{
states_list.clear();
for(int j = 0; j < num_steps; j++)
{
state = GetRandomState(P[i].numnodes);
state = TrajectoryAsynUpdate(5000, state, P[i]);
F[i][j] = CalculateFrustration(state, P[i]);
score[i][j] = Get_Phenotypic_Score(state, P[i]);
states_list.push_back(state);
if(numgen % 50 == 0)
{
(*f) << F[i][j] << " ";
(*g) << score[i][j] << " ";
}
meanf += F[i][j];
}
if(numgen % 50 == 0)
{
for(int j = 0; j < num_steps; j++)
{
for(int k = j + 1; k < num_steps; k++)
{
(*h) << StateOverlap(states_list[j], states_list[k], P[i]) << " ";
}
}
}
}
(*meanfile) << meanf / ((double) P.size()*num_steps) << "\n";
if(numgen % 50 == 0)
{
(*f) << "\n";
(*g) << "\n";
(*h) << "\n";
for(int netindex = 0; netindex < P.size(); netindex++)
{
networkfile.open("outputfiles/network_files" + std::to_string(world_rank) + "/network_" + std::to_string(numgen) + "_" + std::to_string(netindex) + ".topo");
Print_Network(P[netindex], &networkfile);
networkfile.close();
}
}
New_P.clear();
index = Get_Networks_Order(F);
for(int i = 0; i < (int) (selection_frac*P.size()); i++)
{
New_P.push_back(P[index[i]]);
}
for(int i = 0; i < P.size(); i++)
{
P[i] = New_P[(int) (distribution(generator)*New_P.size())];
if(distribution(generator) < 0.05)
{
Mutate_Network(&P[i]);
}
}
}
return;
}
<file_sep>/Stable_States_Large_Networks.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <boost/unordered_map.hpp>
#include <mpi.h>
#include "Network_Type.hpp"
#include "Process_Topology_Methods.hpp"
#include "Boolean_Modeling_Methods.hpp"
std::string State_To_String(std::vector<int> state)
{
std::string s = "";
for(int i = 0; i < state.size(); i++)
{
s = s + std::to_string(state[i]);
}
return(s);
}
void Get_Stable_States(std::string filename, int network_id, int world_rank)
{
RegNetwork R = ReadTopologyFile(filename + "_" + std::to_string(network_id) + ".ids", filename + "_" + std::to_string(network_id) + ".topo", filename + "_" + std::to_string(network_id) + ".phs");
if(!R.isvalid)
{
std::cout << "Network input failed. Your input files disrespected Tuco Salamanca." << "\n";
return;
}
long firststate, laststate, singlerunsize;
int degenerate_flag = 0;
singlerunsize = ((long) std::pow(2, 20)) / (16*16);
if(singlerunsize == 0)
{
degenerate_flag = 1;
singlerunsize = (long) std::pow(2, R.numnodes) - 1;
}
std::vector<int> state;
boost::unordered_map<std::string, long> SS_Dec;
boost::unordered_map<std::string, int> SS_F, SS_score;
for(int i = 0; i < 16; i++)
{
firststate = 16*world_rank*singlerunsize + i*singlerunsize;
laststate = 16*world_rank*singlerunsize + i*singlerunsize + singlerunsize - 1;
for(long j = firststate; j <= laststate; j++)
{
if(j > singlerunsize && degenerate_flag == 1)
{
break;
}
state = GetRandomState(R.numnodes);
state = TrajectoryAsynUpdate(R.numnodes*R.numnodes, state, R);
if(IsStableState(state, R))
{
if(SS_Dec.find(State_To_String(state)) == SS_Dec.end())
{
SS_Dec[State_To_String(state)] = 1;
SS_F[State_To_String(state)] = CalculateFrustration(state, R);
SS_score[State_To_String(state)] = Get_Phenotypic_Score(state, R);
}
else
{
SS_Dec[State_To_String(state)] += 1;
}
}
}
}
std::ofstream f("outputfiles/RUN" + std::to_string(network_id) + "/output_" + std::to_string(world_rank) + ".log");
if(!static_cast<bool>(f))
{
std::cout << "The output file specified is AWOL. Go figure." << "\n";
return;
}
for(auto p: SS_Dec)
{
f << p.second << " " << SS_F[p.first] << " " << SS_score[p.first] << " ";
for(int j = 0; j < p.first.length(); j++)
{
f << p.first[j] << " ";
}
f << "\n";
}
f.close();
return;
}
int main(int argc, char *argv[])
{
MPI_Init(NULL, NULL);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int world_rank = 0;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
InitializeRandomNumGen(std::time(NULL) + world_rank);
std::string filename = argv[1];
int network_id = std::stoi(argv[2]);
Get_Stable_States("inputfiles/" + filename, network_id, world_rank);
MPI_Finalize();
return(0);
}
<file_sep>/Process_Topology_Methods.hpp
RegNetwork ReadTopologyFile(std::string filename1, std::string filename2, std::string filename3)
{
RegNetwork R;
R.numnodes = 0;
R.numedges = 0;
R.nodeIDs = std::vector<std::string>();
R.interactions = std::vector<std::vector<int>>();
R.phenotype_pos = std::vector<int>();
R.phenotype_neg = std::vector<int>();
std::string nodeName;
int nodeID, numlines;
std::ifstream f(filename1);
if(!static_cast<bool>(f))
{
std::cout << "Error reading the .ids file." << "\n";
return(R);
}
while(f >> nodeName >> nodeID)
{
R.nodeIDs.push_back(nodeName);
R.numnodes += 1;
}
f.close();
f.open(filename1);
numlines = 0;
while(getline(f, nodeName))
{
numlines += 1;
}
f.close();
if(numlines != R.nodeIDs.size())
{
std::cout << "The format of the .ids file is ridonc, and frankly, completely wrong." << "\n";
return(R);
}
std::string source, target;
int sourceID, targetID, interactionType;
f.open(filename2);
if(!static_cast<bool>(f))
{
std::cout << "Error reading the .topo file." << "\n";
return(R);
}
getline(f, source);
while(f >> source >> target >> interactionType)
{
if(std::find(R.nodeIDs.begin(), R.nodeIDs.end(), source) == R.nodeIDs.end())
{
std::cout << "One of the network nodes is missing from the .ids file." << "\n";
return(R);
}
if(std::find(R.nodeIDs.begin(), R.nodeIDs.end(), target) == R.nodeIDs.end())
{
std::cout << "One of the network nodes is missing from the .ids file." << "\n";
return(R);
}
sourceID = std::find(R.nodeIDs.begin(), R.nodeIDs.end(), source) - R.nodeIDs.begin();
targetID = std::find(R.nodeIDs.begin(), R.nodeIDs.end(), target) - R.nodeIDs.begin();
R.interactions.push_back({0, 0, 0});
R.interactions[R.numedges][0] = sourceID;
R.interactions[R.numedges][1] = targetID;
R.interactions[R.numedges][2] = interactionType;
R.numedges += 1;
}
f.close();
f.open(filename2);
numlines = 0;
while(getline(f, source))
{
numlines += 1;
}
f.close();
if(numlines - 1 != R.interactions.size())
{
std::cout << "The format of the .topo file is ridonc, and frankly, completely wrong." << "\n";
return(R);
}
int nodeid_pos, nodeid_neg;
f.open(filename3);
if(!static_cast<bool>(f))
{
std::cout << "Phenotype file could not be read for this network. Moving on." << "\n";
}
else
{
while(f >> nodeid_pos >> nodeid_neg)
{
R.phenotype_pos.push_back(nodeid_pos);
R.phenotype_neg.push_back(nodeid_neg);
}
}
f.close();
if(R.numnodes == R.nodeIDs.size() && R.numedges == R.interactions.size())
{
R.isvalid = true;
}
return(R);
}
void Print_Network(RegNetwork R, std::ofstream *f)
{
(*f) << "Source\tTarget\tType\n";
for(int i = 0; i < R.interactions.size(); i++)
{
(*f) << R.nodeIDs[R.interactions[i][0]] << "\t";
(*f) << R.nodeIDs[R.interactions[i][1]] << "\t";
(*f) << R.interactions[i][2] << "\n";
}
return;
}<file_sep>/Network_Type.hpp
class RegNetwork
{
public:
bool isvalid = false;
int numnodes = 0, numedges = 0;
std::vector<std::string> nodeIDs;
std::vector<std::vector<int>> interactions;
std::vector<int> phenotype_pos, phenotype_neg;
};<file_sep>/Boolean_Modeling_Methods.hpp
#include <random>
std::mt19937 generator;
std::uniform_real_distribution<> distribution{0.0, 1.0};
void InitializeRandomNumGen(long seed)
{
generator = std::mt19937(seed);
}
long BinaryToDecimal(std::vector<int> state)
{
long dec_state = 0;
for(int i = 0; i < state.size(); i++)
{
dec_state += state[i]*((long) std::pow(2, state.size() - i - 1));
}
return(dec_state);
}
std::vector<int> GetRandomState(int numnodes)
{
std::vector<int> state;
for(int i = 0; i < numnodes; i++)
{
if(distribution(generator) < 0.5)
{
state.push_back(0);
}
else
{
state.push_back(1);
}
}
return(state);
}
std::vector<int> DecimalToBinary(long DecimalState, int numnodes)
{
std::vector<int> state;
if(DecimalState == 0)
{
state.push_back(0);
}
else
{
while(DecimalState != 0)
{
state.push_back(DecimalState % 2);
DecimalState = DecimalState / 2;
}
}
if(state.size() > numnodes)
{
std::cout << "Mistakes have been made in converting to binary for this network. Basically, you suck." << "\n";
return(std::vector<int>());
}
while(state.size() < numnodes)
{
state.push_back(0);
}
std::reverse(state.begin(), state.end());
return(state);
}
int CalculateFrustration(std::vector<int> state, RegNetwork R)
{
if(state.size() != R.numnodes)
{
std::cout << "Invalid network state. Stand there in your wrongness and be wrong and get used to it." << "\n";
return(-1);
}
int F = 0;
int source, target, interactiontype, fedge;
int s_i, s_j, J_ij;
for(int i = 0; i < R.numedges; i++)
{
source = R.interactions[i][0];
target = R.interactions[i][1];
interactiontype = R.interactions[i][2];
s_i = state[source];
s_j = state[target];
J_ij = interactiontype;
if(s_i == 0)
{
s_i = -1;
}
if(s_j == 0)
{
s_j = -1;
}
if(J_ij == 2)
{
J_ij = -1;
}
fedge = s_i*s_j*J_ij;
if(fedge < 0)
{
F += 1;
}
}
return(F);
}
std::vector<int> TrajectoryAsynUpdate(int numsteps, std::vector<int> state, RegNetwork R)
{
if(state.size() != R.numnodes)
{
std::cout << "Invalid network state. Run fast. Run far." << "\n";
return(std::vector<int>());
}
int errflag = 0;
int nodetoupdate, input;
std::vector<int> nextstate;
for(int i = 0; i < state.size(); i++)
{
nextstate.push_back(state[i]);
}
int source, target, interactiontype;
for(int step = 0; step < numsteps; step++)
{
nodetoupdate = (int) (distribution(generator)*R.numnodes);
input = 0;
for(int i = 0; i < R.numedges; i++)
{
source = R.interactions[i][0];
target = R.interactions[i][1];
if(target != nodetoupdate)
{
continue;
}
interactiontype = R.interactions[i][2];
if(interactiontype == 1)
{
if(nextstate[source] == 0)
{
input += (1)*(-1);
}
else if(nextstate[source] == 1)
{
input += (1)*(1);
}
else
{
errflag = 1;
}
}
else if(interactiontype == 2)
{
if(nextstate[source] == 0)
{
input += (-1)*(-1);
}
else if(nextstate[source] == 1)
{
input += (-1)*(1);
}
else
{
errflag = 1;
}
}
else
{
errflag = 1;
}
}
if(errflag == 1)
{
std::cout << "Wicked weird stuff going on here. Take some time and think about what you have done." << "\n";
return(std::vector<int>());
}
if(input > 0)
{
nextstate[nodetoupdate] = 1;
}
else if(input < 0)
{
nextstate[nodetoupdate] = 0;
}
else
{
nextstate[nodetoupdate] = nextstate[nodetoupdate];
}
}
return(nextstate);
}
double StateOverlap(std::vector<int> state1, std::vector<int> state2, RegNetwork R)
{
if(state1.size() != R.numnodes || state2.size() != R.numnodes)
{
std::cout << "Invalid network state. This calculation will now come to a sudden arboreal stop." << "\n";
return(-INFINITY);
}
double Q = 0.0;
int s_a, s_b;
for(int i = 0; i < state1.size(); i++)
{
s_a = state1[i];
s_b = state2[i];
if(s_a == 0)
{
s_a = -1;
}
if(s_b == 0)
{
s_b = -1;
}
Q += s_a*s_b;
}
Q = Q / (double) state1.size();
return(Q);
}
std::vector<int> NextStateSynUpdate(std::vector<int> state, RegNetwork R)
{
if(state.size() != R.numnodes)
{
std::cout << "Invalid network state. Run fast. Run far." << "\n";
return(std::vector<int>());
}
int errflag = 0;
std::vector<int> nextstate, input;
for(int i = 0; i < state.size(); i++)
{
nextstate.push_back(state[i]);
input.push_back(0);
}
int source, target, interactiontype;
for(int i = 0; i < R.numedges; i++)
{
source = R.interactions[i][0];
target = R.interactions[i][1];
interactiontype = R.interactions[i][2];
if(interactiontype == 1)
{
if(state[source] == 0)
{
input[target] += (1)*(-1);
}
else if(state[source] == 1)
{
input[target] += (1)*(1);
}
else
{
errflag = 1;
}
}
else if(interactiontype == 2)
{
if(state[source] == 0)
{
input[target] += (-1)*(-1);
}
else if(state[source] == 1)
{
input[target] += (-1)*(1);
}
else
{
errflag = 1;
}
}
else
{
errflag = 1;
}
}
for(int i = 0; i < R.numnodes; i++)
{
if(input[i] > 0)
{
nextstate[i] = 1;
}
else if(input[i] < 0)
{
nextstate[i] = 0;
}
else
{
nextstate[i] = state[i];
}
}
if(errflag == 1)
{
std::cout << "Wicked weird stuff going on here. Take some time and think about what you have done." << "\n";
return(std::vector<int>());
}
return(nextstate);
}
bool IsStableState(std::vector<int> state, RegNetwork R)
{
std::vector<int> nextstate = NextStateSynUpdate(state, R);
if(nextstate.size() == 0)
{
return(false);
}
for(int i = 0; i < state.size(); i++)
{
if(nextstate[i] != state[i])
{
return(false);
}
}
return(true);
}
int Get_Phenotypic_Score(std::vector<int> state, RegNetwork R)
{
if(R.phenotype_pos.size() == 0 || R.phenotype_neg.size() == 0)
{
std::cout << "I pity the fool who tries to calculate a phenotypic score for this network. I do. I do." << "\n";
return(-50);
}
if(R.phenotype_pos.size() != R.phenotype_neg.size())
{
std::cout << "Something is seriosuly broken over here. Go back to genesis, or to the part where the network files were read." << "\n";
return(-50);
}
int score = 0;
for(int i = 0; i < R.phenotype_pos.size(); i++)
{
if(state[R.phenotype_pos[i]] == 1)
{
score += 1;
}
else if(state[R.phenotype_pos[i]] == 0)
{
score -= 1;
}
if(state[R.phenotype_neg[i]] == 1)
{
score -= 1;
}
else if(state[R.phenotype_neg[i]] == 0)
{
score += 1;
}
}
return(score);
}
<file_sep>/Mutate_Network.hpp
void Mutate_Network(RegNetwork *R)
{
int edge1 = (int) ((R->numedges)*(distribution(generator)));
int edge2 = (int) ((R->numedges)*(distribution(generator)));
while(edge2 == edge1)
{
edge2 = (int) ((R->numedges)*(distribution(generator)));
}
int target1 = R->interactions[edge1][1];
int target2 = R->interactions[edge2][1];
R->interactions[edge1][1] = target2;
R->interactions[edge2][1] = target1;
return;
}
| c960f53473d3644dadc31686825bd4853d246cb7 | [
"Markdown",
"Python",
"C++"
] | 15 | C++ | st35/frustration-biological-networks | 28d88c3e4c03fca343217f2c2a30dc5aa3488e16 | 1c96ca428c0dd6aca23784aef9adb122320d03bd |
refs/heads/main | <repo_name>Petervrancken/fsd_transport_be<file_sep>/src/Entity/Vervoersmiddel.php
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\VervoersmiddelRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
/**
* @ApiResource(
* collectionOperations={"get","post"},
* itemOperations={
* "get"={
* "normalization_context"={"groups"={"vervoersmiddel:read", "vervoersmiddel:item:get"}}
* },
* "put"
* },
* normalizationContext={"groups"={"vervoersmiddel:read"}},
* denormalizationContext={"groups"={"vervoersmiddel:write"}},
* )
* @ORM\Entity(repositoryClass=VervoersmiddelRepository::class)
* @ApiFilter(SearchFilter::class, properties={"user.id": "exact"})
*/
class Vervoersmiddel
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
* @Groups({"vervoersmiddel:read"})
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @Groups({"vervoersmiddel:read", "vervoersmiddel:write", "verplaatsing:read"})
*/
private $naam;
/**
* @ORM\OneToMany(targetEntity=Verplaatsing::class, mappedBy="vervoersmiddel")
*/
private $verplaatsingen;
/**
* @ORM\OneToMany(targetEntity=Tarief::class, mappedBy="vervoersmiddel", cascade={"persist"} )
* @Groups ({"verplaatsing:read","vervoersmiddel:write", "vervoersmiddel:read"})
*/
private $tarieven;
/**
* @ORM\ManyToOne(targetEntity=User::class, inversedBy="vervoersmiddelen")
* @ORM\JoinColumn(nullable=false)
* @Groups({"vervoersmiddel:write", "vervoersmiddel:read"})
* @Assert\Valid()
*/
private $user;
/**
* @ORM\ManyToOne(targetEntity=Categorie::class, inversedBy="vervoersmiddelen")
* @ORM\JoinColumn(nullable=false)
* @Groups({"vervoersmiddel:write"})
*/
private $categorie;
public function __construct()
{
$this->verplaatsingen = new ArrayCollection();
$this->tarieven = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getNaam(): ?string
{
return $this->naam;
}
public function setNaam(string $naam): self
{
$this->naam = $naam;
return $this;
}
/**
* @return Collection|Verplaatsing[]
*/
public function getVerplaatsingen(): Collection
{
return $this->verplaatsingen;
}
public function addVerplaatsingen(Verplaatsing $verplaatsingen): self
{
if (!$this->verplaatsingen->contains($verplaatsingen)) {
$this->verplaatsingen[] = $verplaatsingen;
$verplaatsingen->setVervoersmiddel($this);
}
return $this;
}
public function removeVerplaatsingen(Verplaatsing $verplaatsingen): self
{
if ($this->verplaatsingen->removeElement($verplaatsingen)) {
// set the owning side to null (unless already changed)
if ($verplaatsingen->getVervoersmiddel() === $this) {
$verplaatsingen->setVervoersmiddel(null);
}
}
return $this;
}
/**
* @return Collection|Tarief[]
*/
public function getTarieven(): Collection
{
return $this->tarieven;
}
public function addTarieven(Tarief $tarieven): self
{
if (!$this->tarieven->contains($tarieven)) {
$this->tarieven[] = $tarieven;
$tarieven->setVervoersmiddel($this);
}
return $this;
}
public function removeTarieven(Tarief $tarieven): self
{
if ($this->tarieven->removeElement($tarieven)) {
// set the owning side to null (unless already changed)
if ($tarieven->getVervoersmiddel() === $this) {
$tarieven->setVervoersmiddel(null);
}
}
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getCategorie(): ?Categorie
{
return $this->categorie;
}
public function setCategorie(?Categorie $categorie): self
{
$this->categorie = $categorie;
return $this;
}
}
<file_sep>/src/Entity/User.php
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass=UserRepository::class)
* @ApiResource(
* normalizationContext={"groups"={"user:read"}},
* denormalizationContext={"groups"={"user:write"}}
* )
* @UniqueEntity(fields={"email"})
*/
// userinterface iets met wachtwoorden kan geimplementeerd worden
class User implements UserInterface
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
* @Groups({"vervoersmiddel:read"})
*/
private $id;
/**
* @ORM\Column(type="string", length=180, unique=true)
* @Groups({"user:read", "user:write"})
* @Assert\NotBlank(
* message="Verplicht in te vullen"
* )
* @Assert\Email(
* message="Geen geldig e-mail adres"
* )
*/
private $email;
/*
/**
* @ORM\Column(type="json")
*
*
private $roles = [];
*/
/**
* @var string The hashed password
* @ORM\Column(type="string")
* @Groups({"user:write"})
* @Assert\Length(
* min=7,
*
* minMessage="Wachtwoord moet minstens 6 tekens bevatten",
*
* )
*/
private $password;
/**
* @ORM\Column(type="string", length=255)
* @Groups({"user:read", "user:write", "verplaatsing:read"})
* @Assert\NotBlank(
* message="Veld verplicht invulLen"
* )
*/
private $naam;
/**
* @ORM\Column(type="string", length=255)
* @Groups({"user:read", "user:write", "verplaatsing:read"})
* @Assert\NotBlank(
* message="Veld verplicht invullen"
* )
*/
private $voornaam;
/**
* @ORM\Column(type="string", length=255, nullable=true)
* @Groups({"user:read", "user:write"})
*/
private $photo;
/**
* @ORM\Column(type="smallint")
* @Groups({"user:read"})
* @Assert\NotBlank()
*/
private $admin = 2;
/**
* @ORM\OneToMany(targetEntity=Verplaatsing::class, mappedBy="user")
* @Assert\NotBlank(
* message="Veld verplicht invullen"
* )
*/
private $verplaatsingen;
/**
* @ORM\OneToMany(targetEntity=Vervoersmiddel::class, mappedBy="user")
* @Assert\NotBlank(
* message="Voer voertuig in"
* )
*/
private $vervoersmiddelen;
/**
* @ORM\Column(type="string", length=255, nullable=true)
* @Groups({"user:read", "user:write"})
* @Assert\NotBlank (
* message="Verplicht in te vullen"
* )
*/
private $Functie;
public function __construct()
{
$this->verplaatsingen = new ArrayCollection();
$this->vervoersmiddelen = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
/*
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);*/
return [];
}
public function setRoles(array $roles): self
{
/*
$this->roles = $roles;
return $this;*/
}
/**
* @see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* Returning a salt is only needed, if you are not using a modern
* hashing algorithm (e.g. bcrypt or sodium) in your security.yaml.
*
* @see UserInterface
*/
public function getSalt(): ?string
{
return null;
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = <PASSWORD>;
}
public function getNaam(): ?string
{
return $this->naam;
}
public function setNaam(string $naam): self
{
$this->naam = $naam;
return $this;
}
public function getVoornaam(): ?string
{
return $this->voornaam;
}
public function setVoornaam(string $voornaam): self
{
$this->voornaam = $voornaam;
return $this;
}
public function getPhoto(): ?string
{
return $this->photo;
}
public function setPhoto(?string $photo): self
{
$this->photo = $photo;
return $this;
}
public function getAdmin(): ?int
{
return $this->admin;
}
public function setAdmin(int $admin): self
{
$this->admin = $admin;
return $this;
}
/**
* @return Collection|Verplaatsing[]
*/
public function getVerplaatsingen(): Collection
{
return $this->verplaatsingen;
}
public function addVerplaatsingen(Verplaatsing $verplaatsingen): self
{
if (!$this->verplaatsingen->contains($verplaatsingen)) {
$this->verplaatsingen[] = $verplaatsingen;
$verplaatsingen->setUser($this);
}
return $this;
}
public function removeVerplaatsingen(Verplaatsing $verplaatsingen): self
{
if ($this->verplaatsingen->removeElement($verplaatsingen)) {
// set the owning side to null (unless already changed)
if ($verplaatsingen->getUser() === $this) {
$verplaatsingen->setUser(null);
}
}
return $this;
}
/**
* @return Collection|Vervoersmiddel[]
*/
public function getVervoersmiddelen(): Collection
{
return $this->vervoersmiddelen;
}
public function addVervoersmiddelen(Vervoersmiddel $vervoersmiddelen): self
{
if (!$this->vervoersmiddelen->contains($vervoersmiddelen)) {
$this->vervoersmiddelen[] = $vervoersmiddelen;
$vervoersmiddelen->setUser($this);
}
return $this;
}
public function removeVervoersmiddelen(Vervoersmiddel $vervoersmiddelen): self
{
if ($this->vervoersmiddelen->removeElement($vervoersmiddelen)) {
// set the owning side to null (unless already changed)
if ($vervoersmiddelen->getUser() === $this) {
$vervoersmiddelen->setUser(null);
}
}
return $this;
}
public function getFunctie(): ?string
{
return $this->Functie;
}
public function setFunctie(?string $Functie): self
{
$this->Functie = $Functie;
return $this;
}
}
<file_sep>/src/Entity/Tarief.php
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\TariefRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\BooleanFilter;
use ApiPlatform\Core\Serializer\Filter\PropertyFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
/**
* @ApiResource(
* normalizationContext={"groups"={"tarief:read"}},
* denormalizationContext={"groups"={"tarief:write"}},
* )
* @ORM\Entity(repositoryClass=TariefRepository::class)
* @ApiFilter(BooleanFilter::class, properties={"published"})
* @ApiFilter(PropertyFilter::class)
* @ApiFilter(SearchFilter::class, properties={"vervoersmiddel.id": "exact"})
*/
class Tarief
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
* @Groups({"tarief:read"})
*/
private $id;
/**
* @ORM\Column(type="float")
* @Groups({"tarief:read", "tarief:write", "vervoersmiddel:read", "verplaatsing:read", "vervoersmiddel:write"})
*/
private $prijs;
/**
* @ORM\Column(type="date")
* @Groups({"tarief:read", "tarief:write", "vervoersmiddel:write", "vervoersmiddel:read"})
*/
private $datum;
/**
* @ORM\ManyToOne(targetEntity=Vervoersmiddel::class, inversedBy="tarieven")
* @ORM\JoinColumn(nullable=false)
* @Groups({"tarief:read", "tarief:write", "vervoersmiddel:write"})
*/
private $vervoersmiddel;
/**
* @ORM\Column(type="boolean")
* @Groups({"vervoersmiddel:write", "verplaatsing:read"})
*/
private $published;
public function getId(): ?int
{
return $this->id;
}
public function getPrijs(): ?float
{
return $this->prijs;
}
public function setPrijs(float $prijs): self
{
$this->prijs = $prijs;
return $this;
}
public function getDatum(): ?\DateTimeInterface
{
return $this->datum;
}
public function setDatum(\DateTimeInterface $datum): self
{
$this->datum = $datum;
return $this;
}
public function getVervoersmiddel(): ?Vervoersmiddel
{
return $this->vervoersmiddel;
}
public function setVervoersmiddel(?Vervoersmiddel $vervoersmiddel): self
{
$this->vervoersmiddel = $vervoersmiddel;
return $this;
}
public function getPublished(): ?bool
{
return $this->published;
}
public function setPublished(bool $published): self
{
$this->published = $published;
return $this;
}
}
<file_sep>/migrations/Version20210408140227.php
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20210408140227 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE verplaatsing ADD km_start INT NOT NULL, ADD km_stop INT NOT NULL, ADD loc_start VARCHAR(255) NOT NULL, ADD loc_stop VARCHAR(255) NOT NULL, DROP kmStart, DROP kmStop, DROP locStart, DROP locStop');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE verplaatsing ADD kmStart INT NOT NULL, ADD kmStop INT NOT NULL, ADD locStart VARCHAR(255) CHARACTER SET utf8mb4 NOT NULL COLLATE `utf8mb4_unicode_ci`, ADD locStop VARCHAR(255) CHARACTER SET utf8mb4 NOT NULL COLLATE `utf8mb4_unicode_ci`, DROP km_start, DROP km_stop, DROP loc_start, DROP loc_stop');
}
}
<file_sep>/src/Entity/Verplaatsing.php
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\VerplaatsingRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\RangeFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\OrderFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\BooleanFilter;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ApiResource(
* normalizationContext={"groups"={"verplaatsing:read"}},
* denormalizationContext={"groups"={"verplaatsing:write"}}
* )
*
* @ORM\Entity(repositoryClass=VerplaatsingRepository::class)
* @ApiFilter(RangeFilter::class, properties={"datum"})
* @ApiFilter(OrderFilter::class, properties={"datum"})
* @ApiFilter(SearchFilter::class, properties={"user.id": "partial"})
* @ApiFilter(BooleanFilter::class, properties={"vervoersmiddel.tarieven.published"})
*/
class Verplaatsing
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
* @Groups({"verplaatsing:read"})
*/
private $id;
/**
* @ORM\Column(type="datetime")
* @Groups({"verplaatsing:read", "verplaatsing:write", "vervoersmiddel:item:get"})
* @Assert\NotBlank(
* message="Verplicht in te vullen"
* )
*/
private $datum;
/**
* @ORM\Column(type="integer")
* @Groups({"verplaatsing:read", "verplaatsing:write"})
* @Assert\NotBlank (
* message="Verplicht in te vullen"
* )
*/
private $kmStart;
/**
* @ORM\Column(type="integer")
* @Groups({"verplaatsing:read", "verplaatsing:write"})
* @Assert\NotBlank (
* message="Verplicht in te vullen"
* )
*/
private $kmStop;
/**
* @ORM\Column(type="string", length=255)
* @Groups({"verplaatsing:read", "verplaatsing:write", "vervoersmiddel:item:get"})
* @Assert\NotBlank (
* message="Verplicht in te vullen"
* )
*/
private $locStart;
/**
* @ORM\Column(type="string", length=255)
* @Groups({"verplaatsing:read", "verplaatsing:write", "vervoersmiddel:item:get"})
* @Assert\NotBlank (
* message="Verplicht in te vullen"
* )
*/
private $locStop;
/**
* @ORM\ManyToOne(targetEntity=User::class, inversedBy="verplaatsingen")
* @ORM\JoinColumn(nullable=false)
* @Groups({"verplaatsing:read", "verplaatsing:write"})
*/
private $user;
/**
* iri="vervoersmiddels"
* @ORM\ManyToOne(targetEntity=Vervoersmiddel::class, inversedBy="verplaatsingen")
* @ORM\JoinColumn(nullable=false)
* @Groups({"verplaatsing:read", "verplaatsing:write"})
*
*/
private $vervoersmiddel;
public function getId(): ?int
{
return $this->id;
}
public function getDatum(): ?\DateTimeInterface
{
return $this->datum;
}
public function setDatum(\DateTimeInterface $datum): self
{
$this->datum = $datum;
return $this;
}
public function getKmStart(): ?int
{
return $this->kmStart;
}
public function setKmStart(int $kmStart): self
{
$this->kmStart = $kmStart;
return $this;
}
public function getKmStop(): ?int
{
return $this->kmStop;
}
public function setKmStop(int $kmStop): self
{
$this->kmStop = $kmStop;
return $this;
}
public function getLocStart(): ?string
{
return $this->locStart;
}
public function setLocStart(string $locStart): self
{
$this->locStart = $locStart;
return $this;
}
public function getLocStop(): ?string
{
return $this->locStop;
}
public function setLocStop(string $locStop): self
{
$this->locStop = $locStop;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getVervoersmiddel(): ?Vervoersmiddel
{
return $this->vervoersmiddel;
}
public function setVervoersmiddel(?Vervoersmiddel $vervoersmiddel): self
{
$this->vervoersmiddel = $vervoersmiddel;
return $this;
}
}
<file_sep>/migrations/Version20210406142901.php
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20210406142901 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE tarief ADD vervoersmiddel_id INT NOT NULL');
$this->addSql('ALTER TABLE tarief ADD CONSTRAINT FK_BF4873BEE074DE3E FOREIGN KEY (vervoersmiddel_id) REFERENCES vervoersmiddel (id)');
$this->addSql('CREATE INDEX IDX_BF4873BEE074DE3E ON tarief (vervoersmiddel_id)');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE tarief DROP FOREIGN KEY FK_BF4873BEE074DE3E');
$this->addSql('DROP INDEX IDX_BF4873BEE074DE3E ON tarief');
$this->addSql('ALTER TABLE tarief DROP vervoersmiddel_id');
}
}
<file_sep>/migrations/Version20210406141938.php
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20210406141938 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE verplaatsing ADD user_id INT NOT NULL, ADD vervoersmiddel_id INT NOT NULL');
$this->addSql('ALTER TABLE verplaatsing ADD CONSTRAINT FK_E0656B2BA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)');
$this->addSql('ALTER TABLE verplaatsing ADD CONSTRAINT FK_E0656B2BE074DE3E FOREIGN KEY (vervoersmiddel_id) REFERENCES vervoersmiddel (id)');
$this->addSql('CREATE INDEX IDX_E0656B2BA76ED395 ON verplaatsing (user_id)');
$this->addSql('CREATE INDEX IDX_E0656B2BE074DE3E ON verplaatsing (vervoersmiddel_id)');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE verplaatsing DROP FOREIGN KEY FK_E0656B2BA76ED395');
$this->addSql('ALTER TABLE verplaatsing DROP FOREIGN KEY FK_E0656B2BE074DE3E');
$this->addSql('DROP INDEX IDX_E0656B2BA76ED395 ON verplaatsing');
$this->addSql('DROP INDEX IDX_E0656B2BE074DE3E ON verplaatsing');
$this->addSql('ALTER TABLE verplaatsing DROP user_id, DROP vervoersmiddel_id');
}
}
<file_sep>/migrations/Version20210406144314.php
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20210406144314 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE vervoersmiddel ADD user_id INT NOT NULL, ADD categorie_id INT NOT NULL');
$this->addSql('ALTER TABLE vervoersmiddel ADD CONSTRAINT FK_8C9D106EA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)');
$this->addSql('ALTER TABLE vervoersmiddel ADD CONSTRAINT FK_8C9D106EBCF5E72D FOREIGN KEY (categorie_id) REFERENCES categorie (id)');
$this->addSql('CREATE INDEX IDX_8C9D106EA76ED395 ON vervoersmiddel (user_id)');
$this->addSql('CREATE INDEX IDX_8C9D106EBCF5E72D ON vervoersmiddel (categorie_id)');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE vervoersmiddel DROP FOREIGN KEY FK_8C9D106EA76ED395');
$this->addSql('ALTER TABLE vervoersmiddel DROP FOREIGN KEY FK_8C9D106EBCF5E72D');
$this->addSql('DROP INDEX IDX_8C9D106EA76ED395 ON vervoersmiddel');
$this->addSql('DROP INDEX IDX_8C9D106EBCF5E72D ON vervoersmiddel');
$this->addSql('ALTER TABLE vervoersmiddel DROP user_id, DROP categorie_id');
}
}
| 27e23523e1a1011d18d5be3e56b8dc7b80db03ee | [
"PHP"
] | 8 | PHP | Petervrancken/fsd_transport_be | 5007684eac9a6d76b7c30bbb7e97bb8a13607fa3 | 9ffd5aa06dc4d1f9ebe576e2d8c93ae07df97433 |
refs/heads/master | <file_sep>$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=Jimi_Hendrix&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
// console.log(data);
var markup = data.parse.text["*"];
console.log(markup);
var blurb = $('<div></div>').html(markup);
console.log(blurb);
// console.log(blurb);
// append links as li elements to the links ul.
// console.log(blurb.find('a'));
// blurb.find('a').each((link)=>{
// $('#links').append(link);
// });
let alist = $(blurb).find('p').find('a');
let firstlink = alist[0].title.split(" ").join("_");
let urlString = "http://wikipedia.com/wiki/" + firstlink;
window.location.href = urlString;
$('#links').html(alist);
$('#paragraph').html($(blurb).find('p'));
},
error: function (errorMessage) {
}
});
});
| d176f593a3b66b684ea800adc5b0f23f7512d51d | [
"JavaScript"
] | 1 | JavaScript | noahskang/Get-To-Philosophy | 73334801fb6a69cc276e4a0f96d0ced76af2b5d2 | d6ee9b280f079abfd1bd3052d8e042f8c45f6fce |
refs/heads/master | <file_sep># Bomber - Game Design Course Project
> Note:
> This project developed by Unity 5.3.5f1, build to running in Windows x86/64 platform
> All Doc (include TDD, PPT) in `Doc` Folder
# Project Members
In no particular order:
* <NAME>: [GitHub](https://github.com/xiaofeng94)
* <NAME>: [GitHub](https://github.com/Finspire13)
* <NAME>: [GitHub](https://github.com/WalterMa)
* <NAME>
# Screenshots




<file_sep>using UnityEngine;
using System.Collections;
public class NormalBombFire : MonoBehaviour,Distroyable,BombFire,Locatable
{
private bool fireSwitch = false;
private int lifeTime = 1;
private int damge = 10;
private SetBomb owner;
public SetBomb Owner {
get{return this.owner;}
set{this.owner = value;}
}
private Position position;
public Position pos{
get{ return position; }
set{ position=value; }
}
public void setProperties(SetBomb owner,int lifeTime){
this.owner = owner;
this.lifeTime = lifeTime;
}
// Use this for initialization
void Start ()
{
GameDataProcessor.instance.addObject (this);
RhythmRecorder.instance.addObservedSubject (this);
fireSwitch = true;
// lifeTime = 1;
}
// Update is called once per frame
void Update ()
{
if (fireSwitch) {
fireSwitch = false;
attack ();
// Debug.Log ("x="+this.position.x+",y="+this.position.y);
}
if (lifeTime <= 1) {
GameDataProcessor.instance.removeFromDangerMap (this);
distroy();
return;
}
}
public int Damage{
get{return this.damge;}
set{this.damge=value;}
}
// set and get lifeTime
public int Blood
{
get{return this.lifeTime;}
set{this.lifeTime = value;}
}
// set and get lifeTime
public int LifeTime
{
get{return this.lifeTime;}
set{this.lifeTime = value;}
}
public void attackBy(Attackable source){
}
public void actionOnBeat (){
--lifeTime;
fireSwitch = true;
// Debug.Log ("--lifeTime");
}
public void distroy(){
GameDataProcessor.instance.removeObject (this);
RhythmRecorder.instance.removeObserver (this);
Destroy(this.gameObject,0.5f);
}
public void attack(){
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (this.pos);
// Debug.Log ("x="+this.pos.x+",y="+this.pos.y);
if (objs != null) {
for (int i = 0; i < objs.Count; ++i) {
if (objs [i] is Distroyable) {
// Debug.Log (".....5,0");
// Debug.Log ("x="+((Locatable)objs [i]).pos.x+",y="+((Locatable)objs [i]).pos.y);
((Distroyable)objs [i]).attackBy (this);
}
}
}
}
void OnDestroy(){
this.distroy ();
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class Explosion : MonoBehaviour {
private int stepLenth = 1;
private int power = 4;
public int Power
{
get {return power;}
set {power = value;}
}
private bool active = false;
public bool Active
{
get {return active;}
set {active = value;}
}
private int lifeTime = 10;
public int LifeTime
{
get {return lifeTime;}
set {lifeTime = value;}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void FixedUpdate () {
if (active) {
lifeTime--;
}
// Debug.Log ("lifeTime:" + lifeTime.ToString());
if (lifeTime <= 0 && active) {
GameObject fire = Resources.Load("firebase") as GameObject;
GameObject[] fires = new GameObject[power*4+1];
//(GameObject)Instantiate(fire,this.gameObject.transform.position,this.gameObject.transform.rotation);
Vector3 currPos = this.gameObject.transform.position;
fires[0] = (GameObject)Instantiate(fire,currPos,this.gameObject.transform.rotation);
Vector3 tempPos = currPos;
for(int i = 1;i < power+1;++i){
tempPos.x += stepLenth;
fires[i] = (GameObject)Instantiate(fire,tempPos,this.gameObject.transform.rotation);
}
tempPos = currPos;
for(int i = power+1;i < power*2+1;++i){
tempPos.x -= stepLenth;
fires[i] = (GameObject)Instantiate(fire,tempPos,this.gameObject.transform.rotation);
}
tempPos = currPos;
for(int i = power*2+1;i < power*3+1;++i){
tempPos.z += stepLenth;
fires[i] = (GameObject)Instantiate(fire,tempPos,this.gameObject.transform.rotation);
}
tempPos = currPos;
for(int i = power*3+1;i < power*4+1;++i){
tempPos.z -= stepLenth;
fires[i] = (GameObject)Instantiate(fire,tempPos,this.gameObject.transform.rotation);
}
active = false;
Destroy(this.gameObject,5);
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class LevelEndCanvasAction : MonoBehaviour {
public Text gameStateText;
public string gameLoseText = "Oh... You Lose";
public string gameWinText = "Wow! You win";
public Button endButton;
public Button playAgainButton;
public Button selectLevelButton;
// Use this for initialization
void Start () {
endButton.onClick.AddListener (() => clickEndButton ());
playAgainButton.onClick.AddListener (() => clickPlayAgainButton ());
selectLevelButton.onClick.AddListener (clickSelectLevelButton);
switch (GameManager.instance.levelState) {
case LevelState.lose:
gameStateText.text = gameLoseText;
break;
case LevelState.win:
gameStateText.text = gameWinText;
break;
default:
break;
}
}
// Update is called once per frame
void Update () {
}
void clickEndButton(){
GameManager.instance.changeGameState (GameState.end);
}
void clickPlayAgainButton(){
GameManager.instance.changeGameState (GameState.playing);
}
void clickSelectLevelButton(){
GameManager.instance.changeGameState (GameState.levelSelect);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class BaseBuff : MonoBehaviour,Buff,Locatable,RhythmObservable,ScoreCount
{
protected Position position;
public Position pos{
get{return position; }
set{position = value; }
}
protected int lifeTime = 25;
public int LifeTime{
get{return lifeTime; }
set{lifeTime = value; }
}
public int buffValue = 10;
public int Value {
get{return buffValue; }
set{buffValue = value; }
}
protected string gameName = "Buff-Base";
protected float gameValue = 10f;
public string getName(){
return this.gameName;
}
public float getValue(){
return this.gameValue;
}
public void addToScore(){
GameManager.instance.addToPlayerScoreList (this);
}
public void actionOnBeat (){
--lifeTime;
}
// Use this for initialization
void Start ()
{
RhythmRecorder.instance.addObservedSubject (this,0.1f);
GameDataProcessor.instance.addToBenefitMap (this);
// this.lifeTime = 200;
// this.buffValue = 5;
}
// Update is called once per frame
void Update ()
{
if (!this.position.Equals(null)) {
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (this.position);
for (int i = 0; i < objs.Count; ++i) {
if (objs[i] is SetBomb) {
if(GameManager.instance.isBuffValid(objs[i])){
//your effect;
}
lifeTime = 0;
if (objs [i] is PlayerConrol) {
this.addToScore ();
}
}
}
} else {
Debug.Log ("buff positon is null!!!");
}
if (lifeTime <= 0) {
this.distroy ();
}
}
void distroy(){
RhythmRecorder.instance.removeObserver (this);
GameDataProcessor.instance.removeFromBenefitMap (this);
Destroy (this.gameObject, 0);
}
void OnDestroy(){
this.distroy ();
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System;
public class WallCube : MonoBehaviour, Locatable {
private Position position;
public Position pos
{
get { return position; }
set { position = value; }
}
// Use this for initialization
void Start () {
//Initize position of cube
//Debug.Log(Mathf.RoundToInt(transform.localPosition.x)+", "+Mathf.RoundToInt(transform.localPosition.z));
this.position = new Position(Mathf.RoundToInt(transform.localPosition.z),Mathf.RoundToInt(transform.localPosition.x));
// Debug.Log(Mathf.RoundToInt(transform.localPosition.z)+", "+Mathf.RoundToInt(transform.localPosition.x));
// Debug.Log ("WC:"+this.position.x+","+this.position.y);
}
}
<file_sep>using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using System.Collections;
[System.Serializable]
public class PassStringEvent : UnityEvent<string>{}
public class ListContentController : MonoBehaviour {
public PassStringEvent OnClick;
void Start(){
}
public void ListContentClickTrigger(){
OnClick.Invoke (GetComponentInChildren<Text>().text);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class RhythmList {
public static string Default = "default";
public static string Test = Application.dataPath+"/Rhythm/TestRhythm.txt";
public static string Tombtorial = Application.dataPath+"/Rhythm/rhythm2.txt";
public static string Rhythmortis = Application.dataPath+"/Rhythm/rhythm1.txt";
public static string WatchYourStep = Application.dataPath+"/Rhythm/rhythm3.txt";
}
public class MusicList{
public static string Default = "default";
public static string Tombtorial = Application.dataPath+"/Music/Tombtorial.mp3";
public static string Rhythmortis = Application.dataPath+"/Music/Rhythmortis.mp3";
public static string WatchYourStep = Application.dataPath+"/Music/Watch Your Step.mp3";
}
<file_sep>using UnityEngine;
using System.Collections;
public class SquareBomb :MonoBehaviour,Bomb,Distroyable,Locatable
{
private SetBomb owner = null;
public GameObject fire = null;
private int lifeTime = 2;
private int power = 5;
private Position position;
public Position pos{
get{ return position; }
set{ position=value; }
}
private bool isActive = true;
public bool IsActive{
get{ return isActive; }
set{ isActive=value; }
}
public int stepLenth = 1;
// Use this for initialization
void Start ()
{
if (this.fire == null) {
this.fire = Resources.Load ("poisonFireBase") as GameObject;
}
// Debug.Log ("NormalBomb :MonoBehaviour,Bomb,Distroyable,Locatable");
GameDataProcessor.instance.addObject (this);
RhythmRecorder.instance.addObservedSubject (this);
GameDataProcessor.instance.addToDangerMap (this);
}
// Update is called once per frame
void Update () {
if (lifeTime <= 0 && isActive) {
this.createFire();
isActive = false;
this.createFire();
GameManager.instance.increaseBombCount(owner);
owner.notifyExplosion(this);
this.distroy();
}
}
public void setProperties(SetBomb owner,int power,int lifeTime,int fireTime){
this.owner = owner;
this.lifeTime = lifeTime;
this.power = power;
this.fireTime = fireTime;
if(this.owner is Locatable){
this.position = ((Locatable)this.owner).pos;
}
// Debug.Log ("NormalBomb:(x,y)="+this.position.x+","+this.position.y);
}
public SetBomb Owner {
get{return this.owner;}
set{this.owner = value;}
}
public GameObject Fire{
get{return this.fire;}
set{this.fire = value;}
}
public int LifeTime{
get{return lifeTime;}
set{lifeTime=value;}
}
private int fireTime = 1;
public int FireTime {
get;
set;
}
public int Blood
{
get{return lifeTime;}
set{lifeTime=value;}
}
public int Power
{
get {return power;}
set {power = value;}
}
public void attackBy(Attackable source){
// Debug.Log ( "Attackable source:"+((Locatable)source).pos.x +","+((Locatable)source).pos.y );
// Debug.Log("source is BombFire:"+source is BombFire);
// if (source is BombFire && isActive) {
//// Debug.Log ("attackBy()...");
// lifeTime = 0;
// this.createFire ();
// isActive = false;
// this.distroy ();
// }
lifeTime = 0;
}
public void distroy(){
// if (owner.CurrNum > 0) {
// owner.CurrNum -= 1;
// }
// this.createFire();
// GameManager.instance.increaseBombCount(owner);
// owner.notifyExplosion(this);
GameDataProcessor.instance.removeObject (this);
RhythmRecorder.instance.removeObserver (this);
AudioPlayer.instance.playSFX(SFX.Explosion);
Destroy(this.gameObject,0);
}
public void actionOnBeat(){
// Debug.Log ("lifeTime:" + lifeTime.ToString());
--lifeTime;
}
private void createFire(){
GameObject[] fires = new GameObject[(power*2+1)*(power*2+1)];
Vector3 tempPos = this.gameObject.transform.position;
int tempX = this.position.x;
int tempY = this.position.y;
int fireIndex = 0;
for (int i = -power; i <= power; i++)
for (int j = -power; j <= power; j++) {
tempPos.x =this.gameObject.transform.position.x+ stepLenth*i;
tempX = this.position.x+stepLenth*i;
tempPos.z =this.gameObject.transform.position.z+ stepLenth*j;
tempY = this.position.y-stepLenth*j;
//Debug.Log (i+" "+j);
if(tempX<0 || tempX >= GameDataProcessor.instance.mapSizeX||tempY<0 || tempY >= GameDataProcessor.instance.mapSizeY){
continue;
}
// Debug.Log (tempX+" "+tempY);
Position currPosition = new Position(tempX,tempY);
fires [fireIndex] = (GameObject)Instantiate (fire, tempPos, this.gameObject.transform.rotation);
NormalBombFire bfScript = (NormalBombFire)fires [fireIndex].GetComponent ("NormalBombFire");
bfScript.setProperties (this.owner, fireTime);
bfScript.pos = currPosition;
fireIndex++;
}
}
public void pushTo (Position finalPos){
float diffX = finalPos.x - this.position.x;
float diffY = finalPos.y - this.position.y;
StartCoroutine (MoveOffset(diffX,diffY));
this.position.x= finalPos.x;
this.position.y = finalPos.y;
}
IEnumerator MoveOffset(float diffX,float diffY){
int frameCount = 10;
for (int i = 0; i < frameCount; ++i) {
// this.transform.position +diffX / frameCount;
// this.transform.position.z -= diffY / frameCount;
this.transform.position += (diffX/frameCount)*Vector3.right;
this.transform.position += (diffY/frameCount)*Vector3.back;
yield return null;
}
}
void OnDestroy(){
this.distroy ();
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
public class PlayingCanvasAction : MonoBehaviour,RhythmObservable {
public GameObject leftSlider;
public GameObject rightSlider;
public GameObject SliderPosition;
public ListViewController ListController;
public Button levelEndButton;
public Text bloodText;
public Text bombNumText;
public Text bombPowerText;
public Text bombLifeText;
public GameObject dialog;
public Text dialogTitle;
public string gameLoseText = "You Lose";
public string gameWinText = "You Win";
// Use this for initialization
void Start () {
RhythmRecorder.instance.addObservedSubject (this,-2);
levelEndButton.onClick.AddListener (() => clickLevelEndButton ());
}
// Update is called once per frame
void Update () {
if (GameManager.instance.playerList.Count != 0) {
bloodText.text = "HP: " + GameManager.instance.PlayerBlood;
PlayerConrol player = (PlayerConrol)GameManager.instance.playerList [0];
bombNumText.text = "Max Bomb: " + player.MaxNum;
bombPowerText.text = "Power: " + player.BombPower;
bombLifeText.text = "Explosion Time: " + player.BombLifeTime;
ListController.deleteAllListContents ();
ArrayList toolList = player.playerTools;
string[] toolNames = new string[toolList.Count];
int i = 0;
foreach(BombTool tool in toolList){
toolNames [i] = tool.getToolName ();
i++;
}
ListController.addListContents (toolNames);
}
}
public void actionOnBeat(){
//StartCoroutine(BeatIt());
GameObject leftSliderInstance = Instantiate (leftSlider) as GameObject;
//leftSliderInstance.transform.SetParent(gameObject.transform);
leftSliderInstance.transform.SetParent(SliderPosition.transform);
leftSliderInstance.GetComponent<RectTransform>().localPosition = new Vector3 (-304f, 0f, 0f);
leftSliderInstance.GetComponent<RectTransform> ().SetAsFirstSibling ();
GameObject rightSliderInstance = Instantiate (rightSlider) as GameObject;
//rightSliderInstance.transform.SetParent(gameObject.transform);
rightSliderInstance.transform.SetParent(SliderPosition.transform);
rightSliderInstance.GetComponent<RectTransform>().localPosition = new Vector3 (304f, 0f, 0f);
rightSliderInstance.GetComponent<RectTransform> ().SetAsFirstSibling ();
}
public void clickLevelEndButton(){
showDialog ();
}
public void endLevel(){
GameManager.instance.changeGameState (GameState.levelEnd);
}
public void showDialog(){
switch (GameManager.instance.levelState) {
case LevelState.lose:
dialogTitle.text = gameLoseText;
break;
case LevelState.win:
dialogTitle.text = gameWinText;
break;
default:
break;
}
ListViewController controller = dialog.GetComponentInChildren<ListViewController> ();
Dictionary<string,float> scoreMap = GameManager.instance.computeScore ();
int totalScore = 0;
string[] scores = new string[scoreMap.Count + 1];
int i = 0;
foreach(KeyValuePair<string, float> kv in scoreMap){
totalScore = totalScore + (int)kv.Value;
scores[i] = kv.Key + ": " + (int)kv.Value;
i++;
}
scores [i] = "Total Score: " + totalScore;
controller.addListContents (scores);
GameManager.instance.totalGameScore += totalScore;
dialog.SetActive (true);
}
public void hideDialog(){
dialog.SetActive (false);
}
void OnDestroy() {
RhythmRecorder.instance.removeObserver (this);
}
}
<file_sep>using System;
using System.IO;
using UnityEngine;
using System.Collections;
public class PersonRhythmProducer:BasicRhythmProducer
{
float currentBeat = 0f;
public PersonRhythmProducer ()
{
this.init();
}
// public override void init(){
// currentRhythm = RhythmList.Default;
//
// startTime = 0;
// beats = new ArrayList ();
// isPlaying = false;
// currentBeatIndice=new ArrayList (); // change to record whether the object can be notified now.
// observedSubjects = new ArrayList ();
// timeOffsets = new ArrayList ();
// standardBeatIndex = 0;
// rhythmFlagOwners = new ArrayList ();
// isFlagsChangable = new ArrayList ();
// }
// public void removeAllObservedSubjects(){
// observedSubjects.Clear ();
// currentBeatIndice.Clear ();
// timeOffsets.Clear ();
// }
public override void addObservedSubject(RhythmObservable newSubject, float timeOffset=0.2f){
observedSubjects.Add (newSubject);
timeOffsets.Add (timeOffset);
currentBeatIndice.Add (true);
// newSubject.actionOnBeat ();
}
// public void removeAllRhythmFlagOwners(){
// rhythmFlagOwners.Clear ();
// isFlagsChangable.Clear ();
// }
//
// public void addRhythmFlagOwner(RhythmFlagOwner newOwner){
// rhythmFlagOwners.Add (newOwner);
// isFlagsChangable.Add (true);
// }
//
// public void removeObserver(RhythmObservable subject){
// int tempIndex = observedSubjects.IndexOf (subject);
// if (tempIndex == -1)
// return;
// currentBeatIndice.RemoveAt (tempIndex);
// timeOffsets.RemoveAt (tempIndex);
// observedSubjects.Remove (subject);
// }
// public void removeFlagOwner(RhythmFlagOwner owner){
// int indx = rhythmFlagOwners.IndexOf (owner);
// if (indx == -1)
// return;
// isFlagsChangable.RemoveAt (indx);
// rhythmFlagOwners.Remove (owner);
// }
//public override bool setRhythm(string newRhythm){
// currentRhythm = newRhythm;
// resetRhythm ();
//
// if (!File.Exists (currentRhythm)) {
// return false;
// }
//
// string text = File.ReadAllText(currentRhythm);
// string[] sArray=text.Split(' ') ;
//
// beats = new ArrayList ();
// foreach (string i in sArray) {
// beats.Add (float.Parse (i));
// }
// return true;
// return true;
//}
// public bool startRhythm()
// {
// if (isPlaying)
// return false;
//
// startTime = Time.time;
// isPlaying = true;
// standardBeatIndex = 0;
//
// return true;
// }
//
// public void resetRhythm(){
//
// startTime = 0;
// isPlaying = false;
// standardBeatIndex = 0;
// }
protected override bool isOnBeat()
{
return true;
}
public override void updateFlagInOwners(){
if (Input.anyKeyDown) {
if (Time.time - currentBeat > 0.2f) {
currentBeat = Time.time;
for (int i = 0; i < rhythmFlagOwners.Count; i++) {
RhythmFlagOwner owner = (RhythmFlagOwner)rhythmFlagOwners [i];
if (owner is MoveAble) {
owner.rhythmFlag = ((MoveAble)owner).Speed;
} else {
owner.rhythmFlag = 1;
}
}
for(int i = 0;i < currentBeatIndice.Count;++i){
currentBeatIndice [i] = true;
}
} else {
for (int i = 0; i < rhythmFlagOwners.Count; i++) {
RhythmFlagOwner owner = (RhythmFlagOwner)rhythmFlagOwners [i];
owner.rhythmFlag = 0;
}
}
}
}
public override void notifyObserver(){
for (int i = 0; i < observedSubjects.Count; i++) {
if (Time.time - currentBeat > (float)timeOffsets [i] && (bool)currentBeatIndice [i]) {
((RhythmObservable)observedSubjects [i]).actionOnBeat ();
currentBeatIndice [i] = false;
}
}
}
public override bool isFinished(){
return false;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System;
public class NormalCube : MonoBehaviour, Locatable,Distroyable,ScoreCount {
private string gameName = "Wall-NormalWall";
private float gameValue = 2f;
public string getName(){
return this.gameName;
}
public float getValue(){
return this.gameValue;
}
public void addToScore(){
GameManager.instance.addToPlayerScoreList (this);
}
private Position position;
public Position pos
{
get { return position; }
set { position = value; }
}
public void actionOnBeat(){
}
private int blood;
public int Blood
{
get { return blood; }
set { blood = value; }
}
public void attackBy(Attackable source)
{
// Debug.Log("NormalCube->attackBy(),damage:"+source.Damage);
// blood -= source.Damage;
blood = 0;
}
public void distroy()
{
GameDataProcessor.instance.removeObject (this);
Destroy(this.gameObject, 0);
}
// Use this for initialization
void Start()
{
//Initize position of cube
//Debug.Log(Mathf.RoundToInt(transform.localPosition.x) + ", " + Mathf.RoundToInt(transform.localPosition.z));
this.position = new Position(Mathf.RoundToInt(transform.localPosition.z),Mathf.RoundToInt(transform.localPosition.x));
// Debug.Log ("NC:"+this.position.x+","+this.position.y);
blood = 1;
}
// Update is called once per frame
void Update()
{
if (blood <= 0)
{
// Debug.Log("cube died!!!");
createBuff ();
distroy();
}
}
void createBuff(){
string[] buffList = {"Heal","GhostForm","BombPowerUp","BombNumberUp","FireLifeTimeUp","SpeedUp","SlowDown","GetSquareBomb" };
// string[] buffList = {"GetSquareBomb"};
//string[] buffList = {"FireLifeTimeUp"};
int buffIndex=UnityEngine.Random.Range (0, buffList.Length);
GameObject buff = Resources.Load(buffList[buffIndex]) as GameObject;
GameObject obj = (GameObject)Instantiate(buff,this.gameObject.transform.position,this.gameObject.transform.rotation);
obj.transform.SetParent (MapDataHelper.instance.getMapModel().transform);
Buff script = (Buff)obj.GetComponent("Buff");
if (script == null) {
Debug.Log ("not script");
} else {
if (script is Locatable) {
// Debug.Log ("script is Locatable");
((Locatable)script).pos = new Position (this.pos.x,this.pos.y);
}
}
}
void OnDestroy(){
this.distroy ();
}
}
<file_sep>using UnityEngine;
using System.Collections;
public enum SFX
{
Explosion,Buff,PlayerDamaged,EnermyDamaged,Debuff,PlayerKilled,EnermyKilled,SetBomb,Start,Victory
}
public class AudioPlayer : MonoBehaviour {
public static AudioPlayer instance = null;
public AudioSource BGMSource;
public AudioSource SFXSource;
public AudioClip idleBGM;
public AudioClip bgm1;
public AudioClip bgm2;
public AudioClip bgm3;
public AudioClip explosion;
public AudioClip buff;
public AudioClip playerDamaged;
public AudioClip enermyDamaged;
public AudioClip debuff;
public AudioClip playerKilled;
public AudioClip enermyKilled;
public AudioClip setBomb;
public AudioClip start;
public AudioClip victory;
void Awake()
{
if (instance == null)
instance = this;
else if (instance != this)
Destroy (gameObject);
DontDestroyOnLoad (gameObject);
BGMSource.loop = true;
BGMSource.volume = 0.55f;
BGMSource.playOnAwake = false;
BGMSource.Pause ();
SFXSource.loop = false;
SFXSource.playOnAwake = false;
SFXSource.volume = 1f;
SFXSource.Pause ();
}
// Use this for initialization
void Start () {
}
public void playBGM(int bgmIndex)
{
switch (bgmIndex) {
case 0:
BGMSource.Pause ();
BGMSource.clip = idleBGM;
BGMSource.Play ();
break;
case 1:
BGMSource.Pause ();
BGMSource.clip = bgm1;
BGMSource.Play ();
break;
case 2:
BGMSource.Pause ();
BGMSource.clip = bgm2;
BGMSource.Play ();
break;
case 3:
BGMSource.Pause ();
BGMSource.clip = bgm3;
BGMSource.Play ();
break;
default:
break;
}
}
public void stopBGM()
{
BGMSource.Pause ();
}
public void playSFX(SFX sfx)
{
switch (sfx) {
case SFX.Buff:
SFXSource.Pause ();
SFXSource.volume = 0.6f;
SFXSource.clip = buff;
SFXSource.Play ();
SFXSource.volume = 1f;
break;
case SFX.Debuff:
SFXSource.Pause ();
SFXSource.clip = debuff;
SFXSource.Play ();
break;
case SFX.EnermyDamaged:
SFXSource.Pause ();
SFXSource.clip = enermyDamaged;
SFXSource.Play ();
break;
case SFX.EnermyKilled:
SFXSource.Pause ();
SFXSource.clip = enermyKilled;
SFXSource.Play ();
break;
case SFX.Explosion:
SFXSource.Pause ();
SFXSource.volume = 0.9f;
SFXSource.clip = explosion;
SFXSource.Play ();
SFXSource.volume = 1f;
break;
case SFX.PlayerDamaged:
SFXSource.Pause ();
SFXSource.clip = playerDamaged;
SFXSource.Play ();
break;
case SFX.PlayerKilled:
SFXSource.Pause ();
SFXSource.clip = playerKilled;
SFXSource.Play ();
break;
case SFX.SetBomb:
SFXSource.Pause ();
SFXSource.clip = setBomb;
SFXSource.Play ();
break;
case SFX.Victory:
SFXSource.Pause ();
SFXSource.clip = victory;
SFXSource.Play ();
break;
case SFX.Start:
SFXSource.Pause ();
SFXSource.clip = start;
SFXSource.Play ();
break;
default:
break;
}
}
// Update is called once per frame
void Update () {
}
}
<file_sep>using System;
using System.IO;
using UnityEngine;
using System.Collections;
public class BasicRhythmProducer
{
public string currentRhythm;
public float startTime;
public ArrayList beats;
public bool isPlaying;
public float onBeatThreshold=0.1f;
public ArrayList currentBeatIndice;
public ArrayList observedSubjects;
public ArrayList timeOffsets;
public int standardBeatIndex;
public ArrayList rhythmFlagOwners;
public ArrayList isFlagsChangable;
public BasicRhythmProducer ()
{
init ();
}
public virtual void init(){
currentRhythm = RhythmList.Default;
startTime = 0;
beats = new ArrayList ();
isPlaying = false;
currentBeatIndice=new ArrayList ();
observedSubjects = new ArrayList ();
timeOffsets = new ArrayList ();
standardBeatIndex = 0;
rhythmFlagOwners = new ArrayList ();
isFlagsChangable = new ArrayList ();
}
public virtual void removeAllObservedSubjects(){
observedSubjects.Clear ();
currentBeatIndice.Clear ();
timeOffsets.Clear ();
}
public virtual void addObservedSubject(RhythmObservable newSubject, float timeOffset=0.2f){
observedSubjects.Add (newSubject);
timeOffsets.Add (timeOffset);
currentBeatIndice.Add (standardBeatIndex);
// newSubject.actionOnBeat ();
}
public virtual void removeAllRhythmFlagOwners(){
rhythmFlagOwners.Clear ();
isFlagsChangable.Clear ();
}
public virtual void addRhythmFlagOwner(RhythmFlagOwner newOwner){
rhythmFlagOwners.Add (newOwner);
isFlagsChangable.Add (true);
}
public virtual void removeObserver(RhythmObservable subject){
int tempIndex = observedSubjects.IndexOf (subject);
if (tempIndex == -1)
return;
currentBeatIndice.RemoveAt (tempIndex);
timeOffsets.RemoveAt (tempIndex);
observedSubjects.Remove (subject);
}
public virtual void removeFlagOwner(RhythmFlagOwner owner){
int indx = rhythmFlagOwners.IndexOf (owner);
if (indx == -1)
return;
isFlagsChangable.RemoveAt (indx);
rhythmFlagOwners.Remove (owner);
}
public virtual bool setRhythm(string newRhythm){
currentRhythm = newRhythm;
resetRhythm ();
if (!File.Exists (currentRhythm)) {
return false;
}
string text = File.ReadAllText(currentRhythm);
string[] sArray=text.Split(' ') ;
beats = new ArrayList ();
foreach (string i in sArray) {
Debug.Log ("!!!@@@");
Debug.Log (i);
beats.Add (float.Parse (i));
}
return true;
}
public virtual bool startRhythm()
{
if (isPlaying)
return false;
startTime = Time.time;
isPlaying = true;
standardBeatIndex = 0;
return true;
}
public virtual void resetRhythm(){
startTime = 0;
isPlaying = false;
standardBeatIndex = 0;
}
protected virtual bool isOnBeat()
{
if (isFinished()||!isPlaying)
return false;
float currentStandardBeat = (float)beats [standardBeatIndex];
return System.Math.Abs (currentStandardBeat - (Time.time - startTime)) < onBeatThreshold;//0.2
}
public virtual void updateFlagInOwners(){
if (isOnBeat ()) {
for (int i = 0; i < rhythmFlagOwners.Count; i++) {
if ((bool)isFlagsChangable [i]) {
RhythmFlagOwner owner = (RhythmFlagOwner)rhythmFlagOwners [i];
if (owner is MoveAble) {
owner.rhythmFlag = ((MoveAble)owner).Speed;
} else {
owner.rhythmFlag = 1;
}
isFlagsChangable [i] = false;
}
}
}
else {
for (int i = 0; i < rhythmFlagOwners.Count; i++) {
RhythmFlagOwner owner = (RhythmFlagOwner)rhythmFlagOwners [i];
owner.rhythmFlag = 0;
}
}
}
public virtual void notifyObserver(){
if (isPlaying&&!isFinished()) {
// Debug.Log ("random:" + GameDataProcessor.instance.getRandom (6));
for (int i = 0; i < observedSubjects.Count; i++) {
int tempBeatIndex = (int)currentBeatIndice [i];
if (tempBeatIndex < beats.Count) {
float currentBeat = (float)beats [tempBeatIndex];
if ((Time.time - startTime) - currentBeat > (float)timeOffsets [i]) {
((RhythmObservable)observedSubjects [i]).actionOnBeat ();
currentBeatIndice [i] = tempBeatIndex + 1;
}
}
}
float currentStandardBeat = (float)beats [standardBeatIndex];
if ((Time.time - startTime) - currentStandardBeat > onBeatThreshold) {
// Debug.Log("OnBeats");
standardBeatIndex++;
for (int i = 0; i < isFlagsChangable.Count; i++) {
isFlagsChangable [i] = true;
}
}
}
}
public virtual bool isFinished(){
return standardBeatIndex >= beats.Count;
}
public virtual void resetGame(){
}
}
<file_sep>using System;
public interface CanBuffed
{
}
<file_sep>using UnityEngine;
using System.Collections;
public class LoadGame : MonoBehaviour {
public GameObject rhythmRecorder;
public GameObject mapDataHelper;
public GameObject gameDataProcessor;
public GameObject gameManager;
public GameObject audioPlayer;
// public GameObject ui;
void Awake(){
if (RhythmRecorder.instance == null) {
Instantiate (rhythmRecorder);
}
if (MapDataHelper.instance == null) {
Instantiate (mapDataHelper);
}
if (GameDataProcessor.instance == null) {
Instantiate (gameDataProcessor);
}
if (GameManager.instance == null) {
Instantiate (gameManager);
}
if (AudioPlayer.instance == null) {
Instantiate (audioPlayer);
}
}
// Use this for initialization
void Start () {
// Debug.Log ("Start:");
// Debug.Log (Time.time);
//if (!RhythmRecorder.instance.setRhythm (RhythmList.Test)) {
// Debug.Log ("error");
//}
//if (!RhythmRecorder.instance.startRhythm ()) {
// Debug.Log ("error");
//}
GameManager.instance.changeGameState (GameState.start);
}
// Update is called once per frame
void Update () {
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class MapToggleInfo : MonoBehaviour {
public Color TargetColor;
public MapDataEncoder.MapDataCodeEnum DataCode;
public void setColorAndCode(bool isOn){
if (isOn) {
MapEditorHelper.TargetColor = TargetColor;
MapEditorHelper.MapDataCode = (int)DataCode;
Debug.Log ("Set Color to editor");
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class RhythmSlider : MonoBehaviour {
public Slider slider;
public float timeToCountDown=2;
public float startTime;
// Use this for initialization
void Start () {
startTime = Time.time;
}
// Update is called once per frame
void Update () {
float currentPercentage = 1 - (Time.time - startTime) / timeToCountDown;
if (currentPercentage < 0) {
Destroy (gameObject);
}
slider.value = currentPercentage;
}
}
<file_sep>using System;
public interface Buff
{
int LifeTime{
get;
set;
}
int Value {
get;
set;
}
}
<file_sep>using System;
using UnityEngine;
public interface BombTool
{
void useToolBy(SetBomb user);
KeyCode getKeyCode ();
string getToolName();
SetBomb Owner {
get;
set;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public enum GameState{start,levelSelect,mapEdit,playing,levelEnd,end};
public enum LevelState{lose, win};
public enum PlayMode{presetMap, customMap};
public class GameManager : MonoBehaviour {
private bool gameVictoryClock = false; //确保游戏胜利或失败只触发一次
public static GameManager instance = null;
public GameObject startCanvas;
public GameObject playingCanvas;
public GameObject levelSelectCanvas;
public GameObject mapEditCanvas;
public GameObject levelEndCanvas;
public GameObject endCanvas;
public GameState currState;
public LevelState levelState;
public ArrayList playerList;
public ArrayList enemyList;
public void addToEnemyList(EnemyBomber enemy){
enemyList.Add (enemy);
}
public void removeFromEnemyList(EnemyBomber enemy){
enemyList.Remove(enemy);
}
public void addToPlayerList(PlayerConrol player){
playerList.Add (player);
}
public void removeFromPlayerList(PlayerConrol player){
playerList.Remove (player);
}
public int enemyNumber = 0;
private int enemyNum;
public int EnemyNum{
get{return enemyNum;}
set{enemyNum = value;}
}
private GameObject currentCanvas;
private int playerBlood;
public int level = 3;
private bool canPlayerBuffed = true;
public PlayMode playMode;
public int presetMap = 1;
public string customMap = "";
public int totalGameScore;
public ArrayList playerScoreList = new ArrayList();
public void addToPlayerScoreList(ScoreCount item){
playerScoreList.Add (item);
}
public int playerBombCount = 0;
public void increaseBombCount(SetBomb setter){
if (setter is PlayerConrol) {
++playerBombCount;
}
}
public Dictionary<string,float> computeScore(){
Dictionary<string,float> scoreMap = new Dictionary<string,float> ();
foreach (ScoreCount sc in playerScoreList) {
if (scoreMap.ContainsKey (sc.getName ())) {
float temp = scoreMap [sc.getName ()];
temp += sc.getValue ();
scoreMap [sc.getName ()] = temp;
} else {
scoreMap.Add (sc.getName(),sc.getValue());
}
}
return scoreMap;
}
public void rhythmSetting (string rhythm){
switch (level) {
case 1:
RhythmRecorder.instance.setProducer (new PersonRhythmProducer());
break;
case 2:
RhythmRecorder.instance.setProducer (new BasicRhythmProducer ());
break;
case 3:
RhythmRecorder.instance.setProducer (new BasicRhythmProducer ());
break;
case 4:
RhythmRecorder.instance.setProducer (new BasicRhythmProducer ());
break;
default:
break;
}
RhythmRecorder.instance.resetRhythm ();
RhythmRecorder.instance.setRhythm (rhythm);
RhythmRecorder.instance.startRhythm ();
}
public void levelSetting(){
GameObject[] enemys = GameObject.FindGameObjectsWithTag ("Enemy");
GameObject[] players = GameObject.FindGameObjectsWithTag ("Player");
switch (level) {
case 1:
for(int i = 0;i < players.GetLength(0);++i){
PlayerConrol player = players [i].GetComponent (typeof(PlayerConrol)) as PlayerConrol;
player.Blood = 100;
}
break;
case 2:
break;
case 3:
for (int i = 0; i < enemys.GetLength (0); ++i) {
EnemyBomber enemy = enemys [i].GetComponent (typeof(EnemyBomber)) as EnemyBomber;
enemy.Blood = 2 * enemy.Blood;
enemy.MaxNum = 9999;
}
break;
case 4:
for (int i = 0;i < enemys.GetLength (0); ++i) {
EnemyBomber enemy = enemys [i].GetComponent (typeof(EnemyBomber)) as EnemyBomber;
enemy.Blood = 10 * enemy.Blood;
enemy.MaxNum = 9999;
enemy.Speed += 1;
}
for(int i = 0;i < players.GetLength(0);++i){
PlayerConrol player = players [i].GetComponent (typeof(PlayerConrol)) as PlayerConrol;
player.Blood = 1;
}
canPlayerBuffed = false;
break;
default:
break;
}
}
public bool isBuffValid(System.Object gatherer){
if (gatherer is PlayerConrol) {
Debug.Log ("canPlayerBuffed:"+canPlayerBuffed);
return canPlayerBuffed;
}
return true;
}
public int PlayerBlood
{
get{ return playerBlood; }
set{ playerBlood = value; }
}
// Use this for initialization
void Awake(){
if (instance == null)
instance = this;
else if (instance != this)
Destroy (gameObject);
DontDestroyOnLoad (gameObject);
currentCanvas = null;
this.level = 3;
playerList = new ArrayList ();
enemyList = new ArrayList ();
}
void Start () {
}
// Update is called once per frame
void Update () {
if (GameState.playing == currState && playerList.Count <= 0 && gameVictoryClock) {
gameVictoryClock = false;
gameOver ();
}
if (GameState.playing == currState && enemyList.Count <= 0 && gameVictoryClock) {
gameVictoryClock = false;
gameVictory ();
}
}
public void changeGameState(GameState gameState){
switch (gameState) {
case GameState.start:
Destroy (currentCanvas);
currentCanvas = Instantiate (startCanvas) as GameObject;
AudioPlayer.instance.playBGM (0);
break;
case GameState.levelSelect:
Destroy (currentCanvas);
currentCanvas = Instantiate (levelSelectCanvas) as GameObject;
break;
case GameState.mapEdit:
Destroy (currentCanvas);
currentCanvas = Instantiate (mapEditCanvas) as GameObject;
break;
case GameState.playing:
Destroy (currentCanvas);
//coupling
GameDataProcessor.instance.gameObjects.Clear ();
currentCanvas = Instantiate (playingCanvas) as GameObject;
string[] rhythmList = { RhythmList.Rhythmortis, RhythmList.Tombtorial, RhythmList.WatchYourStep };
int index = UnityEngine.Random.Range (0, rhythmList.Length);
GameManager.instance.rhythmSetting (rhythmList [index]);
AudioPlayer.instance.playBGM (index % 3 + 1);
if (playMode == PlayMode.presetMap)
MapDataHelper.instance.loadMap (presetMap);
else if (playMode == PlayMode.customMap)
MapDataHelper.instance.loadMap (customMap);
this.resetGame ();
AudioPlayer.instance.playSFX (SFX.Start);
break;
case GameState.levelEnd:
Destroy (currentCanvas);
currentCanvas = Instantiate (levelEndCanvas) as GameObject;
MapDataHelper.instance.deleteMap ();
//AudioPlayer.instance.stopBGM ();
break;
case GameState.end:
Destroy (currentCanvas);
currentCanvas = Instantiate (endCanvas) as GameObject;
AudioPlayer.instance.playBGM (0);
EndCanvasAction action = currentCanvas.GetComponent<EndCanvasAction> ();
action.setScoreText (totalGameScore);
totalGameScore = 0;
break;
default:
break;
}
currState = gameState;
}
public void gameVictory(){
this.levelState = LevelState.win;
PlayingCanvasAction action = currentCanvas.GetComponent<PlayingCanvasAction> ();
AudioPlayer.instance.playSFX (SFX.Victory);
AudioPlayer.instance.playBGM (0);
action.showDialog ();
}
public void gameOver(){
this.levelState = LevelState.lose;
AudioPlayer.instance.playBGM (0);
PlayingCanvasAction action = currentCanvas.GetComponent<PlayingCanvasAction> ();
action.showDialog ();
}
public void resetGame(){
gameVictoryClock = true;
levelState = LevelState.lose;
GameDataProcessor.instance.resetGame ();
RhythmRecorder.instance.resetGame ();
enemyNumber = MapDataHelper.instance.getEnemyNumber ();
playerScoreList.Clear ();
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public enum MonsterState{MON_IDLE,MON_MOVE,MON_PURCHASE,MON_PRE_ATTACK,MON_ATTACK,MON_BACK};
public class MonsterControl : MonoBehaviour,Distroyable,Attackable,Locatable,MoveAble,ScoreCount
{
protected Locatable goal;
protected Position initialPos;
MonsterState lastState;
protected Position[] dirs;
Queue<Position> currPath = new Queue<Position>();
int blood = 30;
public int Blood
{
get{return blood;}
set{blood = value;}
}
public void attackBy(Attackable source){
this.blood -= source.Damage;
AudioPlayer.instance.playSFX (SFX.EnermyDamaged);
if (blood <= 0) {
if (source is BombFire && ((BombFire)source).Owner is PlayerConrol) {
AudioPlayer.instance.playSFX (SFX.EnermyKilled);
this.addToScore ();
}
}
}
public void distroy(){
Debug.Log ("Monster died");
this.currPath.Clear ();
GameDataProcessor.instance.removeObject (this);
RhythmRecorder.instance.removeObserver (this);
Destroy (this.gameObject, 0);
}
int damage = 20;
public int Damage
{
get{return damage;}
set{damage = value;}
}
public void attack(){
int dirIndx = getRandom (3);
int range = 2;
Position[] dirs = {new Position (this.position.x + 1, this.position.y), new Position (this.position.x - 1, this.position.y),
new Position (this.position.x, this.position.y + 1), new Position (this.position.x, this.position.y - 1)};
for (int i = 0; i < range; ++i) {
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (dirs [dirIndx]);
for(int indx = 0;indx < objs.Count;++indx){
if(objs[indx] is Distroyable){
((Distroyable)objs[indx]).attackBy (this);
}
}
dirIndx = (dirIndx + 1) % 4;
}
}
Position position;
public Position pos{
get{return position;}
set{position = value;}
}
int speed = 1;
public int Speed
{
get{return speed;}
set{speed = value;}
}
protected string gameName = "Monster";
protected float gameValue = 100f;
public string getName(){
return this.gameName;
}
public float getValue(){
return this.gameValue;
}
public void addToScore(){
GameManager.instance.addToPlayerScoreList (this);
}
protected int leastDistToPlayer(){
int dist = 9999;
GameObject[] players = GameObject.FindGameObjectsWithTag ("Player");
for (int i = 0; i < players.GetLength (0); ++i) {
Locatable local = (players [i].GetComponentInChildren (typeof(PlayerConrol)) as Locatable);
int tempDist = Mathf.Abs(local.pos.x - this.position.x)
+Mathf.Abs(local.pos.y - this.position.y);
if (tempDist < dist) {
dist = tempDist;
goal = local;
}
}
return dist;
}
protected int distToInitalPos(){
return Mathf.Abs(initialPos.x - this.position.x)
+Mathf.Abs(initialPos.y - this.position.y);
}
protected MonsterState think(){
if (GameManager.instance.level <= 2) {
return MonsterState.MON_IDLE;
}
int distance = leastDistToPlayer ();
int distInitial = distToInitalPos ();
if (distInitial >= 7) {
this.currPath.Clear ();
this.currPath = this.findPathTo (initialPos);
return MonsterState.MON_BACK;
}else{
if (this.lastState == MonsterState.MON_PRE_ATTACK) {
return MonsterState.MON_ATTACK;
}
if (distance <= 2) {
this.currPath.Clear();
this.currPath = this.findPathTo (goal.pos);
return MonsterState.MON_PRE_ATTACK;
}
if (distance <= 3 ) {
this.currPath.Clear();
this.currPath = this.findPathTo (goal.pos);
return MonsterState.MON_PURCHASE;
}
}
Position[] dirs = {new Position (this.position.x + 1, this.position.y), new Position (this.position.x, this.position.y - 1),
new Position (this.position.x - 1, this.position.y ), new Position (this.position.x, this.position.y + 1)};
int dirIndx = 0;
int ranCout = 0;
do {
dirIndx = getRandom (3);
ranCout++;
} while (isWall (dirs [dirIndx]) && ranCout < 100);
this.currPath.Clear ();
if (ranCout < 100) {
this.currPath.Enqueue (dirs [dirIndx]);
}
return MonsterState.MON_IDLE;
}
public void actionOnBeat (){
MonsterState result = think();
switch (result) {
case MonsterState.MON_IDLE:
MonsterIdle ();
break;
case MonsterState.MON_PRE_ATTACK:
MonsterPreAttack ();
break;
case MonsterState.MON_ATTACK:
MonsterAttack ();
break;
case MonsterState.MON_MOVE:
MonsterMove ();
break;
case MonsterState.MON_BACK:
MonsterBack ();
break;
case MonsterState.MON_PURCHASE:
MonsterPurchase ();
break;
}
lastState = result;
}
protected void MonsterIdle(){
MonsterMove ();
}
protected void MonsterMove(){
if (currPath.Count > 0) {
Position temp = currPath.Dequeue ();
StartCoroutine (MoveTo(temp));
this.position.x = temp.x;
this.position.y = temp.y;
// Debug.Log ("Move to ->("+temp.x+","+temp.y+")");
}
}
protected void MonsterPurchase(){
MonsterMove ();
}
protected void MonsterPreAttack(){
MonsterMove ();
Debug.Log ("Monster prepare to attack");
}
protected void MonsterAttack(){
this.attack ();
}
protected void MonsterBack(){
Debug.Log ("Monster back");
MonsterMove ();
}
private IEnumerator MoveTo(Position dest){
int frameCount = 5;
float deltaX = dest.x - this.position.x;
float deltaY = dest.y - this.position.y;
for (int i = 0; i < frameCount; ++i) {
this.transform.position += (deltaX / frameCount) * Vector3.right;
this.transform.position += (deltaY / frameCount) * Vector3.back;
yield return null;
}
}
//寻路算法
protected Queue<Position> findPathTo(Position dest){
Queue<Position> path = new Queue<Position> ();
int[,] floodMark = new int[GameDataProcessor.instance.mapSizeY,GameDataProcessor.instance.mapSizeX];
for (int i = 0; i < floodMark.GetLength (0); ++i) {
for (int j = 0; j < floodMark.GetLength (1); ++j) {
floodMark[i,j] = -1;
}
}
floodMark [this.pos.y, this.pos.x] = 0;
bool canReach = true;
markPathWFS(this.pos,dest,ref floodMark);
if (floodMark [dest.y, dest.x] < 0) {
canReach = false;
} else {
canReach = true;
}
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (dest);
for (int i = 0; i < objs.Count; ++i) {
if (objs [i] is NormalCube || objs [i] is WallCube) {
canReach = false;
break;
}
}
// canReach = !isWall(dest);
if (canReach) {
Stack<Position> pathStack = new Stack<Position>();
// pathStack.Push (dest);
this.createPath (dest, floodMark [dest.y, dest.x],ref floodMark, ref pathStack);
while(pathStack.Count > 0){
path.Enqueue(pathStack.Pop());
}
}
// Position[] arrPath = path.ToArray ();
return path;
}
protected void markPathWFS(Position source,Position dest,ref int[,] floodMark){
Queue<Position> queSearch = new Queue<Position>();
queSearch.Enqueue (source);
floodMark [source.y, source.x] = 0;
GameDataProcessor gdp = GameDataProcessor.instance;
while (queSearch.Count > 0) {
Position curr = queSearch.Dequeue ();
int pathLen = floodMark[curr.y,curr.x] + 1;
if (curr.y > 0 && curr.y < gdp.mapSizeY-1 && curr.x > 0 && curr.x < gdp.mapSizeX-1) {
if (floodMark [curr.y, curr.x + 1] < 0) {
Position temp = new Position (curr.x + 1, curr.y);
bool isHereWall = isWall (temp);
if (isHereWall) {
floodMark [curr.y, curr.x + 1] = 999999;
} else {
floodMark [curr.y, curr.x + 1] = pathLen;
queSearch.Enqueue (temp);
}
if (temp.x == dest.x && temp.y == dest.y) {
break;
}
}
if (floodMark [curr.y, curr.x - 1] < 0) {
Position temp = new Position (curr.x - 1, curr.y);
bool isHereWall = isWall (temp);
if (isHereWall) {
floodMark [curr.y, curr.x - 1] = 999999;
} else {
floodMark [curr.y, curr.x - 1] = pathLen;
queSearch.Enqueue (temp);
}
if (temp.x == dest.x && temp.y == dest.y) {
break;
}
}
if (floodMark [curr.y + 1, curr.x] < 0) {
Position temp = new Position (curr.x, curr.y + 1);
bool isHereWall = isWall (temp);
if (isHereWall) {
floodMark [curr.y + 1, curr.x] = 999999;
} else {
floodMark [curr.y + 1, curr.x] = pathLen;
queSearch.Enqueue (temp);
}
if (temp.x == dest.x && temp.y == dest.y) {
break;
}
}
if (floodMark [curr.y - 1, curr.x] < 0) {
Position temp = new Position (curr.x, curr.y - 1);
bool isHereWall = isWall (temp);
if (isHereWall) {
floodMark [curr.y - 1, curr.x] = 999999;
} else {
floodMark [curr.y - 1, curr.x] = pathLen;
queSearch.Enqueue (temp);
}
if (temp.x == dest.x && temp.y == dest.y) {
break;
}
}
}
}
}
protected bool isWall(Position position){
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (position);
for (int i = 0; i < objs.Count; ++i) {
if (objs [i] is NormalCube || objs [i] is WallCube) {
return true;
}
}
return false;
}
protected void createPath(Position target, int distance, ref int[,] floodMark, ref Stack<Position> pathStatck){
// Stack<Position> pathStatck = new Stack<Position>();
Position currSearchPos = new Position (target.x,target.y);
while (distance > 1) {
Position[] dirs = {new Position (currSearchPos.x + 1, currSearchPos.y), new Position (currSearchPos.x - 1, currSearchPos.y),
new Position (currSearchPos.x, currSearchPos.y + 1), new Position (currSearchPos.x, currSearchPos.y - 1)};
for (int i = 0; i < dirs.GetLength (0); ++i) {
if (floodMark[dirs [i].y, dirs [i].x] == distance-1) {
pathStatck.Push (dirs [i]);
currSearchPos.x = dirs [i].x;
currSearchPos.y = dirs [i].y;
break;
}
}
--distance;
}
}
private int getRandom(int count)
{
return new System.Random().Next(count);
}
// Use this for initialization
void Start ()
{
this.position = new Position(Mathf.RoundToInt(transform.localPosition.z),Mathf.RoundToInt(transform.localPosition.x));
this.initialPos = new Position(Mathf.RoundToInt(transform.localPosition.z),Mathf.RoundToInt(transform.localPosition.x));
GameDataProcessor.instance.addObject (this);
RhythmRecorder.instance.addObservedSubject (this);
}
// Update is called once per frame
void Update ()
{
if (blood <= 0) {
createBuff ();
this.distroy ();
}
}
void createBuff(){
string[] buffList = {"GetBombTriggle","GetBombPusher"};
int buffIndex=UnityEngine.Random.Range (0, buffList.Length);
GameObject buff = Resources.Load(buffList[buffIndex]) as GameObject;
GameObject obj = (GameObject)Instantiate(buff,this.gameObject.transform.position,this.gameObject.transform.rotation);
obj.transform.SetParent (MapDataHelper.instance.getMapModel().transform);
Buff script = (Buff)obj.GetComponent("Buff");
if (script == null) {
Debug.Log ("not script");
} else {
if (script is Locatable) {
// Debug.Log ("script is Locatable");
((Locatable)script).pos = new Position (this.pos.x,this.pos.y);
}
}
}
void OnDestroy(){
this.distroy ();
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class GetBombTriggle : BaseBuff
{
// Use this for initialization
void Start ()
{
RhythmRecorder.instance.addObservedSubject (this,0.1f);
GameDataProcessor.instance.addToBenefitMap (this);
transform.SetParent (MapDataHelper.instance.getMapModel().transform);
this.gameName = "Tool-Pusher";
this.gameValue = 100f;
}
// Update is called once per frame
void Update ()
{
if (!this.position.Equals(null)) {
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (this.position);
for (int i = 0; i < objs.Count; ++i) {
if (objs[i] is SetBomb) {
if(GameManager.instance.isBuffValid(objs[i]) && objs[i] is PlayerConrol){
//your effect;
BombTriggleTool triggle = new BombTriggleTool ((SetBomb)objs[i]);
((SetBomb)objs [i]).obtainTools (triggle);
((SetBomb)objs [i]).BombLifeTime = 10;
}
Debug.Log ("player get triggle");
lifeTime = 0;
if (objs [i] is PlayerConrol) {
AudioPlayer.instance.playSFX (SFX.Buff);
this.addToScore ();
}
}
}
} else {
Debug.Log ("buff positon is null!!!");
}
if (lifeTime <= 0) {
this.distroy ();
}
}
void distroy(){
RhythmRecorder.instance.removeObserver (this);
GameDataProcessor.instance.removeFromBenefitMap (this);
Destroy (this.gameObject, 0);
}
void OnDestroy(){
this.distroy ();
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class PlayerConrol : MonoBehaviour,Controlable,Locatable,SetBomb,Distroyable,CanBuffed,MoveAble
{
private int blood = 20;
public int Blood
{
get{return blood;}
set{blood = value;}
}
public void attackBy(Attackable source){
blood -= source.Damage;
AudioPlayer.instance.playSFX (SFX.PlayerDamaged);
}
public void distroy(){
GameDataProcessor.instance.removeObject (this);
RhythmRecorder.instance.removeFlagOwner (this);
GameManager.instance.removeFromPlayerList (this);
Destroy (this.gameObject, 0);
}
private bool canSetBomb = true;
private bool isGhost=false;
public bool IsGhost
{
get{return isGhost;}
set{isGhost = value;}
}
private int speed = 1;
public int Speed
{
get{return speed;}
set{speed = value;}
}
private int rhmFlag = 0;
public int rhythmFlag{
get{return rhmFlag;}
set{rhmFlag=value;}
}
// private int moveAbility = 1;
// public int MoveAbility{
// get{return moveAbility;}
// set{this.moveAbility = value;}
// }
private Position position;
public Position pos{
get{ return position; }
set{ position=value; }
}
//capacity of bomb at a timeobtainTools
private int maxNum;
public int MaxNum {
get{return this.maxNum;}
set{maxNum = value;}
}
//already used number of bomb
private int currNum;
public int CurrNum {
get{return this.currNum;}
set{currNum = value;}
}
private GameObject bombType;
public void setBomb(GameObject bombType){
this.bombType = bombType;
}
public void installBomb(){
if(currNum < maxNum){
currNum++;
// Debug.Log("player currNum:"+currNum);
if(bombType == null){
Debug.Log("not bomb");
}else{
GameObject go = (GameObject)Instantiate(this.bombType,this.gameObject.transform.position,this.gameObject.transform.rotation);
go.transform.SetParent (MapDataHelper.instance.getMapModel().transform);
Bomb script = (Bomb)go.GetComponent("Bomb");
if(script == null){
Debug.Log("not script");
}else{
// Debug.Log("find script interface Bomb");
//script.LifeTime = bomblifeTime;
//script.isActive = true;
// script.LifeTime = 3;
AudioPlayer.instance.playSFX(SFX.SetBomb);
script.setProperties(this,bombPower,bombLifeTime,bombFireTime);
this.registerBomb (script);
GameDataProcessor.instance.addToDangerMap (script);
}
}
}
}
private int bombPower = 2;
public int BombPower {
get{return bombPower; }
set{
bombPower = value;
// (this.bombType.GetComponent (typeof(Bomb)) as Bomb).Power = bombPower;
}
}
private int bombLifeTime = 3;
public int BombLifeTime {
get{return bombLifeTime; }
set{bombLifeTime = value; }
}
private int bombFireTime = 1;
public int BombFireTime {
get{return bombFireTime; }
set{
bombFireTime = value;
}
}
public void notifyExplosion (Bomb bomb){
if(currNum > 0){
currNum--;
}
bombList.Remove (bomb);
// Debug.Log ("Player notifyExplosion");
}
private int idleMovementPosition;
public GameObject m_ArmLeft;
public GameObject m_ArmRight;
enum moveDirection{
forward,back,left,right
};
private GameObject followCamera;
void Awake(){
rhmFlag = 0;
RhythmRecorder.instance.addRhythmFlagOwner (this);
GameManager.instance.addToPlayerList (this);
this.maxNum = 10;
this.currNum = 0;
this.bombLifeTime = 3;
this.bombPower = 1;
this.bombFireTime = 1;
this.canSetBomb = true;
this.isGhost = false;
this.blood = 20;
}
// Use this for initialization
void Start ()
{
// BombTriggleTool tool = new BombTriggleTool (this);
//// this.obtainTools (tool);
// this.obtainTools (tool);
// BombPushTool pushTool = new BombPushTool (this);
// this.obtainTools (pushTool);
this.position = new Position(Mathf.CeilToInt(transform.localPosition.z),Mathf.CeilToInt(transform.localPosition.x));
//Add follow camera to player
followCamera = GameObject.FindGameObjectWithTag("MainCamera");
// Debug.Log ("player position: x:"+transform.localPosition.z+",y:"+transform.localPosition.x);
// Debug.Log ("player: x:"+this.pos.x+",y:"+this.pos.y);
this.bombType = Resources.Load("TechBomb") as GameObject;
// GameDataProcessor.instance.addObject (this);
idleMovementPosition = 0;
// Debug.Log("PlayerControl Done..");
}
// Update is called once per frame
void Update () {
//this.position = new Position(Mathf.RoundToInt(transform.localPosition.z)+1,Mathf.RoundToInt(transform.localPosition.x)+1);
// Debug.Log ("Player:"+this.position.x+","+this.position.y);
control ();
GameManager.instance.PlayerBlood = this.blood;
if (blood <= 0) {
Debug.Log("you lose!!");
AudioPlayer.instance.playSFX (SFX.PlayerKilled);
distroy();
}
setFollowCamera ();
}
void setFollowCamera(){
if (followCamera != null) {
followCamera.transform.position = new Vector3(transform.position.x, followCamera.transform.position.y, transform.position.z);
}
}
public void control()
{
if (rhmFlag > 0) {
canSetBomb = true;
CheckMovement ();
}
if (Time.frameCount % 10==0) {
IdleMovement ();
}
}
public void actionOnBeat ()
{
}
//need to add move check to avoid walking out of the map
void CheckMovement()
{
if (Input.GetKeyDown (KeyCode.Space) && canSetBomb) {
// Debug.Log ("press down space");
installBomb ();
canSetBomb = false;
//rhmFlag = false;
}
// if (Input.GetKeyDown (KeyCode.Z)) {
// if (activeToolState == 1) {
// triggleAllBomb ();
// }
// if (activeToolState == 2) {
// }
// Debug.Log ("player uses tool");
// }
//check of using of bomb tools
for (int i = 0; i < playerTools.Count; ++i) {
if(playerTools[i] is BombTool){
BombTool currTool = playerTools [i] as BombTool;
if (Input.GetKeyDown (currTool.getKeyCode())) {
currTool.useToolBy (this);
// Debug.Log (currTool.getToolName());
}
}
}
if (Input.GetKeyDown ("up") || Input.GetKeyDown (KeyCode.W)) {
// Debug.Log("up..");
ArrayList frontalObjects=GameDataProcessor.instance.getBackObjects (this);
bool tempFlag = true;
foreach (Locatable l in frontalObjects) {
if (l is WallCube||l is NormalCube)
tempFlag = false;
}
if ((tempFlag||isGhost)&&this.position.y>0) {
StartCoroutine (Move (moveDirection.forward));
this.position.y -= 1;
}
--rhmFlag;
}
if (Input.GetKeyDown ("down") || Input.GetKeyDown (KeyCode.S)) {
// Debug.Log("down..");
ArrayList frontalObjects=GameDataProcessor.instance.getFrontalObjects (this);
bool tempFlag = true;
foreach (Locatable l in frontalObjects) {
if (l is WallCube||l is NormalCube)
tempFlag = false;
}
if ((tempFlag||isGhost)&&this.position.y<GameDataProcessor.instance.mapSizeY-1) {
StartCoroutine (Move (moveDirection.back));
this.position.y += 1;
}
--rhmFlag;
}
if (Input.GetKeyDown ("right") || Input.GetKeyDown (KeyCode.D)) {
// Debug.Log("right..");
ArrayList frontalObjects=GameDataProcessor.instance.getRightObjects (this);
bool tempFlag = true;
foreach (Locatable l in frontalObjects) {
if (l is WallCube||l is NormalCube)
tempFlag = false;
}
if ((tempFlag||isGhost)&&this.position.x<GameDataProcessor.instance.mapSizeX-1) {
StartCoroutine (Move (moveDirection.right));
this.position.x += 1;
}
--rhmFlag;
}
if (Input.GetKeyDown ("left") || Input.GetKeyDown (KeyCode.A)) {
// Debug.Log("left..");
ArrayList frontalObjects=GameDataProcessor.instance.getLeftObjects (this);
bool tempFlag = true;
foreach (Locatable l in frontalObjects) {
if (l is WallCube||l is NormalCube)
tempFlag = false;
}
if ((tempFlag||isGhost)&&this.position.x>0) {
StartCoroutine (Move (moveDirection.left));
this.position.x -= 1;
}
--rhmFlag;
}
}
IEnumerator Move(moveDirection dir)
{
for (int i = 0; i < 4; i++) {
if (i == 0||i == 1) {
transform.position += 0.5F*Vector3.up;
m_ArmLeft.transform.position += 0.5F*Vector3.up;
m_ArmRight.transform.position += 0.5F*Vector3.up;
}
else if (i == 2||i == 3) {
transform.position += 0.5F*Vector3.down;
m_ArmLeft.transform.position += 0.5F*Vector3.down;
m_ArmRight.transform.position += 0.5F*Vector3.down;
}
switch (dir) {
case moveDirection.forward:
transform.position += 0.25F*Vector3.forward;
//m_ArmLeft.transform.position += 0.25F*Vector3.forward;
//m_ArmRight.transform.position += 0.25F*Vector3.forward;
GameDataProcessor.instance.updatePosition(this,this.position);
break;
case moveDirection.back:
transform.position += 0.25F*Vector3.back;
//m_ArmLeft.transform.position += 0.25F*Vector3.back;
//m_ArmRight.transform.position += 0.25F*Vector3.back;
GameDataProcessor.instance.updatePosition(this,this.position);
break;
case moveDirection.right:
transform.position += 0.25F*Vector3.right;
//m_ArmLeft.transform.position += 0.25F*Vector3.right;
//m_ArmRight.transform.position += 0.25F*Vector3.right;
GameDataProcessor.instance.updatePosition(this,this.position);
break;
case moveDirection.left:
transform.position += 0.25F*Vector3.left;
//m_ArmLeft.transform.position += 0.25F*Vector3.left;
//m_ArmRight.transform.position += 0.25F*Vector3.left;
GameDataProcessor.instance.updatePosition(this,this.position);
break;
}
yield return null;
}
}
void IdleMovement() {
if (idleMovementPosition == 1) {
m_ArmLeft.transform.position += 0.3F*Vector3.down;
m_ArmRight.transform.position += 0.3F*Vector3.down;
idleMovementPosition = 0;
}
else if (idleMovementPosition == 0) {
m_ArmLeft.transform.position += 0.3F*Vector3.up;
m_ArmRight.transform.position += 0.3F*Vector3.up;
idleMovementPosition = 1;
}
}
private ArrayList bombList = new ArrayList();
public ArrayList playerTools = new ArrayList();
public void registerBomb (Bomb bomb){
bombList.Add (bomb);
}
public ArrayList getAllBomb(){
return bombList;
}
public bool obtainTools (BombTool tool){
// foreach(BombTool temp in playerTools){
// Debug.Log (temp.getToolName()+"has already existed");
// return false;
// }
for (int i = 0; i < playerTools.Count; ++i) {
if(playerTools[i].GetType() == tool.GetType()){
Debug.Log ("already own this tool");
return false;
}
}
playerTools.Add (tool);
return true;
}
void OnDestroy(){
this.distroy ();
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class NormalBomb :MonoBehaviour,Bomb,Distroyable,Locatable
{
private SetBomb owner = null;
public GameObject fire = null;
private int lifeTime = 2;
private int power = 5;
private Position position;
public Position pos{
get{ return position; }
set{ position=value; }
}
private bool isActive = true;
public bool IsActive{
get{ return isActive; }
set{ isActive=value; }
}
public int stepLenth = 1;
// public NormalBomb(GameObject owner,BombFire fire,int lifeTime){
// this.owner = owner;
// this.fire = fire;
// this.lifeTime = lifeTime;
// this.isActive = true;
// }
// public NormalBomb(GameObject owner,BombFire fire){
// NormalBomb (owner, fire, 5);
// }
// public NormalBomb(){
// NormalBomb (null, null, 0);
// }
// Use this for initialization
void Start ()
{
if (this.fire == null) {
this.fire = Resources.Load("firebase") as GameObject;
}
// Debug.Log ("NormalBomb :MonoBehaviour,Bomb,Distroyable,Locatable");
GameDataProcessor.instance.addObject (this);
RhythmRecorder.instance.addObservedSubject (this);
GameDataProcessor.instance.addToDangerMap (this);
}
// Update is called once per frame
void Update () {
if (lifeTime <= 0 && isActive) {
isActive = false;
this.createFire();
GameManager.instance.increaseBombCount(owner);
owner.notifyExplosion(this);
this.distroy();
}
}
public void setProperties(SetBomb owner,int power,int lifeTime,int fireTime){
this.owner = owner;
this.lifeTime = lifeTime;
this.power = power;
this.fireTime = fireTime;
if(this.owner is Locatable){
this.position = ((Locatable)this.owner).pos;
}
// Debug.Log ("NormalBomb:(x,y)="+this.position.x+","+this.position.y);
}
public SetBomb Owner {
get{return this.owner;}
set{this.owner = value;}
}
public GameObject Fire{
get{return this.fire;}
set{this.fire = value;}
}
public int LifeTime{
get{return lifeTime;}
set{lifeTime=value;}
}
private int fireTime = 1;
public int FireTime {
get;
set;
}
public int Blood
{
get{return lifeTime;}
set{lifeTime=value;}
}
public int Power
{
get {return power;}
set {power = value;}
}
public void attackBy(Attackable source){
// Debug.Log ( "Attackable source:"+((Locatable)source).pos.x +","+((Locatable)source).pos.y );
// Debug.Log("source is BombFire:"+source is BombFire);
// if (source is BombFire && isActive) {
//// Debug.Log ("attackBy()...");
// lifeTime = 0;
// this.createFire ();
// isActive = false;
// this.distroy ();
// }
lifeTime = 0;
// this.distroy ();
}
public void distroy(){
// this.createFire();
// GameManager.instance.increaseBombCount(owner);
// owner.notifyExplosion(this);
AudioPlayer.instance.playSFX(SFX.Explosion);
GameDataProcessor.instance.removeObject (this);
RhythmRecorder.instance.removeObserver (this);
Destroy(this.gameObject,0);
}
public void actionOnBeat(){
// Debug.Log ("lifeTime:" + lifeTime.ToString());
--lifeTime;
}
private void createFire(){
GameObject[] fires = new GameObject[power*4+1];
//(GameObject)Instantiate(fire,this.gameObject.transform.position,this.gameObject.transform.rotation);
Vector3 currPos = this.gameObject.transform.position;
fires[0] = (GameObject)Instantiate(fire,currPos,this.gameObject.transform.rotation);
NormalBombFire bfScript = (NormalBombFire)fires[0].GetComponent("NormalBombFire");
bfScript.setProperties (this.owner,fireTime);
bfScript.pos = new Position(this.position.x,this.position.y);
// Debug.Log ("x="+this.position.x+",y="+this.position.y);
Vector3 tempPos = currPos;
int tempX = this.position.x;
for(int i = 1;i < power+1;++i){
bool isCountinueCreate = true;
tempPos.x += stepLenth;
tempX += stepLenth;
if(tempX<0 || tempX >= GameDataProcessor.instance.mapSizeX){
break;
}
Position currPosition = new Position(tempX,this.position.y);
fires [i] = (GameObject)Instantiate (fire, tempPos, this.gameObject.transform.rotation);
bfScript = (NormalBombFire)fires [i].GetComponent ("NormalBombFire");
bfScript.setProperties (this.owner, fireTime);
bfScript.pos = currPosition;
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (currPosition);
foreach (Locatable l in objs) {
if (l is WallCube || l is NormalCube) {
isCountinueCreate = false;
}
}
// Debug.Log ("x="+tempX+",y="+this.position.y);
if (isCountinueCreate == false) {
break;
}
}
tempPos = currPos;
tempX = this.position.x;
for(int i = power+1;i < power*2+1;++i){
bool isCountinueCreate = true;
tempPos.x -= stepLenth;
tempX -= stepLenth;
if(tempX<0 || tempX >= GameDataProcessor.instance.mapSizeX){
break;
}
Position currPosition = new Position(tempX,this.position.y);
fires[i] = (GameObject)Instantiate(fire,tempPos,this.gameObject.transform.rotation);
bfScript = (NormalBombFire)fires[i].GetComponent("NormalBombFire");
bfScript.setProperties (this.owner,fireTime);
bfScript.pos = currPosition;
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (currPosition);
foreach (Locatable l in objs) {
if (l is WallCube || l is NormalCube) {
isCountinueCreate = false;
}
}
// Debug.Log ("x="+tempX+",y="+this.position.y);
if (isCountinueCreate == false) {
break;
}
}
tempPos = currPos;
int tempY = this.position.y;
for(int i = power*2+1;i < power*3+1;++i){
bool isCountinueCreate = true;
tempPos.z += stepLenth;
tempY -= stepLenth;
if(tempY<0 || tempY >= GameDataProcessor.instance.mapSizeY){
break;
}
Position currPosition = new Position(this.position.x,tempY);
fires[i] = (GameObject)Instantiate(fire,tempPos,this.gameObject.transform.rotation);
bfScript = (NormalBombFire)fires[i].GetComponent("NormalBombFire");
bfScript.setProperties (this.owner,fireTime);
bfScript.pos = currPosition;
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (currPosition);
foreach (Locatable l in objs) {
if (l is WallCube || l is NormalCube) {
isCountinueCreate = false;
}
}
// Debug.Log ("x="+this.position.x+",y="+tempY);
if (isCountinueCreate == false) {
break;
}
}
tempPos = currPos;
tempY = this.position.y;
for(int i = power*3+1;i < power*4+1;++i){
bool isCountinueCreate = true;
tempPos.z -= stepLenth;
tempY += stepLenth;
if(tempY<0 || tempY >= GameDataProcessor.instance.mapSizeY){
break;
}
Position currPosition = new Position(this.position.x,tempY);
fires[i] = (GameObject)Instantiate(fire,tempPos,this.gameObject.transform.rotation);
bfScript = (NormalBombFire)fires[i].GetComponent("NormalBombFire");
bfScript.setProperties (this.owner,fireTime);
bfScript.pos = currPosition;
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (currPosition);
foreach (Locatable l in objs) {
if (l is WallCube || l is NormalCube) {
isCountinueCreate = false;
}
}
// Debug.Log ("x="+this.position.x+",y="+tempY);
if (isCountinueCreate == false) {
break;
}
}
}
public void pushTo (Position finalPos){
float diffX = finalPos.x - this.position.x;
float diffY = finalPos.y - this.position.y;
StartCoroutine (MoveOffset(diffX,diffY));
this.position.x= finalPos.x;
this.position.y = finalPos.y;
}
IEnumerator MoveOffset(float diffX,float diffY){
int frameCount = 10;
for (int i = 0; i < frameCount; ++i) {
// this.transform.position +diffX / frameCount;
// this.transform.position.z -= diffY / frameCount;
this.transform.position += (diffX/frameCount)*Vector3.right;
this.transform.position += (diffY/frameCount)*Vector3.back;
yield return null;
}
}
void OnDestroy(){
this.distroy ();
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class MapDataEncoder{
//Represent MapData componet
public static int C_NORMAL_CUBE = 3;
public static int C_WALL_CUBE = 4;
public static int C_EMPTY = 0;
public static int C_PLAYER = 1;
public static int C_ENEMY = 2;
public static int C_MONSTER = 5;
public enum MapDataCodeEnum{
EMPTY = 0,
PLAYER = 1,
ENEMY = 2,
NORMAL_CUBE = 3,
WALL_CUBE = 4,
MONSTER = 5
};
}
<file_sep>using UnityEngine;
using System.Collections;
public class BombFireLifetimeUp : MonoBehaviour,Buff,Locatable,RhythmObservable,ScoreCount
{
private Position position;
public Position pos{
get{return position; }
set{position = value; }
}
private int lifeTime = 25;
public int LifeTime{
get{return lifeTime; }
set{lifeTime = value; }
}
public int buffValue = 50;
public int Value {
get{return buffValue; }
set{buffValue = value; }
}
private string gameName = "Buff-FireTimeUp";
private float gameValue = 10f;
public string getName(){
return this.gameName;
}
public float getValue(){
return this.gameValue;
}
public void addToScore(){
GameManager.instance.addToPlayerScoreList (this);
}
public void actionOnBeat (){
--lifeTime;
}
// Use this for initialization
void Start ()
{
RhythmRecorder.instance.addObservedSubject (this,0.1f);
GameDataProcessor.instance.addToBenefitMap (this);
// this.lifeTime = 200;
// this.buffValue = 5;
}
// Update is called once per frame
void Update ()
{
if (!this.position.Equals(null)) {
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (this.position);
for (int i = 0; i < objs.Count; ++i) {
if (objs[i] is SetBomb) {
if(GameManager.instance.isBuffValid(objs[i])){
((SetBomb)objs[i]).BombFireTime += 1;
}
Debug.Log ("player fireLifeTimeUp !");
lifeTime = 0;
if (objs [i] is PlayerConrol) {
AudioPlayer.instance.playSFX (SFX.Buff);
this.addToScore ();
}
}
}
} else {
Debug.Log ("buff positon is null!!!");
}
if (lifeTime <= 0) {
this.distroy ();
}
}
void distroy(){
RhythmRecorder.instance.removeObserver (this);
GameDataProcessor.instance.removeFromBenefitMap (this);
Destroy (this.gameObject, 0);
}
void OnDestroy(){
this.distroy ();
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.IO;
public class MapEditorHelper : MonoBehaviour {
public static Color TargetColor = new Color(255, 255, 255);
public static int MapDataCode{ get; set;}
static int playerNum = 1;
MapDataHelper.MapData mMapData;
public RectTransform MapGirdLayout;
public Color DefaultColor;
public GameObject DialogPanel;
string fileName = "";
public static bool checkCodeConstraint(int gridCode, bool editable){
if (!editable) {
return false;
}
if (MapDataCode == MapDataEncoder.C_PLAYER) {
if (playerNum != 0) {
playerNum--;
return true;
} else {
return false;
}
} else {
if (gridCode == MapDataEncoder.C_PLAYER) {
playerNum++;
}
return true;
}
}
void Awake(){
mMapData.row = 15;
mMapData.column = 15;
mMapData.data = new int[15, 15];
mMapData.isCreatable = false;
initMapGridCard ();
}
void getMapData(){
int row;
int column;
int num = 0;
foreach (RectTransform child in MapGirdLayout) {
column = num % 15;
row = num / 15;
// Debug.Log (child.gameObject.GetComponent<MapGirdCard> ().MapDataCode + child.name);
mMapData.data[row, column] = child.gameObject.GetComponent<MapGirdCard> ().MapDataCode;
num++;
}
}
void initMapGridCard(){
int row;
int column;
int num = 0;
foreach (RectTransform child in MapGirdLayout) {
column = num % 15;
row = num / 15;
if (row == 0 || row == 14 || column == 0 || column == 14) {
MapGirdCard card = child.GetComponent<MapGirdCard> ();
card.MapDataCode = MapDataEncoder.C_WALL_CUBE;
child.GetComponent<Image> ().color = DefaultColor;
card.Editable = false;
}
num++;
}
}
public void saveMapDatatoFile(){
if (fileName != "") {
getMapData ();
using (StreamWriter sw = new StreamWriter (Application.persistentDataPath + "/" + fileName + ".cmap")) {
sw.WriteLine (mMapData.row + "," + mMapData.column);
string s;
for (int r = 0; r < mMapData.row; r++) {
s = "";
for (int c = 0; c < mMapData.column; c++) {
if (c == 0)
s = s + mMapData.data [r, c];
else
s = s + "," + mMapData.data [r, c];
}
sw.WriteLine (s);
}
}
Debug.Log (Application.persistentDataPath);
fileName = "";
playerNum = 1;
}
}
public void showDialogPanel(){
InputField inputFiled = DialogPanel.GetComponentInChildren<InputField> ();
DialogPanel.SetActive (true);
if (inputFiled.text != "") {
inputFiled.ActivateInputField ();
}
}
public void hideDialogPanel(){
DialogPanel.SetActive (false);
fileName = "";
}
public void setSavedFileName(string name){
fileName = name;
}
public void exitMapEditor(){
playerNum = 1;
GameManager.instance.changeGameState (GameState.start);
}
}
<file_sep>using System;
using UnityEngine;
using System.Collections;
public class BombTriggleTool: BombTool,ScoreCount
{
private KeyCode code = KeyCode.Z;
private SetBomb owner;
private string toolName="BombTriggleTool";
private float gameValue = 50f;
public string getName(){
return "Tool-"+this.toolName;
}
public float getValue(){
return this.gameValue;
}
public void addToScore(){
// GameManager.instance.addToPlayerScoreList (this);
}
public BombTriggleTool (SetBomb owner)
{
this.owner = owner;
}
public string getToolName(){
return toolName;
}
public void useToolBy(SetBomb user){
ArrayList bombList = user.getAllBomb ();
for (int i = 0; i < bombList.Count; ++i) {
if (bombList [i] is Bomb) {
((Bomb)bombList [i]).LifeTime = 0;
}
}
bombList.Clear ();
}
public KeyCode getKeyCode (){
return code;
}
public SetBomb Owner {
get{ return owner;}
set{ this.owner = value;}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class BeatsIcon : MonoBehaviour,RhythmObservable {
// Use this for initialization
void Start () {
RhythmRecorder.instance.addObservedSubject (this,-0.1f);
}
// Update is called once per frame
void Update () {
}
public void actionOnBeat(){
StartCoroutine(BeatIt());
}
IEnumerator BeatIt()
{
for (int i = 0; i < 10; i++) {
if (i <4) {
this.GetComponent<RectTransform>().localScale += 0.1F * Vector3.one;
}
else if (i >5) {
this.GetComponent<RectTransform>().localScale -= 0.1F * Vector3.one;
}
yield return null;
}
}
void OnDestroy() {
RhythmRecorder.instance.removeObserver (this);
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class EndCanvasAction : MonoBehaviour {
public Button tryAgainButton;
public Text scoreText;
// Use this for initialization
void Start () {
tryAgainButton.onClick.AddListener (() => clickTryAgainButton ());
}
// Update is called once per frame
void Update () {
}
void clickTryAgainButton(){
GameManager.instance.changeGameState (GameState.start);
}
public void setScoreText(int score){
scoreText.text = "You Score: " + score;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class FixedRhythmTest : MonoBehaviour,RhythmObservable {
// Use this for initialization
void Start () {
RhythmRecorder.instance.addObservedSubject (this);
}
// Update is called once per frame
void Update () {
}
public void actionOnBeat(){
Debug.Log ("Fixed:" + Time.time);
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEditor;
[CustomEditor(typeof(MapDataHelper))]
public class MapUnityEditorHelper: Editor {
public override void OnInspectorGUI()
{
DrawDefaultInspector();
MapDataHelper helper = target as MapDataHelper;
if (GUILayout.Button("Create Map Model"))
{
helper.createMapModel();
}
if (GUILayout.Button("Delete Map Model"))
{
helper.deleteMap();
}
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class LevelSelectManager : MonoBehaviour {
public ListViewController CustomMapList;
public ListViewController PresetMapList;
public Toggle[] LevelToggles;
public int DifficulityLevel = 1;
private string[] presetMaps;
// Use this for initialization
void Start () {
PassStringEvent onCustomCLick = new PassStringEvent ();
PassStringEvent onPresetClick = new PassStringEvent ();
onCustomCLick.AddListener (startWithCustomMap);
onPresetClick.AddListener (startWithPresetMap);
CustomMapList.addListContents (MapDataHelper.instance.getCustomMapList(), onCustomCLick);
presetMaps = MapDataHelper.instance.getPresetMapList ();
PresetMapList.addListContents (presetMaps, onPresetClick);
DifficulityLevel = GameManager.instance.level;
initToggles ();
}
public void startWithPresetMap(string mapName){
GameManager.instance.playMode = PlayMode.presetMap;
GameManager.instance.presetMap = System.Array.IndexOf(presetMaps, mapName) + 1;
GameManager.instance.changeGameState (GameState.playing);
}
public void startWithCustomMap(string mapName){
GameManager.instance.playMode = PlayMode.customMap;
GameManager.instance.customMap = mapName;
GameManager.instance.changeGameState (GameState.playing);
}
public void backToMenu(){
GameManager.instance.changeGameState (GameState.start);
}
void initToggles(){
foreach (Toggle tg in LevelToggles) {
tg.isOn = false;
}
LevelToggles [DifficulityLevel - 1].isOn = true;
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class MapGirdCard : MonoBehaviour {
public int MapDataCode{ get; set;}
public bool Editable = true;
public void setGridColor(){
if (MapEditorHelper.checkCodeConstraint (MapDataCode, Editable)) {
Debug.Log ("set color in grid"+MapEditorHelper.TargetColor);
GetComponent<Image> ().color = MapEditorHelper.TargetColor;
MapDataCode = MapEditorHelper.MapDataCode;
}
}
}
<file_sep>using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public enum EnemyState{EMEMY_IDLE,EMEMY_WALK,EMEMY_SETBOMB,EMEMY_AVOID};
public class EnemyBomber : MonoBehaviour,Distroyable,SetBomb,Locatable,CanBuffed,MoveAble,ScoreCount
{
int speed = 1;
public int Speed
{
get{return speed; }
set{speed = value; }
}
private bool rhmFlag;
private int blood = 50;
private int maxNum;
private int currNum;
private Position position;
private string gameName = "EnemyBomber";
private float gameValue = 100f;
public string getName(){
return this.gameName;
}
public float getValue(){
return this.gameValue;
}
public void addToScore(){
GameManager.instance.addToPlayerScoreList (this);
}
public Position pos{
get{ return position;}
set{ position=value;}
}
void Awake(){
this.bombType = Resources.Load("NormalBomb") as GameObject;
RhythmRecorder.instance.addObservedSubject (this);
this.position = new Position(Mathf.RoundToInt(transform.localPosition.z),Mathf.RoundToInt(transform.localPosition.x));
GameDataProcessor.instance.addObject (this);
GameManager.instance.addToEnemyList (this);
// Debug.Log ("enemy pos:x="+position.x+",y="+position.y);
this.maxNum = 3;
this.currNum = 0;
this.bombLifeTime = 3;
this.bombPower = 2;
this.bombFireTime = 1;
this.blood = 50;
this.currPath = new Queue<Position>();
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
// control ();
// if (mapInitClock && GameDataProcessor.isInitialized()) {
// decisionMap = new int[GameDataProcessor.mapSizeY, GameDataProcessor.mapSizeX];
// mapInitClock = false;
// }
if (blood <= 0) {
this.distroy();
}
}
public bool rhythmFlag{
get{ return rhmFlag;}
set{ rhmFlag = value;}
}
public int Blood
{
get{return blood; }
set{blood = value; }
}
public void attackBy(Attackable source){
Debug.Log ("AI was attacked by"+source.ToString());
this.blood -= source.Damage;
AudioPlayer.instance.playSFX (SFX.EnermyDamaged);
if (blood <= 0) {
if (source is BombFire && ((BombFire)source).Owner is PlayerConrol) {
AudioPlayer.instance.playSFX (SFX.EnermyKilled);
this.addToScore ();
}
}
}
public void distroy(){
GameManager.instance.removeFromEnemyList (this);
GameDataProcessor.instance.removeObject (this);
RhythmRecorder.instance.removeObserver (this);
Destroy (this.gameObject, 0);
}
public int MaxNum {
get{return maxNum;}
set{maxNum = value;}
}
//already used number of bomb
public int CurrNum {
get{return currNum;}
set{currNum = value;}
}
private int bombPower = 4;
public int BombPower {
get{return bombPower; }
set{
bombPower = value;
(this.bombType.GetComponent (typeof(Bomb)) as Bomb).Power = bombPower;
}
}
private int bombLifeTime = 5;
public int BombLifeTime {
get{return bombLifeTime; }
set{bombLifeTime = value; }
}
private int bombFireTime = 1;
public int BombFireTime {
get{return bombFireTime; }
set{bombFireTime = value; }
}
public void notifyExplosion (Bomb bomb){
if(currNum > 0){
currNum--;
}
bombList.Remove (bomb);
// Debug.Log ("AI notifyExplosion");
}
private GameObject bombType;
public void setBomb(GameObject bombType){
this.bombType = bombType;
}
public void installBomb(){
if(currNum < maxNum){
currNum++;
if(bombType == null){
// Debug.Log("not bomb");
}else{
GameObject go = (GameObject)Instantiate(this.bombType,this.gameObject.transform.position,this.gameObject.transform.rotation);
go.transform.SetParent (MapDataHelper.instance.getMapModel().transform);
Bomb script = (Bomb)go.GetComponent("Bomb");
if(script == null){
// Debug.Log("not script");
}else{
// Debug.Log("find script interface Bomb");
//script.LifeTime = bomblifeTime;
//script.isActive = true;
// script.LifeTime = 3;
script.setProperties(this,bombPower,bombLifeTime,bombFireTime);
GameDataProcessor.instance.addToDangerMap (script);
}
}
}
}
// *************** AI control ***************
// private int[,] decisionMap = null;
// private bool mapInitClock = true;
Queue<Position> currPath;
EnemyState lastState;
private int getRandom(int count)
{
return new System.Random().Next(count);
}
public void actionOnBeat (){
EnemyState result = enemyThink();
switch (result) {
case EnemyState.EMEMY_AVOID:
walkAction ();
break;
case EnemyState.EMEMY_IDLE:
idleAction ();
break;
case EnemyState.EMEMY_WALK:
walkAction ();
break;
case EnemyState.EMEMY_SETBOMB:
setBombAction ();
break;
}
lastState = result;
}
private EnemyState enemyThink(){
if (isNowSafe ()) {
ArrayList decisionMap = computDecisionMap ();
//run before initialization of gamedataprocessor.dangermap;
if (decisionMap == null) {
return EnemyState.EMEMY_IDLE;
}
int indx = getRandom (3);
if (currPath == null || currPath.Count <= 0) {
MyPair pair = decisionMap [indx] as MyPair;
Position dest = new Position (pair.px, pair.py);
// Debug.Log ("0...dest:" + dest.x + "," + dest.y);
this.currPath = findPathTo (dest);
// Debug.Log ("walk to dest and think again!");
return EnemyState.EMEMY_WALK;
}
indx = getRandom (30);
// Debug.Log ("random indx:"+indx);
if (indx < 3 && decisionMap.Count > indx) {
MyPair pair = decisionMap [indx] as MyPair;
Position dest = new Position (pair.px, pair.py);
// Debug.Log ("1...:" + dest.x + "," + dest.y);
this.currPath = findPathTo (dest);
// Debug.Log ("EMEMY_WALK");
return EnemyState.EMEMY_WALK;
} else if (indx < 5) {
// Debug.Log ("EMEMY_IDLE");
return EnemyState.EMEMY_IDLE;
} else if (indx < 10 + bombOffset() && lastState != EnemyState.EMEMY_IDLE) {
// Debug.Log ("EMEMY_SETBOMB");
return EnemyState.EMEMY_SETBOMB;
}
// Debug.Log ("EMEMY_WALK");
return EnemyState.EMEMY_WALK;
} else {
// Debug.Log ("Unsafe!!");
// currPath.Clear ();
Queue<Position> queTemp = new Queue<Position> ();
int[,] dangerMap = GameDataProcessor.instance.dangerMap;
int maxX = GameDataProcessor.instance.mapSizeX;
int maxY = GameDataProcessor.instance.mapSizeY;
if (!isWall (new Position (this.pos.x + 1, this.pos.y)) && this.pos.x < maxX-1 &&
(dangerMap [this.pos.y, this.pos.x + 1] >= 2 || dangerMap [this.pos.y, this.pos.x + 1] == -1)) {
queTemp.Enqueue (new Position (this.pos.x + 1, this.pos.y));
queTemp.Enqueue (new Position (this.pos.x + 1, this.pos.y));
// currPath.Enqueue (new Position (this.pos.x + 1, this.pos.y));
// Debug.Log ("to right:");
} else if (!isWall (new Position (this.pos.x - 1, this.pos.y)) && this.pos.x >= 1 &&
(dangerMap [this.pos.y, this.pos.x - 1] >= 2 || dangerMap [this.pos.y, this.pos.x - 1] == -1)) {
queTemp.Enqueue (new Position (this.pos.x - 1, this.pos.y));
queTemp.Enqueue (new Position (this.pos.x - 1, this.pos.y));
// Debug.Log ("to left:");
} else if (!isWall (new Position (this.pos.x, this.pos.y + 1)) && this.pos.y < maxY-1 &&
(dangerMap [this.pos.y + 1, this.pos.x] >= 2 || dangerMap [this.pos.y + 1, this.pos.x] == -1)) {
queTemp.Enqueue (new Position (this.pos.x, this.pos.y + 1));
queTemp.Enqueue (new Position (this.pos.x, this.pos.y + 1));
// Debug.Log ("to down:");
} else if (!isWall (new Position (this.pos.x, this.pos.y - 1)) && this.pos.y >= 1 &&
(dangerMap [this.pos.y - 1, this.pos.x] >= 2 || dangerMap [this.pos.y - 1, this.pos.x] == -1)) {
queTemp.Enqueue (new Position (this.pos.x, this.pos.y - 1));
queTemp.Enqueue (new Position (this.pos.x, this.pos.y - 1));
// Debug.Log ("to up:");
} else {
// Debug.Log ("to random:");
currPath.Clear ();
if (!isWall (new Position (this.pos.x + 1, this.pos.y)) && this.pos.x < maxX-1) {
currPath.Enqueue (new Position (this.pos.x + 1, this.pos.y));
currPath.Enqueue (new Position (this.pos.x + 1, this.pos.y));
} else if (!isWall (new Position (this.pos.x - 1, this.pos.y)) && this.pos.x >= 1) {
currPath.Enqueue (new Position (this.pos.x - 1, this.pos.y));
currPath.Enqueue (new Position (this.pos.x - 1, this.pos.y));
} else if (!isWall (new Position (this.pos.x, this.pos.y + 1)) && this.pos.y < maxY-1) {
currPath.Enqueue (new Position (this.pos.x, this.pos.y + 1));
currPath.Enqueue (new Position (this.pos.x, this.pos.y + 1));
} else if (!isWall (new Position (this.pos.x, this.pos.y - 1)) && this.pos.y >= 1) {
currPath.Enqueue (new Position (this.pos.x, this.pos.y - 1));
currPath.Enqueue (new Position (this.pos.x, this.pos.y - 1));
}
return EnemyState.EMEMY_AVOID;
}
queTemp.Enqueue (new Position(this.pos.x,this.pos.y));
while(currPath.Count > 0){
queTemp.Enqueue (currPath.Dequeue ());
}
while (queTemp.Count > 0) {
currPath.Enqueue (queTemp.Dequeue ());
}
// Debug.Log ("EnemyState.EMEMY_AVOID:"+EnemyState.EMEMY_AVOID);
return EnemyState.EMEMY_AVOID;
}
//************** test code *****
// bool canGetPath = false;
// if (canGetPath) {
//// MyPair pair = decisionMap [indx] as MyPair;
// Position dest = new Position (1, 1);
// Debug.Log ("0...dest:" + dest.x + "," + dest.y);
// this.currPath = findPathTo (dest);
// // Debug.Log ("walk to dest and think again!");
// }
// return EnemyState.EMEMY_WALK;
//************** test end *****
}
private int bombOffset(){
int offset = 0;
Position[] dirs = {new Position(this.pos.x+1,this.pos.y),
new Position(this.pos.x-1,this.pos.y),
new Position(this.pos.x,this.pos.y+1),
new Position(this.pos.x,this.pos.y-1)};
for (int i = 0; i < dirs.GetLength (0); ++i) {
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (dirs[i]);
for (int j = 0; j < objs.Count; ++j) {
if (objs [j] is NormalCube) {
offset += 3;
break;
}
if (objs [j] is SetBomb) {
offset += 6;
}
}
}
if (currNum > 0) {
offset -= 2;
}
if (lastState == EnemyState.EMEMY_AVOID) {
offset -= 5;
}
return offset;
}
private bool isWall(Position position){
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (position);
for (int i = 0; i < objs.Count; ++i) {
if (objs [i] is NormalCube || objs [i] is WallCube) {
return true;
}
}
return false;
}
private bool isNowSafe(){
int p = this.getRandom (20);
if (p < 18) {
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (this.pos);
for (int i = 0; i < objs.Count; ++i) {
if (objs [i] is BombFire) {
// Debug.Log ("safe: BombFire");
return false;
}
}
int[,] dangerMap = GameDataProcessor.instance.dangerMap;
if (dangerMap [this.pos.y, this.pos.x] < 2 && dangerMap [this.pos.y, this.pos.x] >= 0) {
// Debug.Log ("safe: danger");
return false;
}
return true;
} else {
// Debug.Log ("ignore safety");
return true;
}
}
private void idleAction(){
// Debug.Log("Enemy idle");
this.currPath.Clear();
}
private void walkAction(){
// Debug.Log("Enemy walk");
if (currPath != null && currPath.Count > 0) {
for (int count = 0;count < speed && currPath.Count > 0;++count) {
Position temp = currPath.Dequeue ();
// Debug.Log("->("+temp.x+","+temp.y+")");
float deltaX = ((float)(temp.y - this.pos.y) / 4f);
float deltaY = ((float)(temp.x - this.pos.x) / 4f);
// Debug.Log ("move to y:"+((float)(temp.y - this.pos.y))/4f);
// Debug.Log ("move to x:"+((float)(temp.x - this.pos.x))/4f);
StartCoroutine (enemyMove (deltaX, deltaY));
this.pos = temp;
}
}
}
private void setBombAction(){
// Debug.Log("Enemy setBomb");
installBomb ();
walkAction ();
}
// private void avoidAction(){
// if (currPath != null && currPath.Count > 0) {
// Position temp = currPath.Dequeue ();
// Debug.Log("->("+temp.x+","+temp.y+")");
// this.transform.position += (temp.y - this.pos.y) * Vector3.back;
// this.transform.position += (temp.x - this.pos.x) * Vector3.right;
// this.pos = temp;
// Debug.Log ("position: " + this.transform.position + " ");
// }
// }
private IEnumerator enemyMove(float deltaX,float deltaY){
for (int i = 0; i < 4; ++i) {
this.transform.position += deltaX * Vector3.back;
this.transform.position += deltaY * Vector3.right;
// Debug.Log ("move to y:"+((float)(direction.y - this.pos.y)/4f));
// Debug.Log ("move to x:"+((float)(direction.x - this.pos.x)/4f));
yield return null;
}
}
//寻路算法
private Queue<Position> findPathTo(Position dest){
Queue<Position> path = new Queue<Position> ();
int[,] floodMark = new int[GameDataProcessor.instance.mapSizeY,GameDataProcessor.instance.mapSizeX];
for (int i = 0; i < floodMark.GetLength (0); ++i) {
for (int j = 0; j < floodMark.GetLength (1); ++j) {
floodMark[i,j] = -1;
}
}
floodMark [this.pos.y, this.pos.x] = 0;
// bool isReachDest = false;
// bool canReach = markPath (this.pos,dest,1,ref floodMark,ref isReachDest);
bool canReach = true;
markPathWFS(this.pos,dest,ref floodMark);
if (floodMark [dest.y, dest.x] < 0) {
canReach = false;
} else {
canReach = true;
}
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (dest);
for (int i = 0; i < objs.Count; ++i) {
if (objs [i] is NormalCube || objs [i] is WallCube) {
canReach = false;
break;
}
}
// canReach = !isWall(dest);
if (canReach) {
Stack<Position> pathStack = new Stack<Position>();
pathStack.Push (dest);
this.createPath (dest, floodMark [dest.y, dest.x],ref floodMark, ref pathStack);
while(pathStack.Count > 0){
path.Enqueue(pathStack.Pop());
}
}
// Position[] arrPath = path.ToArray ();
return path;
}
// private bool markPath (Position lastPos,Position target,int pathDistance,ref int[,] floodMark,ref bool isReachDest){
// if (lastPos.x == target.x && lastPos.y == target.y) {
//// floodMark [lastPos.y, lastPos.x]
// isReachDest = true;
// return true;
// }
//
// ArrayList objs;
// Position curr = new Position(lastPos.x+1,lastPos.y);
// bool rightAccess = true;
// if (floodMark [curr.y, curr.x] != -1) {
// rightAccess = false;
// } else {
// objs = GameDataProcessor.instance.getObjectAtPostion(curr);
// for (int i = 0; i < objs.Count; ++i) {
// if (objs [i] is NormalCube || objs [i] is WallCube) {
// floodMark [curr.y, curr.x] = 999999;
// rightAccess = false;
// break;
// }
// }
// }
// if (rightAccess) {
// floodMark [curr.y, curr.x] = pathDistance;
// }
//
// curr = new Position(lastPos.x-1,lastPos.y);
// bool leftAccess = true;
// if (floodMark [curr.y, curr.x] != -1) {
// leftAccess = false;
// } else {
// objs = GameDataProcessor.instance.getObjectAtPostion (curr);
// for (int i = 0; i < objs.Count; ++i) {
// if (objs [i] is NormalCube || objs [i] is WallCube) {
// floodMark [curr.y, curr.x] = 999999;
// leftAccess = false;
// break;
// }
// }
// }
// if (leftAccess) {
// floodMark [curr.y, curr.x] = pathDistance;
// }
//
// curr = new Position(lastPos.x,lastPos.y+1);
// bool downAccess = true;
// if (floodMark [curr.y, curr.x] != -1) {
// downAccess = false;
// } else {
// objs = GameDataProcessor.instance.getObjectAtPostion (curr);
// for (int i = 0; i < objs.Count; ++i) {
// if (objs [i] is NormalCube || objs [i] is WallCube) {
// floodMark [curr.y, curr.x] = 999999;
// downAccess = false;
// break;
// }
// }
// }
// if (downAccess) {
// floodMark [curr.y, curr.x] = pathDistance;
// }
//
// curr = new Position(lastPos.x,lastPos.y-1);
// bool upAccess = true;
// if (floodMark [curr.y, curr.x] != -1) {
// upAccess = false;
// } else {
// objs = GameDataProcessor.instance.getObjectAtPostion (curr);
// for (int i = 0; i < objs.Count; ++i) {
// if (objs [i] is NormalCube || objs [i] is WallCube) {
// floodMark [curr.y, curr.x] = 999999;
// upAccess = false;
// break;
// }
// }
// }
// if (upAccess) {
// floodMark [curr.y, curr.x] = pathDistance;
// }
//
// if (rightAccess) {
// curr = new Position (lastPos.x + 1, lastPos.y);
// rightAccess = markPath (curr, target, pathDistance + 1, ref floodMark, ref isReachDest);
// if (isReachDest) {
// return true;
// }
// }
// if (leftAccess) {
// curr = new Position (lastPos.x - 1, lastPos.y);
// leftAccess = markPath (curr, target, pathDistance + 1, ref floodMark, ref isReachDest);
// if (isReachDest) {
// return true;
// }
// }
// if (downAccess) {
// curr = new Position (lastPos.x, lastPos.y + 1);
// downAccess = markPath (curr, target, pathDistance + 1, ref floodMark, ref isReachDest);
// if (isReachDest) {
// return true;
// }
// }
// if (upAccess) {
// curr = new Position (lastPos.x, lastPos.y - 1);
// upAccess = markPath (curr, target, pathDistance + 1, ref floodMark, ref isReachDest);
// if (isReachDest) {
// return true;
// }
// }
// return upAccess || rightAccess || downAccess || upAccess;
// }
private void markPathWFS(Position source,Position dest,ref int[,] floodMark){
Queue<Position> queSearch = new Queue<Position>();
queSearch.Enqueue (source);
floodMark [source.y, source.x] = 0;
GameDataProcessor gdp = GameDataProcessor.instance;
while (queSearch.Count > 0) {
Position curr = queSearch.Dequeue ();
int pathLen = floodMark[curr.y,curr.x] + 1;
if (curr.y > 0 && curr.y < gdp.mapSizeY-1 && curr.x > 0 && curr.x < gdp.mapSizeX-1) {
if (floodMark [curr.y, curr.x + 1] < 0) {
Position temp = new Position (curr.x + 1, curr.y);
bool isHereWall = isWall (temp);
if (isHereWall) {
floodMark [curr.y, curr.x + 1] = 999999;
} else {
floodMark [curr.y, curr.x + 1] = pathLen;
queSearch.Enqueue (temp);
}
if (temp.x == dest.x && temp.y == dest.y) {
break;
}
}
if (floodMark [curr.y, curr.x - 1] < 0) {
Position temp = new Position (curr.x - 1, curr.y);
bool isHereWall = isWall (temp);
if (isHereWall) {
floodMark [curr.y, curr.x - 1] = 999999;
} else {
floodMark [curr.y, curr.x - 1] = pathLen;
queSearch.Enqueue (temp);
}
if (temp.x == dest.x && temp.y == dest.y) {
break;
}
}
if (floodMark [curr.y + 1, curr.x] < 0) {
Position temp = new Position (curr.x, curr.y + 1);
bool isHereWall = isWall (temp);
if (isHereWall) {
floodMark [curr.y + 1, curr.x] = 999999;
} else {
floodMark [curr.y + 1, curr.x] = pathLen;
queSearch.Enqueue (temp);
}
if (temp.x == dest.x && temp.y == dest.y) {
break;
}
}
if (floodMark [curr.y - 1, curr.x] < 0) {
Position temp = new Position (curr.x, curr.y - 1);
bool isHereWall = isWall (temp);
if (isHereWall) {
floodMark [curr.y - 1, curr.x] = 999999;
} else {
floodMark [curr.y - 1, curr.x] = pathLen;
queSearch.Enqueue (temp);
}
if (temp.x == dest.x && temp.y == dest.y) {
break;
}
}
}
}
}
private void createPath(Position target, int distance, ref int[,] floodMark, ref Stack<Position> pathStatck){
// Stack<Position> pathStatck = new Stack<Position>();
if (distance == 1) {
return;
}
int[,] dangerMap = GameDataProcessor.instance.dangerMap;
int maxX = GameDataProcessor.instance.mapSizeX;
int maxY = GameDataProcessor.instance.mapSizeY;
// Debug.Log ("right:"+this.pos.y + "," + (this.pos.x + 1));
// Debug.Log ("left:"+this.pos.y + "," + (this.pos.x - 1));
// Debug.Log ("down:"+(this.pos.y+1) + "," + (this.pos.x ));
// Debug.Log ("up:"+(this.pos.y-1) + "," + (this.pos.x));
//in danger of explosion
bool isRightSafe = (target.x + 1 < maxX) ? !(dangerMap [target.y, target.x + 1] == distance) : false;
bool isLeftSafe = (target.x - 1 >= 0) ? !(dangerMap [target.y, target.x-1] == distance):false;
bool isDownSafe = (target.y + 1 < maxY) ? !(dangerMap [target.y+1, target.x] == distance):false;
bool isUpSafe = (target.y - 1 >= 0) ? !(dangerMap [target.y-1, target.x] == distance):false;
if (isRightSafe && floodMark [target.y, target.x + 1] == distance - 1) {
Position temp = new Position (target.x + 1, target.y);
pathStatck.Push (temp);
createPath (temp, distance - 1, ref floodMark, ref pathStatck);
} else if (isLeftSafe && floodMark [target.y, target.x - 1] == distance - 1) {
Position temp = new Position (target.x - 1, target.y);
pathStatck.Push (temp);
createPath (temp, distance - 1, ref floodMark, ref pathStatck);
} else if (isDownSafe && floodMark [target.y + 1, target.x] == distance - 1) {
Position temp = new Position (target.x, target.y + 1);
pathStatck.Push (temp);
createPath (temp, distance - 1, ref floodMark, ref pathStatck);
} else if (isUpSafe && floodMark [target.y - 1, target.x] == distance - 1) {
Position temp = new Position (target.x, target.y - 1);
pathStatck.Push (temp);
createPath (temp, distance - 1, ref floodMark, ref pathStatck);
} else {
//everywhere is no safe
return;
}
// Queue<Position> path = new Queue<Position> ();
// while(pathStatck.Count > 0){
// path.Enqueue(pathStatck.Pop());
// }
// return pathStatck;
}
private ArrayList computDecisionMap(){
ArrayList topValuePlace = new ArrayList();
int[,] dangerMap = GameDataProcessor.instance.dangerMap;
float[,] benefitMap = GameDataProcessor.instance.benefitMap;
if (dangerMap == null || benefitMap == null) {
return null;
}
for (int i = 0; i < dangerMap.GetLength (0); ++i) {
for (int j = 0; j < dangerMap.GetLength (1); ++j) {
float value = 0;
if (dangerMap [i, j] == -1) {
value = 15 + benefitMap[i,j]*2 + distanceBenefit(j,i);
} else {
value = dangerMap [i, j] + benefitMap[i,j]*2 + distanceBenefit(j,i);
}
topValuePlace.Add (new MyPair (j, i, value));
}
}
topValuePlace.Sort ();
return topValuePlace;
}
private float distanceBenefit(int x,int y){
float outDist = 10 - Math.Abs(this.pos.x-x)-Math.Abs(this.pos.y-y);
float inDist = 2 - Math.Abs (this.pos.x - x) - Math.Abs (this.pos.y - y);
return (outDist > 0&& inDist < 0) ? getRandom(10) : 0;
}
public class MyPair:IComparable{
public float value;
public int px;
public int py;
public MyPair(int x,int y,float value){
this.px = x;
this.py = y;
this.value = value;
}
public int CompareTo(object obj)
{
if (obj is MyPair) {
MyPair other = obj as MyPair;
return this.value > other.value ? -1 : 1;
} else {
return 0;
}
}
}
ArrayList bombList = new ArrayList();
public void registerBomb (Bomb bomb){
bombList.Add (bomb);
}
public void triggleAllBomb(){
for (int i = 0; i < bombList.Count; ++i) {
if (bombList [i] is Bomb) {
((Bomb)bombList [i]).LifeTime = 0;
}
}
bombList.Clear ();
}
public void obtainBombTriggle(){
}
public void obtainBombPush(){
}
public ArrayList getAllBomb(){
return null;
}
public bool obtainTools (BombTool tool){
return false;
}
void OnDestroy(){
this.distroy ();
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class DifficultyLevelSelectController : MonoBehaviour {
public int level;
public void DifficultyLevelSelect(bool isSelect){
if (isSelect) {
GameManager.instance.level = this.level;
}
}
}
<file_sep>using System.IO;
using UnityEngine;
using System.Collections;
public interface RhythmObservable{
void actionOnBeat ();
}
public interface RhythmFlagOwner{
int rhythmFlag{ get; set;}
}
public class RhythmRecorder: MonoBehaviour{
public static RhythmRecorder instance = null;
protected BasicRhythmProducer producer;
// protected string currentRhythm;
//
// protected float startTime;
// protected ArrayList beats;
// protected bool isPlaying;
// protected float onBeatThreshold=0.1f;
//
// protected ArrayList currentBeatIndice;
// protected ArrayList observedSubjects;
// protected ArrayList timeOffsets;
// protected int standardBeatIndex;
//
// protected ArrayList rhythmFlagOwners;
// protected ArrayList isFlagsChangable;
void Awake()
{
// if (instance == null)
// instance = this;
// else if (instance != this)
// Destroy (gameObject);
//
// DontDestroyOnLoad (gameObject);
//
//
// currentRhythm = RhythmList.Default;
//
// startTime = 0;
// beats = new ArrayList ();
// isPlaying = false;
// currentBeatIndice=new ArrayList ();
// observedSubjects = new ArrayList ();
// timeOffsets = new ArrayList ();
// standardBeatIndex = 0;
// rhythmFlagOwners = new ArrayList ();
// isFlagsChangable = new ArrayList ();
//************
if (instance == null)
instance = this;
else if (instance != this)
Destroy (gameObject);
DontDestroyOnLoad (gameObject);
producer = new BasicRhythmProducer ();
// producer = new PersonRhythmProducer();
}
void Start(){
}
public void setProducer(BasicRhythmProducer producer){
if (producer.GetType () != this.producer.GetType ()) {
this.producer = producer;
}
}
public void removeAllObservedSubjects(){
// producer.observedSubjects.Clear ();
// producer.currentBeatIndice.Clear ();
// producer.timeOffsets.Clear ();
producer.removeAllObservedSubjects();
}
public void addObservedSubject(RhythmObservable newSubject, float timeOffset=0.2f){
producer.addObservedSubject (newSubject,timeOffset);
// newSubject.actionOnBeat ();
}
public void removeAllRhythmFlagOwners(){
// producer.rhythmFlagOwners.Clear ();
// producer.isFlagsChangable.Clear ();
producer.removeAllRhythmFlagOwners();
}
public void addRhythmFlagOwner(RhythmFlagOwner newOwner){
// producer.rhythmFlagOwners.Add (newOwner);
// producer.isFlagsChangable.Add (true);
producer.addRhythmFlagOwner(newOwner);
}
public void removeObserver(RhythmObservable subject){
// int tempIndex = producer.observedSubjects.IndexOf (subject);
// if (tempIndex == -1)
// return;
// producer.currentBeatIndice.RemoveAt (tempIndex);
// producer.timeOffsets.RemoveAt (tempIndex);
// producer.observedSubjects.Remove (subject);
producer.removeObserver(subject);
}
public void removeFlagOwner(RhythmFlagOwner owner){
// int indx = producer.rhythmFlagOwners.IndexOf (owner);
// if (indx == -1)
// return;
// producer.isFlagsChangable.RemoveAt (indx);
// producer.rhythmFlagOwners.Remove (owner);
producer.removeFlagOwner (owner);
}
/*private void notifyAllObservedSubjects(){
int count = observedSubjects.Count;
for (int i = 0; i < count; i++) {
RhythmObservable subject = (RhythmObservable)observedSubjects [i];
subject.actionOnBeat ();
}
}*/
public bool setRhythm(string newRhythm){
// currentRhythm = newRhythm;
// resetRhythm ();
//
// if (!File.Exists (currentRhythm)) {
// return false;
// }
//
// string text = File.ReadAllText(currentRhythm);
// string[] sArray=text.Split(' ') ;
//
// beats = new ArrayList ();
// foreach (string i in sArray) {
// beats.Add (float.Parse (i));
// }
// return true;
return producer.setRhythm(newRhythm);
}
public bool startRhythm()
{
// if (isPlaying)
// return false;
//
// startTime = Time.time;
// isPlaying = true;
// standardBeatIndex = 0;
//
// return true;
return producer.startRhythm();
}
public void resetRhythm(){
// startTime = 0;
// isPlaying = false;
// standardBeatIndex = 0;
producer.resetRhythm();
}
void Update(){
producer.updateFlagInOwners ();
producer.notifyObserver ();
}
// protected bool isOnBeat()
// {
// if (isFinished()||!isPlaying)
// return false;
// float currentStandardBeat = (float)beats [standardBeatIndex];
// return System.Math.Abs (currentStandardBeat - (Time.time - startTime)) < onBeatThreshold;//0.2
// }
//
// protected void updateFlagInOwners(){
// if (isOnBeat ()) {
// for (int i = 0; i < rhythmFlagOwners.Count; i++) {
// if ((bool)isFlagsChangable [i]) {
// RhythmFlagOwner owner = (RhythmFlagOwner)rhythmFlagOwners [i];
// if (owner is MoveAble) {
// owner.rhythmFlag = ((MoveAble)owner).Speed;
// } else {
// owner.rhythmFlag = 1;
// }
// isFlagsChangable [i] = false;
// }
// }
// }
// else {
// for (int i = 0; i < rhythmFlagOwners.Count; i++) {
// RhythmFlagOwner owner = (RhythmFlagOwner)rhythmFlagOwners [i];
// owner.rhythmFlag = 0;
// }
// }
// }
//
// protected void notifyObserver(){
// if (isPlaying&&!isFinished()) {
// // Debug.Log ("random:" + GameDataProcessor.instance.getRandom (6));
// for (int i = 0; i < observedSubjects.Count; i++) {
// int tempBeatIndex = (int)currentBeatIndice [i];
// if (tempBeatIndex < beats.Count) {
// float currentBeat = (float)beats [tempBeatIndex];
// if ((Time.time - startTime) - currentBeat > (float)timeOffsets [i]) {
// ((RhythmObservable)observedSubjects [i]).actionOnBeat ();
// currentBeatIndice [i] = tempBeatIndex + 1;
// }
// }
// }
//
// float currentStandardBeat = (float)beats [standardBeatIndex];
// if ((Time.time - startTime) - currentStandardBeat > onBeatThreshold) {
//
// // Debug.Log("OnBeats");
// standardBeatIndex++;
// for (int i = 0; i < isFlagsChangable.Count; i++) {
// isFlagsChangable [i] = true;
// }
// }
// }
// }
//
// public bool isFinished(){
// return standardBeatIndex >= beats.Count;
// }
// public ArrayList getPlayersPosition(){
// ArrayList result = new ArrayList ();
// for (int i = 0; i < rhythmFlagOwners.Count; ++i) {
// if (rhythmFlagOwners [i] is Controlable && rhythmFlagOwners [i] is Locatable) {
// result.Add (rhythmFlagOwners [i]);
// }
// }
//
// return result;
// }
// public void testPrint()
// {
// Debug.Log (beats);
// }
public void resetGame(){
producer.resetGame ();
}
}<file_sep>using UnityEngine;
using System.Collections;
using System.IO;
public class MapDataHelper : MonoBehaviour {
public TextAsset[] LEVEL_MAP_DATA;
public GameObject NORMAL_CUBE;
public GameObject WALL_CUBE;
public GameObject PLANE;
public GameObject PLAYER;
public GameObject ENEMY;
public GameObject[] Objects;
private int enemyCount = 0;
public int getEnemyNumber(){
return enemyCount;
}
[HideInInspector]
public static MapDataHelper instance = null;
public struct MapData
{
public int row;
public int column;
public int[,] data;
public bool isCreatable;
};
private MapData mMapData;
private GameObject mMapModel;
public GameObject getMapModel(){
return mMapModel;
}
void Awake()
{
if (instance == null)
instance = this;
else if (instance != this)
Destroy (gameObject);
DontDestroyOnLoad (gameObject);
mMapData.isCreatable = false;
}
public void setMapData(MapData mapData){
this.mMapData = mapData;
}
public void loadMap(int levelNum){
deleteMap ();
enemyCount = 0;
loadFromAsset (LEVEL_MAP_DATA[levelNum-1]);
createMap ();
}
public void loadMap(string fileName){
deleteMap ();
enemyCount = 0;
loadFromFile (fileName);
createMap ();
}
public string[] getCustomMapList(){
string filter = "*.cmap";
string[] maps = Directory.GetFiles(Application.persistentDataPath, filter);
for (int i = 0, len = maps.Length; i < len; i++) {
maps [i] = Path.GetFileName (maps[i]);
}
return maps;
}
public string[] getPresetMapList(){
string[] maps = new string[LEVEL_MAP_DATA.Length];
for (int i = 0, len = maps.Length; i < len; i++) {
maps [i] = "Preset Map " + (i+1);
}
return maps;
}
void loadFromAsset(TextAsset textAsset)
{
if (textAsset != null)
{
string txtMapData = textAsset.text;
// Split to lines
string[] lines = txtMapData.Split(new char[] { '\r', '\n' }, System.StringSplitOptions.RemoveEmptyEntries);
// Split with ','
char[] spliter = new char[1] { ',' };
// Get row and length from first line
string[] sizewh = lines[0].Split(spliter, System.StringSplitOptions.RemoveEmptyEntries);
mMapData.row = int.Parse(sizewh[0]);
mMapData.column = int.Parse(sizewh[1]);
int[,] mapdata = new int[mMapData.row, mMapData.column];
for (int lineNum = 1; lineNum <= mMapData.row; lineNum++)
{
string[] data = lines[lineNum].Split(spliter, System.StringSplitOptions.RemoveEmptyEntries);
for (int col = 0; col < mMapData.column; col++)
{
mapdata[lineNum-1, col] = int.Parse(data[col]);
}
}
mMapData.data = mapdata;
mMapData.isCreatable = true;
}
else
{
mMapData.isCreatable = false;
Debug.LogWarning("Map data asset is null");
}
}
void loadFromFile(string fileName){
if (fileName != "")
{
string[] lines = File.ReadAllLines(Application.persistentDataPath+"/"+fileName);
// Split with ','
char[] spliter = new char[1] { ',' };
// Get row and length from first line
string[] sizewh = lines[0].Split(spliter, System.StringSplitOptions.RemoveEmptyEntries);
mMapData.row = int.Parse(sizewh[0]);
mMapData.column = int.Parse(sizewh[1]);
int[,] mapdata = new int[mMapData.row, mMapData.column];
for (int lineNum = 1; lineNum <= mMapData.row; lineNum++)
{
string[] data = lines[lineNum].Split(spliter, System.StringSplitOptions.RemoveEmptyEntries);
for (int col = 0; col < mMapData.column; col++)
{
mapdata[lineNum-1, col] = int.Parse(data[col]);
}
}
mMapData.data = mapdata;
mMapData.isCreatable = true;
}
else
{
mMapData.isCreatable = false;
Debug.LogWarning("Map data asset is null");
}
}
void createMap()
{
//GameManager.instance.rhythmSetting ();
if (mMapData.isCreatable)
{
if (mMapModel == null)
{
mMapModel = new GameObject("MapModel");
mMapModel.transform.position = new Vector3(0, 0, 0);
//Assign mapSize to GameDataProcessor
if (GameDataProcessor.instance != null)
{
//Debug.Log(mMapData.row + ", " + mMapData.column);
GameDataProcessor.instance.mapSizeX = mMapData.row;
GameDataProcessor.instance.mapSizeY = mMapData.column;
}
for (int x = 0; x < mMapData.row; x++)
{
for (int z = 0; z < mMapData.column; z++)
{
createMapComponent(mMapData.data[x, z], new Vector3(x, 0.5f, z));
}
}
//Rotate map to fix x, z axis, but player will be rotated too
mMapModel.transform.Rotate(0, 90, 0);
}
else
{
Debug.LogWarning("Map had been created. Please delete Map first.");
}
}
else
{
Debug.LogWarning("Map can't be created. Please load MapData first.");
}
//add game level info here
GameManager.instance.levelSetting ();
}
void createMapComponent(int componetChar, Vector3 position)
{
GameObject mapComponent;
switch (componetChar)
{
case (int)MapDataEncoder.MapDataCodeEnum.EMPTY:
break;
case (int)MapDataEncoder.MapDataCodeEnum.NORMAL_CUBE:
mapComponent = (GameObject)Instantiate (Objects[3], position, Quaternion.identity);
mapComponent.transform.parent = mMapModel.transform;
GameDataProcessor.instance.addObject (mapComponent.GetComponent<NormalCube>());
break;
case (int)MapDataEncoder.MapDataCodeEnum.WALL_CUBE:
mapComponent = (GameObject)Instantiate (Objects[4], position, Quaternion.identity);
mapComponent.transform.parent = mMapModel.transform;
GameDataProcessor.instance.addObject (mapComponent.GetComponent<WallCube>());
break;
case (int)MapDataEncoder.MapDataCodeEnum.PLAYER:
mapComponent = (GameObject)Instantiate (Objects[1], position, Quaternion.identity);
mapComponent.transform.parent = mMapModel.transform;
mapComponent.transform.Rotate (0, -90, 0);
GameDataProcessor.instance.addObject (mapComponent.GetComponentInChildren<PlayerConrol> ());
mapComponent.tag = "Player";
break;
case (int)MapDataEncoder.MapDataCodeEnum.ENEMY:
mapComponent = (GameObject)Instantiate (Objects [2], position, Quaternion.identity);
mapComponent.transform.parent = mMapModel.transform;
mapComponent.transform.Rotate (0, -90, 0);
mapComponent.tag = "Enemy";
++enemyCount;
//leave blank
break;
case (int)MapDataEncoder.MapDataCodeEnum.MONSTER:
mapComponent = (GameObject)Instantiate (Objects[5], position, Quaternion.identity);
mapComponent.transform.parent = mMapModel.transform;
mapComponent.transform.Rotate (0, -90, 0);
mapComponent.tag = "Monster";
break;
default:
break;
}
position.y = 0f;
mapComponent = (GameObject)Instantiate(PLANE, position, Quaternion.identity);
mapComponent.transform.parent = mMapModel.transform;
}
public void createMapModel()
{
loadMap (1);
// loadMap("ss.txt");
}
public void deleteMap()
{
if (mMapModel != null) {
Destroy (mMapModel,0);
mMapModel = null;
}
}
}
<file_sep>using System;
using UnityEngine;
using System.Collections;
public class BombPushTool: BombTool,ScoreCount
{
private KeyCode code = KeyCode.X;
private SetBomb owner;
private string toolName="BombPushTool";
// private string gameName = "Tool-BombPushTool";
private float gameValue = 50f;
public string getName(){
return "Tool-"+this.toolName;
}
public float getValue(){
return this.gameValue;
}
public void addToScore(){
// GameManager.instance.addToPlayerScoreList (this);
}
public BombPushTool (SetBomb owner)
{
this.owner = owner;
}
public string getToolName(){
return toolName;
}
public void useToolBy(SetBomb user){
// ArrayList bombList = owner.getAllBomb ();
// for (int i = 0; i < bombList.Count; ++i) {
// if (bombList [i] is Bomb) {
// ((Bomb)bombList [i]).LifeTime = 0;
// }
// }
// bombList.Clear ();
if (user is Locatable) {
Position userPos = (user as Locatable).pos;
Position[] dirs = {new Position (userPos.x+1,userPos.y),new Position (userPos.x-1,userPos.y),
new Position (userPos.x,userPos.y+1),new Position (userPos.x,userPos.y-1) };
for (int i = 0; i < dirs.GetLength (0); ++i) {
ArrayList objs = GameDataProcessor.instance.getObjectAtPostion (dirs[i]);
for (int j = 0; j < objs.Count; ++j) {
if (objs [j] is Bomb && objs [j] is Locatable) {
Locatable bomb = objs [j] as Locatable;
Position finalPos = new Position(bomb.pos.x,bomb.pos.y);
int deltaX = bomb.pos.x - userPos.x;
int deltaY = bomb.pos.y - userPos.y;
bool isFinalPosition = false;
while (!isFinalPosition) {
finalPos.x += deltaX;
finalPos.y += deltaY;
ArrayList obstacles = GameDataProcessor.instance.getObjectAtPostion (finalPos);
foreach (Locatable obs in obstacles) {
finalPos = new Position (obs.pos.x, obs.pos.y);
isFinalPosition = true;
break;
}
}
((Bomb)bomb).pushTo (new Position(finalPos.x-deltaX,finalPos.y-deltaY));
}
}
}
}
Debug.Log("Push bomb......");
}
public KeyCode getKeyCode (){
return code;
}
public SetBomb Owner {
get{ return owner;}
set{ this.owner = value;}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ListViewController : MonoBehaviour {
public GameObject ListView;
public GameObject ListContentPrefab;
public void addListContents(string[] contents, PassStringEvent onClick){
GameObject listContent;
foreach (string content in contents) {
listContent = (GameObject)Instantiate (ListContentPrefab);
listContent.GetComponentInChildren<Text> ().text = content;
listContent.GetComponent<ListContentController> ().OnClick = onClick;
listContent.transform.SetParent(ListView.transform, false);
}
}
public void addListContents(string[] contents){
GameObject listContent;
foreach (string content in contents) {
listContent = (GameObject)Instantiate (ListContentPrefab);
listContent.GetComponentInChildren<Text> ().text = content;
listContent.transform.SetParent(ListView.transform, false);
}
}
public void deleteAllListContents(){
for(int i = 0;i<ListView.transform.childCount;i++)
{
GameObject go = ListView.transform.GetChild(i).gameObject;
Destroy(go);
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class StartCanvasAction : MonoBehaviour {
public Button playButton;
public Button editMapButton;
public Button exitButton;
// Use this for initialization
void Start () {
playButton.onClick.AddListener (() => clickPlayButton ());
editMapButton.onClick.AddListener (clickEditMapButton);
exitButton.onClick.AddListener (clickExitButton);
}
// Update is called once per frame
void Update () {
}
void clickPlayButton(){
//GameManager.instance.changeGameState (GameState.playing);
GameManager.instance.changeGameState (GameState.levelSelect);
}
void clickEditMapButton(){
GameManager.instance.changeGameState (GameState.mapEdit);
}
void clickExitButton(){
Application.Quit ();
}
}
<file_sep>using System;
public interface MoveAble
{
int Speed
{
get;
set;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public struct Position{
public int _x; //left-bottom tp right-top, from 0 to mapSize-1
public int _y;
public Position(int newX,int newY){
_x = newX;
_y = newY;
}
public int x
{
get{ return _x; }
set{ _x = value; }
}
public int y
{
get{ return _y; }
set{ _y = value; }
}
}
public interface Locatable{
Position pos{ get; set;}
}
public class Test:Locatable{
private Position _pos;
public Position pos
{
get{return _pos;}
set{_pos=value;}
}
}
public class GameDataProcessor : MonoBehaviour,RhythmObservable {
public static GameDataProcessor instance = null;
public int mapSizeX;
public int mapSizeY;
public ArrayList gameObjects;
// Use this for initialization
public int[,] dangerMap = null; //for ai
public float[,] benefitMap = null; //for ai
private bool mapInitClock = true;
void Awake()
{
if (instance == null)
instance = this;
else if (instance != this)
Destroy (gameObject);
DontDestroyOnLoad (gameObject);
gameObjects = new ArrayList ();
}
void Start () {
// Locatable test1 = new Test ();
// test1.pos = new Position (2, 3);
// Locatable test2 = new Test ();
// test2.pos = new Position (2, 4);
// GameDataProcessor.instance.addObject (test1);
// GameDataProcessor.instance.addObject (test2);
// Debug.Log(GameDataProcessor.instance.getFrontalObjects (test1, 1).Count);
// Debug.Log (GameDataProcessor.instance.getFrontalObjects (test1, 1)[0].GetType());
RhythmRecorder.instance.addObservedSubject(this);
// initizeMap ();
// Debug.Log ("mapSizeX:"+mapSizeX+",mapSizeY:"+mapSizeY);
}
// Update is called once per frame
void Update () {
// if (mapInitClock && mapSizeX*mapSizeY != 0 ) {
// dangerMap = new int[mapSizeX, mapSizeY];
// benefitMap = new float[mapSizeX, mapSizeY];
// initizeMap ();
// mapInitClock = false;
// int temp = mapSizeX;
// mapSizeX = mapSizeY;
// mapSizeY = temp;
// }
}
public void resetGame(){
dangerMap = new int[mapSizeX, mapSizeY];
benefitMap = new float[mapSizeX, mapSizeY];
initizeMap ();
int temp = mapSizeX;
mapSizeX = mapSizeY;
mapSizeY = temp;
}
public bool isInitialized(){
return (!mapInitClock);
}
public bool addObject(Locatable item){
// if (item.pos.x < 0 || item.pos.x >= mapSizeX || item.pos.y < 0 || item.pos.y >= mapSizeY)
// return false;
gameObjects.Add (item);
return true;
}
public void removeObject(Locatable item){
gameObjects.Remove (item);
}
public void clearObjects(){
gameObjects.Clear ();
}
public bool updatePosition(Locatable target, Position pos){
if (gameObjects.IndexOf (target) == -1)
return false;
if (pos.x < 0 || pos.x >= mapSizeX || pos.y < 0 || pos.y >= mapSizeY)
return false;
target.pos = pos;
return true;
}
public ArrayList getFrontalObjects(Locatable item,int range=1){
if (gameObjects.IndexOf (item) == -1)
return null;
int itemY = item.pos.y;
int itemX = item.pos.x;
ArrayList result = new ArrayList ();
for (int i = 0; i < gameObjects.Count; i++) {
Locatable temp = (Locatable) gameObjects [i];
if (temp.pos.x == itemX && temp.pos.y > itemY && temp.pos.y <= itemY + range) {
result.Add (temp);
}
}
return result;
}
public ArrayList getBackObjects(Locatable item,int range=1){
if (gameObjects.IndexOf (item) == -1)
return null;
int itemY = item.pos.y;
int itemX = item.pos.x;
ArrayList result = new ArrayList ();
for (int i = 0; i < gameObjects.Count; i++) {
Locatable temp = (Locatable) gameObjects [i];
if (temp.pos.x == itemX && temp.pos.y < itemY && temp.pos.y >= itemY - range) {
result.Add (temp);
}
}
return result;
}
public ArrayList getRightObjects(Locatable item,int range=1){
if (gameObjects.IndexOf (item) == -1)
return null;
int itemY = item.pos.y;
int itemX = item.pos.x;
ArrayList result = new ArrayList ();
for (int i = 0; i < gameObjects.Count; i++) {
Locatable temp = (Locatable) gameObjects [i];
if (temp.pos.y == itemY && temp.pos.x > itemX && temp.pos.x <= itemX + range) {
result.Add (temp);
}
}
return result;
}
public ArrayList getLeftObjects(Locatable item,int range=1){
if (gameObjects.IndexOf (item) == -1)
return null;
int itemY = item.pos.y;
int itemX = item.pos.x;
ArrayList result = new ArrayList ();
for (int i = 0; i < gameObjects.Count; i++) {
Locatable temp = (Locatable) gameObjects [i];
if (temp.pos.y == itemY && temp.pos.x < itemX && temp.pos.x >= itemX - range) {
result.Add (temp);
}
}
return result;
}
public ArrayList getObjectsAtTheSamePosition(Locatable item){
if (gameObjects.IndexOf (item) == -1)
return null;
int itemY = item.pos.y;
int itemX = item.pos.x;
ArrayList result = new ArrayList ();
for (int i = 0; i < gameObjects.Count; i++) {
Locatable temp = (Locatable) gameObjects [i];
if (temp.pos.y == itemY && temp.pos.x == itemX) {
result.Add (temp);
}
}
return result;
}
public void actionOnBeat (){
// int ran = this.getRandom (10);
// Debug.Log ("random:"+ran);
if (this.getRandom (10) == 0) {
// Debug.Log ("refresh danger map");
refreshDangerMap ();
}
if (this.getRandom(15) == 0){
// Debug.Log ("refresh benefit map!!!");
refreshBenefitMap ();
}
updateDangerMap ();
updateBenefitMap ();
}
public void refreshDangerMap(){
if (dangerMap != null) {
for (int i = 0; i < dangerMap.GetLength (0); ++i) {
for (int j = 0; j < dangerMap.GetLength (1); ++j) {
dangerMap [i, j] = -1;
}
}
}
}
public void initizeMap(){
for (int i = 0; i < dangerMap.GetLength (0); ++i) {
for (int j = 0; j < dangerMap.GetLength (1); ++j) {
dangerMap [i,j] = -1;
}
}
for (int i = 0; i < benefitMap.GetLength (0); ++i) {
for (int j = 0; j < benefitMap.GetLength (1); ++j) {
benefitMap [i,j] = 0f;
}
}
}
public ArrayList getObjectAtPostion(Position pos){
int itemY = pos.y;
int itemX = pos.x;
ArrayList result = new ArrayList ();
for (int i = 0; i < gameObjects.Count; i++) {
Locatable temp = (Locatable) gameObjects [i];
if (temp.pos.y == itemY && temp.pos.x == itemX) {
result.Add (temp);
}
}
return result;
}
private void refreshDangerMap(Position pos,int dangerValue){
if (pos.x>=0 && pos.x<mapSizeX && pos.y>=0 && pos.y<mapSizeY &&
dangerMap [pos.y, pos.x] != -1 && dangerMap [pos.y, pos.x] > dangerValue) {
dangerMap [pos.y, pos.x] = dangerValue;
ArrayList objs = getObjectAtPostion (pos);
if (objs != null) {
for (int indx = 0; indx < objs.Count; ++indx) {
if (objs [indx] is Bomb) {
Bomb bomb = (Bomb)objs [indx];
for (int i = pos.x - bomb.Power; i < pos.x + bomb.Power + 1; ++i) {
if (i >= 0 && i < this.mapSizeX && dangerMap [pos.y, i] > dangerValue) {
dangerMap [pos.y, i] = dangerValue;
}
refreshDangerMap (new Position (i, pos.y), dangerValue);
}
for (int j = pos.y - bomb.Power; j < pos.y + bomb.Power + 1; ++j) {
if (j >= 0 && j < this.mapSizeY && dangerMap [j, pos.x] > dangerValue) {
dangerMap [j, pos.x] = dangerValue;
}
refreshDangerMap (new Position (pos.x, j), dangerValue);
}
}
}
}
}
}
public void addToDangerMap(Bomb bomb){
if(bomb is Locatable){
Position pos = ((Locatable)bomb).pos;
if (dangerMap [pos.y, pos.x] == -1) {
dangerMap [pos.y, pos.x] = bomb.LifeTime;
for (int i = pos.x - bomb.Power; i < pos.x + bomb.Power + 1; ++i) {
if (i >= 0 && i < this.mapSizeX && dangerMap [pos.y, i] == -1) {
dangerMap [pos.y, i] = bomb.LifeTime;
}
Position currPosition = new Position (i, pos.y);
refreshDangerMap (currPosition, bomb.LifeTime);
}
for (int j = pos.y - bomb.Power; j < pos.y + bomb.Power + 1; ++j) {
if (j >= 0 && j < this.mapSizeY && dangerMap [j, pos.x] == -1) {
dangerMap [j, pos.x] = bomb.LifeTime;
}
refreshDangerMap (new Position (pos.x, j), bomb.LifeTime);
}
} else {
if (dangerMap [pos.y, pos.x] <= bomb.LifeTime) {
for (int i = pos.x - bomb.Power; i < pos.x + bomb.Power + 1; ++i) {
if (i >= 0 && i < this.mapSizeX && (dangerMap [pos.y, i] == -1 || dangerMap [pos.y, i] > dangerMap [pos.y, pos.x])) {
dangerMap [pos.y, i] = dangerMap [pos.y, pos.x];
}
}
for (int j = pos.y - bomb.Power; j < pos.y + bomb.Power + 1; ++j) {
if (j >= 0 && j < this.mapSizeY && (dangerMap [j, pos.x] == -1 || dangerMap [j, pos.x] > dangerMap [pos.y, pos.x])) {
dangerMap [j, pos.x] = dangerMap [pos.y, pos.x];
}
}
}
refreshDangerMap (pos, bomb.LifeTime);
}
}
}
public void updateDangerMap(){
if (dangerMap != null) {
for (int i = 0; i < dangerMap.GetLength (0); ++i) {
for (int j = 0; j < dangerMap.GetLength (1); ++j) {
if (dangerMap [i, j] > 0) {
--dangerMap [i, j];
}
}
}
}
}
public void removeFromDangerMap(BombFire fire){
if(fire is Locatable){
Position pos = ((Locatable)fire).pos;
dangerMap [pos.y, pos.x] = -1;
}
}
public void addToBenefitMap(Buff buff){
if (buff is Locatable) {
int x = ((Locatable)buff).pos.x;
int y = ((Locatable)buff).pos.y;
this.benefitMap [y,x] += (float)buff.Value;
}
}
public void removeFromBenefitMap(Buff buff){
if (buff is Locatable) {
int x = ((Locatable)buff).pos.x;
int y = ((Locatable)buff).pos.y;
float value = this.benefitMap [y,x] - buff.Value;
if (value > 0) {
this.benefitMap [y,x] = value;
} else {
this.benefitMap [y,x] = 0f;
}
}
}
public void refreshBenefitMap(){
if (benefitMap != null) {
for (int i = 0; i < benefitMap.GetLength (0); ++i) {
for (int j = 0; j < benefitMap.GetLength (1); ++j) {
if (benefitMap [i, j] >= 5) {
benefitMap [i, j] = 0f;
}
}
}
}
}
//for benefitMap's value of player position
private void updatePlayerValue(){
// ArrayList positions = RhythmRecorder.instance.getPlayersPosition ();
ArrayList positions = GameManager.instance.playerList;
for (int i = 0; i < positions.Count; ++i) {
if (positions [i] is Locatable) {
Position pos = ((Locatable)positions [i]).pos;
benefitMap [pos.y, pos.x] += (float)getRandom(5);
}
}
}
public void updateBenefitMap(){
if (benefitMap != null) {
for (int i = 0; i < benefitMap.GetLength (0); ++i) {
for (int j = 0; j < benefitMap.GetLength (1); ++j) {
if (benefitMap [i, j] > 0) {
benefitMap [i, j] -= 0.5f;
}
}
}
}
updatePlayerValue ();
}
//提供小于max的随机数字
public int getRandom (int max){
return new System.Random ().Next (max);
}
}
<file_sep>using System;
public interface ScoreCount
{
string getName();
float getValue();
void addToScore();
}
| d7f8a2d9f2369eb0e4c0ff88f111284e0ff72884 | [
"Markdown",
"C#"
] | 45 | Markdown | Finspire13/Bomber-GameDesign | 9c5e2457c1301105e5d80f9c9702b9138f7f2c0c | d2339183f39166f73364174e1c5bb7152c62ce4d |
refs/heads/main | <repo_name>HrudakovSerhii/hrudakovserhii.github.io<file_sep>/README.md
# hrudakovserhii.github.io
Smart web component with input functionality to add/remove email addresses in emails list.
<file_sep>/js/index.js
/**
* EmailInput function to hold/add/remove email address strings
*
* Function create email items using initial value and input functionality.
* Use API functions to get access to content from EmailInput.
*
* @param {DocumentFragment} parentNode EmailInput container element
* @param {Function} onChange Event handler to catch Emails list updates
* @param {string} value Initial value of Emails list. Should contain email addresses divided by comma (<EMAIL>,<EMAIL>...)
* @param {string} className Custom style name of EmailInput root view
* @param {string} validEmailItemClassName Custom style name of valid email item view
* @param {string} invalidEmailItemClassName Custom style for invalid email item view
* @param {string} removeButtonClassName Custom style name of email item remove button view
* @param {string} inputClassName Custom style name of email item remove button view
* @param {string} inputPlaceHolder Input field placeHolder Custom style name of email item remove button view
*
* @return {
* {
* addEmail: (function(email:string): void),
* getEmails: (function(): string[]),
* getEmailCount: (function(): number),
* el: HTMLDivElement
* }
* } {
* addEmail: add new Emails in a list,
* getEmails: return emails string array
* getEmailCount: return emails count number
* el: return EmailInput element reference
* }
*/
function EmailsInput(
parentNode,
onChange,
value = "",
className = "",
validEmailItemClassName = "",
invalidEmailItemClassName = "",
removeButtonClassName = "",
inputClassName = "",
inputPlaceHolder = ""
) {
if (typeof window === "undefined") return undefined;
else
window.addEventListener("load", () => {
if (!parentNode.hasChildNodes()) init(value);
});
var _counter = 0;
var _emailsList = [];
var inputField = window.document.createElement("div");
var _emailItemTemplate =
`<div class="email--item email--item-valid ` +
validEmailItemClassName +
`">
<span></span>
<button class="button--email-item-remove ` +
removeButtonClassName +
`">
<svg width="8" height="8" viewBox="0 0 8 8" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8 0.8L7.2 0L4 3.2L0.8 0L0 0.8L3.2 4L0 7.2L0.8 8L4 4.8L7.2 8L8 7.2L4.8 4L8 0.8Z" fill="#050038" />
</svg>
</button>
</div>`;
var _newEmailItemTemplate =
`<div class="email--item email--item-new ` +
inputClassName +
`">
<input class="email-input--item-new" type="email" placeholder="` +
inputPlaceHolder +
`" value="" />
</div>`;
var emailRegexp = /(?!.*\.{2})^([A-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[A-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/;
var getElByTemplate = function (template, id) {
var templateEl = window.document.createElement("template");
templateEl.setAttribute("style", "display:none");
templateEl.setAttribute("id", id.toString());
templateEl.innerHTML = template;
return templateEl.content;
};
var addEmails = function (emailsString) {
var emails = emailsString.split(",");
for (var i = 0; i < emails.length; i += 1) {
var email = emails[i].trim();
if (email?.length) {
if (!_emailsList.find((d) => d === email)) {
addEmailBlock(email);
_emailsList.push(email);
onChange && onChange(_emailsList);
} else {
showError(`Email ${email} already exist in board`);
}
}
}
};
var onRemoveEmail = function (e) {
var emailToRemove = e.target.parentNode.querySelector(".email--item span").textContent;
_emailsList = _emailsList.filter((email) => email !== emailToRemove);
e.target.removeEventListener("click", this);
e.target.parentNode.remove();
onChange && onChange(_emailsList);
};
var addEmailBlock = function (email) {
var isInvalid = !emailRegexp.test(email);
var emailBlock = getEmailBlockNode(email);
if (isInvalid) {
emailBlock.querySelector(".email--item").className += ` email--item-invalid ${invalidEmailItemClassName}`;
}
inputField.insertBefore(emailBlock, inputField.querySelector(".email--item-new"));
};
var showError = function (error) {
alert(error);
};
// Catch ,(comma) and Enter keys press and create new emailBlocks
var onKeyPress = function (e) {
e.stopPropagation();
var value = e.target.value;
if (e.key === "," || e.key === "Enter") {
if (value.length > 1) {
addEmails(value);
e.currentTarget.value = "";
} else if (e.key === "," && !value.length) {
showError("Email can't start with `,` character");
}
}
};
// <EMAIL>, <EMAIL>
// Handle paste event on input
var onTextInput = function (e) {
var value = e.target.value;
if (value.includes(",")) {
if (value.length > 1) addEmails(value);
else e.currentTarget.value = "";
e.currentTarget.value = "";
}
};
// Create new emailBlocks if any text left in email input
var onFocusOut = function (e) {
e.stopPropagation();
var value = e.target.value;
if (value.length) addEmails(value);
e.currentTarget.value = "";
};
var getEmailBlockNode = function (email) {
var id = (_counter += 1);
var newEmailNode = getElByTemplate(_emailItemTemplate, id);
newEmailNode.querySelector(".email--item span").textContent = email;
newEmailNode.querySelector(".email--item").setAttribute("key", id.toString());
newEmailNode.querySelector(".email--item .button--email-item-remove").addEventListener("click", onRemoveEmail);
return newEmailNode;
};
var focusOnInput = function (e) {
if (e.target.className.includes("emails-list")) e.target.querySelector(".email-input--item-new").focus();
};
var init = function (initEmails) {
inputField.setAttribute("class", `emails-list ${className}`);
inputField.addEventListener("click", focusOnInput);
var newEmailInputNode = getElByTemplate(_newEmailItemTemplate, "email-input-el");
var newEmailInputNodeInput = newEmailInputNode.querySelector(".email-input--item-new");
newEmailInputNodeInput.addEventListener("keydown", onKeyPress);
newEmailInputNodeInput.addEventListener("input", onTextInput);
newEmailInputNodeInput.addEventListener("focusout", onFocusOut);
inputField.append(newEmailInputNode);
parentNode.append(inputField);
addEmails(initEmails);
};
init(value);
return {
el: inputField,
addEmail: addEmails,
getEmailCount: () => _emailsList.length,
getEmails: () => _emailsList
};
}
if (typeof module !== "undefined") module.exports = EmailsInput;
| 514167f70e188a5199a3823516ee26e472a21f88 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | HrudakovSerhii/hrudakovserhii.github.io | d2d240865123d7711e8e3a2d2107b2ae9908764a | 8913350e76df5035f38839792fecd8964887c2f3 |
refs/heads/master | <repo_name>Salaboy/jbpm-case-mgmt<file_sep>/kie-server-rest-jbpm-case-mgmt/src/main/java/org/kie/server/remote/rest/jbpm/casemgmt/CaseResource.java
package org.kie.server.remote.rest.jbpm.casemgmt;
import java.text.MessageFormat;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Variant;
import org.jbpm.services.api.DefinitionService;
import org.jbpm.services.api.ProcessService;
import org.jbpm.services.api.RuntimeDataService;
import org.jbpm.services.api.model.ProcessDefinition;
import org.kie.internal.KieInternalServices;
import org.kie.internal.process.CorrelationKeyFactory;
import org.kie.server.remote.rest.common.exception.ExecutionServerRestOperationException;
import org.kie.server.services.api.KieServerRegistry;
import org.kie.server.services.impl.marshal.MarshallerHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.kie.server.api.rest.RestURI.*;
import static org.kie.server.remote.rest.common.util.RestUtils.*;
import static org.kie.server.remote.rest.jbpm.resources.Messages.*;
@Path("/server")
public class CaseResource {
public static final String START_CASE_POST_URI = "containers/{" + CONTAINER_ID + "}/case/{" + PROCESS_ID +"}/instances";
public static final Logger logger = LoggerFactory.getLogger(CaseResource.class);
private ProcessService processService;
private DefinitionService definitionService;
private RuntimeDataService runtimeDataService;
private MarshallerHelper marshallerHelper;
private CorrelationKeyFactory correlationKeyFactory = KieInternalServices.Factory.get().newCorrelationKeyFactory();
public CaseResource(ProcessService processService, DefinitionService definitionService, RuntimeDataService runtimeDataService, KieServerRegistry context) {
this.processService = processService;
this.definitionService = definitionService;
this.runtimeDataService = runtimeDataService;
this.marshallerHelper = new MarshallerHelper(context);
}
protected static String getRelativePath(HttpServletRequest httpRequest) {
String url = httpRequest.getRequestURI();
url.replaceAll( ".*/rest", "");
return url;
}
@POST
@Path(START_CASE_POST_URI)
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response startCase(@javax.ws.rs.core.Context HttpHeaders headers, @PathParam("id") String containerId, @PathParam("pId") String processId, @DefaultValue("") String payload) {
Variant v = getVariant(headers);
String type = getContentType(headers);
// Check for presence of process id
try {
ProcessDefinition procDef = definitionService.getProcessDefinition(containerId, processId);
if( procDef == null ) {
throw ExecutionServerRestOperationException.notFound(MessageFormat.format(PROCESS_DEFINITION_NOT_FOUND, processId, containerId), v);
}
} catch( Exception e ) {
logger.error("Unexpected error during processing {}", e.getMessage(), e);
throw ExecutionServerRestOperationException.internalServerError(
MessageFormat.format(PROCESS_DEFINITION_FETCH_ERROR, processId, containerId, e.getMessage()), v);
}
logger.debug("About to unmarshal parameters from payload: '{}'", payload);
Map<String, Object> parameters = marshallerHelper.unmarshal(containerId, payload, type, Map.class);
logger.debug("Calling start process with id {} on container {} and parameters {}", processId, containerId, parameters);
Long processInstanceId = processService.startProcess(containerId, processId, parameters);
// return response
try {
String response = marshallerHelper.marshal(containerId, type, processInstanceId);
logger.debug("Returning CREATED response with content '{}'", response);
return createResponse(response, v, Response.Status.CREATED);
} catch (Exception e) {
logger.error("Unexpected error during processing {}", e.getMessage(), e);
throw ExecutionServerRestOperationException.internalServerError(
MessageFormat.format(CREATE_RESPONSE_ERROR, e.getMessage()), v);
}
}
}
<file_sep>/jbpm-case-mgmt-core/src/main/java/org/jbpm/casemgmt/model/CaseInstanceImpl.java
/*
* Copyright 2015 JBoss by Red Hat.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.casemgmt.model;
import java.util.ArrayList;
import java.util.List;
import org.jbpm.casemgmt.api.CaseInstance;
/**
*
* @author salaboy
*/
public class CaseInstanceImpl implements CaseInstance {
// temporal until its generated by the DB
private static Long idGenerator = 0L;
public enum CaseStatus {
ACTIVE, // As soon is created the instance is set to Active
CLOSED, // A case can be manually closed via the API
TERMINATED, // A case can be automatically terminated by the case internal definition
SUSPENDED // A case can be manually suspended
};
private Long id;
private String name;
private String description;
private CaseStatus status = CaseStatus.ACTIVE;
private String recipient;
private Long parentAdhocProcessInstance;
private List<Long> taskIds; // ?? List<CaseTask>
private List<Long> processInstanceIds; // ?? List<ProcessTask>
private List<Long> caseIds; // ?? List<CaseTask>
public CaseInstanceImpl() {
this.id = ++idGenerator;
}
public CaseInstanceImpl(String name) {
this();
this.name = name;
}
@Override
public Long getId() {
return id;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getDescription() {
return description;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public CaseStatus getStatus() {
return status;
}
@Override
public void setStatus(CaseStatus status) {
this.status = status;
}
@Override
public String getRecipient() {
return recipient;
}
@Override
public void setRecipient(String recipient) {
this.recipient = recipient;
}
@Override
public Long getParentAdhocProcessInstance() {
return parentAdhocProcessInstance;
}
@Override
public void setParentAdhocProcessInstance(Long parentAdhocProcessInstance) {
this.parentAdhocProcessInstance = parentAdhocProcessInstance;
}
@Override
public List<Long> getProcessInstanceIds() {
return processInstanceIds;
}
@Override
public void setProcessInstanceIds(List<Long> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
}
@Override
public List<Long> getTaskIds() {
return taskIds;
}
@Override
public void setTaskIds(List<Long> taskIds) {
this.taskIds = taskIds;
}
@Override
public List<Long> getCaseIds() {
return caseIds;
}
@Override
public void setCaseIds(List<Long> caseIds) {
this.caseIds = caseIds;
}
@Override
public void addHumanTaskId(Long taskId) {
if (taskIds == null) {
taskIds = new ArrayList<Long>();
}
taskIds.add(taskId);
}
@Override
public void addProcessTaskId(Long processId) {
if (processInstanceIds == null) {
processInstanceIds = new ArrayList<Long>();
}
processInstanceIds.add(processId);
}
@Override
public void addCaseTaskId(Long caseId) {
if (caseIds == null) {
caseIds = new ArrayList<Long>();
}
caseIds.add(caseId);
}
}
<file_sep>/jbpm-console-ng-case-mgmt/jbpm-console-ng-case-mgmt-client/src/main/java/org/jbpm/console/ng/cm/client/casegrid/CasesListGridPresenter.java
/*
* Copyright 2012 JBoss 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 org.jbpm.console.ng.cm.client.casegrid;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.cellview.client.ColumnSortList;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.Range;
import org.jboss.errai.bus.client.api.messaging.Message;
import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.ErrorCallback;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.jbpm.console.ng.cm.client.i18n.Constants;
import org.jbpm.console.ng.cm.model.CaseSummary;
import org.jbpm.console.ng.cm.service.CaseInstancesService;
import org.jbpm.console.ng.ga.model.PortableQueryFilter;
import org.jbpm.console.ng.gc.client.list.base.AbstractListView.ListView;
import org.jbpm.console.ng.gc.client.list.base.AbstractScreenListPresenter;
import org.uberfire.client.annotations.WorkbenchPartTitle;
import org.uberfire.client.annotations.WorkbenchPartView;
import org.uberfire.client.annotations.WorkbenchScreen;
import org.uberfire.client.mvp.UberView;
import org.uberfire.paging.PageResponse;
@Dependent
@WorkbenchScreen(identifier = "Cases List")
public class CasesListGridPresenter extends AbstractScreenListPresenter<CaseSummary> {
public interface CaseListView extends ListView<CaseSummary, CasesListGridPresenter> {
}
@Inject
private CaseListView view;
private Constants constants = GWT.create(Constants.class);
@Inject
private Caller<CaseInstancesService> casesService;
public CasesListGridPresenter() {
dataProvider = new AsyncDataProvider<CaseSummary>() {
@Override
protected void onRangeChanged(HasData<CaseSummary> display) {
view.showBusyIndicator(constants.Loading());
final Range visibleRange = display.getVisibleRange();
getData(visibleRange);
}
};
}
@Override
protected ListView getListView() {
return view;
}
@Override
public void getData(Range visibleRange) {
ColumnSortList columnSortList = view.getListGrid().getColumnSortList();
if (currentFilter == null) {
currentFilter = new PortableQueryFilter(visibleRange.getStart(),
visibleRange.getLength(),
false, "",
(columnSortList.size() > 0) ? columnSortList.get(0)
.getColumn().getDataStoreName() : "",
(columnSortList.size() > 0) ? columnSortList.get(0)
.isAscending() : true);
}
// If we are refreshing after a search action, we need to go back to offset 0
if (currentFilter.getParams() == null || currentFilter.getParams().isEmpty()
|| currentFilter.getParams().get("textSearch") == null || currentFilter.getParams().get("textSearch").equals("")) {
currentFilter.setOffset(visibleRange.getStart());
currentFilter.setCount(visibleRange.getLength());
currentFilter.setFilterParams("");
} else {
currentFilter.setFilterParams("(LOWER(t.name) like '"+currentFilter.getParams().get("textSearch")
+"' or LOWER(t.description) like '"+currentFilter.getParams().get("textSearch")+"') ");
currentFilter.setOffset(0);
currentFilter.setCount(view.getListGrid().getPageSize());
}
currentFilter.getParams().put("userId", identity.getIdentifier());
currentFilter.setOrderBy((columnSortList.size() > 0) ? columnSortList.get(0)
.getColumn().getDataStoreName() : "");
currentFilter.setIsAscending((columnSortList.size() > 0) ? columnSortList.get(0)
.isAscending() : true);
casesService.call(new RemoteCallback<PageResponse<CaseSummary>>() {
@Override
public void callback(PageResponse<CaseSummary> response) {
updateDataOnCallback(response);
}
}, new ErrorCallback<Message>() {
@Override
public boolean error(Message message, Throwable throwable) {
view.hideBusyIndicator();
view.displayNotification("Error: Getting Cases: " + throwable.toString());
GWT.log(message.toString());
return true;
}
}).getData(currentFilter);
}
@WorkbenchPartTitle
public String getTitle() {
return constants.Cases_List();
}
@WorkbenchPartView
public UberView<CasesListGridPresenter> getView() {
return view;
}
}
<file_sep>/README.md
# jbpm-case-mgmt
jBPM Case Management Modules
This modules provide the functionality described here:
<file_sep>/jbpm-console-ng-case-mgmt/jbpm-console-ng-case-mgmt-client/src/main/java/org/jbpm/console/ng/cm/client/details/CaseDetailsPresenter.java
/*
* Copyright 2012 JBoss 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 org.jbpm.console.ng.cm.client.details;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.TextArea;
import org.jboss.errai.bus.client.api.messaging.Message;
import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.ErrorCallback;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.jbpm.console.ng.cm.model.CaseKey;
import org.jbpm.console.ng.cm.model.CaseSummary;
import org.jbpm.console.ng.cm.model.events.CaseRefreshedEvent;
import org.jbpm.console.ng.cm.model.events.CaseSelectionEvent;
import org.jbpm.console.ng.cm.service.CaseInstancesService;
import org.uberfire.client.mvp.PlaceManager;
import org.uberfire.ext.widgets.common.client.common.popups.errors.ErrorPopup;
@Dependent
public class CaseDetailsPresenter {
public interface CaseDetailsView extends IsWidget {
void init( final CaseDetailsPresenter presenter );
void displayNotification( final String text );
TextArea getTaskDescriptionTextArea();
}
@Inject
private PlaceManager placeManager;
@Inject
CaseDetailsView view;
@Inject
private Caller<CaseInstancesService> casesService;
@Inject
private Event<CaseRefreshedEvent> caseRefreshed;
private long currentCaseId = 0;
private String currentCaseName = "";
@PostConstruct
public void init() {
view.init( this );
}
public IsWidget getView() {
return view;
}
public void refreshCase() {
casesService.call(new RemoteCallback<CaseSummary>(){
@Override
public void callback(CaseSummary response) {
String text = response.toString() + "\n";
text += "Human Tasks" + response.getHumanTasksDetails() + "\n";
text += "Process Tasks" + response.getProcessesDetails() + "\n";
view.getTaskDescriptionTextArea().setText(text);
}
}, new ErrorCallback<Message>(){
@Override
public boolean error(Message message, Throwable throwable) {
ErrorPopup.showMessage( "Unexpected error encountered : " + throwable.getMessage() );
return true;
}
}).getItem(new CaseKey(currentCaseId));
}
public void onCaseSelectionEvent( @Observes final CaseSelectionEvent event ) {
this.currentCaseId = event.getCaseId();
this.currentCaseName = event.getCaseName();
refreshCase();
}
public void onCaseRefreshedEvent( @Observes final CaseRefreshedEvent event ) {
if ( currentCaseId == event.getCaseId() ) {
refreshCase();
}
}
}
<file_sep>/jbpm-console-ng-case-mgmt/jbpm-console-ng-case-mgmt-client/src/main/resources/org/jbpm/console/ng/cm/client/i18n/Constants.properties
New_Case=New Case
Filters=Filters
Id=Id
Case=Case
Description=Description
Status=Status
Actions=Actions
Create_Case=Create Case
Name=Name
No_Cases_Found=No Case Found
Cases_List=Cases List
Loading=Loading
Create=Create
Case_Must_Have_A_Name=The Case Must Have A Name
New_Case_Instance=New Case Instance
Provide_Case_Name=Please Provide a Case Name
CaseCreatedWithId=Case Created with Id{0}
Basic=Basic
Advanced=Advanced
Case_Name=Case Name
Case_Template=Case Template
DeploymentId=Deployment Id
Create_Task=Create Task
Create_Process=Create Process
Create_SubCase=Create SubCase
Recipient=Recipient<file_sep>/jbpm-console-ng-case-mgmt/jbpm-console-ng-case-mgmt-client/src/main/resources/org/jbpm/console/ng/cm/client/i18n/Constants_zh_CN.properties
Tasks_List=任务列表
Day=日
Week=周
Month=月
Grid=网格
New_Task=新建任务
Personal=个人
Group=组
Active=活动的
All=所有的
No_Tasks_Found=没有找到任务
Priority=优先级
Task=任务
Id=ID
Status=状态
Due_On=到期日
Parent=父软件包
Complete=完成
Release=释放
Claim=要求
Work=操作
Start=启动
Details=细节
Actions=动作
No_Parent=无父软件包
User=用户
Process_Instance_Id=过程实例 ID
Process_Definition_Id=过程定义 ID
Process_Instance_Details=过程实例细节
No_Comments_For_This_Task=这个任务没有注释
Comment=注释
At=在
Added_By=添加人
Add_Comment=添加注释
Task_Must_Have_A_Name=这个任务必须有一个名称
Create=创建
Task_Name=任务名称
Quick_Task=快速任务?
Description=描述
Comments=注释
Filters=过滤器
Process_Context=过程上下文
Update=更新
Form=表单
Today=今天
Advanced=高级的
Refresh=刷新
Tasks_Refreshed=任务已刷新
Add_User=添加用户
Add_Group=添加组
Remove_User=删除用户
Remove_Group=删除组
Assignments=分配
Auto_Assign_To_Me=自动分配给我
Created_On=创建于
Text_Require=这个文本是必需的
UserOrGroup=用户或组
Forward=前移
Delegate=委托
Potential_Owners=潜在所有者
No_Potential_Owners=没有潜在所有者
Add_TypeRole=添加类型角色
Type_Role=类型角色
Parent_Group=父组
Save=保存
Delete=删除
Calendar=日历
Logs=日志
Task_Log=任务日志
Provide_User_Or_Group=你应该提供至少一个用户或组
<file_sep>/jbpm-console-ng-case-mgmt/jbpm-console-ng-case-mgmt-api/src/main/java/org/jbpm/console/ng/cm/model/events/CaseRefreshedEvent.java
/*
* Copyright 2012 JBoss by Red Hat.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.console.ng.cm.model.events;
import java.io.Serializable;
import org.jboss.errai.common.client.api.annotations.Portable;
@Portable
public class CaseRefreshedEvent implements Serializable {
private long caseId;
private String caseName;
public CaseRefreshedEvent(long caseId, String caseName) {
this.caseId = caseId;
this.caseName = caseName;
}
public CaseRefreshedEvent(long caseId) {
this.caseId = caseId;
}
public CaseRefreshedEvent() {
}
public long getCaseId() {
return caseId;
}
public void setCaseId(long caseId) {
this.caseId = caseId;
}
public String getCaseName() {
return caseName;
}
public void setCaseName(String caseName) {
this.caseName = caseName;
}
}
<file_sep>/jbpm-console-ng-case-mgmt/jbpm-console-ng-case-mgmt-backend/src/main/java/org/jbpm/console/ng/cm/backend/server/CaseAuditServiceImpl.java
/*
* Copyright 2015 JBoss by Red Hat.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.console.ng.cm.backend.server;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
import org.jboss.errai.bus.server.annotations.Service;
import org.jbpm.console.ng.cm.model.CaseEventKey;
import org.jbpm.console.ng.cm.model.CaseEventSummary;
import org.jbpm.console.ng.cm.service.CaseAuditService;
import org.jbpm.console.ng.ga.model.QueryFilter;
import org.uberfire.paging.PageResponse;
/**
*
* @author salaboy
*/
@Service
@ApplicationScoped
public class CaseAuditServiceImpl implements CaseAuditService{
@Override
public PageResponse<CaseEventSummary> getData(QueryFilter filter) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public CaseEventSummary getItem(CaseEventKey key) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<CaseEventSummary> getAll(QueryFilter filter) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
<file_sep>/jbpm-console-ng-case-mgmt/jbpm-console-ng-case-mgmt-client/src/main/java/org/jbpm/console/ng/cm/client/detailsmulti/CaseDetailsMultiPresenter.java
/*
* Copyright 2012 JBoss 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 org.jbpm.console.ng.cm.client.detailsmulti;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import com.google.gwt.user.client.ui.IsWidget;
import org.jbpm.console.ng.cm.model.events.CaseSelectionEvent;
import org.jbpm.console.ng.gc.client.experimental.details.AbstractTabbedDetailsPresenter;
import org.jbpm.console.ng.gc.client.experimental.details.AbstractTabbedDetailsView.TabbedDetailsView;
import org.jbpm.console.ng.cm.client.details.CaseDetailsPresenter;
import org.jbpm.console.ng.ht.client.i18n.Constants;
import org.uberfire.client.annotations.DefaultPosition;
import org.uberfire.client.annotations.WorkbenchMenu;
import org.uberfire.client.annotations.WorkbenchPartTitle;
import org.uberfire.client.annotations.WorkbenchPartView;
import org.uberfire.client.annotations.WorkbenchScreen;
import org.uberfire.client.mvp.UberView;
import org.uberfire.client.workbench.events.ChangeTitleWidgetEvent;
import org.uberfire.lifecycle.OnStartup;
import org.uberfire.mvp.PlaceRequest;
import org.uberfire.workbench.model.CompassPosition;
import org.uberfire.workbench.model.Position;
import org.uberfire.workbench.model.menu.MenuFactory;
import org.uberfire.workbench.model.menu.MenuItem;
import org.uberfire.workbench.model.menu.Menus;
import org.uberfire.workbench.model.menu.impl.BaseMenuCustom;
@Dependent
@WorkbenchScreen(identifier = "Case Details Multi", preferredWidth = 500)
public class CaseDetailsMultiPresenter extends AbstractTabbedDetailsPresenter {
public interface CaseDetailsMultiView
extends TabbedDetailsView<CaseDetailsMultiPresenter> {
void setupPresenters(
final CaseDetailsPresenter taskDetailsPresenter
);
IsWidget getRefreshButton();
IsWidget getCloseButton();
}
@Inject
private Event<ChangeTitleWidgetEvent> changeTitleWidgetEvent;
@Inject
private Event<CaseSelectionEvent> caseSelected;
@Inject
private CaseDetailsPresenter taskDetailsPresenter;
@Inject
private CaseDetailsMultiView view;
@PostConstruct
public void init() {
view.setupPresenters(taskDetailsPresenter);
}
@WorkbenchPartView
public UberView<CaseDetailsMultiPresenter> getView() {
return view;
}
@DefaultPosition
public Position getPosition() {
return CompassPosition.EAST;
}
@WorkbenchPartTitle
public String getTitle() {
return Constants.INSTANCE.Details();
}
@OnStartup
public void onStartup(final PlaceRequest place) {
super.onStartup(place);
}
public void onCaseSelectionEvent(@Observes final CaseSelectionEvent event) {
deploymentId = String.valueOf(event.getCaseId());
processId = event.getCaseName();
view.getTabPanel().getTabWidget(0).getParent().setVisible(true);
changeTitleWidgetEvent.fire(new ChangeTitleWidgetEvent(this.place, String.valueOf(deploymentId) + " - " + processId));
}
public void refresh() {
caseSelected.fire(new CaseSelectionEvent(Long.valueOf(deploymentId), processId));
}
@WorkbenchMenu
public Menus buildMenu() {
return MenuFactory
.newTopLevelCustomMenu(new MenuFactory.CustomMenuBuilder() {
@Override
public void push(MenuFactory.CustomMenuBuilder element) {
}
@Override
public MenuItem build() {
return new BaseMenuCustom<IsWidget>() {
@Override
public IsWidget build() {
return view.getRefreshButton();
}
};
}
}).endMenu()
.newTopLevelCustomMenu(new MenuFactory.CustomMenuBuilder() {
@Override
public void push(MenuFactory.CustomMenuBuilder element) {
}
@Override
public MenuItem build() {
return new BaseMenuCustom<IsWidget>() {
@Override
public IsWidget build() {
return view.getCloseButton();
}
};
}
}).endMenu().build();
}
}
<file_sep>/jbpm-case-mgmt-core/src/main/java/org/jbpm/casemgmt/model/CaseTaskImpl.java
/*
* Copyright 2015 JBoss by Red Hat.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.casemgmt.model;
import java.util.Map;
import org.jbpm.casemgmt.api.CaseTask;
/**
*
* @author salaboy
*/
public class CaseTaskImpl implements CaseTask {
private static Long idGenerator = 0L;
private Long id;
private String name;
private Map<String, Object> params;
public CaseTaskImpl() {
this.id = ++idGenerator;
}
public CaseTaskImpl(String name) {
this();
this.name = name;
}
@Override
public Long getId() {
return id;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Object> getParams() {
return params;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
@Override
public String toString() {
return "CaseTaskImpl{" + "id=" + id + ", name=" + name + ", params=" + params + '}';
}
}
<file_sep>/jbpm-case-mgmt-core/src/main/java/org/jbpm/casemgmt/model/HumanTaskImpl.java
/*
* Copyright 2015 JBoss by Red Hat.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.casemgmt.model;
import java.util.ArrayList;
import java.util.List;
import org.jbpm.casemgmt.api.HumanTask;
/**
*
* @author salaboy
*/
public class HumanTaskImpl implements HumanTask {
private static Long idGenerator = 0L;
private Long id;
private String name;
private List<String> groups = new ArrayList<String>();
private List<String> users = new ArrayList<String>();
public HumanTaskImpl() {
this.id = ++idGenerator;
}
public HumanTaskImpl(String name) {
this();
this.name = name;
}
public HumanTaskImpl(String name, List<String> users, List<String> groups) {
this(name);
this.groups = groups;
this.users = users;
}
@Override
public Long getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public List<String> getGroups() {
return groups;
}
@Override
public List<String> getUsers() {
return users;
}
public void setName(String name) {
this.name = name;
}
public void setGroups(List<String> groups) {
this.groups = groups;
}
public void setUsers(List<String> users) {
this.users = users;
}
}
<file_sep>/jbpm-case-mgmt-core/src/main/java/org/jbpm/casemgmt/service/api/CaseInstancesService.java
/*
* Copyright 2015 JBoss by Red Hat.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.casemgmt.service.api;
import java.util.List;
import org.jbpm.casemgmt.api.CaseInstance;
import org.jbpm.casemgmt.api.CaseTask;
import org.jbpm.casemgmt.api.HumanTask;
import org.jbpm.services.api.model.ProcessInstanceDesc;
import org.kie.api.task.model.TaskSummary;
import org.kie.internal.query.QueryFilter;
/**
*
* @author salaboy
*/
public interface CaseInstancesService {
List<CaseInstance> getCaseInstances(QueryFilter qf);
Long createCaseInstance(String caseIdentifier, String recipient, String deploymentId, String template);
void registerLifeCycleListener(CaseInstanceLifeCycleListener listener);
void activateCaseInstance(Long caseId);
void closeCaseInstance(Long caseId);
void terminateCaseInstance(Long caseId);
void suspendCaseInstance(Long caseId);
void addHumanTask(Long caseId, HumanTask humanTask);
void addSubCaseTask(Long caseId, CaseTask caseTask);
CaseInstance getCaseInstanceById(Long caseId);
List<TaskSummary> getAllCaseHumanTasks(Long caseId);
List<ProcessInstanceDesc> getAllCaseProcessTasks(Long caseId);
List<CaseInstance> getAllCaseCaseTasks(Long caseId);
}
<file_sep>/jbpm-console-ng-case-mgmt/jbpm-console-ng-case-mgmt-client/src/main/java/org/jbpm/console/ng/cm/client/details/CaseDetailsViewImpl.java
/*
* Copyright 2012 JBoss 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 org.jbpm.console.ng.cm.client.details;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import com.github.gwtbootstrap.client.ui.ControlLabel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.TextArea;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.Templated;
import org.jbpm.console.ng.ht.client.i18n.Constants;
import org.uberfire.client.mvp.PlaceManager;
import org.uberfire.workbench.events.NotificationEvent;
@Dependent
@Templated(value = "CaseDetailsViewImpl.html")
public class CaseDetailsViewImpl extends Composite implements CaseDetailsPresenter.CaseDetailsView {
private CaseDetailsPresenter presenter;
@Inject
@DataField
public TextArea taskDescriptionTextArea;
@Inject
@DataField
public ControlLabel taskDescriptionLabel;
@Inject
private PlaceManager placeManager;
@Inject
private Event<NotificationEvent> notification;
private Constants constants = GWT.create( Constants.class );
@Override
public void init( CaseDetailsPresenter presenter ) {
this.presenter = presenter;
taskDescriptionLabel.add( new HTMLPanel( constants.Description() ) );
}
@Override
public TextArea getTaskDescriptionTextArea() {
return taskDescriptionTextArea;
}
@Override
public void displayNotification( String text ) {
notification.fire( new NotificationEvent( text ) );
}
}
| c109f90c4462b3bba00ea2c481719ccede43e313 | [
"Markdown",
"Java",
"INI"
] | 14 | Java | Salaboy/jbpm-case-mgmt | 351b20aeb52e678e0d7adcf38dbe93831f832ef2 | 5e11b96682b0d97f20f85f3d72820e19fdd0f4cb |
refs/heads/main | <repo_name>ruipedrolousada/ruipedrolousada<file_sep>/PI21/Ficha 8/Deque.c
#include <stdio.h>
#include <stdlib.h>
#include "Deque.h"
void initDeque (Deque *q){
}
int DisEmpty (Deque q){
return -1;
}
int pushBack (Deque *q, int x){
return -1;
}
int pushFront (Deque *q, int x){
return -1;
}
int popBack (Deque *q, int *x){
return -1;
}
int popFront (Deque *q, int *x){
return -1;
}
int popMax (Deque *q, int *x){
return -1;
}
int back (Deque q, int *x){
return -1;
}
int front (Deque q, int *x){
return -1;
}<file_sep>/PI21/Ficha 8/Queue.h
#include "Listas.h"
typedef struct {
LInt inicio,fim;
} Queue;
void initQueue (Queue *q);
int QisEmpty (Queue q);
int enqueue (Queue *q, int x);
int dequeue (Queue *q, int *x);
int frontQ (Queue q, int *x);
typedef LInt QueueC;
void initQueueC (QueueC *q);
int QisEmptyC (QueueC q);
int enqueueC (QueueC *q, int x);
int dequeueC (QueueC *q, int *x);
int frontC (QueueC q, int *x);<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/src/Servidores/ThreadsServer/ThreadHandleVoos.java
package Servidores.ThreadsServer;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import Connections.Demultiplexer;
import Servidores.Server;
import Servidores.Dados.Reservas;
import Servidores.Dados.ServerData;
import Viagens.Cidade;
import Viagens.Voo;
public class ThreadHandleVoos extends Thread {
Demultiplexer dm;
private ServerData db;
public ThreadHandleVoos(Demultiplexer demultiplexer) {
this.dm = demultiplexer;
db = Server.getDataBase();
}
@Override
public void run() {
while(true)
{
try {
String message =new String( dm.receive(4));
HandleVoosFromClient(message);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
return;
}
}
}
private void HandleVoosFromClient(String message) throws IOException, InterruptedException {
Scanner sc = new Scanner(message);
sc.useDelimiter(";");
Queue<Cidade> queue = new LinkedList<>();
int numeroCidades = Integer.parseInt( sc.next());
for (int i = 0; i < numeroCidades; i++) {
queue.add(new Cidade( sc.next() ) );
}
LocalDate data = LocalDate.parse( sc.next());
// System.out.println("A data de reserva é " + data);
boolean isValid = ValidadeVoosFromClient(new LinkedList<>(queue));
String idRes = ReservarVoo(queue,data);
if (idRes == null)
{
dm.send(4,"-2");
}
else if(isValid && !idRes.equals("-1"))
{
dm.send(4,idRes.getBytes());
}
else if(idRes.equals("encerrado")) {
dm.send(4, "encerrado".getBytes());
}else
dm.send(4, "-1".getBytes());
sc.close();
}
private String ReservarVoo(Queue<Cidade> queue, LocalDate data) {
Cidade origem = queue.poll(); //BRAGA
Cidade next = null;
List<Voo> listaVoos = new ArrayList<>();
boolean found = db.GetDiasEncerrados().hasData(data);
if (found) return "encerrado";
while(!queue.isEmpty())
{
next= queue.poll(); //VENEZA
Reservas allReservas = db.GetReservas();
Voo vooFoundWithReserva;
try {
vooFoundWithReserva = allReservas.DecrementLugarReserva(data, origem, next);
} catch (Exception e) {
//Nao há espaco para marcar esse voo
System.out.println("Reserva encontra-se cheia, o voo vai ser cancelado");
return "-1";
}
if(vooFoundWithReserva == null) {
var grafo =db.GetGrafoCidades();
int capacidadeMaxima = grafo.GetSizeVoo(origem, next);
//Criar um voo com a capacidade maxima predefenida pelo servidor
Voo v = new Voo(origem, next, capacidadeMaxima-1, data);
listaVoos.add(v);
}
else
listaVoos.add(vooFoundWithReserva);
origem = next;
}
StringBuilder idReserv = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 9; i++) {//id com 9 digitos
idReserv.append(random.nextInt(10));}// gerar um número aleatório entre 0 e 9
db.GetReservas().addReserva(idReserv.toString(),listaVoos, data);
return idReserv.toString();
}
private boolean ValidadeVoosFromClient(Queue<Cidade> queue) {
List<Cidade> l;
while(true)
{
if ( (l =db.GetGrafoCidades().GetPossibleVoo(queue.poll()) ) == null) return false;
if (queue.peek() == null) return true;
if (!l.contains(queue.peek())) return false;
}
}
}
<file_sep>/PI21/teste1.c
#include <stdio.h>
void ex2(){
int x;
double soma=0,count=0;
double med;
while (x!=0){
printf("Insira o número: \n");
scanf("%d", &x);
soma = soma+x;
count++;
}
med = soma/count;
printf("%f\n", med);
}
int main(){
ex2();
return 0;
}<file_sep>/FM7/Main.java
import java.util.ArrayList;
import java.util.List;
/**
* Escreva a descrição da classe Main aqui.
*
* @author (seu nome)
* @version (número de versão ou data)
*/
public class Main{
public static void main(String[] args) throws Exception {
Gestor g = new Gestor();
try{
g = LoadWrite.loadTextFile(args[0]);
}catch(LinhaInvalidaException e){
System.out.println("Ficheiro " + args[0] + "esta mal formado.");
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Nao foi passado ficheiro , inicializando um gestor vazio.");
}
cFM controller = new Controller();
mFM model = new Model(g,controller);
vFM view = new View(controller);
controller.addModel(model);
controller.addView(view);
view.run();
}
}
<file_sep>/PI21/Ficha 6/main.c
/* Main function of the C program. */
#include <stdio.h>
//#include "stack.h"
#include "Queue.h"
int main() {
int i ;
/*struct staticStack s1;
SStack S1 = &s1;
struct dinStack d1;
DStack D1 = &d1;*/
struct staticQueue q1;
SQueue Q1 = &q1;
//struct dinQueue r1;
//DQueue R1 = &r1;
//printf ("Testing Stacks .... \n");
//SinitStack (S1);
//DinitStack (D1);
/*for (i=0; i<15; i++) {
if (Spush (S1,i) != 0) printf ("ERROR pushing %d\n", i);
if (Dpush (D1,i) != 0) printf ("ERROR pushing %d\n", i);
}
ShowSStack (S1);
ShowDStack (D1);*/
printf ("Testing Queues .... \n");
SinitQueue (Q1);
//DinitQueue (R1);
for (i=0; i<15; i++) {
if (Senqueue (Q1,i) != 0) printf ("ERROR enqueueing %d\n", i);
//if (Denqueue (R1,i) != 0) printf ("ERROR enqueueing %d\n", i);
}
ShowSQueue (Q1);
//ShowDQueue (R1);
return 0;
} <file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/src/Viagens/Voo.java
package Viagens;
import java.time.LocalDate;
public class Voo{
public Cidade origem;
public Cidade destino;
public Integer lugaresLivres;
public LocalDate date;
//final Integer lugares = 350;
public Voo(Cidade o, Cidade d, Integer c,LocalDate data) {
this.origem = o;
this.destino = d;
this.lugaresLivres = c;
this.date = data;
}
public Voo() {
this.origem = new Cidade();
this.destino = new Cidade();
this.lugaresLivres = 0;
}
public Cidade getOrigem() {
return origem;
}
public void setOrigem(Cidade origem) {
this.origem = origem;
}
public Cidade getDestino() {
return destino;
}
public void setDestino(Cidade destino) {
this.destino = destino;
}
public Integer getLugaresLivres() {
return lugaresLivres;
}
public void setLugaresLivres(Integer lugaresLivres) {
this.lugaresLivres = lugaresLivres;
}
@Override
public boolean equals(Object obj) {
if (! (obj instanceof Voo)) return false;
Voo v = (Voo) obj;
return (v.origem.equals(this.origem) && v.destino.equals(this.destino));
}
}
<file_sep>/PI21/stack.c
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
// Static stacks
void SinitStack (SStack s){
// ...
}
int SisEmpty (SStack s){
return 1;
}
int Spush (SStack s, int x){
int r = 0;
return r;
}
int Spop (SStack s, int *x) {
int r=0;
return r;
}
int Stop (SStack s, int *x) {
int r=0;
return r;
}
void ShowSStack (SStack s){
int i;
printf ("%d Items: ", s->sp);
for (i=s->sp-1; i>=0; i--)
printf ("%d ", s->values[i]);
putchar ('\n');
}
// Stacks with dynamic arrays
int dupStack (DStack s) {
int r = 0, i;
int *t = malloc (2*s->size*sizeof(int));
if (t == NULL) r = 1;
else {
for (i=0; i<s->size; i++)
t[i] = s->values[i];
free (s->values);
s->values = t;
s->size*=2;
}
return r;
}
void DinitStack (DStack s) {
}
int DisEmpty (DStack s) {
return 1;
}
int Dpush (DStack s, int x){
int r=0;
return r;
}
int Dpop (DStack s, int *x){
int r=0;
return r;
}
int Dtop (DStack s, int *x){
int r=0;
return r;
}
void ShowDStack (DStack s){
int i;
printf ("%d Items: ", s->sp);
for (i=s->sp-1; i>=0; i--)
printf ("%d ", s->values[i]);
putchar ('\n');
}<file_sep>/IdeaProjects/POO/ficha2/src/Main.java
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void exercicio1a(){
Exercicio1 exe = new Exercicio1();
int[] array = exe.arrays();
int x = exe.minimo(array);
System.out.println("o min é: " + x);
}
public static void exercicio1b(){
Exercicio1 exe = new Exercicio1();
int[] array = exe.arrays();
Scanner x = new Scanner(System.in);
System.out.println("digite 2 indices: " );
int y = x.nextInt();
int z = x.nextInt();
int[] resul = exe.indice(array,y,z);
System.out.println(Arrays.toString(resul));
}
public static void exercicio1c(){
Exercicio1 exe = new Exercicio1();
int[] array1 = {1,3,4,5,6,7,8,9,10,11,12,13,14,15};
int[] array2 = {20,4,6,30,15};
int[] array = exe.comum(array1,array2);
System.out.println(Arrays.toString(array));
}
public static void exercicio2a(){
Exercicio2 exe = new Exercicio2();
int[][] array = exe.actualiza();
System.out.println(Arrays.deepToString(array));
}
public static void exercicio2b(){
Exercicio2 exe = new Exercicio2();
int [][] array = exe.actualiza();
int x = exe.soma(array);
System.out.println("o valor é " + x);
}
public static void exercicio2c(){
Exercicio2 exe = new Exercicio2();
int [][] array = exe.actualiza();
double x = exe.mediaAluno(array);
System.out.println("a média é " + x);
}
public static void exercicio2d(){
Scanner input = new Scanner(System.in);
System.out.println("qual o indice da discplina: ");
int y = input.nextInt();
Exercicio2 exe = new Exercicio2();
int [][] array = exe.actualiza();
double x = exe.mediaDisciplina(array,y);
System.out.println("a média é " + x);
}
public static void exercicio2e(){
Exercicio2 exe = new Exercicio2();
int [][] array = {{1,2,3},{4,30,6},{7,8,9}};
double x = exe.maiorNota(array);
System.out.print("a maior nota é " + x);
}
public static void exercicio2f(){
Exercicio2 exe = new Exercicio2();
int [][] array = {{10,2,3},{4,1,6},{7,8,9}};
double x = exe.menorNota(array);
System.out.print("a menor nota é: " + x);
}
public static void exercicio2g(){
Exercicio2 exe = new Exercicio2();
int [][] array = {{10,2,11},{4,30,6},{7,8,45}};
int[] x = exe.xNotas(array);
System.out.print(Arrays.toString(x));
}
public static void exercicio2h(){
Exercicio2 exe = new Exercicio2();
int [][] array = {{10,2,11},{4,30,6},{7,8,45}};
String x = exe.stringNotas(array);
System.out.print(x);
}
public static void exercicio2i(){
Exercicio2 exe = new Exercicio2();
int [][] array = {{13,20,12,10,11},{20,20,14,9,5},{11,20,10,20,10},{19,20,18,2,1},{9,20,4,20,19}};
int x = exe.indiceMaiorMedia(array);
System.out.print("o indice da disciplina com maior media é: "+ x);
}
public static void exercicio4a(){
Exercicio4 exe = new Exercicio4();
int[] array = {4,5,89,2,7,5,10,12};
int[] x = exe.ordenaArray(array);
System.out.print(Arrays.toString(x));
}
public static void main(String[] args) {
exercicio4a();
}
}
<file_sep>/PI21/Ficha 8/Listas.c
#include <stdio.h>
#include <stdlib.h>
#include "Listas.h"
LInt newLInt (int x, LInt xs){
LInt r = malloc (sizeof(struct slist));
if (r!=NULL) {
r->valor = x; r->prox = xs;
}
return r;
}
DList newDList (int x, DList xs){
DList r = malloc (sizeof(struct dlist));
if (r!=NULL) {
r->valor = x; r->prox = xs; r->ant = NULL;
}
return r;
}<file_sep>/FM7/Jogo.java
import java.time.LocalDate;
import java.util.*;
import java.io.Serializable;
import java.util.stream.Collectors;
import java.util.Random;
/**
* Escreva a descrição da classe Jogo aqui.
*
* @author (seu nome)
* @version (número de versão ou data)
*/
public class Jogo implements Serializable{
private Equipa eq1, eq2;
private Map<Integer,Integer> tEq1 = new HashMap<Integer,Integer>();
private Map<Integer,Integer> sEq1 = new HashMap<Integer,Integer>();
private Map<Integer,Integer> tEq2 = new HashMap<Integer,Integer>();
private Map<Integer,Integer> sEq2 = new HashMap<Integer,Integer>();
private int[] score = new int[2];
private static int maxTime = 5400;
private int time; private LocalDate day;
public Jogo(){
this.eq1 = new Equipa();
this.eq2 = new Equipa();
this.time = 0;
this.day = LocalDate.now();
}
public Jogo(Equipa eq1,Equipa eq2, Map<Integer, Integer> tEq1, Map<Integer, Integer> sEq1, Map<Integer, Integer> tEq2, Map<Integer, Integer> sEq2, int[] score, int time, LocalDate day) {
this.eq1 = eq1.clone();
this.eq2 = eq2.clone();
this.tEq1 = tEq1.values().stream().collect(Collectors.toMap(x->x,x->x));
this.sEq1 = sEq1.values().stream().collect(Collectors.toMap(x->x,x->x));
this.tEq2 = tEq2.values().stream().collect(Collectors.toMap(x->x,x->x));
this.sEq2 = sEq2.values().stream().collect(Collectors.toMap(x->x,x->x));
this.score = score;
this.time = time;
this.day = day;
}
public Jogo (Jogo g){
this.eq1 = g.getEq1();
this.eq2 = g.getEq2();
this.tEq1 = g.gettEq1();
this.sEq1 = g.getsEq1();
this.tEq2 = g.gettEq2();
this.sEq2 = g.getsEq2();
this.score = g.getScore();
this.time = g.getTime();
this.day = g.getDay();
}
public Equipa getEq1() { return eq1; }
public void setEq1(Equipa eq1) { this.eq1 = eq1; }
public Equipa getEq2() { return eq2; }
public void setEq2(Equipa eq2) { this.eq2 = eq2; }
public Map<Integer, Integer> gettEq1() { return tEq1.values().stream().collect(Collectors.toMap(x->x,x->x)); }
public void settEq1(Map<Integer, Integer> tEq1) { this.tEq1 = tEq1.values().stream().collect(Collectors.toMap(x->x,x->x)); }
public Map<Integer, Integer> getsEq1() { return sEq1.values().stream().collect(Collectors.toMap(x->x,x->x)); }
public void setsEq1(Map<Integer, Integer> sEq1) { this.sEq1 = sEq1.values().stream().collect(Collectors.toMap(x->x,x->x)); }
public Map<Integer, Integer> gettEq2() { return tEq2.values().stream().collect(Collectors.toMap(x->x,x->x)); }
public void settEq2(Map<Integer, Integer> tEq2) { this.tEq2 = tEq2.values().stream().collect(Collectors.toMap(x->x,x->x)); }
public Map<Integer, Integer> getsEq2() { return sEq2.values().stream().collect(Collectors.toMap(x->x,x->x)); }
public void setsEq2(Map<Integer, Integer> sEq2) { this.sEq2 = sEq2.values().stream().collect(Collectors.toMap(x->x,x->x)); }
public int getTime(){
return this.time;
}
public void setTime(int time){
this.time = time;
}
public LocalDate getDay(){
return this.day;
}
public void setDay(LocalDate l){
this.day = l;
}
public int[] getScore(){
int[] r = {score[0],score[1]};
return r;
}
public void setScore(int[] score){
this.score[0] = score[0];
this.score[1] = score[1];
}
public Jogo clone() {
Map<Integer,Integer> tq1 = new HashMap<Integer, Integer>();
for (Map.Entry<Integer,Integer> entry : tEq1.entrySet()) {
tq1.put(entry.getKey(), entry.getValue());
}
Map<Integer,Integer> sq1 = new HashMap<Integer, Integer>();
for (Map.Entry<Integer,Integer> entry : sEq1.entrySet()) {
sq1.put(entry.getKey(), entry.getValue());
}
Map<Integer,Integer> tq2 = new HashMap<Integer, Integer>();
for (Map.Entry<Integer,Integer> entry : tEq2.entrySet()) {
tq2.put(entry.getKey(), entry.getValue());
}
Map<Integer,Integer> sq2 = new HashMap<Integer, Integer>();
for (Map.Entry<Integer,Integer> entry : sEq2.entrySet()) {
sq2.put(entry.getKey(), entry.getValue());
}
return new Jogo(this.eq1,this.eq2,tq1,sq1,tq2,sq2, this.score, this.time, this.day);
}
public static Jogo Loadline(String input,Map<String,Equipa> equipas) {
String[] str = input.split(",");
String[] date = str[4].split("-");
Map<Integer, Integer> tEq1 = new HashMap<>();
Map<Integer, Integer> sEq1 = new HashMap<>();
Map<Integer, Integer> tEq2 = new HashMap<>();
Map<Integer, Integer> sEq2 = new HashMap<>();
for (int i = 5; i < 16; i++) {//titulares
tEq1.put(Integer.parseInt(str[i]), Integer.parseInt(str[i]));
}
for (int i = 16; i < 19; i++) {//sub eq1
String[] sub = str[i].split("->");
sEq1.put(Integer.parseInt(sub[0]), Integer.parseInt(sub[1]));
}
for (int i = 19; i < 30; i++) {//titulares eq2
tEq2.put(Integer.parseInt(str[i]), Integer.parseInt(str[i]));
}
for (int i = 30; i < 33; i++) {//sub eq2
String[] sub = str[i].split("->");
sEq2.put(Integer.parseInt(sub[0]), Integer.parseInt(sub[1]));
}
int[] r = new int[] {Integer.parseInt(str[2]), Integer.parseInt(str[3])};
return new Jogo(equipas.get(str[0]), equipas.get(str[1]),
tEq1, sEq1, tEq2, sEq2,
r, 5400, LocalDate.of(Integer.parseInt(date[0]),
Integer.parseInt(date[1]), Integer.parseInt(date[2])));
}
public void finalGame(){
int a,b,c,d;
int g1=0,g2=0;
int[] score = new int[2];
Random rand = new Random();
a=tEq1.values().stream().mapToInt(x->eq1.getJogador(x).getPontos()).sum();
b=tEq2.values().stream().mapToInt(x->eq2.getJogador(x).getPontos()).sum();
c=(int)((a-b)/11);
d=c;
c=Math.abs(c);
for(int i=0;i<90;i++){
a=rand.nextInt(1000)+1;
b=rand.nextInt(1000)+1;
if(c<10&&c>=5){
if(a<41)g1++;
if(b<31)g2++;
}
if(c<15&&c>=10){
if(a<51)g1++;
if(b<26)g2++;
}
if(c<20&&c>=15){
if(a<56)g1++;
if(b<26)g2++;
}
if(c>=20){
if(a<61)g1++;
if(b<21)g2++;
}
}
if(d<0){a=g1;g1=g2;g2=a;}
this.score[0]=g1;
this.score[1]=g2;
}
public String toString(){
StringBuilder s = new StringBuilder();
s.append(day.toString()+" "+eq1.getNome()+" "+this.score[0]+":"+this.score[1]+" "+eq2.getNome()+"\n");
s.append(eq1.getNome()+" Titulares:");
for(Integer i : tEq1.keySet()){
s.append(i+",");
}
s.append("\n");
s.append(eq2.getNome()+" Titulares:");
for(Integer i : tEq2.keySet()){
s.append(i+",");
}
s.append("\n");
return s.toString();
}
}<file_sep>/PI21/Ficha 8/main.c
#include <stdio.h>
#include "Stack.h"
#include "Queue.h"
#include "Deque.h"
int main (){
int i, a, b;
Stack s; Queue q; Deque d;
printf ("_______________ Testes _______________\n\n");
printf ("Stack:\n");
initStack (&s);
push (&s,1);
push (&s,1);
// altere este código de forma a que a stack tenha no final
// do ciclo a sqwuencia com os numeros de fibonacci
for (i=0; i<10; i++){
pop (&s,&a); top (s,&b); push (&s,b); push (&s,a+b);
}
while (! SisEmpty (s)) {
pop (&s,&a);
printf ("%d ", a);
}
printf ("\nQueue:\n");
initQueue (&q);
enqueue (&q,1);
enqueue (&q,1);
for (i=0; i<10; i++){
dequeue (&q,&a); frontQ (q,&b); enqueue (&q, a); enqueue (&q,a+b);
}
while (! QisEmpty (q)) {
dequeue (&q,&a);
printf ("%d ", a);
}
printf ("\nDeque:\n");
initDeque (&d);
pushFront (&d,1);
pushBack (&d,1);
for (i=0; i<10; i++){
popBack (&d,&a); back (d,&b); pushBack (&d, a); pushFront (&d,a+b);
}
popMax (&d,&a);
printf ("Max: %d \n", a);
while (! DisEmpty (d)) {
popBack (&d,&a);
printf ("%d ", a);
}
printf ("\n\n___________ Fim dos Testes ___________\n\n");
return 0;
}<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/src/Servidores/Dados/GrafoCidades.java
package Servidores.Dados;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import Viagens.Cidade;
class InfoVoo{
public Cidade destino;
public int capacidadeMaxima;
public InfoVoo(Cidade c,int capacidade)
{
destino = c;
capacidadeMaxima = capacidade;
}
}
public class GrafoCidades {
List<Cidade> allCidades = new ArrayList<>();
Map<Cidade,List<InfoVoo>> allVoos = new HashMap<>();
Lock lock = new ReentrantLock();
public void addCidade(Cidade cidade)
{
try {
lock.lock();
allCidades.add(cidade);
} finally {lock.unlock();}
}
//Se pudemos fazer um voo de origem para destino tambem pudemos fazer um de destino para origem
public void addVoo(Cidade origem,Cidade destino,int capacidade)
{
try{
lock.lock();
List<InfoVoo> allVoosDestino = allVoos.get(origem);
if (allVoosDestino == null)
{
List<InfoVoo> l = new ArrayList<InfoVoo>();
InfoVoo info = new InfoVoo(destino, capacidade);
l.add(info);
allVoos.put(origem,l);
}
else {
boolean found = false;
for (InfoVoo infoVoo : allVoosDestino) {
if (infoVoo.destino.equals(destino))
{
found = true;
}
}
if (!found) allVoosDestino.add(new InfoVoo(destino, capacidade));
}
List<InfoVoo> allVoosOrigem = allVoos.get(destino);
if (allVoosOrigem == null)
{
List<InfoVoo> l = new ArrayList<InfoVoo>();
InfoVoo info = new InfoVoo(origem, capacidade);
l.add(info);
allVoos.put(destino,l);
}
else {
boolean found = false;
for (InfoVoo infoVoo : allVoosDestino) {
if (infoVoo.destino.equals(origem))
{
found = true;
}
}
if (!found) allVoosDestino.add(new InfoVoo(origem, capacidade));
}
}
finally{ lock.unlock();}
}
public List<Cidade> GetPossibleVoo(Cidade origem)
{
try{
lock.lock();
var lista = allVoos.get(origem);
List<Cidade> l = new ArrayList<>();
for (InfoVoo infoVoo : lista) {
l.add( infoVoo.destino);
}
return l;
}finally{ lock.unlock();}
}
public List<Cidade> GetAllCidades()
{
try{
lock.lock();
return allVoos.keySet().stream().collect(Collectors.toList());
}finally{ lock.unlock();}
}
public int GetSizeVoo(Cidade origem,Cidade destino)
{
try{
lock.lock();
for (var info :allVoos.get(origem))
{
if (info.destino.equals(destino))
return info.capacidadeMaxima;
}
return -1;
}finally{lock.unlock();}
}
public void PrintVoos()
{
try
{
lock.lock();
System.out.println("-------------------------\nPrinting All Voos");
System.out.println("CIDADE ORIGEM -> CIDADE DESTINO");
for (var entry : allVoos.entrySet()) {
System.out.println(entry.getKey().getNome()+" -> ");
//("Cidades destino);
for (var info : entry.getValue()) {
System.out.print(info.destino.getNome());
}
System.out.print("\n-------------------------\n");
}
}finally{ lock.unlock();}
}
}
<file_sep>/DSS/source/Menu/Phases/Phase8.java
package bin;
import bin.Controller;
import bin.Pedido.Pedido;
import bin.Pedido.Plano;
import bin.Pedido.PlanoExpress;
import bin.Pedido.ReadLoadPedidos;
import bin.Pessoas.Cliente;
import bin.Pessoas.FuncionarioBalcao;
import bin.Pessoas.Pessoa;
import bin.Phase;
import bin.Phase1;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
public class Phase8 extends Phase {
public Phase8() {
Messages = new String[]{"Novo pedido EXPRESS", " "};
TipForInput = "Insira o NIF do Cliente";
InputForStages = new String[]{"Insira o identificador do Pedido"};
numberStages = InputForStages.length + 1;
}
@Override
public Phase HandleCommand(List<String> s) {
String NIF = s.get(0);
String nomeEquipamento = s.get(1);
int pddPorFinalizar = 0;
for (Pedido pdd : Controller.allPedidos) {
if (LocalDate.now().compareTo(pdd.getFim()) < 0) {
pddPorFinalizar++;
}
}
/*for(Pessoa p : Controller.allPessoas){
>>>>>>> 61932bb940790da05df66b3cfcb3558a99a7f224
if((p instanceof Cliente) && ((Cliente) p).getNIF().equals(NIF)) {
*/
for(Cliente cs : Controller.clientes){
if(cs.getNIF().equals(NIF)) {
//pedido express pode ser realizado?????
if (pddPorFinalizar < 4) {
Pedido pdd = new Pedido();
pdd.setNIF(NIF);
pdd.setId(nomeEquipamento);
pdd.setDataRegisto(LocalDate.now());
Plano pll = new PlanoExpress();
pdd.setPl(pll);
pdd.setOrcamento(pll.getCusto() + 10);//mao de obra + custo
ReadLoadPedidos.WritePedido(pdd);
Controller.allPedidos.add(pdd);
//Se foi feito com sucesso
return new Phase1("Pedido EXPRESS adicionado com sucesso!\n");
}else{
ChangeWarningMessage("O pedido EXPRESS não pode ser efetuado devido a sobrecarga de pedidos\n");
return null;
}
}
}
String warning = "Só existem os seguintes Clientes (NIF) -> ";
/*for (Pessoa p : Controller.allPessoas) {
if ( ! (p instanceof Cliente))continue;
warning += ((Cliente) p).getNIF() + " ";
}*/
for (Cliente cs : Controller.clientes) {
warning += cs.getNIF() + " ";
}
warning += " !\n";
ChangeWarningMessage(warning);
return null;
}
}<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/README.md
# Sistemas Distribuidos
Interaction between client and server using multithreads to communicate and **TCP** __sockets__
### Compiling
Use `make server` to initialize the server at the __localhost__
Use `make client` to initialize client
- Client can schedule flights
- Cancel its reservations
- Check currents flights available
All conections and threading is handled by a **Demultiplexer**
<file_sep>/IdeaProjects/POO/Ficha3/src/Circulo.java
public class Circulo {
private double x;
private double y;
private double raio;
public Circulo(){
this.x = 1;
this.y = 1;
this.raio = 1;
}
public Circulo(int x, double y, double raio){
this.x = x;
this.y = y;
this.raio = raio;
}
public Circulo(Circulo cir){
this.x = cir.getX();
this.y = cir.getY();
this.raio = cir.getRaio();
}
public void alteraCentro (double x, double y){
setX(x);
setY(y);
}
public double calculaArea(){
return Math.PI*getRaio()*getRaio();
}
public double calculaPerimetro(){
return 2*Math.PI*getRaio();
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double getRaio() {
return raio;
}
public void setRaio(double raio) {
this.raio = raio;
}
}
<file_sep>/IdeaProjects/POO/Ficha 4/src/Stack.java
import java.lang.reflect.Array;
import java.util.ArrayList;
public class Stack {
private ArrayList<String> str;
public Stack(){
this.str = new ArrayList<String>();
}
public Stack(ArrayList<String> str){
this();
this.str.addAll(str);
}
public Stack(Stack s){
this.str = s.getStr();
}
public ArrayList<String> getStr() {
ArrayList<String> ole = new ArrayList<>();
ole.addAll(this.str);
return ole;
}
public void setStr(ArrayList<String> str) {
this.str = new ArrayList<>();
this.str.addAll(str);
}
public String top(){
this.str.get(this.str.size()-1);
}
public void push(String s){
this.str.add(s);
}
public void pop(){
if(this.str.size()!=0){
this.str.remove(this.str.size()-1);
}
}
public boolean empty(){
return this.str.isEmpty();
}
public int length(){
return this.str.size();
}
}
<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/src/Servidores/ThreadsServer/ThreadEncerrarDia.java
package Servidores.ThreadsServer;
import Connections.Demultiplexer;
import Servidores.Server;
import Servidores.Dados.ServerData;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Scanner;
public class ThreadEncerrarDia extends Thread {
Demultiplexer dm;
private ServerData db;
public ThreadEncerrarDia(Demultiplexer demultiplexer) {
this.dm = demultiplexer;
db = Server.getDataBase();
}
@Override
public void run() {
while (true) {
try {
String message = new String(dm.receive(11));
HandleEncerraDia(message);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
return;
}
}
}
private void HandleEncerraDia(String message) throws IOException, InterruptedException {
Scanner sc = new Scanner(message).useDelimiter(";");
LocalDate date;
try {
date = LocalDate.parse(sc.next());
} catch (Exception e) {
dm.send(11, "100");
sc.close();
return;
}
db.GetDiasEncerrados().addDiaEncerrado(date);
db.GetReservas().RemoveReservasDia(date);
dm.send(11, "200");
sc.close();
}
}<file_sep>/PI21/ficha7.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct celula {
char *palavra;
int ocorr;
struct celula * prox;
} * Palavras;
void libertaLista (Palavras);
int quantasP (Palavras);
void listaPal (Palavras);
char * ultima (Palavras);
Palavras acrescentaInicio (Palavras, char *);
Palavras acrescentaFim (Palavras, char *);
Palavras acrescenta (Palavras, char *);
struct celula * maisFreq (Palavras);
void libertaLista (Palavras l){
Palavras aux;
aux = l;
Palavras aux2 = malloc(sizeof(struct celula));
while(aux != NULL){
aux2 = aux->prox;
free(aux);
aux = aux2;
}
}
/*void libertaLista(Palavras l){
if (l){
libertaLista(l->prox);
free(l);
}
}*/
int quantasP (Palavras l){
int i=0;
while(l != NULL){
i++;
l = l->prox;
}
return i;
}
void listaPal (Palavras l){
Palavras aux;
aux = l;
for(aux; aux != NULL; aux = aux->prox){
printf("%s\n", aux->palavra);
printf("%d\n", aux->ocorr);
}
}
char * ultima (Palavras l){
Palavras aux = l;
while(aux->prox != NULL) aux = aux->prox; return aux->palavra;
}
Palavras acrescentaInicio (Palavras l, char *p){
Palavras aux = malloc(sizeof(struct celula));
aux->palavra = p;
aux->ocorr = 1;
aux->prox = l;
return aux;
}
Palavras acrescentaFim (Palavras l, char *p){
Palavras aux;
aux = l;
Palavras aux2 = malloc(sizeof(struct celula));
for(aux; aux != NULL; aux = aux->prox);
aux2->palavra = p;
aux2->ocorr = 1;
aux2->prox = NULL;
aux = aux2;
return aux;
}
Palavras acrescenta (Palavras l, char *p){
Palavras aux = l;
int r=0;
for(aux; aux != NULL; aux = aux->prox){
if(strcmp(aux->palavra,p) == 0) {aux->ocorr++; r=1;}
}
if(r!=1) l = acrescentaInicio(l,p);
return l;
}
struct celula* maisFreq (Palavras l){
Palavras aux;
aux = l;
struct celula* aux1 = malloc(sizeof(struct celula));
int cont=0;
for(aux; aux != NULL; aux = aux->prox){
if (aux->ocorr > cont) cont = aux->ocorr;
}
for(aux; aux != NULL; aux = aux->prox){
if(aux->ocorr == cont){
aux1->palavra = aux->palavra;
aux1->ocorr = cont;
}
}
return aux1;
}
int main () {
Palavras dic = NULL;
char * canto1 [44] = {"as", "armas", "e", "os", "baroes", "assinalados",
"que", "da", "ocidental", "praia", "lusitana",
"por", "mares", "nunca", "de", "antes", "navegados",
"passaram", "ainda", "alem", "da", "taprobana",
"em", "perigos", "e", "guerras", "esforcados",
"mais", "do", "que", "prometia", "a", "forca", "humana",
"e", "entre", "gente", "remota", "edificaram",
"novo", "reino", "que", "tanto", "sublimaram"};
printf ("\n_____________ Testes _____________\n\n");
int i; struct celula *p;
for (i=0;i<44;i++)
dic = acrescentaInicio (dic, canto1[i]);
printf ("Foram inseridas %d palavras\n", quantasP (dic));
printf ("palavras existentes:\n");
listaPal (dic);
printf ("última palavra inserida: %s\n", ultima (dic));
libertaLista (dic);
dic = NULL;
srand(42);
for (i=0; i<1000; i++)
dic = acrescenta (dic, canto1 [rand() % 44]);
printf ("Foram inseridas %d palavras\n", quantasP (dic));
printf ("palavras existentes:\n");
listaPal (dic);
printf ("última palavra inserida: %s\n", ultima (dic));
p = maisFreq (dic);
//printf ("Palavra mais frequente: %s (%d)\n", p->palavra, p->ocorr);
printf ("\n_________ Fim dos testes _________\n\n");
return 0;
}<file_sep>/PI21/100(3).c
//4
int bitsUm (unsigned int n){
int i,cont=0;
for(i=0; n >=1; i++){
if(n%2 == 1) cont++;
n /= 2;
}
return cont;
}
//5
int trailingZ (unsigned int n){
int i,cont=0;
//if(n==0) cont = 32;
for(i=0; n >1; i++){
if(n%2 == 0) cont++;
n /= 2;
}
return cont;
}
//6
int qDig (unsigned int n){
int cont=0;
while(n>0){
cont++;
n/=10;
}
return cont;
}
//7
char* mystrcat (char s1[], char s2[]){
int i,j;
for(i=0; s1[i] ; i++);
for(j=0; s2[j] ; j++){
s1[j+i]=s2[j];
}
s1[j+i]='\0';
return s1;
}
//8
char* mystrcpy (char *dest, char source[]){
int i;
for(i=0; source[i];i++){
dest[i]=source[i];
}
dest[i]='\0';
return dest;
}
//9
int mystrcmp (char s1[], char s2[]){
int i,r=0;
for(i=0; s1[i] || s2[i]; i++){
if(s1[i] == s2[i]);
else if(s1[i] < s2[i]) return -1;
else return 1;
}
return 0;
}
//10
char *mystrstr (char s1[], char s2[]){
int i,j=0;
for(i=0; s1[i] && s2[j];){
if(s1[i]==s2[j]){
i++;
j++;
}else {
i++;
j=0;
}
}
char* p = &s1[i-j];
if(s2[j]=='\0') return p;
else return NULL;
}
//11
void strrev (char s[]){
int t=0,i,j,y;
while(s[t]!='\0') t++;
for(i=t, j=0; s[i] && s[j] ;i--, j++){
s[j]=s[i];
}
}
//12
void strnoV (char s[]){
int i,j,k=0;
int len;
for(len=0; s[len]; len++);
char aux[len];
for(i=0; s[i]!='\0'; i++){
if(s[i]!='a'||s[i]!='e'||s[i]!='i'||s[i]!='o'||s[i]!='u'||s[i]!='A'||s[i]!='E'||s[i]!='I'||s[i]!='O'||s[i]!='U'){
aux[k] = s[i];
k++;
}
}
aux[k]='\0';
for(j=0; aux[j]!='\0'; j++){
s[j]=aux[j];
}
s[j]='\0';
}
//13
void truncW (char t[], int n){
int i,len,j,k,cont=0;
for(len=0; t[len]; len++);
char aux[len];
for(i=0,j=0; t[i];i++){
if(t[i]!=' ' && cont<n){
aux[j]=t[i];
j++;
cont++;
}
else if(t[i]==' '){
aux[j]=' ';
j++;
cont=0;
}
}
aux[j]='\0';
for(k=0; aux[k]; k++){
t[k]=aux[k];
}
t[k]='\0';
}
//14
char charMaisfreq (char s[]){
int i,j,cont,maisfreq=0;
char x;
if(!s) return 0;
else{
for(i=0; s[i]; i++){
cont=0;
for(j=0; s[j]; j++) if(s[i]==s[j]) cont++;
if(cont>maisfreq){
maisfreq=cont;
x = s[i];
}
}
return x;
}
}
//15
int iguaisConsecutivos (char s[]){
int i,j,cont=0,maior=0;
for(i=0; s[i]; i++){
cont=1;
for(j=i; s[j]; j++){
if(s[i]==s[j+1]) cont++;
else {i=j; break;}
}
if(cont>maior) maior=cont;
}
return maior;
}
//16 ???
int difConsecutivos (char s[]){
int i,j,cont=0,maior=0;
for(i=0; s[i]; i++){
cont=1;
for(j=i; s[j]; j++){
if(s[i]!=s[j+1]) cont++;
else {i=j; break;}
}
if(cont>maior) maior=cont;
}
return maior;
}
//17
int maiorPrefixo (char s1 [], char s2 []){
int i,r=0;
for(i=0; s1[i] && s2[i]; i++){
if(s1[i]==s2[i]) r++;
else break;
}
return r;
}
//18
int maiorSufixo (char s1 [], char s2 []){
int i,j,len1,len2,r=0;
for(len1=0; s1[len1]; len1++);
for(len2=0; s2[len2]; len2++);
for(i=len1-1, j=len2-1; s1[i] && s2[j]; i--,j--){
if(s1[i]==s2[j]) r++;
else break;
}
return r;
}
//19 ??
int sufPref (char s1[], char s2[]){
int i,j,tam=0;
for(i=0,j=0; s2[i] && s1[j];j++){
if(s2[i]==s1[j]){
tam++;
i++;
}
//else{
// i=0;
//tam=0;
//}
}
return tam;
}
//20
int contaPal (char s[]){
int i,r=0;
for(i=0; s[i];i++){
if(s[i]!=' ' && (s[i+1]==' ' || s[i+1]=='\0')) r++;
}
return r;
}
//21
int contaVogais (char s[]){
int i,r=0;
for(i=0; s[i]; i++){
if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O'||s[i]=='U')
r++;
}
return r;
}
//22 8/10
int contida (char a[], char b[]){
int i,j,r=0;
if(!b) return 0;
else if(!a) return 1;
else {
for(i=0; a[i]; i++){
for(j=0; b[j]; j++){
if(a[i]==b[j]) r = 1;
}
if (r!=1) return 0;
}
return 1;
}
}
//23
int palindroma (char s[]){
int i,j,len;
for(len=0; s[len]; len++);
for(i=0,j=len-1; s[i] && s[j]; i++, j--){
if(s[i]!=s[j]) return 0;
}
return 1;
}
//24 ???
int remRep (char x[]){
int i,len,j,meteu;
char aux[len];
for(i=0; x[i]; i++){
if(x[i]==x[i+1]){
//for(j=i; x[j]; j++){
x[i]=x[i+1];
i--;
}
}
for(len=0; x[len]; len++);
return len;
}
//25
int limpaEspacos (char t[]){
int i,j,len,len1,y;
for(len=0; t[len]; len++);
char aux[len];
for(i=0; t[i];){
if(t[i]!=' '){
aux[j]=t[i];
j++;
i++
}
else if(t[i]==' '){
aux[j]=t[i];
while(t[i]==' ') i++;
j++;
}
}
aux[j]='\0';
for(y=0; aux[y]; y++){t[y]=aux[y];}
//for(len1=0; t[len1]; len1++);
return j;
}
//26
void insere (int v[], int N, int x){
int i,j;
for(j=0; v[j]<x; j++);
for(i=N+1; i>j; i--){
v[i]=v[i-1];
}
v[j]=x;
}
//27
void merge (int r [], int a[], int b[], int na, int nb){
int i,j,y,k,aux;
for(i=0; i<na; i++){
r[i]=a[i];
}
for(j=0; j<nb; j++){
r[j+i]=b[j];
}
for(y=1; y<na+nb; y++){
for(k=0; k<na+nb-1; k++){
if(r[k]>r[k+1]){
aux = r[k];
r[k] = r[k+1];
r[k+1] = aux;
}
}
}
}
//28
int crescente (int a[], int i, int j){
int x;
for(x=i; x<j && a[x]; x++){
if(a[x]>a[x+1]) return 0;
}
return 1;
}
//29
int retiraNeg (int v[], int N){
int i,j,t=0;
for(i=0; i<N; i++){
if(v[i]<0){
for(j=i; j<N; j++){
v[j]=v[j+1];
}
N--;
i--;
}
}
return N;
}
//30
int menosFreq (int v[], int N){
int i,f=0,mais=N,elem=v[0];
for(i=0; i<N; i++){
if(v[i]==v[i+1]) f++;
else if(f<mais){
mais=f;
elem = v[i];
f=0;
}
else {
f=0;
}
}
return elem;
}
//31
int maisFreq (int v[], int N){
int i,f=0,mais=0,elem=v[0];
for(i=0; i<N; i++){
if(v[i]==v[i+1]) f++;
else if(f>mais){
mais=f;
elem = v[i];
f=0;
}
else {
f=0;
}
}
return elem;
}
//32
int maxCresc (int v[], int N){
int i,t=1,maior=0;
for(i=0; i<N;i++){
if(v[i]<=v[i+1]) t++;
else if(t>maior) {
maior=t;
t=1;
}
else {
t=1;
}
}
return maior;
}
//33 ????????
int pertence (int v[], int N, int x){
int i,r=0;
for(i=0; i<N; i++){
if(v[i]==x) return 1;
}
return 0;
}
int elimRep (int v[], int n){
int i,j=0,aux[n-1],k,z,y,temp;
for(i=0; i<n-1; i++){
if(!pertence(aux, n-1, v[i])){
aux[j]=v[i];
j++;
}
}
for(k=0; aux[k]; k++){
v[k]=aux[k];
}
for(y=1; y<j; y++){
for(z=0; z<j-1; z++){
if(v[z]>v[z+1]){
temp = v[z];
v[z] = v[z+1];
v[z+1] = temp;
}
}
}
return j;
}
//34
int elimRepOrd (int v[], int n){
int i,j,k,z,y,temp;
for(i=0; i<n; i++){
if(v[i]==v[i+1]){
for(j=n; j>i; j--){
v[j]=v[j-1];
}
n--;
i--;
}
return j;
}
}
//35 ????
int comunsOrd (int a[], int na, int b[], int nb){
int i,j,k=0,t=0,used[na+nb];
for(i=0; i<na; i++){
for(j=0; j<nb; j++){
if(a[i]==b[j] && !pertence(used, na+nb, a[i])){
t++;
used[k]=a[i];
k++;
}
}
}
return t;
}
//36 ???
int comuns (int a[], int na, int b[], int nb){
//37
int minInd (int v[], int n){
int i,indice=0,menor=v[0];
for(i=0; i<n; i++){
if(v[i]<menor){
menor=v[i];
indice = i;
}
}
return indice;
}
//38
void somasAc (int v[], int Ac [], int N){
int i;
for(i=0; i<N; i++){
Ac[i]=v[i]+Ac[i-1];
}
Ac[i]='\0';
}
//39
int triSup (int N, float m [N][N]){
int i,j;
for(i=0; i<N; i++){
for(j=0; i>j; j++){
if(m[i][j]!=0) return 0;
}
}
return 1;
}
//40
void transposta (int N, float m [N][N]){
int i,j,k,z ;
float aux[N][N];
for(i=0; i<N; i++){
for(j=0; j<N; j++){
aux[j][i] = m[i][j];
}
}
for(k=0; k<N; k++){
for(z=0; z<N; z++){
m[k][z] = aux[k][z];
}
}
}
//41
void addTo (int N, int M, int a[N][M], int b[N][M]){
int i,j,k,z;
int aux[N][M];
for(i=0; i<N; i++){
for(j=0; j<M; j++){
a[i][j] += b[i][j];
}
}
}
//42
int unionSet (int N, int v1[N], int v2[N], int r[N]){
int i;
for(i=0; i<N; i++){
if(v1[i]!=0 || v2[i]!=0) r[i]=1;
else r[i]=0;
}
return N;
}
//43 ?
int intersectSet (int N, int v1[N], int v2[N],int r[N]){
int i;
for(i=0; i<N; i++){
if((v1[i]==1 && v2[i]==0) || (v1[i]==0 || v2[i]==1) || (v1[i]==0 && v2[i]==0)) r[i]=0;
else if(v1[i]==1 && v2[i]==1) r[i]=1;
}
return N;
}
//44 ???
int intersectMSet (int N, int v1[N], int v2[N],int r[N]){
int i;
for(i=0; i<N; i++){
if(v1[i]>v2[i]) r[i]=v1[i];
else if(v2[i]>v1[i]) r[i]=v2[i];
else r[i]=v1[i];
}
return N;
}
typedef enum movimento {Norte, Oeste, Sul, Este} Movimento;
typedef struct posicao {
int x, y;
} Posicao;
// 47
Posicao posFinal (Posicao inicial, Movimento mov[], int N){
int i;
//Posicao final;
for(i=0; i<N; i++){
if(mov[i]==Norte) inicial.y += 1;
if(mov[i]==Sul) inicial.y -= 1;
if(mov[i]==Oeste) inicial.x -= 1;
if(mov[i]==Este) inicial.x += 1;
}
return inicial;
}
//48
int caminho (Posicao inicial, Posicao final, Movimento mov[], int N){
int i;
for(i=0; (inicial.x!=final.x) || (inicial.y!=final.y); i++){
if((final.x)>(inicial.x)){
mov[i]=Este;
(inicial.x) ++;
}
else if((inicial.x)>(final.x)){
mov[i]=Oeste;
(inicial.x) --;
}
else if((final.y)>(inicial.y)){
mov[i]=Norte;
(inicial.y) ++;
}
else if((inicial.y)>(final.y)){
mov[i]=Sul;
(inicial.y) --;
}
}
if(i>N) return -1;
else return i;
}
//49
int maisCentral (Posicao pos[], int N){
int i,p=0;
float prox=10;
for(i=0; i<N; i++){
if(sqrt(pos[i].x*pos[i].x + pos[i].y*pos[i].y)<prox){
prox=sqrt(pos[i].x*pos[i].x + pos[i].yi--;
}
//50 ???
int vizinhos (Posicao p, Posicao pos[], int N){
int i;
for(i=0; i<N; i++){
if()
}
}
// parte 2
typedef struct{
int kkkkk;
};
typedef struct lligada {
int valor;
struct lligada *prox;
} *LInt;
//1
int length (LInt l){
int t;
while(l){
t++;
l=l->prox;
}
return t;
}
//2
void freeL (LInt l){
int i;
LInt aux=l;
while(l){
aux=l->prox;
free(l);
l=aux;
}
}
//3
void imprimeL (LInt l){
while(l){
printf("%d\n", l->valor);
l=l->prox;
}
}
//4
LInt newLInt (LInt a, int x){
LInt new = malloc(sizeof(struct lligada));
if(new){
new->valor=x;
new->prox=a;
}
return new;
}
LInt reverseL (LInt l){
LInt aux=NULL;
while(l){
aux = newLInt(l->valor, aux);
l = l->prox;
}
l = aux;
return l;
}
//5
void insertOrd (LInt *l, int x){
while((*l) && (*l)->valor<x) l=&((*l)->prox);
*l = newLInt(x,(*l));
}
//6
int removeOneOrd (LInt *l, int x){
int r=1;
while((*l)){
if((*l)->valor == x){
(*l)= (*l)->prox;
r=0;
}
else l=&((*l)->prox);
}
return r;
}
//7
void merge (LInt *r, LInt a, LInt b){
while(a && b){
if(a->valor < b->valor){
(*r) = malloc(sizeof(struct lligada));
(*r)->valor = a->valor;
a = a->prox;
r=&((*r)->prox);
}
else{
(*r) = malloc(sizeof(struct lligada));
(*r)->valor = b->valor;
b = b->prox;
r=&((*r)->prox);
}
}
if(a==NULL) (*r)=b;
else if(b==NULL) (*r)=a;
}
//8
void splitQS (LInt l, int x, LInt *mx, LInt *Mx){
while(l){
if(l->valor < x){
(*mx) = malloc(sizeof(struct lligada));
(*mx)->valor = l->valor;
mx=&((*mx)->prox);
l = l->prox;
}
else {
(*Mx) = malloc(sizeof(struct lligada));
(*Mx)->valor = l->valor;
Mx=&((*Mx)->prox);
l = l->prox;
}
}
}
//9
LInt parteAmeio (LInt *l){
int len =0;
LInt nova;
LInt *sitio=&nova;
nova = *l;
LInt *aux;
aux = l;
while(*aux){len++; aux = &((*aux)->prox);}
len/=2;
while((*l) && len>0){
sitio = &((*sitio)->prox);
(*l)=(*l)->prox;
len--;
}
(*sitio)=NULL;
return nova;
}
//10
int removeAll (LInt *l, int x){
int removed=0;
while(*l){
if((*l)->valor==x){
(*l)=(*l)->prox;
removed++;
}
else l=&((*l)->prox);
}
return removed;
}
\
//11
int removeDups (LInt *l){
int removed=0;
while(*l){
int x = (*l)->valor;
l = &((*l)->prox);
removed += removeAll(l,x);
}
return removed;
}
//12
int removeMaiorL (LInt *l){
LInt *aux;
aux=l;
int maior=0;
while(*aux){
if((*aux)->valor>maior) maior = (*aux)->valor;
else aux = &((*aux)->prox);
}
while(*l){
if((*l)->valor==maior){
(*l)=(*l)->prox;
return maior;
}
else l= &((*l)->prox);
}
return maior;
}
//13
void init (LInt *l){
while((*l)->prox){
l = &((*l)->prox);
}
free(*l);
(*l)=NULL;
}
//14
void appendL (LInt *l, int x){
LInt celula = malloc(sizeof(struct lligada));
celula->valor=x;
celula->prox=NULL;
while(*l) l = &((*l)->prox);
(*l) = celula;
}
//15
void concatL (LInt *a, LInt b){
while(*a){
a = &((*a)->prox);
}
(*a)=b;
}
//16
LInt cloneL (LInt l){
LInt *aux;
&aux=l;
LInt *new=NULL;
while(*aux){
new = malloc(sizeof(struct lligada));
new->valor= (*aux)->valor;
aux = &((*aux)->prox);
new = &((*new)->prox);
}
return *new;
}
//17
LInt cloneRev (LInt l){
LInt aux = l;
LInt new = NULL;
//malloc(sizeof(struct lligada));
while(l){
new = newLInt(l->valor, new);
l = l->prox;
}
return new;
}
//18
int maximo (LInt l){
LInt *aux;
aux=&l;
int max=0;
while(*aux){
if((*aux)->valor > max) max = (*aux)->valor;
aux = &((*aux)->prox);
}
return max;
}
//19
int take (int n, LInt *l){
int x=0;
while(*l){
if(x<n){
l = &((*l)->prox);
x++;
}
else{
free(*l);
(*l)= (*l)->prox;
}
}
return x;
}
//20
int drop (int n, LInt *l){
int x=0,c=0;
while(*l){
if(x<n){
free(*l);
(*l)= (*l)->prox;
c++;
}
else{
l = &((*l)->prox);
}
x++;
}
return c;
}
//21
LInt Nforward (LInt l, int N){
int x=0;
LInt aux =l;
//LInt new = malloc(sizeof(struct lligada));
while(aux){
if(x==N) return aux;
aux = aux->prox;
x++;
}
return 0;
}
//22
int listToArray (LInt l, int v[], int N){
int i=0;
LInt aux = l;
while(aux && i<N){
v[i]=aux->valor;
aux = aux->prox;
i++;
}
return i;
}
//23
LInt arrayToList (int v[], int N){
int i;
LInt nova=NULL;
LInt *new = &nova;
//nova = &new;
for(i=0; i<N; i++){
while(*new) new = &((*new)->prox);
(*new) = malloc(sizeof(struct lligada));
(*new)->valor = v[i];
(*new)->prox=NULL;
}
return nova;
}
//24
LInt somasAcL (LInt l){
LInt aux = l;
LInt Resul=NULL;
LInt *new=&Resul;
int soma=0;
while(aux){
soma += aux->valor;
while(*new) new = &((*new)->prox);
(*new) = malloc(sizeof(struct lligada));
(*new)->valor = soma;
(*new)->prox=NULL;
aux = aux->prox;
}
return Resul;
}
//25
void remreps (LInt l){
LInt aux;
if(l){
while(l->prox){
//LInt ola = (*aux)->prox;
if(l->valor == l->prox->valor){
aux = l->prox;
l->prox = aux->prox;
free(aux);
}
else{
l = l->prox;
}
}
}
}
//26
LInt rotateL (LInt l){
LInt celula = malloc(sizeof(struct lligada));
LInt *aux = &l;
LInt auxL = l; int len=0;
while(auxL){len++; auxL = auxL->prox;}
if(l==NULL || len==1) return l;
celula->valor = (*aux)->valor;
celula->prox = NULL;
l = l->prox;
while(*aux){
aux = &((*aux)->prox);
}
(*aux) = celula;
return l;
}
//27
LInt parte (LInt l){//l- pares y- impares
int x=0;
LInt new;
LInt *celula=&new;
LInt *aux = &l;
//LInt *celula;
while(*aux){
if(x%2!=0){
while(*celula) celula=&((*celula)->prox);
(*celula) = malloc(sizeof(struct lligada));
(*celula)->valor = (*aux)->valor;
(*celula)->prox=NULL;
//celula = &((*celula)->prox);
(*aux)=(*aux)->prox;
}
else{
aux = &((*aux)->prox);
}
x++;
}
return new;
}
//28
int maximo(int a, int b){
if(a>b) return a;
else return b;
}
int altura (ABin a){
int h=0;
if(a){
h += 1 + maximo( altura(a->esq), altura(a->dir));
}
return h;
}
//29
ABin cloneAB (ABin a){
ABin new = malloc(sizeof(struct nodo));
while(a){
new->valor = a->valor;
new->esq = cloneAB(a->esq);
new->dir = cloneAB(a->dir);
return new;
}
return NULL;
}
//30
void mirror (ABin *a){
ABin aux;
if(*a){
aux = (*a)->esq;
(*a)->esq = (*a)->dir;
(*a)->dir = aux;
mirror(&((*a)->esq));
mirror(&((*a)->dir));
}
}
//31
void inorderAux (ABin a, LInt *l){
//LInt new;
if(a){
inorderAux(a->esq, l);
//CRIAR CELULA (ULTIMA POS, MALLOC, ATUALIZA VALOR, PROX = NULL)
while(*l) l=&((*l)->prox);
(*l) = malloc(sizeof(struct nodo));
(*l)->valor = a->valor;
(*l)->prox = NULL;
//l = &((*l)->prox);
inorderAux(a->dir, l);
}
}
void inorder(ABin a, LInt *l){
(*l)=NULL;
inorderAux(a, l);
}
//32
void preorderAux (ABin a, LInt *l){
if(a){
while(*l) l=&((*l)->prox);
(*l) = malloc(sizeof(struct nodo));
(*l)->valor = a->valor;
(*l)->prox = NULL;
preorderAux(a->esq, l);
preorderAux(a->dir, l);
}
}
void preorder(ABin a, LInt *l){
(*l)=NULL;
preorderAux(a, l);
}
//33=
//34
int depth (ABin a, int x){
int r=1;
if(a==NULL) r=-1;
else if(a->valor == x) return 1;
else{
esquerda = depth(a->esq, x);
direita = depth(a->dir, x);
if(esquerda==-1 && direita==-1) return -1;
else if(esquerda==-1) r+=direita;
else if(direita==-1) r+=esquerda;
else if(direita<esquerda) r+= direita;
else r+= esquerda;
}
return r;
}
//35
int freeAB (ABin a){
int n=0;
if(a){
free(a);
n += 1 + freeAB(a->esq) + freeAB(a->dir);
}
return n;
}
//36
int pruneAB (ABin *a, int l){
int r=0;
if(a==NULL) r=0;
if(l==0) r=freeAB(*a);
//else if()
else if(*a){
r += 1 + pruneAB(&((*a)->esq), l-1) + pruneAB(((*a)->dir), l-1);
}
return r;
}
//37
int iguaisAB (ABin a, ABin b){
int r=0,esquerda,direita;
if(a==NULL && b==NULL) r=1;
else if(a==NULL || b==NULL) r=0;
else{
if(a->valor == b->valor){
esquerda = iguaisAB(a->esq, b->esq);
direita = iguaisAB(a->dir, b->dir);
if(esquerda==0 || direita ==0) r=0;
else r=1;
}
else{
r=0;
}
}
return r;
}
//38
void nivelLAux (ABin a, int n, LInt *new){
//int h=0;
//LInt Resul;
//&new = Resul;
if(!a) return;
if(n==1){
while(*new){ new = &((*new)->prox);}
(*new) = malloc( sizeof( struct lligada));
(*new)->valor = a->valor;
(*new)->prox = NULL;
}
else{
nivelLAux(a->esq, n-1, new);
nivelLAux(a->dir, n-1, new);
}
//return *new;
}
LInt nivelL (ABin a, int n){
LInt Resul=NULL;
nivelLAux(a,n,&Resul);
return Resul;
}
//39
int nivelVaux (ABin a, int n, int v[], int *i){
//int i=0;
if(!a) return 0;
if(n==1){
v[*i]=a->valor;
(*i)++;
}
else{
nivelVaux(a->esq, n-1, v, i);
nivelVaux(a->dir, n-1, v, i);
}
return *i;
}
int nivelV (ABin a, int n, int v[]){
int i=0;
return nivelVaux(a, n, v, &i);
}
//40
int dumpAbinAux (ABin a, int v[], int N, int *i){//esq valor dir
if(!a) (*i)+= 0;
else{
(*i) = dumpAbinAux(a->esq, v, N, i);
if((*i)<N){
v[*i]=a->valor;
(*i)++;
}
(*i) = dumpAbinAux(a->dir, v, N, i);
}
return *i;
}
int dumpAbin(ABin a, int v[], int N){
int i=0;
return dumpAbinAux(a, v, N, &i);
//return i;
}
//41
ABin somasAcA (ABin a){
ABin new;
if(!a) return NULL;
else{
new = malloc(sizeof( struct nodo));
new->valor = soma(a);
new->esq = somasAcA (a->esq);
new->dir = somasAcA (a->dir);
}
return new;
}
int soma(ABin a){
if(!a) return 0;
int s = a->valor + soma(a->esq) + soma(a->dir);
return s;
}
//42
int contaFolhasAux (ABin a, int *r){
if(!a) return 0;
if(!(a->dir) && !(a->esq)){
(*r)= 1 + contaFolhasAux(a->esq, r) + contaFolhasAux(a->dir, r);
}
else{
(*r) = contaFolhasAux(a->esq, r) + contaFolhasAux(a->dir, r);
}
return *r;
}
int contaFolhas(ABin a){
int r=0;
return contaFolhasAux(a, &r);
}
//43
ABin cloneMirror (ABin a){
ABin new;
if(!a) return NULL;
if(a){
new = malloc(sizeof(struct nodo));
new->valor = a->valor;
new->esq = cloneMirror(a->dir);
new->dir = cloneMirror(a->esq);
}
return new;
}
//44
int addOrd (ABin *a, int x){
while((*a)){
if((*a)->valor==x) return 1;
else if(x>(*a)->valor) a = &((*a)->dir);
else a = &((*a)->esq);
}
ABin new = malloc(sizeof(struct nodo));
new->valor = x;
new->esq=NULL;
new->dir=NULL;
(*a)=new;
return 0;
}
//45
int lookupAB(ABin a, int x){
while(a){
if(a->valor==x) return 1;
else if(x>a->valor) a = a->dir;
else a = a->esq;
}
return 0;
}
//46
int depthOrd (ABin a, int x){
if(!lookupAB(a,x)) return -1;
int r=1;//<-
while(a){
if(a->valor==x) return r;
else if(x>a->valor)a = a->dir;
else a = a->esq;
r++;
}
return r;
}
//47
int maiorAB (ABin a){
int maior=0;
while(a){
if(a->valor>maior) maior=a->valor;
else a = a->dir;
}
return maior;
}
//48
void removeMaiorA (ABin *a){
ABin aux;
while((*a)->dir) a = &((*a)->dir);
aux = (*a);
free(*a)
(*a) = aux->esq;
}
//49
int quantosMaioresAux (ABin a, int x, int *r){
//int r=0;
if(!a) return 0;
if(a->valor>x){
(*r) = 1 + quantosMaioresAux(a->esq, x, r) + quantosMaioresAux(a->dir, x, r);
}
else if(a->valor<=x){
(*r) = quantosMaioresAux(a->dir, x, r);
}
return *r;
}
int quantosMaiores (ABin a, int x){
int r =0;
return quantosMaioresAux(a,x,&r);
}
//50
int addOrd (ABin *a, int x){
while((*a)){
if((*a)->valor==x) return 1;
else if(x>(*a)->valor) a = &((*a)->dir);
else a = &((*a)->esq);
}
ABin new = malloc(sizeof(struct nodo));
new->valor = x;
new->esq=NULL;
new->dir=NULL;
(*a)=new;
return 0;
}
void listToBTree (LInt l, ABin *a){
while(l){
addOrd(a, l->valor);
l = l->prox;
}
}
//51
int MaiorAux(ABin a, int x){
int i;
if(!a) i=0;
else if(a->valor > x) i=1;
else if(MaiorAux(a->esq, x)==1 || MaiorAux(a->dir, x)==1) i=1;
else i=0;
return i;
}
int MenorAux(ABin a, int x){
int i;
if(!a) i=0;
else if(a->valor < x) i=1;
else if(MenorAux(a->esq, x)==1 || MenorAux(a->dir, x)==1) i=1;
else i=0;
return i;
}
int deProcura (ABin a){
int i;
if(!a) i=1;
else if(MaiorAux(a->esq, a->valor)==1 || MenorAux(a->dir, a->valor)==1) return 0;
else if(deProcura(a->esq)==0 || deProcura(a->dir)==0) return 0;
else i=1;
return i;
}
<file_sep>/IdeaProjects/POO/Ficha 5/src/parque.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.stream.Collectors;
public class parque {
private String nome;
private Map<String,Lugar> lugares;
public parque(String nome, Map<String,Lugar> lugares){
this();
this.nome = nome;
for (Map.Entry<String, Lugar> map : this.lugares.entrySet()){
this.lugares.put(map.getKey(), map.getValue().clone());
}
}
public parque (parque p){
this.nome = p.getNome();
this.lugares = p.getLugares();
}
public parque (){
this.nome = "";
this.lugares = new HashMap<>();
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Map<String ,Lugar> getLugares() {
Map<String, Lugar> newMap = new HashMap<>();
for (Map.Entry<String, Lugar> map : this.lugares.entrySet()){
newMap.put(map.getKey(), map.getValue().clone());
}
return newMap;
// return this.lugares.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, l -> l.getValue().clone()));
}
public void setLugares(Map<String,Lugar> spot) {
this.lugares = new HashMap<>();
for (Map.Entry<String, Lugar> map : spot.entrySet()){
lugares.put(map.getKey(), map.getValue().clone());
}
}
public ArrayList<String> devolveMatriculaOcupados(){
ArrayList<String> newL = new ArrayList<>();
for (Map.Entry<String, Lugar> map : lugares.entrySet()){
newL.add(map.getKey());
}
return newL;
//return this.lugares.keySet().stream().collect(ArrayList::new);
}
public void novoLugar(Lugar l){
this.lugares.put(l.getMatricula(), l.clone());
}
public void removeLugar(String matricula){
this.lugares.remove(matricula);
}
public void alteraTempo (String matricula, int tempo) {
//Iterator<Lugar> it = this.lugares.values().iterator();
for (Map.Entry<String, Lugar> map : this.lugares.entrySet()){
if (map.getKey().equals(matricula)) map.getValue().setMinutos(tempo);
}
}
public int totalMinutos (){
/*
int r=0;
for (Map.Entry<String,Lugar> map : lugares.entrySet()){
r += map.getValue().getMinutos();
}
return r; */
return this.lugares
.values()
.stream()
.mapToInt(Lugar::getMinutos)
.sum();
}
public boolean lookupMatricula (String matricula){
return this.lugares.containsKey(matricula);
//for (Map.Entry<String, Lugar> map : this.lugares.entrySet()){
// return r;
}
public ArrayList<String> listaMatriculas (int x){
ArrayList<String> newL = new ArrayList<>();
for (Map.Entry<String,Lugar> map : this.lugares.entrySet()){
if(map.getValue().getMinutos()>x && map.getValue().getPermanente()){
newL.add(map.getKey());
}
}
return newL;
}
public Map<String,Lugar> cloneLugares (){
return this.lugares
.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry :: getKey, lugar -> lugar.getValue().clone()));
}
public String info(String matricula){
for (String mat : this.lugares.keySet()){
if (mat.equals(matricula)) return mat;
}
return null;
}
}
<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/src/Connections/Frame.java
package Connections;
import java.nio.charset.StandardCharsets;
public class Frame {
public final int tag;
public final byte[] data;
public Frame(int tag, byte[] data)
{
this.tag = tag;
this.data = data;
}
@Override
public String toString()
{
String s = new String(data, StandardCharsets.UTF_8);
return tag + " ->" + s;
}
}<file_sep>/PI21/Ficha 10/main.c
#include "abin.h"
#include "sol.h"
#include <time.h>
int main (){
int v1[15] = { 1, 3, 5, 7, 9,11,13,15,17,19,21,23,25,27,29},
N=15, i;
ABin a1,r;
srand(time(NULL));
printf ("_______________ Testes _______________\n\n");
// N = rand() % 16;
a1 = RandArvFromArray (v1, N);
printf ("________________________________________\n");
printf ("Primeira árvore de teste (%d elementos)\n", N);
dumpABin (a1, N);
/*
printf ("Espinha\n");
constroiEspinha_sol (&a1);
dumpABin (a1, N);
printf ("Equilibrar espinha\n");
equilibraEspinha_sol (&a1,N);
dumpABin (a1, N);
*/
i = rand() %N;
printf ("Remoção do elemento %d\n", v1[i]);
removeElem_sol (&a1,v1[i]);
dumpABin (a1, --N);
r = removeMenor_sol (&a1);
printf ("Remoção do menor %d\n", r->valor);
dumpABin (a1, --N);
printf ("Remoção da raiz %d\n", a1->valor);
removeRaiz_sol (&a1);
dumpABin (a1, --N);
freeABin (a1);
a1 = newABin(v1[7], RandArvFromArray (v1 ,7),
RandArvFromArray (v1+8,7));
N = 15;
printf ("_______________________________________\n");
printf ("Segunda árvore de teste (%d elementos)\n", N);
dumpABin (a1, N);
printf ("Rotação à direita\n");
rodaDireita (&a1);
dumpABin (a1, N);
printf ("Rotação à esquerda\n");
rodaEsquerda (&a1);
dumpABin (a1, N);
printf ("Promoção do maior\n");
promoveMaior_sol (&a1);
dumpABin (a1, N);
printf ("Promoção do menor\n");
promoveMenor_sol (&a1);
dumpABin (a1, N);
printf ("\n\n___________ Fim dos testes ___________\n\n");
return 0;
}<file_sep>/PI21/Ficha 8/Listas.h
#ifndef _LISTAS_
#define _LISTAS_
typedef struct slist {
int valor;
struct slist * prox;
} * LInt;
LInt newLInt (int x, LInt xs);
typedef struct dlist {
int valor;
struct dlist *ant, *prox;
} *DList;
DList newDList (int x, DList xs);
#endif<file_sep>/FM7/GuardaRedes.java
/**
* Escreva a descrição da classe GuardaRedes aqui.
*
* @author (seu nome)
* @version (número de versão ou data)
*/
public class GuardaRedes extends Jogador{
public int elas;
public GuardaRedes(){
super();
this.elas = 0;
}
public GuardaRedes(String nome, int num, int vel, int res, int des, int imp, int jCab, int rem, int cPas,int cruzamento){
super(nome,num,vel,res,des,imp,jCab,rem,cPas);
this.elas = cruzamento;
}
public GuardaRedes(GuardaRedes m){
super(m);
this.elas = m.getElas();
}
public int getElas(){
return this.elas;
}
public GuardaRedes clone(){
return new GuardaRedes(this.getNome(), this.getNum(), this.getVel() , this.getRes() , this.getDes(), this.getImp(), this.getJCab(),this.getRem(), this.getCPas(),this.elas);
}
public static GuardaRedes loadLine(String s){
String[] div = s.split(",");
if (div.length >= 10)
return new GuardaRedes(div[0],Integer.parseInt(div[1]),
Integer.parseInt(div[2]),Integer.parseInt(div[3]),
Integer.parseInt(div[4]),Integer.parseInt(div[5]),
Integer.parseInt(div[6]),Integer.parseInt(div[7]),
Integer.parseInt(div[8]),Integer.parseInt(div[9]));
else
return new GuardaRedes();
}
public int getPontos(){
int pontos = (int)((this.getVel()*0.9f + this.getRes()*0.8f + this.getDes()*1.2f + this.getImp()*1.2f + this.getJCab()*0.8f + this.getRem()*0.8f + this.getCPas()*1.1f + this.elas*1.3f) / 8);
if (pontos >99) pontos = 99;
return pontos;
}
public String toString(){
return super.toString() + " elas:" + this.elas + "\n";
}
}<file_sep>/PI21/Ficha 8/Stack.c
#include <stdio.h>
#include <stdlib.h>
#include "Stack.h"
void initStack (Stack *s){
}
int SisEmpty (Stack s){
return -1;
}
int push (Stack *s, int x){
return -1;
}
int pop (Stack *s, int *x){
return -1;
}
int top (Stack s, int *x){
return -1;
}
<file_sep>/PI21/Ficha 10/ficha10.c
typedef struct nodo {
int valor;
struct nodo *esq, *dir;
} * ABin;
ABin removeMenor (ABin *a){
}<file_sep>/PI21/100(2).c
typedef struct lligada {
int valor;
struct lligada *prox;
} *LInt;
LInt newLInt (int v, LInt t){
LInt new = (LInt) malloc (sizeof (struct lligada));
if (new!=NULL) {
new->valor = v;
new->prox = t;
}
return new;
}
int length (LInt l){
int r=0;
LInt aux = l;
while(aux){
r++;
aux = aux->prox;
}
return r;
}
void freeL (LInt l){
LInt aux = l;
while(l){
aux = l->prox;
free(l);
l = aux;
}
}
void imprimeL (LInt l){
LInt aux = l;
while(aux){
printf("%d\n " (aux->valor));
aux = aux->prox;
}
}
LInt newL (int v, LInt l){
LInt new = malloc(sizeof(struct lligada));
if(new){
new->valor = v;
new->prox = l;
}
return new;
}
LInt reverseL (LInt l){
LInt aux=NULL;
while(l){
aux = newL(l->valor, aux);
l = l->prox;
}
l= aux;
return aux;
}
void insertOrd (LInt *l, int x){
LInt aux=l;
LInt newL = malloc(sizeof(struct lligada));
while(aux && aux->valor){
}
}
int removeOneOrd (LInt *l, int x){
int r=1;
while(*l){
if ((*l)->valor == x){
(*l) = (*l)->prox;
r = 0;
}
else l = &((*l)->prox);
}
return r;
}
void merge (LInt *r, LInt a, LInt b){
if(a==NULL) (*r)=b;
else if (b==NULL) (*r)
while(a && b){
if(a->valor < b->valor){
//(*r) = malloc(sizeof(struct lligada));
(*r)->valor = a->valor;
a = a->prox;
}else{
//(*r) = malloc(sizeof(struct lligada));
(*r)->valor = b->valor;
b = b->prox;
}
r = &((*r)->prox);
}
}
void splitQS (LInt l, int x, LInt *mx, LInt *Mx){
while(l){
if(l->valor < x){
(*mx) = malloc(sizeof(struct lligada));
(*mx)->valor = l->valor;
mx = &((*mx)->prox);
}else{
(*Mx) = malloc(sizeof(struct lligada));
(*Mx)->valor = l->valor;
Mx = &((*Mx)->prox);
}
l = l->prox;
}
}
LInt parteAmeio (LInt *l){
int r=0,par=0;
LInt newResul = malloc(sizeof(struct lligada));
LInt *aux;
aux = l;
LInt *newResulAux = &newResul;
newResul = *l;
while(*aux) { r++; aux = &((*aux)->prox); }
r/=2;
while(r>0){
newResulAux = &((*newResulAux)->prox;
(*l) = (*l)->prox;
r--;
}
(*newResulAux) = NULL;
return newResul;
}
int removeAll (LInt *l, int x){
int r=0;
while(*l){
if((*l)->valor == x){
(*l) = (*l)->prox;
r++;
}
else l = &((*l)->prox);
}
return r;
}
int pertenceL (LInt *l, int x){
int r=0;
while(*l){
if((*l)->valor == x) r=1;
l = &((*l)->prox);
}
return r;
}
int removeDups (LInt *l){
LInt aux;
aux=&l;
LInt *new = NULL;
int c=0;
while(*l){
if(!pertenceL((*new),aux->valor)){
(*new)->valor = aux->valor;
new = &((*new)->prox);
c++;
}
aux = aux->prox;
}
return c;
}
int removeMaiorL (LInt *l){
int maior=0;
LInt *aux;
aux=l;
while(*aux){
if((*aux)->valor > maior) maior = (*aux)->valor;
aux = &((*aux)->prox);
}
while(*l){
if((*l)->valor == maior){
(*l) = (*l)->prox;
return maior;
}else{
l = &((*l)->prox);
}
}
return maior;
}
void init (LInt *l){
while((*l)->prox){
l = &((*l)->prox);
}
free((*l));
(*l) = NULL;
}
void appendL (LInt *l, int x){
LInt new = malloc(sizeof(struct lligada));
new->valor = x;
new->prox = NULL;
while(*l) l = &((*l)->prox);
(*l)=new;
}
void concatL (LInt *a, LInt b){
while(*a){
a=&((*a)->prox);
}
(*a) = b;
}
LInt cloneL (LInt l){
LInt new = malloc(sizeof(struct lligada));
LInt aux=l;
while(aux){
new->valor = aux->valor;
new = new->prox;
aux = aux->prox;
}
return new;
}
//17
LInt cloneRev (LInt l){
LInt clone=NULL;
LInt ll=l;
while(ll){
LInt aux = malloc(sizeof(struct lligada));
aux->valor = ll->valor;
aux->prox = clone;
clone = aux;
ll = ll->prox;
}
return clone;
}
//outra
LInt cloneRev (LInt l){
LInt aux=NULL;
while(l){
aux = newLInt(l->valor, aux);
l = l->prox;
}
//l= aux;
return aux;
}
int maximo (LInt l){
int max=0;
while(l){
if(l->valor > max) max = l->valor;
l = l->prox;
}
return max;
}
int take (int n, LInt *l){
LInt *aux;
aux = l;
int len=0;
while(*aux){ len++; aux=&((*aux)->prox); }
int cont = n;
if(len > n){
while(*l){
if(n > 0){
l = &((*l)->prox);
}else{
(*l) = (*l)-> prox;
free((*l));
}
n--;
}
return cont;
}else{
return len;
}
}
int drop (int n, LInt *l){
int cont=0;
while(*l && cont<n){
cont++;
free((*l));
(*l) = (*l)->prox;
}
return cont;
}
int drop (int n , LInt *l){
int i;
for(i=0; (*l) && i<n; i++){
free(*l);
(*l)= (*l)->prox;
}
return i;
}
//21
LInt Nforward (LInt l, int N){
int aux=0;
while(l){
if(aux == N){
return l;
}
l = l->prox;
aux++;
}
}
int listToArray (LInt l, int v[], int N){
int i=0,cont=0;
while(l && i<N){
v[i]=l->valor;
l = l->prox;
i++;
cont++;
}
return cont;
}
LInt arrayToList (int v[], int N){
int i;
LInt newL;
LInt aux=NULL;
for(i=N; i>=N; i--){
newL = malloc(sizeof(struct lligada));
newL->valor = v[i];
newL->prox = aux;
aux = newL;
}
//newL->prox = NULL;
return aux;
}
LInt newLInt (int v, LInt l){
LInt new = malloc(sizeof (struct lligada));
if(new){
new->valor = v;
new->prox = l;
}
return new;
}
LInt arrayToList (int v[], int N){
int i;
LInt newL;
LInt aux=NULL;
for(i=N-1; i>=0; i++){
newL = newLInt(v[i],newL);
}
//newL->prox = NULL;
return newL;
}
LInt somasAcL (LInt l){//??????????????????'
LInt new;
int soma=0;
LInt aux = l;
while(aux){
new = malloc(sizeof(struct lligada));
soma += aux->valor;
new->valor = soma;
aux = aux->prox;
new = new->prox;
}
return new;
}
int pertenceL (LInt *l, int x){
int r=0;
while(*l){
if((*l)->valor == x) r=1;
l = &((*l)->prox);
}
return r;
}
void remreps (LInt l){
LInt aux;
aux=l;
LInt *new = NULL;
int c=0;
while(aux){
if(!pertenceL((*new),aux->valor)){
(*new)->valor = aux->valor;
new = &((*new)->prox);
c++;
}
aux = aux->prox;
}
return c;
}
void remreps (LInt l){//?????????????
LInt aux = l;
LInt *aux2 = &aux;
aux = l->prox;
while(l){
while(*aux2){
if(l->valor == (*aux2)->valor){
free(*aux2);
(*aux2) = (*aux2)->prox;
}else{
aux2 = &((*aux2)->prox);
}
}
l = l->prox;
}
}
LInt rotateL (LInt l){//
int r=0;
LInt auxl =l;
while(auxl){r++; auxl = auxl->prox;}
if(l == NULL || r == 1) return l;
LInt new = malloc(sizeof(struct lligada));
LInt *aux=&l;
new->valor = (*aux)->valor;
new->prox = NULL;
l = l->prox;
while(*aux){ aux = &((*aux)->prox); }
(*aux) = new;
return l;
}
LInt parte (LInt l){//na lista l os impares
LInt new=NULL,celula;
LInt *new2=&new;
LInt *aux = &l;
int i=0;
while(*aux){
if(i % 2 == 0){
aux = &((*aux)->prox);
}else{
celula = malloc(sizeof(struct lligada));
celula->valor = (*aux)->valor;
celula->prox = NULL;
(*new2) = celula;
(*aux) = (*aux)->prox;
new2 = &((*new2)->prox);
}
i++;
}
return new;
}
typedef struct nodo {
int valor;
struct nodo *esq, *dir;
} *ABin;
int altura (ABin a){
int h=0;
if(a){
h+= 1 + max (altura(a->esq) , altura(a->dir));
}
return h;
}
ABin cloneAB (ABin a){
ABin new = malloc(sizeof(struct nodo));
while(a){
new->valor = a->valor;
new->esq = cloneAB(a->esq);
new->dir = cloneAB(a->dir);
return new;
}
return NULL;
}
void mirror (ABin *a){
ABin aux;
if(*a){
aux = (*a)->dir;
(*a)->dir = (*a)->esq;
(*a)->esq = aux;
mirror(&((*a)->esq));
mirror(&((*a)->dir));
}
}
/*
Numa arvore de procura:
_inorder: ordem crescente;
_preorder : valor, esquerda, direita;
_posorder: esquerda,direita, valor;
*/
void auxinorder (ABin a, LInt *l){
if(a==NULL);
else{
auxinorder(a->esq, l);
while(*l){ l = &((*l)->prox);}
(*l) = malloc(sizeof(struct lligada));
(*l)->valor = a->valor;
(*l)->prox = NULL;
auxinorder(a->dir, l);
}
}
void inorder (ABin a, LInt *l){
(*l)=NULL;
auxinorder(a, l);
}
int depth (ABin a, int x){
int h=1,esq,dir,r=1;
if(a==NULL) r= -1;
else if(a->valor == x) return 1;
else {
esq = depth(a->esq,x);
dir = depth(a->dir, x);
if ((esq == -1) && (dir == -1)) return -1;
else if(esq == -1) r += dir;
else if (dir == -1) r += esq;
else if (esq>dir) r += dir;
else r+= esq;
}
return r;
}
int freeAB (ABin a){
//ABin aux;
int soma=0;
if(a){
free(a);
soma += 1 + freeAB(a->esq) + freeAB(a->dir);
}
return soma
}
int pruneAB (ABin *a, int l){
}
int iguaisAB (ABin a, ABin b){
int r,esq,dir;
if(a==NULL && b==NULL) r=1;
else if(a==NULL || b==NULL) r=0;
else{
if(a->valor == b->valor){
esq = iguaisAB(a->esq, b->esq);
dir = iguaisAB (a->dir, b->dir);
if(esq==0 || dir==0) r= 0;
else r=1;
}else{
r =0;
}
}
return r;
}
LInt nivel (ABin a, int n){
LInt new;
LInt *aux = &new;
if(a == NULL) return;
while(*aux) {aux = &((*aux)->valor);}
(*aux) = malloc(sizeof(struct lligada));
(*aux)->prox = NULL;
if(n==1){
(*aux)->valor = a->valor;
}else{
nivel(a->esq, n-1);
nivelL(a->dir, n-1);
}
return new;
}
int dumpAbin (ABin a, int v[], int N){
int i=0;
if(a==NULL) return 0;
else if (N==0) return 0;
else{
}
}
int contaFolhas (ABin a){
int r=0;
if(a == NULL) return 0;
else if(a->dir == NULL && a->esq == NULL ) r+= 1 + contaFolhas(a->esq) + contaFolhas(a->dir);
else {
r+= contaFolhas(a->esq) + contaFolhas(a->dir);
}
}
ABin cloneMirror (ABin a){
ABin new;
//new=a;
if(a){
new =malloc(sizeof(struct nodo));
new->valor = a->valor;
new->esq = cloneMirror(a->dir);
new->dir = cloneMirror(a->esq);
}else return NULL;
return new;
}
int addOrd (ABin *a, int x){
while(*a){
if((*a)->valor == x) return 1;
else if((*a)->valor < x) a = &((*a)->dir);
else a = &((*a)->esq);
}
ABin new = malloc(sizeof(struct nodo));
new->valor = x;
new->dir = new->esq = NULL;
(*a)=new;
return 0;
}
int lookupAB (ABin a, int x){
//ABin *aux=&a;
while(a){
if(a->valor == x) return 1;
if(a->valor < x) a = a->dir;
else a = a->esq;
}
return 0;
}
int depthOrd (ABin a, int x){
int r=1;
if(a==NULL) return -1;
else if(a->valor == x) return r;
else {
if(a->valor < x) d;
}
}
}
//4
int bitsUm (unsigned int n){
int r=0;
while(n>0){
if(n%2 == 1) r++;
n /= 2;
}
return r;
}
//5
int trailingZ (unsigned int n){
int r=0;
while(n>0){
if(n%2 == 0) r++;
n /= 2;
}
return r;
}
//6
int qDig (unsigned int n){
int r=0;
while(n>0){
n /= 10;
r++;
}
return r;
}
//7
char* mystrcat (char s1[], char s2[]){
int i,j;
for(i=0; s1[i]; i++);
for(j=0; s2[j];j++){
s1[i]=s2[j];
i++;
}
s1[i]='\0';
return s1;
}
//8
char* mystrcpy (char *dest, char source[]){
int i;
for(i=0; source[i];){
dest[i]=source[i];
i++;
}
dest[i]='\0';
return dest;
}
//9
int mystrcmp (char s1[], char s2[]){
int i,r;
for(i=0; s1[i] || s2[i]; i++){
if(s1[i]==s2[i]);
else if (s1[i]<s2[i]) return -1;
else return 1;
}
return 0;
}
//10
char* mystrstr (char s1[], char s2[]){
int i=0,j=0;
while (s1[i] && s2[j]){
if(s1[i]==s2[j]){ i++; j++; }
else{ i++; j=0; }
}
char *p = &s1[i-j];
if(s2[j]=='\0') return p;
else return NULL;
}
//11
void strrev (char s[]){
int i,j,t=0;
while(s[t]) t++;
for(i=0, j=t-1; s[i] && s[j]; i++, j--){
s[i]=s[j];
}
}
//12
void strnoV (char s[]){
int i,j,k=0;
char aux[strlen(s)];
for(i=0;s[i]!='\0';i++){
if(s[i]!='a'||s[i]!='e'||s[i]!='i'||s[i]!='o'||s[i]!='u'||s[i]!='A'||s[i]!='E'||s[i]!='I'||s[i]!='O'||s[i]!='U'){
aux[k] = s[i];
k++;
}
}
aux[k]= '\0';
for(j=0; aux[j]!='\0';j++){
s[j] = aux[j];
}
s[j] = '\0';
}
//13?????????????
void truncW (char t[], int n){
int i,k=0;
char aux[lenght(t)];
for(i=0;t[i]; i++){
while(t[i]!=' ') aux[k]=t[i];
}
}
//14
char charMaisfreq (char s[]){
int maior=0,r=0,j,i;
char a;
if(!s) return 0;
else {
for(i=0; s[i]; i++){
r=0;
for(j=0; s[j];j++){
if(s[i]==s[j]){
r++;
}
}
if(r>maior) {maior = r; a = s[i];}
}
}
return a;
}
//15
int iguaisConsecutivos (char s[]){
int i,j,r=0,maior=0;
for(i=0;s[i];i++){
r=1;
for(j=i;s[j];j++){
if(s[i]==s[j+1]) r++;
else{ i=j; break; }
}
if(r>maior) maior=r;
}
return maior;
}
//16 ?????????
int difConsecutivos (char s[]){
int i,j,r=1,maior=0;
for(i=0;s[i];i++){
if((s[i]>='A' && s[i]<='Z') || s[i]<='a' && s[i]>= 'z'){
if(s[i]!=s[i+1]) r++;
else{
if(r>maior) maior=r;
r=1;
}
}
}
return maior;
}
//17
int maiorPrefixo (char s1 [], char s2 []){
int i,r;
for(i=0;s1[i] && s2[i] && (s1[i]==s2[i]);i++){
}
return i;
}
//18
int maiorSufixo (char s1 [], char s2 []){
int i,j,k=0,y=0,r=0;
while(s1[k]) k++;
while(s2[y]) y++;
for(i=k-1, j=y-1;s1[i] && s2[j] && s1[i]==s2[j];i--, j--){
r++;
}
return r;
}
//19
int sufPref (char s1[], char s2[]){
int i,j,r=0;
int y=0,k=0;
while(s1[y]) y++;
while(s2[k]) k++;
for(j=k-1,i=y-1;s1[i] && s2[j]; j--){
if(s1[i]==s2[j]) {
r++;
i--;
}
}
return r;
}
//20
int contaPal (char s[]){
int i,r=0;
for(i=0; s[i] ;i++){
if((s[i]!=' ') && ((s[i+1]==' ') || s[i+1]=='\0')){
r++;
}
}
return r;
}
//21
int contaVogais (char s[]){
int i,cont=0;
for(i=0; s[i]; i++){
if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O'||s[i]=='U'){
cont++;
}
}
return cont;
}
//22
int contida (char a[], char b[]){
int i,j;
for(i=0; a[i]; i++){
if(strchr(b,a[i])==NULL) return 0;
}
return 1;
}
//23
int palindroma (char s[]){
int i,j,k=0;
while(s[k]) k++;
for(i=0, j=k-1; s[i];i++,j--){
if(s[i]!=s[j]) return 0;
}
return 1;
}
//24
int remRep (char x[]){
int i,j,k=0,y=0;
while(x[k]) k++;
for(i=0,j=0; x[i]; i++){
if(x[i]==x[i+1]){
for(j=i; x[j]; j++){
x[j]=x[j+1];
}
i--;
}
}
while(x[y]) y++;
return y;
}
//25
int limpaEspacos (char t[]){//errada
int i,k=0,j=0,y=0;
while(t[k]) k++;
char aux[k];
for(i=0; t[i];){
if(t[i]==' '){
aux[j]=t[i];
while ( t[i]==' ') i++;
}else{
aux[j]=t[i];
i++;
}
j++;
}
aux[j]='\0';
for(y=0;aux[y];y++){
t[y]=aux[y];
}
return j;
}
int limpaEspacos (char x[]){
int i,j,k=0,y=0;
while(x[k]) k++;
for(i=0,j=0; x[i]; i++){
if((x[i]==' ') && (x[i+1]==' ')){
for(j=i; x[j]; j++){
x[j]=x[j+1];
}
i--;
}
}
while(x[y]) y++;
return y;
}
//26
void insere (int v[], int N, int x){
int i,j;
for(i=0; v[i]<x && i<N;i++);
N+=1;
for(j=N; j>i; j--){
v[j]=v[j-1];
}
v[i]=x;
}
//27
void merge (int r [], int a[], int b[], int na, int nb){
int aux,y,i,j,k;
for(i=0; i<na; i++){
r[i]=a[i];
}
for(j=0; j<nb; j++){
r[j+i]=b[j];
}
for(k=1; k < na+nb; k++){
for (y = 0; y < na+nb-1; y++) {
if (r[y] > r[y + 1]) {
aux = r[y];
r[y] = r[y + 1];
r[y + 1] = aux;
}
}
}
}
//28
int crescente (int a[], int i, int j){
int y;
for(y=i; y<j; y++){
if(a[y]>a[y+1]) return 0;
}
return 1;
}
//29
int retiraNeg (int v[], int N){
int i,j;
for(i=0; i<N;i++){
if(v[i]<0){
for(j=i; j<N;j++){
v[j]=v[j+1];
}
N--;
i--;
}
}
return N
}
//30
int menosFreq (int v[], int N){
int i,vezes=0,menor=N,cha=v[0];
for(i=0; i<N;i++){
if(v[i]==v[i+1]) vezes++;
else if(vezes<menor){
menor=vezes;
cha=v[i];
vezes=0;
}else{
vezes=0;
}
}
return cha;
}
//31
int maisFreq (int v[], int N){
int i,vezes=0,maior=0,cha=v[0];
for(i=0; i<N;i++){
if(v[i]==v[i+1]) vezes++;
else if(vezes>maior){
maior=vezes;
cha=v[i];
vezes=0;
}else{
vezes=0;
}
}
return cha;
}
//32
int maxCresc (int v[], int N){
int i,r=1,maior=0;
for(i=0; i<N;i++){
if(v[i]<=v[i+1]){
r++;
}else if(r>maior){
maior=r;
r=1;
}else r=1;
}
return maior;
}
//33
int pertence (int a, int v[], int n){
int i,r=0;
for(i=0; i<n; i++){
if(v[i]==a) return 1;
}
return 0;
}
int elimRep (int v[], int n){
int i,y,j=1,aux[n];
int k,z,temp;
for(i=1; i<n; i++){
if(!pertence(v[i],aux,n)){
aux[j]=v[i];
j++;
}
}
for(y=0;y<j;y++){
v[y]=aux[y];
}
for(k=1;k<n;k++){
for(z=0; z<n-1;z++){
if(v[z]>v[z+1]){
temp = v[z];
v[z] = v[z+1];
v[z+1] = temp;
}
}
}
return j;
}
//34
int elimRepOrd (int v[], int n){
int i,y,j=0;
for(i=0; i<n-1; i++){
if(v[i]==v[i+1]){
for(j=i; j<n;j++){
v[j]=v[j+1];
}
n--;
i--;
}
}
return n;
}
//35
int comunsOrd (int a[], int na, int b[], int nb){
int i=0,j=0,r=0;
while(i<na && i<nb){
if(a[i]==b[j]){
r++;
i++;
j++;
}else if(a[i]>b[j]){
j++;
}else i++;
}
return r;
}
//36
int pertence (int a, int v[], int n){
int i,r=0;
for(i=0; i<n; i++){
if(v[i]==a) return 1;
}
return 0;
}
int comuns (int a[], int na, int b[], int nb){
int i,j,r=0;
for(i=0; i<na; i++) {
for(j=0; j<nb; j++){
if(a[i]==b[j]) {r++; break;}
}
}
return r;
}
//37
int minInd (int v[], int n){
int i,menor=v[n-1],r=0;
for(i=0; i<n; i++){
if(v[i]<menor){ menor=v[i];
r=i;
}
}
return r;
}
//38
void somasAc (int v[], int Ac [], int N){
int i;
for(i=1; i<N; i++){
Ac[i]=Ac[i-1]+v[i];
}
}
int triSup (int N, float m [N][N]){
for(i=0; i<N; i++){
for(j=0; j<N ; j++){
if(j<i){
if( m[i][j]!=0) return 0;
}
}
}
return 1;
}
void transposta (int N, float m [N][N]){
int aux,i,j;
float n[N][N];
for(i=0; i<N; i++){
for(j=0; j<N; j++){
n[j][i] = m[i][j];
}
}
for(i=0; i<N; i++){
for(j=0; j<N; j++){
m[i][j] = n[i][j];
}
}
}
<file_sep>/DSS/source/Menu/Phases/Phase7.java
package bin;
import bin.Controller;
import bin.Pedido.Pedido;
import bin.Pedido.ReadLoadPedidos;
import bin.Pedido.ReadLoadPedidosFinalizados;
import bin.Phase;
import bin.Phase1;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
public class Phase7 extends Phase {
public Phase7(){
Messages = new String[]{ "Finalizar pedido"," " };
TipForInput = "Insira o identificador do Pedido";
InputForStages = new String[]{ "Insira o NIF do cliente" };
numberStages = InputForStages.length +1;
}
@Override
public Phase HandleCommand(List<String> s) {
String idPedido = s.get(0);
String NIF = s.get(1);
for(Pedido pdd : Controller.allPedidos){
if(pdd.getId().equals(idPedido) && pdd.getNIF().equals(NIF)) {
if(LocalDate.now().equals(pdd.getFim()) || LocalDate.now().compareTo(pdd.getFim())>0){
Controller.pedidosFinalizados.add(pdd);
Controller.allPedidos.remove(pdd);
RemoveAndWriteToFile(pdd);
return new Phase1("Pedido finalizado com sucesso!\n");
}
ChangeWarningMessage("A reparação ainda não está concluida!\n");
return null;
}
}
String warning = "Apenas os seguintes pedidos podem ser dados como finalizados -> \n";
if (Controller.allPedidos.size() == 0)
warning = "Não existem pedidos no sistema";
for (Pedido p : Controller.allPedidos) {
if((LocalDate.now().equals(p.getFim()) || LocalDate.now().compareTo(p.getFim())>0) && !Controller.pedidosFinalizados.contains(p)){
warning +="NIF = " + p.getNIF() + " ID = " + p.getId() + "\n";
}
}
warning += "\n";
ChangeWarningMessage(warning);
return null;
}
private void RemoveAndWriteToFile(Pedido pdd)
{
ReadLoadPedidosFinalizados.WritePedido(pdd);
ReadLoadPedidos.RemovePedido(pdd);
}
}
<file_sep>/IdeaProjects/Ficha6/src/VeiculosOcasiao.java
import java.util.ArrayList;
import java.util.List;
public class VeiculosOcasiao extends Veiculo{
private boolean promocao;
public VeiculosOcasiao(){
super();
this.promocao = false;
}
public VeiculosOcasiao(String marca, String modelo, String matricula, int ano, double velociademedia, double precokm, List<Integer> classificacao, int kms, int kmsUltimo, boolean promocao) {
super(marca,modelo,matricula,ano,velociademedia,precokm,classificacao,kms,kmsUltimo);
this.promocao = promocao;
}
public VeiculosOcasiao(VeiculosOcasiao v) {
super(v);
this.promocao = v.getPromocao();
}
public boolean getPromocao(){
return promocao;
}
public void setPromocao(boolean promocao){
this.promocao = promocao;
}
public VeiculosOcasiao clone(){
return new VeiculosOcasiao(this);
}
public double custoRealKM() {
double custo = 0;
if (promocao) {
custo = super.getKms() * 1.1 * 0.75;
} else {
custo = super.getKms() * 1.1;
}
return custo;
}
}
<file_sep>/DSS/source/Menu/Phases/Phase5.java
package bin;
import bin.*;
import bin.Pedido.Pedido;
import bin.Pedido.Plano;
import bin.Phase;
import bin.Phase1;
import java.time.LocalDate;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Phase5 extends Phase {
public Phase5(){
Messages = new String[]{ "Definir tempo de reparação e custo de peças (Pedido mais antigo)"," " };
TipForInput = "Insira o tempo de reparação em horas";
InputForStages = new String[]{ "Insira o custo total das peças"};
numberStages = InputForStages.length +1;
}
@Override
public Phase HandleCommand(List<String> s) {
String tempoReparacao = s.get(0);
String c = s.get(1);
int tempo;
int custo;
try {
tempo = Integer.parseInt(tempoReparacao);
custo = Integer.parseInt(c);
} catch (Exception e) {
ChangeWarningMessage("Por favor insira números !\n");
return null;
}
if (Controller.allPedidos.size() == 0)
{
ChangeWarningMessage("Não existem pedidos no sistema!\n");
return null;
}
Controller.allPedidos.sort(Comparator.comparing(Pedido::getDataRegisto));
Pedido pdd = Controller.allPedidos.get(0);
Plano pll = new Plano();
pll.setTotalHoras(tempo);
pll.setCusto(custo);
pdd.setPl(pll);
pdd.setOrcamento(pll.getCusto()+10);//custo das peças + mão de obra
//Se foi feito com sucesso
return new Phase1("Plano adicionado com sucesso!\n");
}
}<file_sep>/DSS/source/Main.java
package bin;
import java.time.LocalDate;
import java.util.*;
import bin.Controller;
import bin.Interpreter;
import bin.Pedido.*;
import bin.Pessoas.*;
public class Main {
public static void main(String[] args) {
Controller.LoadDataBase();
Interpreter it = new Interpreter();
it.Initialize();
}
}
<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/src/Connections/Demultiplexer.java
package Connections;
import java.util.HashMap;
import java.util.Map;
import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Demultiplexer{
public TaggedConnection tagConnection;
public Lock lock ;
private Map<Integer,Entry> bufferMensagens = new HashMap<>();
private Entry get(int tag){
Entry e = bufferMensagens.get(tag);
return e;
}
public Demultiplexer(TaggedConnection taggedConnection) {
tagConnection = taggedConnection;
lock = new ReentrantLock();
}
private Thread ReadingSocketThread;
public void start() {
bufferMensagens.put(1, new Entry());
bufferMensagens.put(2, new Entry());
bufferMensagens.put(3, new Entry());
bufferMensagens.put(4, new Entry());//Receber voos do cliente
bufferMensagens.put(8, new Entry());//Cancelar uma Reserva
bufferMensagens.put(9, new Entry());//Admin adicionar voos
bufferMensagens.put(10, new Entry());//Registar usuarios
bufferMensagens.put(11, new Entry());//Encerrar o dia
ReadingSocketThread = new Thread(() -> {
try {
while(true)
{
var f = tagConnection.receive();
System.out.println("Received ["+ f.tag +"] " + new String(f.data));
Entry e=null;
try{
//Adicionar a frame à nossa queue
e = get(f.tag);
//Fechar o acesso desta entry pois estamos prestes a escrever
e.lock.lock();
e.queue.add(f.data);
//Acordar thread que está à espera da informaçao
e.cond.signal();
}finally{
e.lock.unlock();
}
}
}
catch (Exception e) {
System.out.println("DeMultiplexer foi interrompido");
for (var entrada : bufferMensagens.values()) {
entrada.lock.lock();
entrada.alive = false;
entrada.cond.signalAll();
}
}
});
ReadingSocketThread.start();
}
public void send(int i, String s){
tagConnection.send(i,s.getBytes());
}
public void send(int i, byte[] bytes) {
tagConnection.send(i, bytes);
}
public byte[] receive(int i)throws IOException, InterruptedException {
Entry e = get(i);
e.lock.lock();
while(e.alive){
if (! e.queue.isEmpty())
{
byte[] b = e.queue.poll();
return b;
}
//Este await liberta automaticamente o lock;
e.cond.await();
}
throw new InterruptedException();
}
public void close() {
try {
tagConnection.close();
} catch (Exception e) {}
}
}
<file_sep>/POO21/ex1.java
public class OlaMundo {
/∗∗
∗ O meu primeiro método
∗/
public static void main ( String [] args ) {
// Colocar código aqui!
System.out.println (" <NAME> !");
}
}
<file_sep>/IdeaProjects/POO/Ficha3/src/Lampada.java
import java.time.LocalDate;
public class Lampada {
private Boolean on;
private Boolean off;
private Boolean eco;
private double consumoON;
private double consumoOFF;
private double consumoECO;
private LocalDate date;
private Boolean[] historico;
public Lampada(){
this.on = false;
this.off = true;
this.eco = false;
this.consumoON = 5;
this.consumoOFF = 0;
this.consumoECO = 2;
}
public Lampada (Boolean on, Boolean off, Boolean eco, double consumoON, double consumoOFF, double consumoECO){
this.on = on;
this.off = off;
this.eco = eco;
this.consumoON = consumoON;
this.consumoOFF = consumoOFF;
this.consumoECO = consumoECO;
}
public enum meda{
ON,
OFF,
ECO;
}
public Lampada (Lampada l){
this.on = l.getOn();
this.off = l.getOff();
this.eco = l.getEco();
this.consumoON = l.getConsumoON();
this.consumoOFF = l.getConsumoOFF();
this.consumoECO = l.getConsumoECO();
}
public void lampON(){
setOn(true);
setOff(false);
setEco(false);
}
public void lampOFF(){
setOn(false);
setOff(true);
setEco(false);
}
public void lampECO(){
setOff(false);
setEco(true);
setOn(false);
}
public Boolean getOn() {
return on;
}
public void setOn(Boolean on) {
this.on = on;
}
public Boolean getOff() {
return off;
}
public void setOff(Boolean off) {
this.off = off;
}
public Boolean getEco() {
return eco;
}
public void setEco(Boolean eco) {
this.eco = eco;
}
public double getConsumoON() {
return consumoON;
}
public void setConsumoON(double consumoON) {
this.consumoON = consumoON;
}
public double getConsumoOFF() {
return consumoOFF;
}
public void setConsumoOFF(double consumoOFF) {
this.consumoOFF = consumoOFF;
}
public double getConsumoECO() {
return consumoECO;
}
public void setConsumoECO(double consumoECO) {
this.consumoECO = consumoECO;
}
}
<file_sep>/DSS/source/Menu/Phases/Phase6.java
package bin;
import bin.Controller;
import bin.Main;
import bin.Pedido.Pedido;
import bin.Pedido.Plano;
import bin.Pessoas.Cliente;
import bin.Pessoas.FuncionarioBalcao;
import bin.Pessoas.Pessoa;
import bin.Phase;
import bin.Phase1;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
public class Phase6 extends Phase {
public Phase6(){
Messages = new String[]{ "Iniciar reparação"," " };
TipForInput = "Insira o identificador do Pedido";
InputForStages = new String[]{"" };
numberStages = InputForStages.length +1;
}
@Override
public Phase HandleCommand(List<String> s) {
String idPedido = s.get(0);
//String NIFcliente = s.get(1);
//boolean temp = false;
for(Pedido pdd : Controller.allPedidos){
if(pdd.getId().equals(idPedido)) {
//temp = true;
pdd.setInicio(LocalDate.now());
long days = (long)(pdd.getPl().getTotalHoras())/24;
pdd.setFim(LocalDate.now().plus(days, ChronoUnit.DAYS));
return new Phase1("Reparação concluida com sucesso!\n");
}
}
String warning = "Apenas nos seguintes pedidos ainda não foi iniciada a reparação -> \n";
if (Controller.allPedidos.size() == 0)
warning = "Não existem pedidos no sistema";
for (Pedido p : Controller.allPedidos) {
if(p.getInicio()==null){
warning +="ID = " + p.getId() + " NIF = " + p.getNIF() + "\n";
}
}
warning += "\n";
ChangeWarningMessage(warning);
return null;
}
}<file_sep>/DSS/source/Pessoas/FuncionarioReparacao.java
package bin.Pessoas;
import bin.Pessoas.Pessoa;
public class FuncionarioReparacao extends Pessoa {
public FuncionarioReparacao(String nome, String ID, String password) {
super(nome, ID, password);
}
}
<file_sep>/DSS/source/Pedido/ReadLoadPedidos.java
package bin.Pedido;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import bin.Pessoas.*;
public class ReadLoadPedidos {
public static String nameFile = "dados/pedidos.txt";
public static void WritePedido(Pedido p){
var fwriter = GetFileWriter();
String writePedido = "";
writePedido += GetNameClassPedido(p) + ";";
writePedido += p.getId() + ";";
writePedido += p.getNIF() + ";";
writePedido += p.getDataRegisto() + ";";
writePedido += p.getInicio() + ";";
writePedido += p.getFim() + ";";
writePedido += p.getOrcamento() + ";\n";
System.out.println(writePedido);
try {
fwriter.write(writePedido);
fwriter.flush();
fwriter.close();
} catch (Exception e) {e.printStackTrace();}
}
public static List<Pedido> ReadAllPedidos() {
var br = GetFileReader();
var allLines= br.lines().collect(Collectors.toList());
List<Pedido> allPedidos = new ArrayList<Pedido>();
Scanner sc= null;
for (int i = 0; i < allLines.size(); i++) {
sc = new Scanner(allLines.get(i));
sc.useDelimiter(";");
String className = sc.next();
String id = sc.next();
String NIF = sc.next();
LocalDate registo = LocalDate.parse(sc.next());
LocalDate inicio = LocalDate.parse(sc.next());
LocalDate fim = LocalDate.parse(sc.next());
Integer orcamento = Integer.parseInt( sc.next());
Plano pl = new Plano(0, orcamento);
Pedido pI = new Pedido(id, NIF, registo, inicio, fim, orcamento, pl);
if (pI != null)
allPedidos.add(pI);
}
if (sc != null)
sc.close();
return allPedidos;
}
public static void RemovePedido(Pedido pdd)
{
var br = GetFileReader();
var allLines= br.lines().collect(Collectors.toList());
List<Pedido> allPedidos = new ArrayList<Pedido>();
Scanner sc= null;
File f = null;
FileWriter filePedidos = null;
//Abrir um ficheiro temporario
try {
f = new File("temp.txt");
filePedidos = new FileWriter(f,true);
for (int i = 0; i < allLines.size(); i++) {
sc = new Scanner(allLines.get(i));
sc.useDelimiter(";");
sc.next();
String id = sc.next();
if (id.equals(pdd.getId()))
continue;
filePedidos.write(allLines.get(i) + "\n");
}
File inFile = new File(nameFile);
inFile.delete();
f.renameTo(inFile);
filePedidos.close();
sc.close();
} catch (Exception e) { e.printStackTrace();}
}
private static FileWriter GetFileWriter()
{
try {
File f = new File(nameFile);
FileWriter filePedidos = new FileWriter(f,true);
return filePedidos;
} catch (Exception e) { e.printStackTrace(); return null; }
}
private static BufferedReader GetFileReader()
{
try {
File f = new File(nameFile);
FileReader filePedidos = new FileReader(f);
BufferedReader br = new BufferedReader(filePedidos);
return br;
} catch (Exception e) {e.printStackTrace(); return null; }
}
private static String GetNameClassPedido(Pedido p)
{
String s;
try {
s = p.getClass().getSimpleName();
} catch (Exception e) {
s = "";
}
return s;
}
}<file_sep>/DSS/Makefile
pessoas= source/Pessoas/Pessoa.java \
source/Pessoas/Cliente.java \
source/Pessoas/Gestor.java \
source/Pessoas/FuncionarioBalcao.java \
source/Pessoas/FuncionarioReparacao.java \
source/Pessoas/ReadLoadPessoas.java\
source/Pessoas/ReadLoadClientes.java\
phases= source/Menu/Phases/Phase.java \
source/Menu/Phases/Phase1.java \
source/Menu/Phases/Phase2.java \
source/Menu/Phases/Phase3.java \
source/Menu/Phases/Phase4.java\
source/Menu/Phases/Phase5.java\
source/Menu/Phases/Phase6.java\
source/Menu/Phases/Phase7.java\
source/Menu/Phases/Phase8.java\
source/Menu/Phases/Phase9.java\
source/Menu/Phases/Phase10.java\
source/Menu/Phases/Phase11.java\
pedidos= source/Pedido/Pedido.java \
source/Pedido/Plano.java \
source/Pedido/PlanoExpress.java \
source/Pedido/ReadLoadPedidos.java\
source/Pedido/ReadLoadPedidosFinalizados.java\
default:
javac -d . \
$(pessoas) \
$(pedidos) \
$(phases) \
source/Controller.java \
source/Menu/ShowMenu.java \
source/Menu/Interpreter.java \
source/Main.java
clean:
rm bin/*.class
app:
java bin.Main
# Esta linha é necessario pois ao adicionar argumentos extra na make
# Não queremos que eles sejam executados
%:
@:<file_sep>/DSS/source/Pessoas/ReadLoadClientes.java
package bin.Pessoas;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class ReadLoadClientes {
public static String nameFile = "dados/clientes.txt";
public static void WriteCliente(Cliente c){
var fwriter = GetFileWriter();
String WriteCliente = "";
WriteCliente += c.getNome() + ";";
WriteCliente += c.getNIF() + ";\n";
System.out.println(WriteCliente);
try {
fwriter.write(WriteCliente);
fwriter.flush();
fwriter.close();
} catch (Exception e) {e.printStackTrace();}
}
public static List<Cliente> ReadAllCliente()
{
var br = GetFileReader();
var allLines= br.lines().collect(Collectors.toList());
List<Cliente> clientes = new ArrayList<Cliente>();
Scanner sc;
for (int i = 0; i < allLines.size(); i++) {
sc = new Scanner(allLines.get(i));
sc.useDelimiter(";");
Cliente pI = null;
String nomeCliente = sc.next();
String nifCliente = sc.next();
pI = BuildClienteFromString(nomeCliente, nifCliente);
if (pI != null)
clientes.add(pI);
}
return clientes;
}
public static Cliente BuildClienteFromString(String nomeCliente, String nifCliente) {
Cliente pI = new Cliente(nifCliente,nomeCliente);
return pI;
}
private static FileWriter GetFileWriter()
{
try {
File f = new File(nameFile);
return new FileWriter(f,true);
} catch (Exception e) { e.printStackTrace(); return null; }
}
private static BufferedReader GetFileReader()
{
try {
File f = new File(nameFile);
FileReader fileClientes = new FileReader(f);
BufferedReader br = new BufferedReader(fileClientes);
return br;
} catch (Exception e) {e.printStackTrace(); return null; }
}
}
<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/src/Clientes/Menu/Phases/PhaseRegisto.java
package Clientes.Menu.Phases;
import Connections.Demultiplexer;
import java.io.IOException;
import java.util.List;
public class PhaseRegisto extends Phase{
public PhaseRegisto(Demultiplexer dm)
{
super(dm);
Messages = new String[]{
"Registo",
"",
};
TipForInput = "Username";
InputForStages = new String[]{
"Password",
};
numberStages = InputForStages.length +1;
}
@Override
public Phase HandleCommand(List<String> s) {
String username = s.get(0);
String password = s.get(1);
String message = username + ";" + password + ";";
//pinheiro;123;
dm.send(10, message);
try {
String responseServer = new String( dm.receive(10));
if (responseServer.equals("200"))
return new PhaseMainMenu(dm,"Utilizador registado com sucesso");
return null;
} catch (IOException | InterruptedException e) {}
return null;
}
}
<file_sep>/PI21/50quest.c
#include <stdio.h>
#include <string.h>
void ex1(){
int max=0,x;
while (x!=0){
printf("Insira o número: \n");
scanf("%d", &x);
if (x>max)
max=x;
}
printf("%d\n", max);
}
void ex2(){
int x;
double soma=0,count=0;
double med;
while (x!=0){
printf("Insira o número: \n");
scanf("%d", &x);
soma = soma+x;
count++;
}
med = soma/count;
printf("%f\n", med);
}
void ex3(){
int x;
double max=0,smax=0;
while (x!=0){
printf("Insira o número: \n");
scanf("%d", &x);
if (x>max)
max=x;
}
printf("%f\n", smax);
}
int bitsUm (unsigned int n){
int count=0;
for (int i = 0;n>1; i++){
if (n%2 == 1) count++;
n=n/2;
}
count=count+1;
printf("%d\n", count);
return count;
}
//main bitsUm
/*
int main(){
int n;
printf("Insira o número: \n");
scanf("%d", &n);
bitsUm(n);
return 0;
}
*/
int trailingZ (unsigned int n){
int count=0;
for (int i = 0;n>1; i++){
if (n%2 == 0) count++;
n=n/2;
}
printf("%d\n", count);
return count;
}
int qDig (unsigned int n){
int count=0;
if (n==0) count=1;
else {
while (n!=0){
count = count+1;
n=n/10;
}
}
printf("%d\n", count);
return count;
}
char* mystrcat (char s1[], char s2[]){
int i,j;
for(i=0;s1[i];i++);
for(j=0;s2[j];j++){
s1[i++] = s2[j];
}
s1[i] = '\0';
for (int x = 0;x<i; x++){
printf("%c\n", s1[x]);
}
return s1;
}
/*
int strcmp (char s1[], char s2[]){
int i,j;
for (int i = 0; s1[i] == s2[i]; i++){
}
}
}
*/
char *strstr (char s1[], char s2[]){
int i,x=0;
while(s1[x]!='\0') x++;
for(i=0;i<x; i++){
if (s2[i]==s1[i]) printf("%d\n", i);
else printf("NULL");
}
}
int main(){
/*int n;
printf("Insira o número: \n");
scanf("%d", &n);*/
mystrcat("m,a,o","o,l,a");
return 0;
}
<file_sep>/PI21/ficha4.c
#include <stdio.h>
#include <string.h>
int isVowel(char c){
return c == 'a'|| c =='e'|| c =='i'|| c=='o' || c =='u'|| c =='A'|| c =='E'|| c =='I'|| c=='O' || c =='U';
}
int contaVogais (char *s){
int count=0,i;
for(i=0; s[i]!='\0'; i++){ //for (;*s;s++)
if(isVowel(s[i])) //if(isVowel())
count++;
}
return count;
}
int retiraVogaisRep (char *s){
int removidas=0,i=0;
char aux[100];
for (int i=0; s[i]!='\0';i++){
if(isVowel(s[i]) && s[i] == s[i+1]){
removidas++;
}
else aux[i-removidas] = s[i];
}
aux[i-removidas] = '\0';
strcpy(s,aux);
return removidas;
}
int duplicaVogais (char *s){
char aux[100];
int i, acrescentadas=0, j=0;
for (int i=0; s[i]!='\0'; i++){
if(isVowel(s[i])){
aux[j]=s[i];
aux[j+1] = s[i];
j+=2;
acrescentadas++;
}
else {aux[j]=s[i];j++;}
}
aux[j]= '\0';
strcpy(s,aux);
return acrescentadas;
}
int ordenado (int v[], int N){
int x;
for(int i=0;i<N-1;i++){
if (v[i]<v[i+1]){ x=1;}
else {x=0;break;}
}
return x;
}
void merge (int a[], int na, int b[], int nb, int r[]){
int i,j;
for(i=0;i<na;i++){
r[i]=a[i];
}
for(j=0;j<nb;j++){
r[i+j]=b[j];
}
}
int partition (int v[], int N, int x){
int aux,j,k=0;
for (int cont = 1; cont < N; cont++){
for (int i = 0; i < N - 1; i++){
if (v[i] > v[i+1]){
aux = v[i];
v[i] = v[i+1];
v[i+1] = aux;
}
}
}
for(j=0;j<N;j++){
if(v[j]<=x) k++;
}
return k;
}
int main(){
char s1 [100] = "Esta e uma string com duplicados";
int x;
int v[10] = {10,2,3,20,25,4,1,0,6,5};//{2,3,4,10,20,25}
x=partition(v,10,10);
printf("%d\n",x);
//printf ("A string \"%s\" tem %d vogais\n", s1, contaVogais (s1));
//x = retiraVogaisRep (s1);
//printf ("Foram retiradas %d vogais, resultando em \"%s\"\n", x, s1);
//x = duplicaVogais (s1);
//printf ("Foram acrescentadas %d vogais, resultando em \"%s\"\n", x, s1);
return 0;
}<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/src/Clientes/ThreadClient/ThreadGetInfoServer.java
package Clientes.ThreadClient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import Clientes.Client;
import Clientes.ClientData;
import Connections.Demultiplexer;
import Viagens.Cidade;
public class ThreadGetInfoServer extends Thread {
private ClientData clientData;
private Demultiplexer dm;
public ThreadGetInfoServer(Demultiplexer dm)
{
this.dm = dm;
clientData = Client.GetClientData();
}
@Override
public void run() {
try {
while(true)
{
var answer = dm.receive(3);
clientData.wait = true;
int size =ParseFirstMessageShow(answer);
answer = dm.receive(3);
ParseSecondMessageShow(answer,size);
clientData.wait = false;
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private int ParseFirstMessageShow(byte[] answer) {
Scanner sc = new Scanner(new String( answer));
sc.useDelimiter(";");
int size = Integer.parseInt( sc.next());
var mapVoos = clientData.GetAllVoos();
var allCidades = clientData.GetAllCidades();
for (int i = 0; i < size; i++) {
Cidade cidade = new Cidade( sc.next());
//Se a cidade ja existir no mapa ela nao é adicionada
if (allCidades.contains(cidade))
continue;
mapVoos.put(cidade, new ArrayList<>());
allCidades.add(cidade);
}
sc.close();
return size;
}
private void ParseSecondMessageShow(byte[] answer,int size) {
var allCidades = clientData.GetAllCidades();
Scanner sc = new Scanner(new String( answer));
sc.useDelimiter("@");
for (int i = 0; i < size; i++) {
String lineDestination = sc.next();
Scanner scVooDestino = new Scanner(lineDestination);
// System.out.println("got line " + lineDestination);
scVooDestino.useDelimiter(";");
while(scVooDestino.hasNext())
{
String destino = scVooDestino.next();
// System.out.println("Adding " + allCidades.get(i).getNome() + " -> " + destino);
clientData.addVoo(allCidades.get(i) ,new Cidade( destino) );
}
scVooDestino.close();
}
sc.close();
}
}
<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/Makefile
server:
java -cp bin Servidores.Server
client:
java -cp bin Clientes.Client<file_sep>/IdeaProjects/POO/Ficha3/src/Main_tele.java
public class Main_tele {
public static void telemovel() {
Telemovel t1 = new Telemovel();
t1.instalaApp("Instagram", 20);
t1.instalaApp("Facebook", 100);
t1.removeApp("instagram", 20);
t1.recebeMsg("olá");
t1.recebeMsg("RNFIREQYHNRYEQBFNRYEB");
t1.recebeMsg("bom");
String res = t1.maiorMsg();
System.out.println(res);
System.out.println(t1.toString());
}
public static void main (String[]args){
telemovel();
}
}
<file_sep>/FM7/JogadorType.java
public enum JogadorType{
AVANCADO, LATERAL, MEDIO, DEFESA, GUARDAREDES
}<file_sep>/IdeaProjects/Ficha6/src/VeiculoNãoExiste.java
public class VeiculoNãoExiste extends Exception{
public VeiculoNãoExiste(String msg) {
super(msg);
}
}
<file_sep>/DSS/source/Pedido/Plano.java
package bin.Pedido;
import java.util.Random;
public class Plano {
protected Integer totalHoras;
protected Integer custo;
public Plano(){
this.custo = 0;
this.totalHoras = 0;
}
public Plano(Integer totalHoras, Integer custo) {
this.totalHoras = totalHoras;
this.custo = custo;
}
public Integer getTotalHoras() {
return totalHoras;
}
public void setTotalHoras(Integer totalHoras) {
this.totalHoras = totalHoras;
}
public Integer getCusto() {
return custo;
}
public void setCusto(Integer custo) {
this.custo = custo;
}
//random???? 10 a 100 euros?
public static Integer calculaCusto(){
Random random = new Random();
return random.nextInt(101 - 10) + 10;
}
//random???? 1 a 5 dias?
public static Integer calculaHoras(){
Random random = new Random();
return random.nextInt(121 - 24) + 24;
}
}
<file_sep>/PI21/Ficha 8/Queue.c
#include <stdio.h>
#include <stdlib.h>
#include "Queue.h"
void initQueue (Queue *q){
}
int QisEmpty (Queue q){
return -1;
}
int enqueue (Queue *q, int x){
return -1;
}
int dequeue (Queue *q, int *x){
return -1;
}
int frontQ (Queue q, int *x){
return -1;
}
typedef LInt QueueC;
void initQueueC (QueueC *q);
int QisEmptyC (QueueC q){
return -1;
}
int enqueueC (QueueC *q, int x){
return -1;
}
int dequeueC (QueueC *q, int *x){
return -1;
}
int frontC (QueueC q, int *x){
return -1;
}<file_sep>/PI21/100.c
#include <stdio.h>
//ex4
int bitsUm (unsigned int x){
int r=0;
for(int i = 0; x<1; i++){
if(x%2 == 1) r++;
x = x/2;
}
return r+1;
}
//ex5
int trailingZ (unsigned int x){
int r=0;
for(int i = 0; x<1; i++){
if(x%2 == 0) r++;
x = x/2;
}
return r;
}
//6
int qDig (unsigned int n){
int r=0;
for(int i=0;n!=0;i++){
if(n/10!=0) r++;
n /= 10;
}
return r+1;
}
//ex7
char* Mystrcat (char s1[], char s2[]){
int i;
for(i=0;s1[i];i++); i++;
for(int j=0;s2[j];j++){
s1[i]=s2[j];
i++;
}
s1[i] ="\0";
return s1;
}
//ex8
char *Mystrcpy (char *dest, char source[]){
for(int i=0; source[i];i++){
dest[i] = source[i];
}
return dest;
}
//ex9
int Mystrcmp (char s1[], char s2[]){
int r;
for(int i=0;s1[i]!='\0' || s2[i]!='\0' ;i++){
if (s1[i]==s2[i]) r = 0;
else if(s1[i]<s2[1]) r = -1;
else r = 1;
}
return r;
}
//ex10
char *Mystrstr (char s1[], char s2[]){
int i=0,j=0,pos=0;
while(s1[i]!='\0' && s2[i]='\0'){
if(s1[i]==s2[j]){ i++; j++;}
else i++;
}
if(s2[j]=='\0') return s1[i-j];
return NULL;
}
//ex11
void strrev (char s[]){
int i,j,n,k=0;
for(i=0;s[i];i++);
char aux[i];
for(j=i-1;j>=0;j--){
aux[k]=s[j];
k++;
}
for(n=0;n<i;n++){
s[n]=aux[n];
}
}
void strnoV (char s[]){
int n,i,k=0;
char aux[strlen(s)];
for (i = 0; s[i]; i++){
if(s[i]!='a'||s[i]!='e'||s[i]!='i'||s[i]!='o'||s[i]!='u'||s[i]!='A'||s[i]!='E'||s[i]!='I'||s[i]!='O'||s[i]!='U')
aux[k]=s[i];
k++;
}
aux[k]='\0';
for(n=0;n<i;n++){
s[n]=aux[n];
}
s[n]='\0';
}
void truncW (char t[], int n){
}
char charMaisfreq (char s[]){
int i,j,cont,var=0;
char r;
for(i=0; s[i]; i++){
cont=0;
for(j=0; s[j]; j++){
if(s[i]==s[j]){ cont++;}
}
if(cont > var) {
var = cont;
r=s[i];
}
}
return r;
}
int iguaisConsecutivos (char s[]){
int i,j,cont,var=0;
for(i=0; s[i]; i++){
cont=1;
for(j=i; s[j]; j++){
if(s[i]==s[j+1]) cont++;
else {i=j; break;}
}
if(cont > var) {var = cont;}
cont=0;
}
return var;
}
int difConsecutivos (char s[]){
int i,j,k,cont,var=0;
for(i=0; s[i]; i++){
cont=1;
for(j=i; s[j]; j++){
for(k=i;s[k];k++){
if((s[i]!=s[j+1]) && ) cont++;
else {i=j; break;}
}
}
if(cont > var) {var = cont;}
cont=0;
}
return var;
}
int maiorPrefixo (char s1 [], char s2 []){
int i;
for(i=0;s1[i]==s2[i] && s1 && s2;i++);
return i;
}
int maiorSufixo (char s1 [], char s2 []){
int i,j,cont=0;
if(s1 && s2){
for(i=strlen(s1)-1,j=strlen(s2)-1;i>=0 && j>=0 && s1[i]==s2[j];i--, j--) cont++;
}
return cont;
}
int sufPref (char s1[], char s2[]){
int i,j=0,cont=0;
if(s1 && s2){
for(i=0;i<strlen(s1) && j<strlen(s2);i++) {
if(s1[i]==s2[j]) j++;
else j=0;
}
}
return j;
}
int contaPal (char s[]){
int cont=0, i;
if(s){
for(i=0; i < strlen(s);i++){
if(s[i]==' '){
if(s[i]==s[i+1]) j
cont++;
}
}
if((s[0]==' ') && s[strlen(s)-1]==' ')return cont - 1;
else if((s[0]==' ') || s[strlen(s)-1]==' ' )return cont;
return cont+1;
}
else return 0;
}
int contaVogais (char s[]){
int cont =0;
for(i=0; i<strlen(s);i++){
if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O'||s[i]=='U') cont++;
}
return cont;
}
int contida (char a[], char b[]){
int i,j;
for(i=0;i<strlen(a);i++){
if(strchr(b,a[i])==NULL) return 0;
}
return 1;
}
int palindroma (char s[]){
int n=0,i,j=0,k;
char aux[strlen(s)];
for(k=strlen(s)-1;s[k];k--){
aux[n]=s[k];
n++;
}
//return strcmp(s,aux);
for(i=0; s[i];i++){
if(s[i]==aux[j]) j++;
else return 0;
}
return 1;
}
int remRep (char x[]){
int i,j=0, first=1;
char aux[strlen(x)];
for(i=0;x[i];i++){
//aux[i]=x[i]
if(x[i]==x[i+1]&&first) {aux[j]=x[i];j++; first=0}
else if(x[i]!=x[i+1]) {aux[j]=x[i];j++}
else{ i++; first=1;
}
aux[j] = '\0';
strcpy(x,aux);
return strlen(aux);
}
int limpaEspacos (char t[]){
int i=0,j=0,k=0;
char aux[strlen(t)];
for(i=0;t[i];){
//while(t[i]){
if(t[i]==' '){
aux[j]=t[i];
while (t[i]==' ') i++;
}else {aux[j] = t[i];i++;}
j++;
}
aux[j]= '\0';
strcpy(t,aux);
return j;
}
//errADA
void insere (int v[], int N, int x){
int i=0,k,j=0;
//int aux[strlen(v)];
while(v[i]<x) i++;
for(j=i;j<=N;j++){
v[j]=v[j+1];
}
v[i]=x;
}
//ex 27
void merge (int r [], int a[], int b[], int na, int nb){
int i,j,cont,aux;
for(i=0;i<na;i++){
r[i] = a[i];}
for(j=0;j<nb;j++){
r[i+j] = b[j];}
for (cont = 1; cont < na+nb; cont++) {
for (i = 0; i < na+nb - 1; i++) {
if (r[i] > r[i + 1]) {
aux = r[i];
r[i] = r[i + 1];
r[i + 1] = aux;
}
}
}
}
int crescente (int a[], int i, int j){
int k;
if(a){
for(k=i;k<j;){
if(a[k]>a[k+1]) return 0;
else k++;
}
}
return 1;
}
int retiraNeg (int v[], int N){
int i,j,cont=0;
for(i=0;i<N;i++){
if(v[i]<0){
cont++;
for(j=i;j<N;j++){
v[j]=v[j+1];
}
N--;
i--;
}
}
return N;
}
typedef struct lligada {
int valor;
struct lligada *prox;
} *LInt;
int length (LInt l){
LInt aux = l;
int cont;
while(aux){
cont++;
aux=(aux->prox);
}
return cont;
}
void freeL (LInt l){
LInt aux;
while(l){
aux = l->prox;
free(l);
l = aux;
}
}
void imprimeL (LInt l){
while(l){
printf("%d ", l->valor);
l = l->prox;
}
}
LInt reverseL (LInt l){
LInt aux,ant=NULL;
while(l){
aux = l->prox;
l->prox = ant;
ant = l;
l = aux;
}
return ant;
}
void insertOrd (LInt *l, int x){
LInt aux;
LInt newL = malloc(sizeof(struct lligada));
newL->valor = x;
aux = *l;
while(aux && (aux)->prox<x){
aux = (aux)->prox;
}
newL->prox = aux;
aux = newL;
}
int removeOneOrd (LInt *l, int x){
int r=1;
while((*l) && r){
if(((*l)->valor)==x) {
(*l) = (*l)->prox; r=0;
}
else l = &((*l)->prox);
}
return r;
}
void merge (LInt *r, LInt a, LInt b){
while(a && b){
if(a->valor < b->valor){
*r = malloc(sizeof(struct lligada));
(*r)->valor = a->valor;
a = a->prox;
}
else {
*r = malloc(sizeof(struct lligada));
(*r)->valor = b->valor;
b = b->prox;
}
r = &((*r)->prox);
}
if(a==NULL) (*r)=b;
else (*r)=a;
}
void splitQS (LInt l, int x, LInt *mx, LInt *Mx){
while(l){
if(l->valor < x){
*mx = malloc(sizeof(struct lligada));
(*mx)-> valor = l->valor;
mx = &((*mx)->prox);
}
else {
*Mx = malloc(sizeof(struct lligada));
(*Mx)->valor = l->valor;
Mx = &((*Mx)->prox);
}
l = l->prox;
}
}
LInt parteAmeio (LInt *l){
LInt aux = malloc(sizeof(struct lligada));
while(*l){
while((*l))
}
}
int removeAll (LInt *l, int x){
int cont=0;
while(*l){
if((*l)->valor == x){
(*l) = (*l)->prox;//passa e remove
cont++;
}
else l = &((*l)->prox);
}
return cont;
}
int removeDups (LInt *l){
int cont=0;
LInt *aux;
aux = l;
LInt new = malloc(sizeof(struct lligada));
while(*l){
while(*aux){
if((*l)->valor==(*aux)->valor){
cont++;
(*aux) = (*aux)->prox;
}
else aux = &((*aux)->prox);
}
(*l) = (*l)->prox;
}
l = aux;
return cont;
}
int removeMaiorL (LInt *l){
int maior=0;
LInt *aux;
aux = l;
while(*aux){
if((*aux)->valor>maior){ maior=(*aux)->valor;}
aux = &((*aux)->prox);
}
while(*l){
if(((*l)->valor)==maior){
(*l) = (*l)->prox;
return maior;
}
else l = &((*l)->prox);
}
return maior;
}
void init (LInt *l){
while( ((*l)->prox) && (l = &((*l)->prox)) );
free(*l);
(*l)=NULL;
}
void appendL (LInt *l, int x){
LInt *aux = malloc(sizeof(struct lligada));
while( ((*l)->prox) && (l = &((*l)->prox)) );
(*aux)->valor = x;
(*aux)->prox = NULL;
*l = (*aux);
}
void concatL (LInt *a, LInt b){
while(*a) a = &((*a)->prox);
(*a)=b;
}
LInt cloneL (LInt l){
LInt *aux = &l;
LInt *new = malloc(sizeof(struct lligada));
while(l){
(*new)->valor = (*l)->valor;
l = &((*l)->prox);
new = &((*new)->prox);
}
return new;
}
int freeAB (ABin a){
int cont=0;
while(a){
free(a);
cont+= 1 + freeAB(a->esq) +freeAB(a->dir);
}
}
LInt new;
if(l==NULL) return NULL;
while(l) {
new = malloc(sizeof(struct lligada));
new->valor = l->valor;
l = l->prox;
new->prox=l;
}
return new;
}
LInt cloneRev (LInt l){
}
int maximo (LInt l){
LInt aux = l;
int max=0;
while(aux){
if(aux->valor > max) {
max = aux->valor;
}
aux = aux->prox;
}
return max;
}
int drop (int n, LInt *l){
int cont=0,
while((*l) && cont<n ){
free(*l);
(*l) = (*l)->prox;
cont++;
}
return cont;
}
int take (int n, LInt *l){
int nodos=0,r=0,cont=0;
LInt *aux;
aux = l;
while(*aux)
{aux=&((*aux)->prox); nodos++;}
if(nodos>n){
while((*l)){
if(r>=n){
free(*l);
(*l) = (*l)->prox;
}else{
l = &((*l)->prox);
cont++;
}
r++;
}
}
else cont = nodos;
return cont;
}
LInt Nforward (LInt l, int N){
//LInt aux = l;
while(l && N>0){
//aux->valor = l->valor
l = l->prox;
N--;
}
return l;
}
int listToArray (LInt l, int v[], int N){
int i=0;
LInt aux =l;
while(aux && i<N){
v[i]=aux->valor;
aux = aux->prox;
i++;
}
return i;
}
LInt somasAcL (LInt l){
int t=0;
LInt new=NULL;
LInt aux = l;
while(aux){
new = malloc(sizeof(struct lligada));
t += aux->valor;
new->valor = t;
aux = aux->prox;
new = new->prox;
}
return new;
}
void remreps (LInt l){
LInt aux = l;
LInt ant;
while(l){
while(aux){
if(l->valor == aux->valor){
ant->prox = aux->prox;
free(aux);
}
ant = aux->prox;
aux = aux->prox;
}
l = l->prox;
}
}
LInt rotateL (LInt l){
int g;
LInt aux =l;
LInt new = malloc(sizeof(struct lligada));
if(aux){
new->valor=aux->valor;
new->prox = NULL;
while(aux->prox){
aux = aux->prox;
}
aux->prox = new;
l=l->prox;
}
return l;
}
LInt parte (LInt l){
int x=1;
LInt par=NULL;
LInt *aux = &l;
LInt *auxPar = ∥
while(*aux){
if(x%2==0) {
par = malloc(sizeof(struct lligada));
//ult->prox = par->prox;
par->valor = (*aux)->valor;
par->prox =NULL;
*auxPar = par;
auxPar = &((*auxPar)->prox);
(*aux) = (*aux)->prox;
}else{
aux = &((*aux)->prox);
}
x++;
}
return par;
}
typedef struct nodo {
int valor;
struct nodo *esq, *dir;
} *ABin;
int altura (ABin a){
int h=0;
if(a){
h += 1+ max(altura(a->esq),altura(a->dir));
}
return h;
}
ABin cloneAB (ABin a){
ABin new = malloc(sizeof(struct nodo));
//if(a==NULL) return NULL;
while(a){
new->valor = a->valor;
new->esq = cloneAB(a->esq);
new->dir = cloneAB(a->dir);
return new;
}
return NULL;
}
void mirror (ABin *a){
ABin aux;
if((*a)==NULL);
else {
aux = (*a)->esq;
(*a)->esq = (*a)->dir;
(*a)->dir = aux;
mirror(&(*a)->dir);
mirror(&(*a)->esq);
}
}
/*
Numa arvore de procura:
_inorder: ordem crescente;
_preorder : valor, esquerda, direita;
_posorder: esquerda,direita, valor;
*/
void inorder (ABin a , LInt *l){
if(a==NULL);
else{
inorder(a->esq,l);
while(*l){l = &((*l)->prox);}
(*l) = malloc(sizeof(struct lligada));
(*l)->valor = a->valor;
(*l)->prox = NULL;
inorder(a->dir,l);
}
}
void preorder (ABin a, LInt *l){
if(a==NULL);
else{
while(*l){l = &((*l)->prox);}
(*l) = malloc(sizeof(struct lligada));
(*l)->valor = a->valor;
(*l)->prox = NULL;
preorder(a->esq,l);
preorder(a->dir,l);
}
}
void posorderAux (ABin a, LInt *l){
if(a){
posorderAux(a->esq,l);
posorderAux(a->dir,l);
while(*l){l = &((*l)->prox);}
(*l) = malloc(sizeof(struct lligada));
(*l)->valor = a->valor;
(*l)->prox = NULL;
}
}
void posorder(ABin a, LInt *l){
(*l)=NULL;
posorderAux(a,l);
}
int depth (ABin a, int x){
int r=1, esq, dir;
if ( a == NULL) r = -1;
else if ( a -> valor == x) return 1;
else{
esq = depth ( a->esq, x);
dir = depth ( a->dir, x);
if ( esq == -1 && dir == -1) r = -1;
else if ( esq == -1 ) r+=dir;
else if ( dir == -1 ) r+=esq;
else if ( esq > dir ) r+= dir;
else r += esq;
}
return r;
}
int freeAB (ABin a){
int cont=0;
while(a){
free(a);
cont+= 1 + freeAB(a->esq) +freeAB(a->dir);
}
}
int pruneAB(ABin *a, int l){
if(*a==NULL) return 0;
int x=0;
x += pruneAB(&((*a)->esq),l-1);
x += pruneAB(&((*a)->dir),l-1);
if(l<1){
free(*a);
x++;
*a=NULL;
}else if(l==1){
(*a)->esq=NULL;
(*a)->dir=NULL;
}
return x;
}
int iguaisAB (ABin a, ABin b){
int r,esq,dir;
if((a==NULL) && (b==NULL)) r=1;
else if((a==NULL) || (b==NULL)) r=0;
else{
if(a->valor == b->valor){
esq = iguaisAB(a->esq,b->esq);
dir = iguaisAB(a->dir,b->dir);
if(esq==0 || dir==0) r=0;
else r =1
}
else r =0;
}
return r;
}
LInt nivelL (ABin a, int n){
LInt new;
LInt *aux = &new;
if(a==NULL) return;
while(*aux) new = &((*aux)->prox);
aux = malloc(sizeof(struct lligada));
aux->prox == NULL;}
if(n==1){
aux->valor = a->valor;
else{
nivelL(a->esq,n-1);
nivelL(a->dir,n-1);
}
return new;
}
int contaFolhas (ABin a){
int r=0;
if(a==NULL) return 0;
if(a->dir==NULL && a->esq==NULL) r += 1 + contaFolhas(a->esq) + contaFolhas(a->dir);
else r += contaFolhas(a->esq) + contaFolhas(a->dir);
return r;
}
ABin cloneMirror (ABin a){
ABin new =malloc(sizeof(struct nodo));
if(a){
new->valor = a->valor;
new->esq = cloneMirror(a->dir);
new->dir = cloneMirror(a->esq);
}
else return NULL;
return new;
}
int addOrd (ABin *a, int x){
}
<file_sep>/PI21/Ficha 10/abin.c
#include "abin.h"
ABin newABin (int r, ABin e, ABin d) {
ABin a = malloc (sizeof(struct nodo));
if (a!=NULL) {
a->valor = r; a->esq = e; a->dir = d;
}
return a;
}
ABin RandArvFromArray (int v[], int N) {
ABin a = NULL;
int m;
if (N > 0){
m = rand() % N;
a = newABin (v[m], RandArvFromArray (v,m), RandArvFromArray (v+m+1,N-m-1));
}
return a;
}
// Questão 1
ABin removeMenor (ABin *a){
ABin r = NULL;
while(*a && (*a)->esq)
a = &((*a)->esq);
r = *a;
*a = (*a)->dir;
return r;
}
void removeRaiz (ABin *a){
ABin aux;
if(*a){
aux = removeMenor(&((*a)->dir));
if(aux){
aux->esq = (*a)->esq;
aux->dir = (*a)->dir;
free(*a);
*a = aux;
}
else{
aux = *a;
*a = (*a)->esq;
free(aux);
}
}
}
int removeElem (ABin *a, int x){
int r = -1;
if(*a){
if((*a)->valor == x){
removeRaiz(a);
r=0;
}else if((*a)->valor < x){
r = removeElem(&((*a)->dir),x);
}else {
r = removeElem(&((*a)->esq),x)
}
}
return r;
}
// Questão 2
void rodaEsquerda (ABin *a){
ABin b = (*a)->dir;
(*a)->dir = b->esq;
b->esq = (*a);
*a = b;
}
void rodaDireita (ABin *a){
ABin b = (*a)->esq;
(*a)->esq = b->dir;
b->dir = *a;
*a = b;
}
void promoveMenor (ABin *a){
if(*a && (*a)->esq){
promoveMenor(&((*a)->esq));
rodaDireita(a);
}
}
void promoveMaior (ABin *a){
if(*a && (*a)->dir){
promoveMenor(&((*a)->dir));
rodaEsquerda(a);
}
ABin removeMenorAlt (ABin *a){
ABin r = NULL;
promoveMenor(a);
r = *a;
*a = (*a)->dir;
return r;
}
// Questão 3
int constroiEspinhaAux (ABin *a, ABin *ult){
int r =0;
if(*a){
r = constroiEspinhaAux(&((*a)->esq),ult);
rodaDireita(a);
r += 1 + constroiEspinhaAux(&((*a)->dir),ult);
}
return (-1);
}
int constroiEspinha (ABin *a){
ABin ult;
return (constroiEspinhaAux (a,&ult));
}
ABin equilibraEspinha (ABin *a, int n) {
return NULL;
}
void equilibra (ABin *a) {
}<file_sep>/PI21/piex1.c
#include <stdio.h>
/*
int x, y;
x = 3;
y = x+1;
x = x*y; y = x + y;
printf("%d %d\n", x, y);
int x, y;
x = 0;
printf ("%d %d\n", x, y);
*/
/*char a, b, c;
a = 'A'; b = ' '; c = '0';
printf ("%c %d\n", a, a);
a = a+1; c = c+2;
printf ("%c %d %c %d\n", a, a, c, c);
c = a + b;
printf ("%c %d\n", c, c);*/
/*int i;
for (i=0; (i<20) ; i++)
if (i%2 == 0) putchar ('_');
else putchar ('#');*/
void f (int n) {
while (n>0) {
if (n%2 == 0) putchar ('0');
else putchar ('1');
n = n/2;
}
putchar ('\n');
}
int main () {
int i;
for (i=0;(i<16);i++)
f (i);
return 0;
}
<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/src/Clientes/Menu/Phases/PhaseMainMenu.java
package Clientes.Menu.Phases;
import java.util.List;
import Connections.Demultiplexer;
public class PhaseMainMenu extends Phase{
static boolean isAdmin= false;
public PhaseMainMenu(Demultiplexer dm,boolean adminValue)
{
this(dm);
isAdmin = adminValue;
SetMessages();
}
public PhaseMainMenu(Demultiplexer dm,String sucessMessage)
{
this(dm);
ChangeSucessMessage(sucessMessage);
}
public PhaseMainMenu(Demultiplexer dm)
{
super(dm);
SetMessages();
TipForInput = "$";
InputForStages = new String[]{};
numberStages = InputForStages.length +1;
}
private void SetMessages() {
if (isAdmin)
{
Messages = new String[]{
"Trabalho Pratico SD",
"",
"Menu",
"quit -> Sair do programa",
"add -> adicionar um novo voo",
"cancel -> cancelar uma reserva",
"close -> encerrar as reservas um dia",
"register -> registar um usuario",
};
}
else
{
Messages = new String[]{
"Trabalho Pratico SD",
"",
"Menu",
"quit -> Sair do programa",
"book -> fazer uma reserva",
"show -> mostrar voos",
"cancel -> cancelar uma reserva"
};
}
}
@Override
public Phase HandleCommand(List<String> s) {
String command = s.get(0);
return HandleConsole(command,isAdmin);
}
public Phase HandleConsole(String command,boolean admin)
{
if (isAdmin){
switch (command) {
case "book":
return new PhaseBooking(dm);
case "add":
return new PhaseAdmInserirVoo(dm);
case "close":
return new PhaseEncerrarDia(dm);
case "cancel":
return new PhaseCancelarReserva(dm);
case "register":
return new PhaseRegisto(dm);
default:
break;
}
}
else{
switch (command) {
case "book":
return new PhaseBooking(dm);
case "show":
return new PhaseShowVoos(dm);
case "cancel":
return new PhaseCancelarReserva(dm);
default:
break;
}
}
return null;
}
}
<file_sep>/PI21/pi_aula1.c
#include <stdio.h>
void imprimequadrado (){
int k,i;
for (k=0;k<5;k++){
for(i=0;i<5;i++){
putchar('#');
}
putchar('\n');
}
}
void imprimexadrez (){
int k,i,a;
for (k=0;k<5;k++){
if (k%2==0){
for(i=0;i<5;i++){
if (i%2==0) putchar('#');
else putchar('_');
}
}
else {
for(a=0;a<5;a++){
if (a%2==0) putchar('_');
else putchar('#');
}
}
putchar('\n');
}
}
void imprimetriangulo (int b){
for (int i=1; i<=b; i++){
for (int k = 0; k <i; k++){
putchar('#');
}
putchar('\n');
}
for (int y=(b-1); y>=0; y--){
for (int x = 0; x <y; x++){
putchar('#');
}
putchar('\n');
}
}
int main (){
int b;
printf("Insira base: " );
scanf("%d", &b);
imprimetriangulo(b);
}
void imprimetriagulo2 (){
for (int y; y; y){
for (int x; x<; x){
putchar(' ');
}
}
}
<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/src/Servidores/ThreadsServer/ThreadShowMenu.java
package Servidores.ThreadsServer;
import java.io.IOException;
import java.util.List;
import Connections.Demultiplexer;
import Servidores.Server;
import Servidores.Dados.ServerData;
import Viagens.Cidade;
public class ThreadShowMenu extends Thread {
Demultiplexer dm;
ServerData db;
public ThreadShowMenu(Demultiplexer dm)
{
this.dm = dm;
db = Server.getDataBase();
}
@Override
public void run() {
while(true)
{
try {
var nextAnswer = dm.receive(3);
String answer = new String(nextAnswer);
if (answer.equals("Show"));
{
HandleShowServertoClient();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
dm.close();
}
}
}
private void HandleShowServertoClient() {
List<Cidade> allCities = db.GetGrafoCidades().GetAllCidades();
StringBuilder sBuilder = new StringBuilder();
sBuilder.append(allCities.size()).append(";");
for (int i = 0; i < allCities.size(); i++) {
sBuilder.append(allCities.get(i).getNome()).append(";");
}
//9;Hong Kong;Madrid;Turim;Veneza;New York;Pyongyang;Nevada;Braga;Porto;
dm.send(3,sBuilder.toString().getBytes());
sBuilder.delete(0, sBuilder.length());
for (int i = 0; i < allCities.size(); i++) {
List<Cidade> allDestinos = db.GetGrafoCidades().GetPossibleVoo(allCities.get(i));
for (Cidade cidade : allDestinos) {
sBuilder.append(cidade.getNome()).append(";");
}
sBuilder.append("@");
}
dm.send(3,sBuilder.toString().getBytes());
}
}
<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/src/Clientes/Menu/Phases/PhaseAutenticaçao.java
package Clientes.Menu.Phases;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
import Clientes.ThreadClient.ThreadGetInfoServer;
import Connections.Demultiplexer;
public class PhaseAutenticaçao extends Phase{
static Thread threadGetInfoServer;
public PhaseAutenticaçao(Demultiplexer dm)
{
super(dm);
Messages = new String[]{
"Autenticação",
"",
};
TipForInput = "Username";
InputForStages = new String[]{
"Password",
};
numberStages = InputForStages.length +1;
}
@Override
public Phase HandleCommand(List<String> s) {
String username = s.get(0);
String password = s.get(1);
if (username.isEmpty() || password.isEmpty()) return null;
String message = username + ";" + password + ";";
dm.send(1, message.getBytes());
try {
byte[] answerFromServer = dm.receive(1);
String answerString = new String(answerFromServer);
ChangeWarningMessage(answerString);
Scanner sc = new Scanner(answerString).useDelimiter(";");
String sucessCode;String isAdminString;
try {
sucessCode = sc.next();
isAdminString = sc.next();
} catch (Exception e) {
ChangeWarningMessage("Autenticação falhou...\n");
sc.close();
return null;
}
sc.close();
boolean isAdmin;
if (isAdminString.equals("1"))
isAdmin = true;
else isAdmin = false;
if (sucessCode.equals("200"))
{
//Cliente entrou com sucesso no servidor
//Cliente demonstra que quer comunicar com o servidor
dm.send(3, "Show".getBytes());
Thread getInfoServer = new ThreadGetInfoServer(dm);
getInfoServer.start();
return new PhaseMainMenu(dm,isAdmin);
}
else
{
ChangeWarningMessage("Autenticaçao do cliente falhou");
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
<file_sep>/PI21/Ficha 9/abin.c
#include <stdio.h>
#include <stdlib.h>
typedef struct nodo {
int valor;
struct nodo *esq, *dir;
} * ABin;
ABin newABin (int r, ABin e, ABin d) {
ABin a = malloc (sizeof(struct nodo));
if (a!=NULL) {
a->valor = r; a->esq = e; a->dir = d;
}
return a;
}
ABin RandArvFromArray (int v[], int N) {
ABin a = NULL;
int m;
if (N > 0){
m = rand() % N;
a = newABin (v[m], RandArvFromArray (v,m), RandArvFromArray (v+m+1,N-m-1));
}
return a;
}
int altura (ABin a){
int d=0;
if(a!=NULL) d+= 1+ max(altura(a->dir), altura(a->esq));
return d;
}
int nFolhas (ABin a){
int r=0;
while(a!=NULL){
if(a->dir==NULL && a->esq==NULL) r=1;
else r = nFolhas(a->esq) + nFolhas(a->dir);
}
}
ABin maisEsquerda (ABin a){
for(a,a!=NULL;a = a->esq) return a->valor;
}
void imprimeNivel (ABin a, int l){
}
int procuraE (ABin a, int x){
return (-1);
}
struct nodo *procura (ABin a, int x){
return NULL;
}
int nivel (ABin a, int x){
return (-1);
}
void imprimeAte (ABin a, int x){
}
#include <time.h>
int main (){
int v1[15] = { 1, 3, 5, 7, 9,11,13,15,17,19,21,23,25,27,29},
v2[15] = {21, 3,15,27, 9,11,23, 5,17,29, 1,13,25, 7,19},
N=15;
ABin a1, a2,r;
srand(time(NULL));
printf ("_______________ Testes _______________\n\n");
// N = rand() % 16;
a1 = RandArvFromArray (v2, N);
printf ("Primeira árvore de teste (%d elementos)\n", N);
dumpABin (a1, N);
printf ("altura = %d\n", altura (a1));
printf ("numero de folhas: %d\n", nFolhas (a1));
printf ("Nodo mais à esquerda: ");
r = maisEsquerda (a1);
if (r==NULL) printf ("(NULL)\n"); else printf ("%d\n", r->valor);
printf ("Elementos no nivel 3_______\n");
imprimeNivel (a1, 3);
printf ("\n___________________________\n");
printf ("procura de 2: %d\n", procuraE (a1, 2));
printf ("procura de 9: %d\n", procuraE (a1, 9));
freeABin (a1);
// N = rand() % 16;
a2 = RandArvFromArray (v1, N);
printf ("\nSegunda árvore de teste (%d elementos)\n", N);
dumpABin (a2, N);
printf ("procura de 9: ");
r = procura (a2, 9);
if (r==NULL) printf ("(NULL)\n"); else printf ("%d\n", r->valor);
printf ("procura de 2: ");
r = procura (a2, 2);
if (r==NULL) printf ("(NULL)\n"); else printf ("%d\n", r->valor);
printf ("nível do elemento 2: %d\n", nivel (a2, 2));
printf ("nível do elemento 9: %d\n", nivel (a2, 9));
imprimeAte (a2, 20);
freeABin (a1);
printf ("\n\n___________ Fim dos testes ___________\n\n");
return 0;
} <file_sep>/PI21/Ficha 8/Stack.h
#include "Listas.h"
typedef LInt Stack;
void initStack (Stack *s);
int SisEmpty (Stack s);
int push (Stack *s, int x);
int pop (Stack *s, int *x);
int top (Stack s, int *x);<file_sep>/IdeaProjects/POO/Ficha3/src/Carro.java
public class Carro {
private String marca;
private String modelo;
private int anoConstrucao;
private double consumo;
private double kmTotais;
private double kmUltimoPercurso;
private double mediaConsumoTotal;
private double mediaConsumoUltimoPercurso;
private estado e;
public enum estado{
LIGADO,
DESLIGADO;
}
public Carro(){
this.marca = "";
this.modelo = "";
this.anoConstrucao = 2000;
this.consumo = 5;
this.kmTotais = 0;
this.kmUltimoPercurso = 0;
this.mediaConsumoTotal = 0;
this.mediaConsumoUltimoPercurso = 0;
this.e = estado.DESLIGADO;
}
public Carro ( String marca, String modelo, int anoConstrucao, double consumo, double kmTotais, double kmUltimoPercurso,double mediaConsumoTotal,double mediaConsumoUltimoPercurso, estado e){
this.marca = marca;
this.modelo = modelo;
this.anoConstrucao = anoConstrucao;
this.consumo = consumo;
this.kmTotais = kmTotais;
this.kmUltimoPercurso = kmUltimoPercurso;
this.mediaConsumoTotal = mediaConsumoTotal;
this.mediaConsumoUltimoPercurso = mediaConsumoUltimoPercurso;
this.e = e;
}
public Carro (Carro car){
this.marca = car.getMarca();
this.modelo = car.getModelo();
this.anoConstrucao = car.getAnoConstrucao();
this.consumo = car.getConsumo();
this.kmTotais = car.getKmTotais();
this.kmUltimoPercurso = car.getKmUltimoPercurso();
this.mediaConsumoTotal = car.getMediaConsumoTotal();
this.mediaConsumoUltimoPercurso = car.getMediaConsumoUltimoPercurso();
this.e = car.getE();
}
public void ligaCarro(){
if (e == estado.DESLIGADO){
setE(estado.LIGADO);
setKmUltimoPercurso(0);
setMediaConsumoUltimoPercurso(0);
}
else System.out.println("O carro já está ligado!");
}
public void desligaCarro(){
if(e == estado.LIGADO){
setE(estado.DESLIGADO);
}
else System.out.println("O carro já está desligado!");
}
public void resetUltimaViagem(){
setMediaConsumoUltimoPercurso(0);
setKmUltimoPercurso(0);
}
public void avancaCarro (double metros, double velocidade){
if (this.e == estado.LIGADO){
double km = metros/1000;
setKmTotais(getKmTotais()+km);
setKmUltimoPercurso(km);
setMediaConsumoUltimoPercurso((this.consumo*velocidade)/100);
setMediaConsumoTotal(getMediaConsumoTotal());
}
else System.out.println("O carro está desligado!");
}
public void travaCarro(double metros){
if (this.e == estado.LIGADO){
double km = metros/1000;
setKmTotais(getKmTotais()+km);
}
else System.out.println("O carro está desligado!");
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
public int getAnoConstrucao() {
return anoConstrucao;
}
public void setAnoConstrucao(int anoConstrucao) {
this.anoConstrucao = anoConstrucao;
}
public double getConsumo() {
return consumo;
}
public void setConsumo(double consumo) {
this.consumo = consumo;
}
public double getKmTotais() {
return kmTotais;
}
public void setKmTotais(double kmTotais) {
this.kmTotais = kmTotais;
}
public double getKmUltimoPercurso() {
return kmUltimoPercurso;
}
public void setKmUltimoPercurso(double kmUltimoPercurso) {
this.kmUltimoPercurso = kmUltimoPercurso;
}
public double getMediaConsumoTotal() {
return mediaConsumoTotal;
}
public void setMediaConsumoTotal(double mediaConsumoTotal) {
this.mediaConsumoTotal = mediaConsumoTotal;
}
public double getMediaConsumoUltimoPercurso() {
return mediaConsumoUltimoPercurso;
}
public void setMediaConsumoUltimoPercurso(double mediaConsumoUltimoPercurso) {
this.mediaConsumoUltimoPercurso = mediaConsumoUltimoPercurso;
}
public estado getE() {
return e;
}
public void setE(estado e) {
this.e = e;
}
}
<file_sep>/IdeaProjects/POO/Ficha3/src/Main.java
public class Main {
public static void circulo(){
Circulo c1 = new Circulo();
c1.setRaio(3);
c1.alteraCentro(2,5);
System.out.println(c1.calculaArea());
System.out.println("O perimetro é: "+c1.calculaPerimetro());
System.out.println("o novo raio é: "+c1.getRaio());
}
public static void futebol(){
Futebol f1 = new Futebol();
f1.startGame();
f1.goloVisitado();
f1.goloVisitado();
f1.goloVisitante();
f1.resultadoActual();
f1.endGame();
}
public static void main (String[]args){
futebol();
}
}
<file_sep>/PI21/ficha5.c
#include <stdio.h>
#include <string.h>
typedef struct aluno {
int numero;
char nome[100];
int miniT [6];
float teste;
} Aluno;
void dumpV (int v[], int N){
int i;
for (i=0; i<N; i++) printf ("%d ", v[i]);
}
void imprimeAluno (Aluno *a){
int i;
printf ("%-5d %s (%d", a->numero, a->nome, a->miniT[0]);
for(i=1; i<6; i++) printf (", %d", a->miniT[i]);
printf (") %5.2f %d\n", a->teste, nota(*a));
}
int nota (Aluno a){//70 teste // 30 mini(6)
int NminiT=0,aux;
for(int i=0; i<6; i++){
NminiT += a.miniT[i];
}
aux= (NminiT*0.3*20/12)+(a.teste*0.7);
/*if( ((NminiT/6)*(20/12)>=8) && (aux>=9.5) ) return aux;
else return 0;*/
return( (NminiT*20/12>=8) && (aux>=9.5) && (a.teste>=8) ) ? aux : 0;
}
int procuraNum (int num, Aluno t[], int N){
int x,i;
for(i=0;i<N;i++){
if (num == t[i].numero) {x=i; break;}
}
return (x==i) ? x : -1;
}
void ordenaPorNome (Aluno t [], int N){
int aux;
for (int cont = 1; cont < N; cont++){
for (int i = 0; i < N - 1; i++){
if (strlen(t[i].nome) > strlen(t[i+1].nome)){
aux = strlen(t[i].nome);
strlen(t[i].nome) = strlen(t[i+1].nome);
strlen(t[i+1].nome) = aux;
}
}
}
}
void ordenaPorNum (Aluno t [], int N){
int aux;
for (int cont = 1; cont < N; cont++){
for (int i = 0; i < N - 1; i++){
if (t[i].numero > t[i+1].numero){
aux = t[i].numero;
t[i].numero = t[i+1].numero;
t[i+1].numero = aux;
}
}
}
}
int procuraNumInd (int num, int ind[], Aluno t[], int N){
return -1;
}
void criaIndPorNum (Aluno t [], int N, int ind[]){
ordenaPorNum(t,N);
for(int i=0;i<N;i++){
ind[i]=t[i].numero;
}
}
void criaIndPorNome (Aluno t [], int N, int ind[]){
ordenaPorNome(t,N);
for(int i=0;i<N;i++){
ind[i]=t[i].nome;
}
}
void imprimeTurmaInd (int ind[], Aluno t[], int N){
int i;
for (i=0; i<N; i++)
imprimeAluno (t + ind[i]);
}
int main() {
Aluno Turma1 [7] = {{4444, "André", {2,1,0,2,2,2}, 10.5}
,{3333, "Paulo", {0,0,2,2,2,1}, 8.7}
,{8888, "Carla", {2,1,2,1,0,1}, 14.5}
,{2222, "Joana", {2,0,2,1,0,2}, 3.5}
,{7777, "Maria", {2,2,2,2,2,1}, 5.5}
,{6666, "Bruna", {2,2,2,1,0,0}, 12.5}
,{5555, "Diogo", {2,2,1,1,1,0}, 8.5}
} ;
int indNome [7], indNum [7];
int i;
printf ("\n-------------- Testes --------------\n");
ordenaPorNum (Turma1, 7);
printf ("procura 5555: %d \n", procuraNum (5555, Turma1, 7));
printf ("procura 9999:%d \n", procuraNum (9999, Turma1, 7));
for (i=0; i<7; imprimeAluno (Turma1 + i++));
//nota(Turma1[0]);
// criaIndPorNum (Turma1, 7, indNum);
// criaIndPorNome (Turma1, 7, indNome);
// imprimeTurmaInd (indNum, Turma1, 7);
// imprimeTurmaInd (indNome, Turma1, 7);
// printf ("procura 5555:%d \n", procuraNumInd (5555, indNum, Turma1, 7));
// printf ("procura 9999:%d \n", procuraNumInd (9999, indNum, Turma1, 7));
printf ("\n---------- Fim dos Testes ----------\n");
return 0;
}<file_sep>/FM7/Model.java
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.Map;
/**
* Escreva a descrição da classe Model aqui.
*
* @author (seu nome)
* @version (número de versão ou data)
*/
public class Model implements mFM{
private Gestor jogo = new Gestor();
private cFM controller;
public Model(Gestor jogo,cFM controller){
this.jogo = jogo;
this.controller = controller;
}
public void addJogo(Gestor g){
this.jogo = jogo;
}
public void addController(cFM controller){
this.controller = controller;
}
public List<String> stringTeamsnome(){
Map<String,Equipa> equipas = jogo.getEquipas();
return equipas.values().stream().map(x -> x.getNome()).collect(Collectors.toList());
}
public List<String> stringTeams(){
Map<String,Equipa> equipas = jogo.getEquipas();
return equipas.values().stream().map(x -> x.toString()).collect(Collectors.toList());
}
public List<String> stringJogadores(){
Map<String,Jogador> jogadores = jogo.getJogadores();
return jogadores.values().stream().map(x -> x.toString()).collect(Collectors.toList());
}
public List<String> stringJogos(){
List<Jogo> jogos = jogo.getJogos();
return jogos.stream().map(x -> x.toString()).collect(Collectors.toList());
}
public void addJogador (Jogador j){
jogo.addJogador(j);
}
public void addEquipa (Equipa equipa){
jogo.addEquipa(equipa);
}
public void addJogador(String equipa,String jogador) throws NoTeamJogadorException{
try{
jogo.addJogador(equipa,jogador);
}
catch(NoTeamJogadorException e){
throw e;
}
}
public void removeJogador (String equipa,String jogador) throws NoTeamJogadorException{
try{
jogo.removeJogador(equipa,jogador);
}
catch(NoTeamJogadorException e){
throw e;
}
}
public String getHist(String nome)throws NoTeamJogadorException{
try{
return jogo.getHist(nome);
}catch(NoTeamJogadorException e){
throw e;
}
}
public Equipa getEquipa(String equipa)throws NoTeamJogadorException{
try{
return jogo.getTeam(equipa);
}catch(NoTeamJogadorException e){
throw e;
}
}
public List<Integer> getNumjogadoresequipa(String equipa) throws NoTeamJogadorException{
try{
return jogo.getNumjogadoresequipa(equipa);
}catch(NoTeamJogadorException e){
throw e;
}
}
public boolean containsNumJogador(String equipa,Integer numJogador) throws NoTeamJogadorException{
try{
return jogo.containsNumJogador(equipa,numJogador);
}catch(NoTeamJogadorException e){
throw e;
}
}
public void addJogo(Jogo j){
jogo.addJogo(j);
}
}<file_sep>/IdeaProjects/POO/ficha2/src/Exercicio5.java
/*
public class Exercicio5 {
public String[] arrayString (String[] array){
for(int i=0; i<array.length;i++){
}
}
}
*/
<file_sep>/PI21/testepi.c
#include <stdio.h>
void imprimetriangulo (){
int i,k;
for (i=1; i<5; i++){
for (k = 0; k <i; k++){
putchar('#');
}
putchar('\n');
}
}
int main (){
imprimetriangulo();
}
<file_sep>/PI21/Ficha 10/sol.h
// Questão 1
ABin removeMenor_sol (ABin *a);
void removeRaiz_sol (ABin *a);
int removeElem_sol (ABin *a, int x);
// Questão 2
int constroiEspinha_sol (ABin *a);
ABin equilibraEspinha_sol (ABin *a, int n);
void equilibra_sol (ABin *a);
// Questão 3
void promoveMenor_sol (ABin *a);
void promoveMaior_sol (ABin *a);
<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/src/Clientes/Menu/Phases/PhaseAdmInserirVoo.java
package Clientes.Menu.Phases;
import Clientes.Client;
import Connections.Demultiplexer;
import Viagens.Cidade;
import java.util.List;
public class PhaseAdmInserirVoo extends Phase {
public PhaseAdmInserirVoo(Demultiplexer dm)
{
super(dm);
List<Cidade> allCities = Client.GetClientData().GetAllCidades();
String arr[] = new String[allCities.size() +1];
arr[0] = "(ADM) Adicionar Novo Voo";
for (int i = 0; i < allCities.size(); i++) {
arr[i+1] = allCities.get(i).getNome();
}
Messages =arr;
TipForInput = "Origem";
InputForStages = new String[]{
"Destino",
"Capacidade",
};
numberStages = InputForStages.length +1;
this.dm = dm;
}
@Override
public Phase HandleCommand(List<String> s) {
if (s.get(0).isEmpty() || s.get(1).isEmpty() || s.get(2).isEmpty())
return null;
//Converter braga para Braga
String origin = ConvertToUpperCase(s.get(0));
String destiny = ConvertToUpperCase(s.get(1));
int capaci;
try {
capaci = Integer.parseInt(s.get(2));
} catch (Exception e) {
return null;
}
Cidade origem = new Cidade(origin);
Cidade destino = new Cidade(destiny);
try {
String isValid = HandleAux(origem,destino,capaci);
if (isValid.equals("true"))
{
String sucessMessage = "O voo " +origin+ "->" +destiny+ " foi adicionado com sucesso!\n";
return new PhaseMainMenu(dm,sucessMessage);
}else if(isValid.equals("false")){
ChangeWarningMessage("O voo já existe!\n");
}else ChangeWarningMessage("O voo não foi adicionado!\n");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
private String HandleAux(Cidade origin, Cidade destiny, Integer capaci) throws Exception {
StringBuilder sb = new StringBuilder();
sb.append(origin.getNome()).append(";");
sb.append(destiny.getNome()).append(";");
sb.append(capaci).append(";");
String message = sb.toString();
dm.send(9,message.getBytes());
String response = new String( dm.receive(9));
if (response.equals("200"))
return "true";
if(response.equals("jaexiste"))
return "false";
else return "-1";
}
private String ConvertToUpperCase(String s1) {
return Character.toUpperCase(s1.charAt(0)) + s1.substring(1);
}
}<file_sep>/DSS/source/Menu/Phases/Phase2.java
package bin;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import bin.Phase;
import bin.Phase1;
import bin.Pessoas.Cliente;
import bin.Pessoas.FuncionarioBalcao;
import bin.Pessoas.FuncionarioReparacao;
import bin.Pessoas.Gestor;
import bin.Pessoas.Pessoa;
import bin.Controller;
import bin.Pessoas.ReadLoadPessoas;
public class Phase2 extends Phase{
public Phase2()
{
Messages = new String[]{
"Autenticação",
"",
};
TipForInput = "Username";
InputForStages = new String[]{
"Encargo",
"Password",
};
numberStages = InputForStages.length +1;
}
@Override
public Phase HandleCommand(List<String> s) {
String username = s.get(0);
String tipoFuncionario = s.get(1);
String password = s.get(2);
if (!ReadLoadPessoas.stringPessoas.containsKey(tipoFuncionario) )
{
String temp = "Esse tipo de encargo não existe, disponivel: ";
for (String string : ReadLoadPessoas.stringPessoas.keySet()) {
temp += string + " ";
}
temp += "\n";
ChangeWarningMessage(temp);
return null;
}
for (Pessoa p : Controller.allPessoas) {
//Found the person we were looking after
if (p.getClass().equals(ReadLoadPessoas.stringPessoas.get(tipoFuncionario)) &&
p.getNome().equals(username))
{
if(!p.getPassword().equals(password))
{
ChangeWarningMessage("O usuario "+ username + " existe\nmas a password está incorreta :(\n");
return null;
}
Phase1.currentPessoa = p;
return new Phase1("Login feito com sucesso!\n");
}
}
//Se nao existir esse usuario na base de dados
ChangeWarningMessage("Não existe o usuário "+ username + "\n");
return null;
}
}
<file_sep>/PI21/ficha3.c
#include <stdio.h>
#include <math.h>
void swapM (int *x, int *y){
int aux;
aux = *x;
*x = *y;
*y = aux;
printf("x= %d | y=%d\n", *x, *y );
}
void swap (int v[], int i, int j){
int aux;
aux = v[i];
v[i]= v[j];
v[j]=aux;
}
int soma (int v[], int N){
int aux=0;
for (int i = 0; i < N; i++){
aux += v[i];
}
return aux;
}
void inverteArray (int v[], int N){
int j=0;
for(int i=0; i < N/2 ; i++){
j=N-i-1;
swap(v,i,j);
}
}
int maximum (int v[], int N , int *m){
*m=v[0];
for(int i=0;i<N;i++){
if (v[i] > *m) *m=v[i]
}
}
void quadrados (int q[], int N){
for(int i=0;i<N;i++){
q[i]=pow(i,2);
}
}
void pascal (int v[], int N){
}
int main(){
int x=5,y=3;
inverteArray()
return 0;
}<file_sep>/PI21/Ficha 10/abin.h
#include <stdio.h>
#include <stdlib.h>
typedef struct nodo {
int valor;
struct nodo *esq, *dir;
} * ABin;
ABin newABin (int r, ABin e, ABin d);
ABin RandArvFromArray (int v[], int N);
ABin cloneABin (ABin a);
void dumpABin (ABin a, int N);
void freeABin (ABin a);
// Questão 1
ABin removeMenor (ABin *a);
void removeRaiz (ABin *a);
int removeElem (ABin *a, int x);
// Questão 2
void rodaEsquerda (ABin *a);
void rodaDireita (ABin *a);
void promoveMenor (ABin *a);
void promoveMaior (ABin *a);
ABin removeMenorAlt (ABin *a);
// Questão 3
int constroiEspinha (ABin *a);
ABin equilibraEspinha (ABin *a, int n);
void equilibra (ABin *a);<file_sep>/DSS/source/Menu/Phases/Phase3.java
package bin;
import java.util.List;
import java.util.ArrayList;
import bin.Phase;
import bin.Phase1;
import bin.Pessoas.Pessoa;
import bin.Pessoas.ReadLoadPessoas;
import bin.Controller;
public class Phase3 extends Phase {
public Phase3(){
Messages = new String[]{ "Registe-se no Sistema"," " };
TipForInput = "Insira o nome";
InputForStages = new String[]{
"Insira o encargo",
"Insira uma password" };
numberStages = InputForStages.length +1;
}
@Override
public Phase HandleCommand(List<String> s) {
String name = s.get(0);
String cargo = s.get(1);
String password = s.get(2);
//Se nao existir esse usuario na base de dados
for (Pessoa p : Controller.allPessoas) {
if (p.getNome().equals(name))
{
//Já existe um usuario com esse nome :(
ChangeWarningMessage("Já existe um usuario com esse nome!\n");
return null;
}
}
//Se o cargo nao existir na nossa base de dados
if (!ReadLoadPessoas.stringPessoas.containsKey(cargo))
{
String messageTemp = "Encargos disponiveis -> ";
for (String string : ReadLoadPessoas.stringPessoas.keySet()) {
messageTemp += string + " ";
}
messageTemp += "\n";
ChangeWarningMessage(messageTemp);
return null;
}
Pessoa p = ReadLoadPessoas.BuildPessoaFromString(cargo, name, "randomID", password);
//Guardar na base de dados
ReadLoadPessoas.WritePessoa(p);
Phase1.currentPessoa = p;
//Se foi feito com sucesso
return new Phase1("Registo efetuado com Sucesso!\n");
}
}
<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/src/Connections/BreadthFirst.java
package Connections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import Viagens.Cidade;
public class BreadthFirst {
public static Stack<Cidade> BFS( Map<Cidade,List<Cidade>> mapa,Cidade origem,Cidade destino) throws Exception
{
if (!mapa.containsKey(origem) || !mapa.containsKey(destino))
throw new Exception("Não existe esse elemento no mapa");
Map<Cidade,Cidade> cityTree = new HashMap<>();
//Inicializar o a estrutura de todas as cidades visitadas como falsa
Map<Cidade,Boolean> visited = new HashMap<Cidade,Boolean>();
for (Cidade c : mapa.keySet()) {
visited.put(c, false);
}
// Create a queue for BFS
LinkedList<Cidade> queue = new LinkedList<Cidade>();
// System.out.println("Starting at " + r1.ruaNome);
// Mark the current node as visited and enqueue it
visited.put(origem, true);
queue.add(origem);
//Cidade origem não tem um pai
cityTree.put(origem, null);
Cidade current = null;
while (queue.size() != 0)
{
// Dequeue a vertex from queue and print it
current = queue.poll();
if (current.equals(destino))
{
//City of destination has been found;
break;
}
for (Cidade next : mapa.get(current)) {
if ( ! visited.get(next) )
{
visited.put(next,true);
queue.add(next);
//Adicionar a relaçao pai filho
cityTree.put(next,current);
}
}
}
Stack<Cidade> caminho = new Stack<Cidade>();
Cidade pai = destino;
while(pai !=null)
{
caminho.push(pai);
pai = cityTree.get(pai);
}
return caminho;
}
}
<file_sep>/PI21/Ficha 8/Deque.h
#include "Listas.h"
typedef struct {
DList back, front;
} Deque;
void initDeque (Deque *q);
int DisEmpty (Deque q);
int pushBack (Deque *q, int x);
int pushFront (Deque *q, int x);
int popBack (Deque *q, int *x);
int popFront (Deque *q, int *x);
int popMax (Deque *q, int *x);
int back (Deque q, int *x);
int front (Deque q, int *x);<file_sep>/FM7/README.TXT
----------------------------------------------------------------------------
Este é o arquivo README do projeto. Você deve descrever aqui o seu projeto.
Informe ao usuário (alguém que não sabe nada sobre este projeto!) tudo que
ele/ela precisa saber. Os comentários devem incluir, pelo menos:
------------------------------------------------------------------------
TITULO DO PROJETO:
OBJETIVO DO PROJETO:
VERSÃO ou DATA:
COMO INICIAR O PROJETO:
AUTORES:
a93252,<NAME>,ruipedrolousada
a93267,<NAME>,AlexandreDanielSoares
a93225,<NAME>,PWACN
INSTRUÇÕES PARA O USUÁRIO:
<file_sep>/IdeaProjects/Ficha6/src/AutocarroInteligente.java
import java.lang.annotation.Documented;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class AutocarroInteligente extends Veiculo implements BonificaKms{
private double ocupacao;
private double pontos;
public AutocarroInteligente (){
super();
this.ocupacao = 0;
this.pontos = 0;
}
public AutocarroInteligente(String marca, String modelo, String matricula, int ano, double velociademedia, double precokm, List<Integer> classificacao, int kms, int kmsUltimo, double ocupacao, double pontos){
super(marca,modelo,matricula,ano,velociademedia,precokm,classificacao,kms,kmsUltimo);
this.ocupacao = ocupacao;
this.pontos = pontos;
}
public AutocarroInteligente(AutocarroInteligente a){
super(a);
this.ocupacao = a.getOcupacao();
this.pontos = a.getPontos();
}
public double getOcupacao(){
return this.ocupacao;
}
public double custoRealKM(){
double custo = 0;
if(this.ocupacao<0.61 && this.ocupacao>=0) {
custo = super.getKms() * super.getPrecokm() * 1.1 * 0.5;
} else if(this.ocupacao>=0.61 && this.ocupacao<=1){
custo = super.getKms() * super.getPrecokm() * 1.1 * 0.25;
}
return custo;
}
public double getPontos(){return pontos;}
public void SetPontos(double pontos){
this.pontos = pontos;
}
public double getPontosAcumulados(){
return super.getKms()*this.pontos;
}
}
<file_sep>/PI21/Ficha 6/Queue.c
#include <stdio.h>
#include <stdlib.h>
#include "Queue.h"
// Static queues
void SinitQueue (SQueue q){
q->length=0;
}
int SisEmptyQ (SQueue q){
if(q->length == 0) return 1;
else return 0;
//return (-1);
}
int Senqueue (SQueue q, int x){
if(q->length < Max){
q->values[q->front - q->length] = x;
return 0;
}
else return 1;
}
/*
int Sdequeue (SQueue q, int *x) {
// ...
return (-1);
}
int Sfront (SQueue q, int *x) {
// ...
return (-1);
}*/
void ShowSQueue (SQueue q){
int i, p;
printf ("%d Items: ", q->length);
for (i=0, p=q->front; i<q->length; i++) {
printf ("%d ", q->values[p]);
p = (p+1)%Max;
}
putchar ('\n');
}
// Queues with dynamic arrays
/*
int dupQueue (DQueue q) {
// ...
return (-1);
}
void DinitQueue (DQueue q) {
// ...
}
int DisEmptyQ (DQueue s) {
return (-1);
}
int Denqueue (DQueue q, int x){
// ...
return (-1);
}
int Ddequeue (DQueue q, int *x){
// ...
return (-1);
}
int Dfront (DQueue q, int *x){
// ...
return (-1);
}
void ShowDQueue (DQueue q){
int i, p;
printf ("%d Items: ", q->length);
for (i=0, p=q->front; i<q->length; i++) {
printf ("%d ", q->values[p]);
p = (p+1)%q->size;
}
putchar ('\n');
}*/
<file_sep>/IdeaProjects/POO/Encomenda/src/Encomenda.java
import java.lang.reflect.Array;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Objects;
public class Encomenda {
private String nome;
private String morada;
private int numeroCliente;
private int numeroEncomenda;
private LocalDate data;
private ArrayList<LinhaEncomenda> linhas;
public Encomenda() {
this.nome = "Maria";
this.morada = "<NAME>";
this.numeroCliente = 232406471;
this.numeroEncomenda = 4321;
this.data = LocalDate.now() ;
this.linhas = new ArrayList<>();
}
public Encomenda(String nome, String morada, int numeroCliente, int numeroEncomenda, LocalDate data, ArrayList<LinhaEncomenda> linhas) {
this.nome = nome;
this.morada = morada;
this.numeroCliente = numeroCliente;
this.numeroEncomenda = numeroEncomenda;
this.data = data;
this.linhas = linhas;
}
public Encomenda(Encomenda enc) {
this.nome = enc.getNome();
this.morada = enc.getMorada();
this.numeroCliente = enc.getNumeroCliente();
this.numeroEncomenda = enc.getNumeroEncomenda();
this.data = enc.getData();
this.linhas = enc.getLinhas();
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getMorada() {
return morada;
}
public void setMorada(String morada) {
this.morada = morada;
}
public int getNumeroCliente() {
return numeroCliente;
}
public void setNumeroCliente(int numeroCliente) {
this.numeroCliente = numeroCliente;
}
public int getNumeroEncomenda() {
return numeroEncomenda;
}
public void setNumeroEncomenda(int numeroEncomenda) {
this.numeroEncomenda = numeroEncomenda;
}
public LocalDate getData() {
return data;
}
public void setData(LocalDate data) {
this.data = data;
}
public ArrayList<LinhaEncomenda> getLinhas() {
return linhas;
}
public void setLinhas(ArrayList<LinhaEncomenda> linhas) {
this.linhas = linhas;
}
public double calculaValorTotal(){
/*double x=0;
for(LinhaEncomenda l : this.linhas) x += l.calculaValorLinhaEnc();
return x;*/
return this.linhas.stream().mapToDouble(LinhaEncomenda :: calculaValorLinhaEnc).sum();
}
public double calculaValorDesconto(){
double x=0;
for(LinhaEncomenda l : this.linhas) x += l.calculaValorDesconto();
return x;
}
public int numeroTotalProdutos(){
int x=0;
for(LinhaEncomenda l : this.linhas) x += l.getQuantidade();
return x;
}
public boolean existeProdutoEncomenda(String refProduto){
for (LinhaEncomenda l : this.linhas) {
if(l.getReferencia().equals(refProduto)) return true;
}
return false;
}
public void adicionaLinha(LinhaEncomenda linha){
this.linhas.add(linha);
}
public void removeProduto(String codProd){
for (LinhaEncomenda l : this.linhas){
if(l.getReferencia().equals(codProd)) this.linhas.remove(l);
}
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Encomenda encomenda = (Encomenda) o;
return numeroCliente == encomenda.numeroCliente && numeroEncomenda == encomenda.numeroEncomenda && data == encomenda.data && Objects.equals(nome, encomenda.nome) && Objects.equals(morada, encomenda.morada) && Objects.equals(linhas, encomenda.linhas);
}
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
/*public Encomenda clone(){
return new Encomenda(this);
} */
public String toString() {
return "Encomenda{" +
"nome='" + this.nome + '\'' +
", morada='" + this.morada + '\'' +
", numeroCliente=" + this.numeroCliente +
", numeroEncomenda=" + this.numeroEncomenda +
", data=" + this.data +
", linhas=" + this.linhas +
'}';
}
}
<file_sep>/IdeaProjects/veiculo/src/VeiculoOcasiao.java
import java.util.ArrayList;
public class VeiculoOcasiao extends Veiculo {
private boolean promocao;
public VeiculoOcasiao() {
super();
this.promocao = false;
}
public VeiculoOcasiao(String marca, String modelo, String matricula,
int ano, double velociademedia, double precokm,
ArrayList<Integer> classificacao,
int kms, int kmsUltimo, boolean p) {
super(marca, modelo, matricula, ano, velociademedia, precokm, classificacao, kms, kmsUltimo);
this.promocao = p;
}
public VeiculoOcasiao(VeiculoOcasiao vo) {
super(vo);
this.promocao = vo.getPromocao();
}
public boolean getPromocao() {
return this.promocao;
}
public double custoRealKM() {
return this.promocao ? super.custoRealKM() * 0.75 : super.custoRealKM();
}
public String toString() {
return "VeiculoOcasiao{" +
"promocao=" + promocao +
'}';
}
}
//equals tostring clone
<file_sep>/Sistemas-Distribuidos-master/Sistemas-Distribuidos-master/src/Connections/TaggedConnection.java
package Connections;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TaggedConnection implements AutoCloseable {
DataInputStream inputSocket = null;
DataOutputStream outputSocket = null;
Socket socket = null;
private final Lock sendLock = new ReentrantLock();
private final Lock receiveLock = new ReentrantLock();
public TaggedConnection(Socket socket) {
try {
inputSocket = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
outputSocket = new DataOutputStream(new BufferedOutputStream( socket.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
this.socket = socket;
}
public void send(Frame f){
send(f.tag,f.data);
}
public void send(int tag,byte[] data){
sendLock.lock();
try {
/*
FORMATO -> Length | Tag | Data
*/
outputSocket.writeInt(4 +data.length);
outputSocket.writeInt(tag);
outputSocket.write(data);
outputSocket.flush();
System.out.println("Sent [" + tag + "] " + new String(data));
}
catch(Exception e){
} finally {
sendLock.unlock();
}
}
public Frame receive() throws IOException {
receiveLock.lock();
try {
int length = inputSocket.readInt();
int tag = inputSocket.readInt();
byte[] data = new byte[length-4];
inputSocket.readFully(data);
return new Frame(tag,data);
} finally {
receiveLock.unlock();
}
}
public void close() throws IOException {
inputSocket.close();
outputSocket.close();
socket.close();
}
}
<file_sep>/FM7/Gestor.java
import java.util.*;
import java.util.stream.Collectors;
import java.io.Serializable;
/**
* Escreva a descrição da classe Gestor aqui.
*
* @author (seu nome)
* @version (número de versão ou data)
*/
public class Gestor implements Serializable{
Map<String,Equipa> equipas = new HashMap<String,Equipa>();
Map<String,Jogador> jogadores = new HashMap<String,Jogador>();
List<Jogo> jogos = new ArrayList<Jogo>();
public Gestor(){}
public Gestor(Map<String,Equipa> equipas,Map<String,Jogador> jogadores,List<Jogo> jogos){
this.equipas = equipas.entrySet().stream().map(c -> c.getValue().clone()).collect(Collectors.toMap(x->x.getNome(),x->x));
this.jogadores = jogadores.entrySet().stream().map(c -> c.getValue().clone()).collect(Collectors.toMap(x->x.getNome(),x->x));
this.jogos = jogos.stream().map(c -> c.clone()).collect(Collectors.toList());
}
public Gestor(Gestor g){
this.equipas = g.getEquipas();
this.jogadores = g.getJogadores();
this.jogos = g.getJogos();
}
public Map<String,Equipa> getEquipas(){
return this.equipas.entrySet().stream().map(c -> c.getValue().clone()).collect(Collectors.toMap(x->x.getNome(),x->x));
}
public Map<String,Jogador> getJogadores(){
return this.jogadores.entrySet().stream().map(c -> c.getValue().clone()).collect(Collectors.toMap(x->x.getNome(),x->x));
}
public List<Jogo> getJogos(){
return this.jogos.stream().map(c -> c.clone()).collect(Collectors.toList());
}
public void addJogador(String equipa,String jogador) throws NoTeamJogadorException{
Jogador j = this.jogadores.get(jogador);
Equipa eq = this.equipas.get(equipa);
if (j == null) throw new NoTeamJogadorException ("Jogador " + jogador);
if (eq == null) throw new NoTeamJogadorException ("Equipa " + equipa);
eq.addJogador(j);
this.equipas.get("").removeJogador(j);
}
public void removeJogador (String equipa,String jogador) throws NoTeamJogadorException{
Jogador j = this.jogadores.get(jogador);
Equipa eq = this.equipas.get(equipa);
if (j == null) throw new NoTeamJogadorException ("Jogador " + jogador);
if (eq == null) throw new NoTeamJogadorException ("Equipa " + equipa);
eq.removeJogador(j);
this.equipas.get("").addJogador(j);
}
public void addEquipa(Equipa equipa){
this.equipas.put(equipa.getNome(),equipa.clone());
}
public Gestor clone(){
return new Gestor (this.equipas,this.jogadores,this.jogos);
}
public void addJogador(Jogador j){
Jogador k = j.clone();
this.jogadores.put(k.getNome(),k);
this.equipas.get("").addJogador(k);
}
public Equipa getTeam(String equipa)throws NoTeamJogadorException{
Equipa eq = this.equipas.get(equipa);
if (eq == null) throw new NoTeamJogadorException();
return eq;
}
public Jogador getJogador(String jogador)throws NoTeamJogadorException{
Jogador j = this.jogadores.get(jogador);
if (j == null) throw new NoTeamJogadorException();
return j;
}
public boolean containsNumJogador(String equipa,Integer numJogador) throws NoTeamJogadorException{
Equipa eq = this.equipas.get(equipa);
if (eq == null) throw new NoTeamJogadorException ("Equipa " + equipa);
return eq.containsNumJogador(numJogador);
}
// rever a funcao abaixo do comentario
public List<Integer> getNumjogadoresequipa(String equipa) throws NoTeamJogadorException{
Equipa e=this.equipas.get(equipa);
if (e == null) throw new NoTeamJogadorException ("Equipa " + equipa);
return e.getNumjogadoresList();
}
public String getHist(String nome) throws NoTeamJogadorException{
Jogador j = this.jogadores.get(nome);
if (j == null) throw new NoTeamJogadorException(nome);
StringBuilder b = new StringBuilder();
j.getHist().stream().forEach(x -> b.append(x + " | "));
return b.toString();
}
public void addJogo(Jogo j){
this.jogos.add(j.clone());
}
}<file_sep>/PI21/teste69.c
/*
typedef struct variable {
char* name;
int* value;
}*VARIABLE;
typedef struct guarda{
TABLE* arrayTable;
char* arrayVar;
}*GUARDA;*/
/*
GUARDA* create_guarda(TABLE arrayTable, char* arrayVar) {
GUARDA* gu = (GUARDA*) malloc (sizeof(GUARDA));
gu->arrayTable = (TABLE*) malloc (strlen(arrayTable) + 1);
gu->arrayVar = (char*) malloc (strlen(arrayVar) + 1);
strcpy(gu->arrayTable, arrayTable);
strcpy(gu->arrayVar, arrayVar);
return gu;}
TABLE* getGuardaTable (GUARDA gua){
return strdup(gua->arrayTable);}
char* getGuardaVar (GUARDA gua){
return strdup(var->value);}
*/
int interpreter (SGR sgr){
char line[1024];
char sn[1024];
char func[1024];
char Arg[1024];
char agr1[64],arg2[64],arg3[64];
int equalSign;
enum OPERATOR{LT, EQ, GT};//+ = -
hash = g_hash_table_new_full (g_str_hash, g_str_equal,(GDestroyNotify) free,(GDestroyNotify) freeTable);//?
TABLE* arrayTable;
char* Var;//guardar variaveis x,y,...
printf("Command:\n");
fgets(line,1024,stdin);
//sscanf(stdin,%c %c %s,var,igual,line2);
while (!strcmp(line,"exit")){
//TABLE* old_arrayTable;
//char* old_var;
//while(line[strlen(line)-1]==";"){
if (strrchr(line,"=")!=NULL) equalSign=1;
if(equalSign){
strtok(line,"=");
strtok(line," ");
strtok(line,"(");
strtok(line,",");
strtok(line,")");
Var = strdup(strtok(line,";"));
char* func = "";
while(func[0]) func = strtok(NULL,";");
if(stricmp(func,"businesses_started_by_letter")){
strtok(NULL,";");
arg2 = strtok(NULL,";");// "A"
arrayTable = business_started_by_letter(sgr,arg2);
}
else if(stricmp(func,"business_info")){
strtok(NULL,",");
arg2=strtok(NULL,";");
arrayTable = business_info(sgr,arg2);
}
else if(stricmp(func,"businesses_reviewed")){
strtok(NULL,",");
arg2=strtok(NULL,";");
arrayTable = businesses_reviewed(sgr,arg2);
}
else if(stricmp(func,"business_with_stars_and_city")){//business_with_stars_and_city(SGR sgr, float stars, char* city);
strtok(NULL,";");
arg2=strtok(NULL,";");//stars
arg3=strtok(NULL,";"); //city
arrayTable = business_with_stars_and_city(sgr,arg2,arg3);
}
else if(strimp(func,"top_businesses_by_city")){
strtok(NULL,",");
arg2=strtok(NULL,";");
arrayTable = top_businesses_by_city(sgr,arg2);
}
else if(stricmp(func,"international_users")){
arrayTable = international_users(sgr);
}
else if(strimp(func,"top_businesses_with_category")){
strtok(NULL,";");
arg2=strtok(NULL,";");//stars
arg3=strtok(NULL,";");
arrayTable = top_businesses_with_category(sgr,arg2,agr3)
}
else if(stricmp(func,"reviews_with_word")){//reviews_with_word(SGR sgr,char* word)
strtok(NULL,",");
arg2=strtok(NULL,")");
arrayTable = reviews_with_word(sgr,arg2);
}
else if(stricmp(func,"fromCSV")){
//arg1=strtok(arg,",");//
//arg2=strtok(NULL,")");
strtok(NULL,",");
arg1=strtok(NULL,")");
FILE *file = fopen(arg1, "r");
if(file!=NULL){
fgets(sn,64,file);
sn = strtok(sn,";");
arrayTable = fromCSV()
fclose(file);
}
}
//projeção colunas
else if(stricmp(func,"proj")){ // y = proj(x,cols)
arg1=strtok(arg,","); //x
arg2=strtok(NULL,")");//cols
}
else{ //indexação
// y = z[1][2]
/*arg1=line[4];//z
arg2=line[7];//1
arg3=line[10];//2*/
strtok(NULL," ");
strtok(NULL,"=");
arg1=strtok(NULL,"[");
strtok(NULL,"]");
arg2=strtok(NULL,"[");
strtok(NULL,"]")
TABLE temp = g_hash_table_lookup(hash,arg1);//table para a key z
if(g_hash_table_lookup(hash,arg1)!=NULL){
TABLE temp1 = memalloc(1,1);
insereTable(temp1,0,0,tableValue(arg2,arg3));
arrayTable = temp1;
/*if(g_hash_table_lookup(hash,Var)!=NULL){
g_hash_table_remove(hash,Var);
//g_free (arrayTable);
//g_free (var);
}
g_hash_table_insert (hash, g_strdup (Var), g_strdup ());*/
}
}
insereHash(strdup(var),arrayTable);
//pos++;
}
else{// !equalSign
//show(x)
if((stricmp(line[0],"s")==0) && (stricmp(line[1],"h")==0) && (stricmp(line[2],"o")==0) && (stricmp(line[3],"w")==0)){
for(int j=5;j<strlen(line);j++){ //show(x);\0
sn[j-5]=line[j];}
sn = strtok(sn,")"); // x
drawTable (g_hash_table_lookup(hash,sn));
}
//toCSV(x,;,filepath)
else if((stricmp(line[0],"t")==0) && (stricmp(line[1],"o")==0) && (stricmp(line[2],"c")==0) && (stricmp(line[3],"s")==0) && (stricmp(line[4],"v")==0)){
for(int j=6;j<strlen(line);j++){ //show(x);
sn[j-6]=line[j];}
sn =strdup (strtok(sn,",")); //x
arg1 =strdup ( strtok(NULL,","));//delim
arg2 =strdup ( strtok(NULL,")")); //filepath
FILE *file = fopen(arg2, "w");
if(file!=NULL){
if(g_hash_table_lookup(hash,sn)!=NULL){
toCSV (g_hash_table_lookup(hash,sn),)
fclose(file);
}
}
free(sn);
free(arg1);
free(arg2);
}
}
}
g_hash_table_destroy(hash);
return 0;
}
void insereHash (char va, TABLE t){
if(g_hash_table_lookup(hash,va)!=NULL){
g_hash_table_remove(hash,Va);
}
g_hash_table_insert (hash,Va,t);
}
<file_sep>/FM7/View.java
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import java.util.Map;
import java.util.stream.*;
import java.util.HashMap;
import java.time.LocalDate;
/**
* Escreva a descrição da classe View aqui.
*
* @author (seu nome)
* @version (número de versão ou data)
*/
public class View implements vFM{
private cFM controller;
public View(cFM controller){
this.controller = controller;
}
public void addController(cFM controller){
this.controller = controller;
}
public void run(){
System.out.println("-----------------WC to FM-------------------------");
String comand,is,nome,eq;
int numero=0;
boolean stay = true;
Scanner in = new Scanner(System.in);
while(stay){
System.out.println("Comandos disponiveis:\n-simular um jogo(jogo);\n-criar jogador(criajogador);\n-criar equipa(criaequipa);\n-historial de equipas de um jogaodr(joHist);\n-adicionar a equipa um jogador(adiconaje);\n-trocar de equipa um jogador(trocaje);\n-remover de uma equipa um jogador(removeje);\n-listar todos os jogadores(jogadores);\n-listar todas as equipas e seus jogadores(equipas);\n-listar o nome todas as equipas(equipasnome);\n-listar todos os jogos(todosjogos);\n-sair(exit);");
comand=in.nextLine();
switch(comand){
case "criajogador":
JogadorType tipo;
System.out.println("Escreva o nome do jogador \n");
nome = in.nextLine();
System.out.println("Escreva o numero do jogador \n");
is = in.nextLine();
numero = Integer.parseInt(is);
System.out.println("Digite o numero correspondente a posiçao do jogador,1 para avançado,2 para medio,3 para lateral,4 para defesa e 5 para guarda redes\n");
String type = in.nextLine();
int i = Integer.parseInt(type);
switch(i){
case 1 :
tipo = JogadorType.AVANCADO;
break;
case 2 :
tipo = JogadorType.MEDIO;
break;
case 3 :
tipo = JogadorType.LATERAL;
break;
case 4 :
tipo = JogadorType.DEFESA;
break;
case 5 :
tipo = JogadorType.GUARDAREDES;
break;
default :
System.out.println("numero mal escolhido ,por default o jogador criado e um avançado\n");
tipo = JogadorType.AVANCADO;
i=1;
break;
}
System.out.println("Escreva ajuda para saber os atributos a introduzir do jogador ou random para serem gerados aleatoriamente \n");
String g = in.nextLine();
List<Integer> val = new ArrayList<>();
int at;
Random rand = new Random();
if(g.equals("ajuda")){
if(i==1){System.out.println("Escreva os atributos separados por virgula do avançado que sao velocidade,resistencia,destreza,impulsao,jogo de cabeça,remate,passe \n");}
if(i==2){System.out.println("Escreva os atributos separados por virgula do medio que sao velocidade,resistencia,destreza,impulsao,jogo de cabeça,remate,passe,recuperaçao \n");}
if(i==3){System.out.println("Escreva os atributos separados por virgula do lateral que sao velocidade,resistencia,destreza,impulsao,jogo de cabeça,remate,passe,cruzamento \n");}
if(i==4){System.out.println("Escreva os atributos separados por virgula do defesa que sao velocidade,resistencia,destreza,impulsao,jogo de cabeça,remate,passe \n");}
if(i==5){System.out.println("Escreva os atributos separados por virgula do guardaredes que sao velocidade,resistencia,destreza,impulsao,jogo de cabeça,remate,passe,elasticidade \n");}
String atributos = in.nextLine();
String[] l = atributos.split(",");
if((i==1)||(i==4)&&(l.length==7)){
for(int j=0;j<7;j++)val.add(Integer.parseInt(l[i]));
}
else if((l.length==8)){
for(int j=0;j<8;j++)val.add(Integer.parseInt(l[i]));
}
else{
System.out.println("O comando foi mal introduzido os atributos foram gerados aleatoriamente");
if((i==1)||(i==4)){
for(int j=0;j<7;j++)val.add(rand.nextInt(61)+40);
}
else{
for(int j=0;j<8;j++)val.add(rand.nextInt(61)+40);
}
}
}
else{
if(!(g.equals("random"))){System.out.println("O comando foi mal introduzido os atributos foram gerados aleatoriamente");}
if((i==1)||(i==4)){
for(int j=0;j<7;j++)val.add(rand.nextInt(61)+40);
}
else{
for(int j=0;j<8;j++)val.add(rand.nextInt(61)+40);
}
System.out.println("Os valores dos atributos sao " + val.toString());
}
controller.newJogador(tipo,nome,numero,val);
break;
case "criaequipa":
System.out.println("Escreva o nome da equipa\n");
nome = in.nextLine();
controller.addEquipa(nome);
break;
case "adicionaje":
System.out.println("Escreva o nome da equipa\n");
is = in.nextLine();
System.out.println("Escreva o nome do jogador\n");
nome = in.nextLine();
try{
controller.addJogador(is,nome);
}
catch(NoTeamJogadorException e){
System.out.println("Houve um problema devido "+ e.getMessage() +" nao existir");
}
break;
case "trocaje":
System.out.println("Escreva o nome da equipa onde esta o jogador\n");
is = in.nextLine();
System.out.println("Escreva o nome da equipa de destino\n");
eq = in.nextLine();
System.out.println("Escreva o nome do jogador\n");
nome = in.nextLine();
try{
controller.removeJogador(is,nome);
}
catch(NoTeamJogadorException e){
System.out.println("Houve um problema devido "+ e.getMessage() +" nao existir");
}
try{
controller.addJogador(eq,nome);
}
catch(NoTeamJogadorException e){
System.out.println("Houve um problema devido "+ e.getMessage() +" nao existir");
}
break;
case "removeje":
System.out.println("Escreva o nome da equipa\n");
is = in.nextLine();
System.out.println("Escreva o nome do jogador\n");
nome = in.nextLine();
try{
controller.removeJogador(is,nome);
}
catch(NoTeamJogadorException e){
System.out.println("Houve um problema devido "+ e.getMessage() +" nao existir");
}
break;
case "joHist":
System.out.println("Escreva o nome do jogador\n");
nome = in.nextLine();
String hist;
try{
hist = controller.getHist(nome);
}catch(NoTeamJogadorException e){
hist = ("Jogador " + e.getMessage() + " nao Exite");
}
System.out.println(hist+"\n");
break;
case "jogo":
Equipa eq1= null;
Equipa eq2= null;
System.out.println("Escreva o nome da primeira equipa\n");
eq = null;
while(eq1 == null){
eq = in.nextLine();
try {
eq1 = controller.getEquipa(eq);
}catch(NoTeamJogadorException e){
System.out.println("Equipa " + eq + "nao existe");
}
}
System.out.println(eq1.toString());
boolean t = false;
List<Integer> l1i= new ArrayList<>();
while(!t){
System.out.println(eq + ": Escreva a lista dos numeros dos jogadores separando-os por uma virgula\n");
String lista1 = in.nextLine();
String[] l1 = lista1.split(",");
for(int k=0;k<l1.length && k < 11;k++){
l1i.add(Integer.parseInt(l1[k]));
}
for(int k=0;k<l1i.size();k++){
try{
t = controller.containsNumJogador(eq,l1i.get(k));
}catch(NoTeamJogadorException e){
System.out.println(e);
}
if(!t){System.out.println("Um dos numeros escolhidos nao pertence a equipa");break;}
}
}
List<Integer> eq1j=new ArrayList<>();
try{eq1j= controller.getNumjogadoresequipa(eq);}
catch(NoTeamJogadorException e){System.out.println(e);}
Map<Integer,Integer> t1= new HashMap<>();
Map<Integer,Integer> s1= new HashMap<>();
for(int y=0;y<eq1j.size();y++){
if(l1i.contains(eq1j.get(y))){t1.put(eq1j.get(y),eq1j.get(y));}
else{s1.put(eq1j.get(y),eq1j.get(y));}
}
System.out.println("Escreva o nome da segunda equipa\n");
is = null;
while(is == null){
is = in.nextLine();
try {
eq2 = controller.getEquipa(is);
}catch(NoTeamJogadorException e){
System.out.println("Equipa " + is + "nao existe");
}
}
System.out.println(eq2.toString());
t = false;
List<Integer> l2i= new ArrayList<>();
while(!t){
System.out.println(is + ": Escreva a lista dos numeros dos jogadores separando-os por uma virgula\n");
String lista2 = in.nextLine();
String[] l2 = lista2.split(",");
for(int k=0;k < l2.length && k < 11;k++){
l2i.add(Integer.parseInt(l2[k]));
}
for(int k=0;k<l2i.size();k++){
try{
t=controller.containsNumJogador(eq2.getNome(),l2i.get(k));
}catch(NoTeamJogadorException e){
System.out.println(e);
}
if(!t){System.out.println("Um dos numeros escolhidos nao pertence a equipa");break;}
}
}
List<Integer> eq2j=new ArrayList<>();
try{eq2j= controller.getNumjogadoresequipa(is);}
catch(NoTeamJogadorException e){System.out.println(e);}
Map<Integer,Integer> t2= new HashMap<>();
Map<Integer,Integer> s2= new HashMap<>();
for(int y=0;y<eq2j.size();y++){
if(l2i.contains(eq2j.get(y))){t2.put(eq2j.get(y),eq2j.get(y));}
else{s2.put(eq2j.get(y),eq2j.get(y));}
}
int score[] = new int[2];score[0]=0;score[1]=0;
LocalDate date = LocalDate.now();
Jogo j = new Jogo (eq1,eq2,t1,s1,t2,s2,score,0,date);
j.finalGame();
controller.addJogo(j);
System.out.println(j.toString());
break;
case "jogadores":
List<String> jogadores = controller.stringJogadores();
jogadores.stream().forEach(x -> System.out.println(x.toString()));
break;
case "equipas":
List<String> teams = controller.stringTeams();
teams.stream().forEach(x -> System.out.println(x.toString()));
break;
case "equipasnome":
List<String> teamsnome = controller.stringTeamsnome();
teamsnome.stream().forEach(x -> System.out.println(x.toString()));
System.out.println("\n");
break;
case "todosjogos":
List<String> jogos = controller.stringJogos();
jogos.stream().forEach(x -> System.out.println(x.toString()));
break;
case "exit":
stay = false;
break;
default:
System.out.println("Comando mal escrito");
break;
}
}
}
}
| 9a3003ee2bafc6a43e30ce5119ca86375365fee3 | [
"Markdown",
"Makefile",
"Java",
"Text",
"C"
] | 82 | C | ruipedrolousada/ruipedrolousada | 6b414ca6f4ec2171d718b69ea70ad82289d1b317 | 5b522d5d3304d6fb9b32f285925667f3d483d4fb |
refs/heads/master | <repo_name>skyj129/iask-web<file_sep>/iask-web/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>IASK</groupId>
<name>IASK</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<org.springframework-version>3.2.3.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
<pinyin-version>2.5.0</pinyin-version>
<tomcat.version>6.0.33</tomcat.version>
<solr.version>4.6.0</solr.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- <dependency>
<groupId>org.directwebremoting</groupId>
<artifactId>dwr</artifactId>
<version>3.0.M1</version>
</dependency> -->
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- pinyin -->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba.druid</groupId>
<artifactId>druid-wrapper</artifactId>
<version>0.2.9</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.34</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>jasper</artifactId>
<scope>provided</scope>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>coyote</artifactId>
<scope>provided</scope>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>dbcp</artifactId>
<scope>provided</scope>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-core</artifactId>
<version>${solr.version}</version>
<exclusions>
<exclusion>
<artifactId>hadoop-annotations</artifactId>
<groupId>org.apache.hadoop</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wltea</groupId>
<artifactId>IKAnalyzer</artifactId>
<version>2012FF_u1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.kohsuke.stapler</groupId>
<artifactId>json-lib</artifactId>
<version>2.1-rev6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<skipTests>true</skipTests>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
<!-- <compilerArgument>-Xlint:all</compilerArgument> -->
<compilerArguments>
<extdirs>src\main\webapp\WEB-INF\lib</extdirs>
</compilerArguments>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<!-- 更改maven默认的打包目录:将class文件和lib目录打包放到指定的目录 -->
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<archiveClasses>false</archiveClasses>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.15.v20140411</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<executions>
<execution>
<id>my-jar</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>api</classifier>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<artifactId>iask</artifactId>
<repositories>
<repository>
<id> maven-china</id>
<name> Maven China Mirror</name>
<url>http://maven.oschina.net/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project><file_sep>/iask-web/src/main/java/com/downjoy/iask/domain/User.java
package com.downjoy.iask.domain;
import com.downjoy.iask.domain.basedomain.BaseDoMain;
/**
* User 用户实体类
*
* @author <EMAIL>
* @since 1.0
*
*/
public class User extends BaseDoMain {
/**
* 用户ID
*/
private Long id;
/**
* 用户名
*/
private String userName;
/**
* 用户昵称
*/
private String userNickName;
/**
* 用户等级
*/
private String userLevel;
/**
* 用户回答问题采纳率
*/
private String userAnswerAdoptionRate;
/**
* 用户头像
*/
private String userAvatar;
/**
* 用户的地址
*/
private String userAdrress;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserNickName() {
return userNickName;
}
public void setUserNickName(String userNickName) {
this.userNickName = userNickName;
}
public String getUserLevel() {
return userLevel;
}
public void setUserLevel(String userLevel) {
this.userLevel = userLevel;
}
public String getUserAnswerAdoptionRate() {
return userAnswerAdoptionRate;
}
public void setUserAnswerAdoptionRate(String userAnswerAdoptionRate) {
this.userAnswerAdoptionRate = userAnswerAdoptionRate;
}
public String getUserAvatar() {
return userAvatar;
}
public void setUserAvatar(String userAvatar) {
this.userAvatar = userAvatar;
}
public String getUserAdrress() {
return userAdrress;
}
public void setUserAdrress(String userAdrress) {
this.userAdrress = userAdrress;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", userNickName="
+ userNickName + ", userLevel=" + userLevel
+ ", userAnswerAdoptionRate=" + userAnswerAdoptionRate
+ ", userAvatar=" + userAvatar + ", userAdrress=" + userAdrress
+ "]";
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/dao/impl/KeyWordsDaoImpl.java
package com.downjoy.iask.dao.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.downjoy.iask.dao.KeyWordsDao;
import com.downjoy.iask.dao.basedao.BaseMybatisDao;
import com.downjoy.iask.domain.DynamicSqlParameter;
import com.downjoy.iask.domain.KeyWords;
import com.downjoy.iask.exception.BaseException;
import com.downjoy.iask.util.PaginationResult;
/**
* @Description: 关键词Dao实现类
* @author <EMAIL>
* @date 2014年9月2日 上午9:48:17
* @version 1.0
*/
@Repository(value = "keyWordsDao")
public class KeyWordsDaoImpl extends BaseMybatisDao<KeyWords, Long> implements
KeyWordsDao
{
@Override
public int update(KeyWords entity) throws BaseException
{
return super.update(entity);
}
@Override
public List<KeyWords> select() throws BaseException
{
super.setSqlmapNamespace(KeyWordsDao.class.getName());
return super.select();
}
/**
* <p>
* Description:
* </p>
*
* @param param
* @return
* @throws BaseException
*/
@Override
public List<KeyWords> selectFk(DynamicSqlParameter param)
throws BaseException
{
// TODO Auto-generated method stub
return null;
}
/**
* <p>
* Description:
* </p>
*
* @param param
* @return
* @throws BaseException
*/
@Override
public PaginationResult<KeyWords> selectFkPagination(
DynamicSqlParameter param) throws BaseException
{
// TODO Auto-generated method stub
return null;
}
}
<file_sep>/iask-web/src/main/webapp/2013/specialtopic/script/showcode.js
//网游详情页安卓苹果多个版本
$(function(){
$(".androiddown span").click(
function(){
$(".androiddown .androidShow").toggle();
$(this).parent().css('z-index',1);
$(this).parent().siblings().css('z-index',0);
}
);
$(".iosdown span").click(
function(){
$(".iosdown .androidShow").toggle();
$(this).parent().css('z-index',1);
$(this).parent().siblings().css('z-index',0);
}
);
})
//==========================================================zhuhh begin
$(function() {
$(document).click(function(e) {
var $androidShow = $('.androiddown .androidShow');
var $iosShow = $('.iosdown .androidShow');
if(!$(e.target).is('.androiddown span')) {
if($androidShow.is(':visible')) {
$androidShow.hide();
}
}
if(!$(e.target).is('.iosdown span')) {
if($iosShow.is(':visible')) {
$iosShow.hide();
}
}
});
})
//==========================================================zhuhh end
<file_sep>/iask-web/src/main/java/com/downjoy/iask/controller/UserController.java
package com.downjoy.iask.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.downjoy.iask.domain.Inform;
import com.downjoy.iask.domain.ResponseSimiResult;
import com.downjoy.iask.domain.User;
import com.downjoy.iask.exception.BaseException;
import com.downjoy.iask.model.RestResult;
import com.downjoy.iask.service.InformService;
import com.downjoy.iask.service.QuestionService;
import com.downjoy.iask.service.RequestSolrSearchService;
import com.downjoy.iask.service.UserService;
import com.downjoy.iask.util.Constants;
import com.downjoy.iask.util.CookieUtils;
/**
* @Description: 用户控制器类
* @author <EMAIL>
* @date 2014年9月2日 上午9:00:58
* @version 1.0
*/
@Controller
public class UserController {
@Autowired
@Qualifier("userService")
private UserService userService;
@Autowired
private QuestionService questionService;
@Autowired
private InformService informService;
@Autowired
@Qualifier("requestSolrSearchService")
private RequestSolrSearchService requestSolrSearchService;
/**
* 举报信息接口
*
* @param userId
* 用户ID
* @param questionId
* 问题ID
* @param informUrl
* 举报地址
* @param informContent
* 举报内容
* @param informType
* 举报类型
* @param request
* 请求参数
* @param response
* 返回参数
*/
@RequestMapping(value = "uploadInformInfo", method = RequestMethod.GET)
public void uploadInformInfo(Long userId, Long questionId,
String informUrl, String informContent, String informType,
HttpServletRequest request, HttpServletResponse response) {
try {
Inform inform = informService.get(questionId);
if (inform == null) {
inform = new Inform();
inform.setQuestionId(questionId);
inform.setUserId(userId);
inform.setInformUrl(informUrl);
inform.setInformContent(informContent);
inform.setInformType(informType);
inform.setInformNum(1);
informService.insert(inform);
} else {
// inform.setQuestionId(questionId);
// inform.setUserId(userId);
// inform.setInformUrl(informUrl);
// inform.setInformContent(informContent);
// inform.setInformType(informType);
inform.setInformNum(inform.getInformNum() + 1);
informService.update(inform);
}
} catch (BaseException e) {
e.printStackTrace();
}
}
@RequestMapping(value = "index", method = RequestMethod.GET)
public String index(HttpServletRequest request, HttpServletResponse response) {
// Cookie[] cookies = request.getCookies();
// for (Cookie c : cookies) {
// String name = c.getName();
// if (name.contains("DJ_MEMBER_INFO")) {
// String value = c.getValue();
// String userName = value.substring(0, value.indexOf("%"));
// String userId = value.substring(value.indexOf("%") + 1,
// value.lastIndexOf("%"));
// break;
// }
// }
// System.out.println(userService);
//
// System.out.println(userTrackerMemcachedClient);
// // 尝试登录
// UserTrackerHelper.tryLogin(userTrackerMemcachedClient, request,
// response, true);
// // 通过request获取用户信息
// UserTracker userTracker = UserTrackerHelper
// .getUserTrackerFromReqAttr(request);
//
// System.out.println(userTracker);
// //检测用户是否登录,true登录成功,false登录失败
// Boolean flag = UserTrackerHelper.isLogined(userTracker);
// //获取用户信息
// Long mid = userTracker.getMemberId();
// //获取消息数
// UserTrackerHelper.getNewMessageCnt(request,userTracker);
// 获取用户信息
// Long mid = userTracker.getMemberId();
// 获取消息数
// UserTrackerHelper.getNewMessageCnt(request, userTracker);
// System.out.println(""+userTracker.getMemberId());
// System.out.println("flag=" + flag);
// System.out.println("mid=" + mid);
// System.out.println("index");
return "index";
}
/**
* 登录接口
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "login", method = RequestMethod.GET)
public @ResponseBody RestResult login(HttpServletRequest request,
HttpServletResponse response) {
User user = CookieUtils.getUserInfo(request);
try {
if (user != null) {
if (userService.getUserCount(user.getId()) == 0) {
userService.insert(user);
} else {
userService.update(user);
}
}
} catch (NumberFormatException e1) {
e1.printStackTrace();
} catch (BaseException e1) {
e1.printStackTrace();
}
RestResult restResult = new RestResult();
restResult.setData(user);
if (user != null) {
request.getSession().setAttribute(Constants.CURRENT_USER_ID,
String.valueOf(user.getId()));
request.getSession().setAttribute(Constants.CURRENT_SESSION_USER,
user);
}
return restResult;
}
/**
* 注册接口
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "register", method = RequestMethod.GET)
public @ResponseBody RestResult register(HttpServletRequest request,
HttpServletResponse response) {
User user = CookieUtils.getUserInfo(request);
try {
if (user != null) {
if (userService.getUserCount(user.getId()) == 0) {
userService.insert(user);
} else {
userService.update(user);
}
}
} catch (NumberFormatException e1) {
e1.printStackTrace();
} catch (BaseException e1) {
e1.printStackTrace();
}
RestResult restResult = new RestResult();
restResult.setData(user);
return restResult;
}
/**
* @description 获取用户问答信息
* @param request
* 请求参数
* @return
*/
@RequestMapping(value = "showUserInfo", method = RequestMethod.GET)
public @ResponseBody List<ResponseSimiResult> showUserInfo(String userId,
HttpServletRequest request, HttpServletResponse response) {
List<ResponseSimiResult> rList = new ArrayList<ResponseSimiResult>();
if (userId != null) {
rList.addAll(requestSolrSearchService.getUserQuestions(userId));
}
return rList;
}
/**
* 回答数排行
*
* @param beginData
* 开始时间
* @param endDate
* 结束时间
* @param rows
* 返回多少个
* @param request
* @param response
* @return
*/
public @ResponseBody RestResult getAnswerNumberList(String beginDate,
String endDate, int rows, HttpServletRequest request,
HttpServletResponse response) {
RestResult restResult = new RestResult();
if (beginDate != null && endDate != null) {
try {
restResult.setData(userService.getAdoptionList(beginDate,
endDate));
} catch (BaseException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 采纳率排行
*
* @param beginData
* 开始时间
* @param endDate
* 结束时间
* @param rows
* 返回多少个
* @param request
* @param response
* @return
*/
public @ResponseBody RestResult getAdoptionList(String beginDate,
String endDate, int rows, HttpServletRequest request,
HttpServletResponse response) {
RestResult restResult = new RestResult();
if (beginDate != null && endDate != null) {
try {
restResult.setData(userService.getAdoptionList(beginDate,
endDate));
} catch (BaseException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 获取用户信息
*
* @param userId
* @param request
* @param response
* @return
*/
public @ResponseBody RestResult getUserInfo(String userId,
HttpServletRequest request, HttpServletResponse response) {
RestResult restResult = new RestResult();
if (userId != null) {
try {
restResult.setData(userService.getUserInfo(Integer
.valueOf(userId)));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (BaseException e) {
e.printStackTrace();
}
}
return restResult;
}
}<file_sep>/iask-web/src/main/webapp/js/ajaxfileupload.js
// 表示当前高亮的节点
var highlightindex = -1;
$(document).ready(function() {
var search = $("#search-buttonss");
var inputText = $("#inputss");
var title = $("#title");
var content = $("#content");
// search.click(function() {
//
// // var searchKey = inputText.val();
// //
// // this.load("search.do",{
// // q:searchKey,
// // title:title.attr("checked"),
// // content:content.attr("checked")
// // });
//
// var qsData = {
// 'q' : inputText.val(),
// 'title' : title.attr("checked"),
// 'content' : content.attr("checked")
// };
//
// $.get("search.do", qsData,function(result){
//
// },"text");
// async : false,
// url : "search.do",
// type : "GET",
// contentType : "application/x-www-form-urlencoded; charset=utf-8",
// data : qsData,
// timeout : 10000,
// beforeSend : function() {
// // jsonp 方式此方法不被触发.原因可能是dataType如果指定为jsonp的话,就已经不是ajax事件了
// },
// success : function(json) {//
// 客户端jquery预先定义好的callback函数,成功获取跨域服务器上的json数据后,会动态执行这个callback函数
// if (json.actionErrors.length != 0) {
// alert(json.actionErrors);
// }
// // genDynamicContent(qsData, type, json);
// },
// complete : function(XMLHttpRequest, textStatus) {
// // $.unblockUI({
// // fadeOut : 10
// // });
// },
// error : function(xhr) {
// // jsonp 方式此方法不被触发.原因可能是dataType如果指定为jsonp的话,就已经不是ajax事件了
// // 请求出错处理
// alert("请求出错(请检查相关度网络状况.)");
// }
// });
});
//});
// var wordInput = $("#word");
// var wordInputOffset = wordInput.offset();
// // // 自动补全框最开始应该隐藏起来
// // $("#auto").hide().css("border", "1px black
// // solid").css("position",
// // "absolute").css("top",
// // wordInputOffset.top + wordInput.height() + 5 + "px").css(
// // "left", wordInputOffset.left + "px").width(
// // wordInput.width() + 2);
//
// // 给文本框添加键盘按下并弹起的事件
// wordInput.keyup(function(event) {
// // 处理文本框中的键盘事件
// var myEvent = event || window.event;
// var keyCode = myEvent.keyCode;
// // 如果输入的是字母,应该将文本框中最新的信息发送给服务器
// // 如果输入的是退格键或删除键,也应该将文本框中的最新信息发送给服务器
// if (keyCode >= 65 && keyCode <= 90 || keyCode == 8
// || keyCode == 46) {
// // 1.首先获取文本框中的内容
// var wordText = $("#word").val();
// var autoNode = $("#auto");
// if (wordText != "") {
//
// $.ajax({
//
// type : "POST",
// url : "AutoComplete.do",
// data : "word=" + wordText,
// dataType : 'text',
// success : function(data) {
//
// // alert(data);
//
// var jqueryObj = $(data);
// // 找到所有的word节点
// var wordNodes = jqueryObj.find("word");
// // 遍历所有的word节点,取出单词内容,然后将单词内容添加到弹出框中
// // 需要清空原来的内容
// autoNode.html("");
// wordNodes.each(function() {
// // 获取单词内容
// var wordNode = $(this);
// // 新建div节点,将单词内容加入到新建的节点中
// // 将新建的节点加入到弹出框的节点中
// $("<div>").html(wordNode.text()).appendTo(
// autoNode);
// });
// // 如果服务器段有数据返回,则显示弹出框
// if (wordNodes.length > 0) {
// autoNode.show();
// } else {
// autoNode.hide();
// // 弹出框隐藏的同时,高亮节点索引值也制成-1
// highlightindex = -1;
// }
//
// // alert('系统提示', '恭喜,密码修改成功!<br>您的新密码为:'
// // );
// // $newpass.val('');
// // $rePass.val('');
// // close();
// // closePwd();
// }
// });
// // 2.将文本框中的内容发送给服务器段
// $.post("AutoComplete.do", {
// word : wordText
// }, function(data) {
// // 将dom对象data转换成JQuery的对象
//
// alert(data);
//
// var jqueryObj = $(data);
// // 找到所有的word节点
// var wordNodes = jqueryObj.find("word");
// // 遍历所有的word节点,取出单词内容,然后将单词内容添加到弹出框中
// // 需要清空原来的内容
// autoNode.html("");
// wordNodes.each(function() {
// // 获取单词内容
// var wordNode = $(this);
// // 新建div节点,将单词内容加入到新建的节点中
// // 将新建的节点加入到弹出框的节点中
// $("<div>").html(wordNode.text()).appendTo(
// autoNode);
// });
// // 如果服务器段有数据返回,则显示弹出框
// if (wordNodes.length > 0) {
// autoNode.show();
// } else {
// autoNode.hide();
// // 弹出框隐藏的同时,高亮节点索引值也制成-1
// highlightindex = -1;
// }
// }, "xml");
// } else {
// autoNode.hide();
// highlightindex = -1;
// }
// } else if (keyCode == 38 || keyCode == 40) {
// // 如果输入的是向上38向下40按键
// if (keyCode == 38) {
// // 向上
// var autoNodes = $("#auto").children("div")
// if (highlightindex != -1) {
// // 如果原来存在高亮节点,则将背景色改称白色
// autoNodes.eq(highlightindex).css(
// "background-color", "white");
// highlightindex--;
// } else {
// highlightindex = autoNodes.length - 1;
// }
// if (highlightindex == -1) {
// // 如果修改索引值以后index变成-1,则将索引值指向最后一个元素
// highlightindex = autoNodes.length - 1;
// }
// // 让现在高亮的内容变成红色
// autoNodes.eq(highlightindex).css("background-color",
// "red");
// }
// if (keyCode == 40) {
// // 向下
// var autoNodes = $("#auto").children("div")
// if (highlightindex != -1) {
// // 如果原来存在高亮节点,则将背景色改称白色
// autoNodes.eq(highlightindex).css(
// "background-color", "white");
// }
// highlightindex++;
// if (highlightindex == autoNodes.length) {
// // 如果修改索引值以后index变成-1,则将索引值指向最后一个元素
// highlightindex = 0;
// }
// // 让现在高亮的内容变成红色
// autoNodes.eq(highlightindex).css("background-color",
// "red");
// }
// } else if (keyCode == 13) {
// // 如果输入的是回车
//
// // 下拉框有高亮内容
// if (highlightindex != -1) {
// // 取出高亮节点的文本内容
// var comText = $("#auto").hide().children("div").eq(
// highlightindex).text();
// highlightindex = -1;
// // 文本框中的内容变成高亮节点的内容
// $("#word").val(comText);
// } else {
// // 下拉框没有高亮内容
// alert("文本框中的[" + $("#word").val() + "]被提交了");
// }
// }
// });
//
// // 给按钮添加事件,表示文本框中的数据被提交
// $("input[type='button']").click(function() {
// alert("文本框中的[" + $("#word").val() + "]被提交了");
// });
// })
// // JavaScript Document
// jQuery
// .extend({
//
// createUploadIframe : function(id, uri) {
// // create frame
// var frameId = 'jUploadFrame' + id;
//
// if (window.ActiveXObject) {
// var io = document.createElement('<iframe id="' + frameId
// + '" name="' + frameId + '" />');
// if (typeof uri == 'boolean') {
// io.src = 'javascript:false';
// } else if (typeof uri == 'string') {
// io.src = uri;
// }
// } else {
// var io = document.createElement('iframe');
// io.id = frameId;
// io.name = frameId;
// }
// io.style.position = 'absolute';
// io.style.top = '-1000px';
// io.style.left = '-1000px';
//
// document.body.appendChild(io);
//
// return io;
// },
// createUploadForm : function(id, fileElementId) {
// // create form
// var formId = 'jUploadForm' + id;
// var fileId = 'jUploadFile' + id;
// var form = jQuery('<form action="" method="POST" name="'
// + formId + '" id="' + formId
// + '" enctype="multipart/form-data"></form>');
// var oldElement = jQuery('#' + fileElementId);
// var newElement = jQuery(oldElement).clone();
// jQuery(oldElement).attr('id', fileId);
// jQuery(oldElement).before(newElement);
// jQuery(oldElement).appendTo(form);
// // set attributes
// jQuery(form).css('position', 'absolute');
// jQuery(form).css('top', '-1200px');
// jQuery(form).css('left', '-1200px');
// jQuery(form).appendTo('body');
// return form;
// },
//
// ajaxFileUpload : function(s) {
// // TODO introduce global settings, allowing the client to modify
// // them for all requests, not only timeout
// s = jQuery.extend({}, jQuery.ajaxSettings, s);
// var id = s.fileElementId;
// var form = jQuery.createUploadForm(id, s.fileElementId);
// var io = jQuery.createUploadIframe(id, s.secureuri);
// var frameId = 'jUploadFrame' + id;
// var formId = 'jUploadForm' + id;
//
// if (s.global && !jQuery.active++) {
// // Watch for a new set of requests
// jQuery.event.trigger("ajaxStart");
// }
// var requestDone = false;
// // Create the request object
// var xml = {};
// if (s.global) {
// jQuery.event.trigger("ajaxSend", [ xml, s ]);
// }
//
// var uploadCallback = function(isTimeout) {
// // Wait for a response to come back
// var io = document.getElementById(frameId);
// try {
// if (io.contentWindow) {
// xml.responseText = io.contentWindow.document.body ?
// io.contentWindow.document.body.innerHTML
// : null;
// xml.responseXML = io.contentWindow.document.XMLDocument ?
// io.contentWindow.document.XMLDocument
// : io.contentWindow.document;
//
// } else if (io.contentDocument) {
// xml.responseText = io.contentDocument.document.body ?
// io.contentDocument.document.body.innerHTML
// : null;
// xml.responseXML = io.contentDocument.document.XMLDocument ?
// io.contentDocument.document.XMLDocument
// : io.contentDocument.document;
// }
// } catch (e) {
// jQuery.handleError(s, xml, null, e);
// }
// if (xml || isTimeout == "timeout") {
// requestDone = true;
// var status;
// try {
// status = isTimeout != "timeout" ? "success"
// : "error";
// // Make sure that the request was successful or
// // notmodified
// if (status != "error") {
// // process the data (runs the xml through
// // httpData regardless of callback)
// var data = jQuery.uploadHttpData(xml,
// s.dataType);
// if (s.success) {
// // ifa local callback was specified, fire it
// // and pass it the data
// s.success(data, status);
// }
// ;
// if (s.global) {
// // Fire the global callback
// jQuery.event.trigger("ajaxSuccess", [ xml,
// s ]);
// }
// ;
// } else {
// jQuery.handleError(s, xml, status);
// }
//
// } catch (e) {
// status = "error";
// jQuery.handleError(s, xml, status, e);
// }
// ;
// if (s.global) {
// // The request was completed
// jQuery.event.trigger("ajaxComplete", [ xml, s ]);
// }
// ;
//
// // Handle the global AJAX counter
// if (s.global && !--jQuery.active) {
// jQuery.event.trigger("ajaxStop");
// }
// ;
// if (s.complete) {
// s.complete(xml, status);
// }
// ;
//
// jQuery(io).unbind();
//
// setTimeout(function() {
// try {
// jQuery(io).remove();
// jQuery(form).remove();
//
// } catch (e) {
// jQuery.handleError(s, xml, null, e);
// }
//
// }, 100);
//
// xml = null;
//
// }
// ;
// }
// // Timeout checker
// if (s.timeout > 0) {
// setTimeout(function() {
//
// if (!requestDone) {
// // Check to see ifthe request is still happening
// uploadCallback("timeout");
// }
//
// }, s.timeout);
// }
// try {
// var form = jQuery('#' + formId);
// jQuery(form).attr('action', s.url);
// jQuery(form).attr('method', 'POST');
// jQuery(form).attr('target', frameId);
// if (form.encoding) {
// form.encoding = 'multipart/form-data';
// } else {
// form.enctype = 'multipart/form-data';
// }
// jQuery(form).submit();
//
// } catch (e) {
// jQuery.handleError(s, xml, null, e);
// }
// if (window.attachEvent) {
// document.getElementById(frameId).attachEvent('onload',
// uploadCallback);
// } else {
// document.getElementById(frameId).addEventListener('load',
// uploadCallback, false);
// }
// return {
// abort : function() {
// }
// };
//
// },
//
// uploadHttpData : function(r, type) {
// var data = !type;
// data = type == "xml" || data ? r.responseXML : r.responseText;
// // ifthe type is "script", eval it in global context
// if (type == "script") {
// jQuery.globalEval(data);
// }
//
// // Get the JavaScript object, ifJSON is used.
// if (type == "json") {
// eval("data = " + data);
// }
//
// // evaluate scripts within html
// if (type == "html") {
// jQuery("<div>").html(data).evalScripts();
// }
//
// return data;
// }
// });
<file_sep>/iask-web/src/main/java/com/downjoy/iask/dao/GameQuestionDao.java
package com.downjoy.iask.dao;
import com.downjoy.iask.dao.basedao.BaseDao;
import com.downjoy.iask.domain.Questions;
/**
* @Description: 游戏问题Dao
* @author <EMAIL>
* @date 2014年9月9日 下午3:42:10
* @version 1.0
*/
public interface GameQuestionDao extends BaseDao<Questions, Long>
{
/**
* @Description: 根据游戏ID获取是否存在问答的记录数
* @param gameId 游戏ID
* @return int 返回类型
* @throws
*/
public int searchQuestionByGameId(String gameId);
}
<file_sep>/iask-web/src/main/webapp/2013/specialtopic/script/imgleftright.js
// JavaScript Document
$(function(){
var page=1;
var i=1;
$('span.next').click(function(){
var $parent=$(this).parents('.gamespicSubcon');
var $vShow=$parent.find('.gamespicSubconS');
var $vContent=$parent.find('.gamespicSubconA');
var $vWidth=$vContent.width();
var len=$vShow.find('li').length;
var pageCount=Math.ceil(len/i);
if(!$vShow.is(":animated")){
if(page==pageCount){
$vShow.animate({left:'0px'},500);
page=1;
}else{
$vShow.animate({left:'-='+$vWidth},500);
page++;
}
}
});
$('span.prev').click(function(){
var $parent=$(this).parents('.gamespicSubcon');
var $vShow=$parent.find('.gamespicSubconS');
var $vContent=$parent.find('.gamespicSubconA');
var $vWidth=$vContent.width();
var len=$vShow.find('li').length;
var pageCount=Math.ceil(len/i);
if(!$vShow.is(':animated')){
if(page==1){
$vShow.animate({left:'-='+($vWidth*(pageCount-1))},500);
page=pageCount;
}else{
$vShow.animate({left:'+='+$vWidth},500);
page--;
}
}
});
})<file_sep>/iask-web/src/main/java/com/downjoy/iask/exception/ParameterException.java
package com.downjoy.iask.exception;
/**
* BaseDaoException 参数异常类
* @author <EMAIL>
* @since 0.1
*/
@SuppressWarnings("serial")
public class ParameterException extends RuntimeException {
/**
* 参数异常类构造方法
*/
public ParameterException() {
super();
}
/**
* 参数异常类构造方法
* @param arg0
* @param arg1
*/
public ParameterException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
/**
* 参数异常类构造方法
* @param arg0
*/
public ParameterException(String arg0) {
super(arg0);
}
/**
* 参数异常类构造方法
* @param arg0
*/
public ParameterException(Throwable arg0) {
super(arg0);
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/util/IAskConfig.java
package com.downjoy.iask.util;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* @author lxw
* 解析iask.properties
*/
public class IAskConfig {
private static IAskConfig instance;
private ResourceBundle resourceBundle = ResourceBundle.getBundle("iask");
private IAskConfig() {
}
public static IAskConfig getInstance() {
if (instance == null) {
synchronized (IAskConfig.class) {
if (instance == null) {
instance = new IAskConfig();
}
}
}
return instance;
}
public String getString(String key) {
try {
return resourceBundle.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
public String getIaskSolrUrl(){
return getString("iask.solr.url");
}
public static void main(String[] args) {
System.out.println(IAskConfig.getInstance().getString("iask.solr.url"));
System.out.println(IAskConfig.getInstance().getIaskSolrUrl());
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/dao/impl/GameDetailInfoDaoImpl.java
package com.downjoy.iask.dao.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.downjoy.iask.dao.GameDetailInfoDao;
import com.downjoy.iask.dao.basedao.BaseMybatisDao;
import com.downjoy.iask.domain.DynamicSqlParameter;
import com.downjoy.iask.domain.GameDetailInfo;
import com.downjoy.iask.exception.BaseException;
import com.downjoy.iask.util.PaginationResult;
/**
* GameDetailInfoDaoImpl 游戏详情Dao实现类
*
* @author <EMAIL>
* @version 1.0
* @param GameDetailInfo
* 游戏详情实体类
* @param <PK>
* 主键类
*/
@Repository
public class GameDetailInfoDaoImpl extends BaseMybatisDao<GameDetailInfo, Long>
implements GameDetailInfoDao {
@Override
public int insert(GameDetailInfo entity) throws BaseException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int update(GameDetailInfo entity) throws BaseException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int update(DynamicSqlParameter param) throws BaseException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int delete(Long primaryKey) throws BaseException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int delete(DynamicSqlParameter param) throws BaseException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int truncate() throws BaseException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int count() throws BaseException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int count(Object param) throws BaseException {
// TODO Auto-generated method stub
return 0;
}
@Override
public GameDetailInfo get(Long primaryKey) throws BaseException {
// TODO Auto-generated method stub
return null;
}
@Override
public List<GameDetailInfo> select() throws BaseException {
super.setSqlmapNamespace(GameDetailInfoDao.class.getName());
return super.select();
}
@Override
public List<GameDetailInfo> select(DynamicSqlParameter param)
throws BaseException {
return super.select(param);
}
@Override
public PaginationResult<GameDetailInfo> selectPagination(
DynamicSqlParameter param) throws BaseException {
// TODO Auto-generated method stub
return null;
}
@Override
public List<GameDetailInfo> selectFk(DynamicSqlParameter param)
throws BaseException {
// TODO Auto-generated method stub
return null;
}
@Override
public PaginationResult<GameDetailInfo> selectFkPagination(
DynamicSqlParameter param) throws BaseException {
// TODO Auto-generated method stub
return null;
}
@Override
public void batchInsert(List<GameDetailInfo> list) throws BaseException {
// TODO Auto-generated method stub
}
@Override
public void batchUpdate(List<GameDetailInfo> list) throws BaseException {
// TODO Auto-generated method stub
}
@Override
public void batchDelete(List<Long> list) throws BaseException {
// TODO Auto-generated method stub
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/dao/impl/AnswerDaoImpl.java
package com.downjoy.iask.dao.impl;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import com.downjoy.iask.dao.AnswerDao;
import com.downjoy.iask.dao.basedao.BaseMybatisDao;
import com.downjoy.iask.domain.Answers;
import com.downjoy.iask.domain.DynamicSqlParameter;
import com.downjoy.iask.exception.BaseException;
import com.downjoy.iask.util.PaginationResult;
/**
* @Description: TODO(这里用一句话描述这个类的作用)
* @author <EMAIL>
* @date 2014年10月8日 下午5:51:20
* @version 1.0
*/
@Repository("answerDao")
public class AnswerDaoImpl extends BaseMybatisDao<Answers, Long> implements
AnswerDao
{
private static final Logger logger = Logger.getLogger(AnswerDaoImpl.class);
/**
* <p>
* Description:
* </p>
*
* @param param
* @return
* @throws BaseException
*/
@Override
public List<Answers> selectFk(DynamicSqlParameter param)
throws BaseException
{
// TODO Auto-generated method stub
return null;
}
/**
* <p>
* Description:
* </p>
*
* @param param
* @return
* @throws BaseException
*/
@Override
public PaginationResult<Answers> selectFkPagination(
DynamicSqlParameter param) throws BaseException
{
// TODO Auto-generated method stub
return null;
}
/**
* <p>
* Description:
* </p>
*
* @param answers
* @return
*/
@Override
public int insertAnswer(Answers answers)
{
super.setSqlmapNamespace(AnswerDao.class.getName());
try
{
return super.insert(answers);
}
catch(BaseException e)
{
e.printStackTrace();
return 0;
}
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/service/impl/DownjoySolrServiceImpl.java
package com.downjoy.iask.service.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.SortClause;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.downjoy.iask.dao.KeyWordRelationDao;
import com.downjoy.iask.domain.KeyWordRelation;
import com.downjoy.iask.domain.KeyWords;
import com.downjoy.iask.exception.BaseException;
import com.downjoy.iask.model.Page;
import com.downjoy.iask.model.Question;
import com.downjoy.iask.service.DownjoySolrService;
import com.downjoy.iask.util.IKAnalzyerUtil;
import com.downjoy.iask.util.SolrContents;
import com.downjoy.iask.util.SolrUtils;
/**
*
* @Description: 中文分词业务逻辑类
* @author <EMAIL>
* @date 2014年8月21日 下午2:53:54
* @version 1.0
*/
@Service("downjoySolrService")
public class DownjoySolrServiceImpl implements DownjoySolrService
{
@Autowired
@Qualifier("keyWordRelationDao")
private KeyWordRelationDao keyWordRelationDao;
public KeyWordRelationDao getKeyWordRelationDao()
{
return keyWordRelationDao;
}
public void setKeyWordRelationDao(KeyWordRelationDao keyWordRelationDao)
{
this.keyWordRelationDao = keyWordRelationDao;
}
/**
* <p>
* Description:查询标题列表
* </p>
*
* @param q
* 查询的参数
* @param gameId
* 游戏ID
* @param pageNum
* 当前页面
* @param pageSize
* 每一页的大小
* @param sort
* 排序字段
* @return
*/
@Override
public Page<Question> queryQuestion(String q, String gameId,
Integer pageNum, Integer pageSize, String sort)
{
boolean isBak = false;
// 需要返回的数据
List<Question> questions = new ArrayList<Question>();
long num = 0;
SolrDocumentList docs = null;
try
{
QueryResponse queryResponse = null;
if (StringUtils.isNotEmpty(q) && q.contains(" "))
{
queryResponse = tokenizeSearch(q, gameId, pageNum, pageSize,
sort);
}
else
{
// 优先使用短语查询
queryResponse = phraseSearch(q, gameId, pageNum, pageSize, sort);
if (queryResponse != null)
{
docs = queryResponse.getResults();
num = docs.getNumFound();
}
// 没有结果,就使用指定专业关键词查询
if (num < 1)
{
List<KeyWords> list = IKAnalzyerUtil.getTerm(q);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < list.size(); i++)
{
sb.append(list.get(i).getKeyWords());
if (i < list.size() - 1)
{
sb.append(" OR ");
}
}
queryResponse = tokenizeSearch(sb.toString(), gameId,
pageNum, pageSize, sort);
}
else
{
isBak = true;// 告诉组装model的方法,这个地方返回的title应该去q_title_bak字段
}
}
if (queryResponse != null)
{
docs = queryResponse.getResults();
num = docs.getNumFound();
}
// 如果上面两种查询都没有结果,那么直接采用,solr的分词查询
if (num < 1)
{
queryResponse = tokenizeSearch(StringUtils.remove(q, " "),
gameId, pageNum, pageSize, sort);
}
if (queryResponse != null)
{
docs = queryResponse.getResults();
num = docs.getNumFound();
Map<String, Map<String, List<String>>> highlightingMap = queryResponse
.getHighlighting();
questions = SolrUtils.docToQuestions(docs, highlightingMap,
true, isBak);
}
}
catch(Exception e)
{
e.printStackTrace();
}
if (!isBak)
{
List<KeyWords> list = IKAnalzyerUtil.getTerm(q);
if (list.size() > 1)
{
KeyWordRelation keyWordRelation = new KeyWordRelation();
keyWordRelation.setSource(list.get(0).getKeyWords());
keyWordRelation.setTarget(list.get(1).getKeyWords());
keyWordRelation.setFirstId(list.get(0).getId());
keyWordRelation.setSencondId(list.get(1).getId());
try
{
keyWordRelationDao.insert(keyWordRelation);
}
catch(BaseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Page<Question> page = new Page<Question>();
page.setList(questions);
page.setTotalItemNumber(num);
page.setPageNum(pageNum);
page.setPageSize(pageSize);
return page;
}
@Override
public Question queryQuestionById(String id)
{
Question question = null;
if (StringUtils.isEmpty(id))
{
return null;
}
try
{
// 设置solr查询
SolrQuery solrQuery = new SolrQuery();
solrQuery.setStart(0);
solrQuery.setRows(1);
StringBuffer queryBuffer = new StringBuffer();
queryBuffer.append(SolrContents.Index_Fields.Q_ID);
queryBuffer.append(SolrContents.DOUBLE_MARKS);
queryBuffer.append(id);
solrQuery.setParam("q", queryBuffer.toString());
// 执行solr查询
HttpSolrServer httpSolrServer = SolrUtils.getSolrServer();
QueryResponse queryResponse = httpSolrServer.query(solrQuery);
if (queryResponse != null)
{
SolrDocumentList docs = queryResponse.getResults();
question = SolrUtils.docToQuestion(docs);
}
}
catch(Exception e)
{
e.printStackTrace();
}
return question;
}
/**
* 精确搜索,也就是完全匹配,不分词
*/
private QueryResponse phraseSearch(String q, String gameId,
Integer pageNum, Integer pageSize, String sort)
{
if (StringUtils.isEmpty(q))
{
return null;
}
if (pageNum <= 0 || pageSize <= 0)
{
return null;
}
try
{
// 设置solr查询
SolrQuery solrQuery = new SolrQuery();
// solrQuery.setSort(SortClause.asc(sort));
solrQuery.setSort(SortClause.desc(sort)); // yangjian modify
solrQuery.setStart((pageNum - 1) * pageSize);
solrQuery.setRows(pageSize);
// 高亮
// solrQuery.setHighlight(true);
// solrQuery.addHighlightField(SolrContents.Index_Fields.Q_TITLE);
// //yangjian modify
// solrQuery.addHighlightField(SolrContents.Index_Fields.Q_TITLE_BAK);
// solrQuery.setHighlightSimplePre("<font color=\"red\">")
// .setHighlightSimplePost("</font>");// 渲染标签
StringBuffer queryBuffer = new StringBuffer();
queryBuffer.append(SolrContents.Index_Fields.Q_TITLE_BAK);
queryBuffer.append(SolrContents.DOUBLE_MARKS);
queryBuffer.append(q);
if (StringUtils.isNotEmpty(gameId))
{
queryBuffer.append(" AND ");
queryBuffer.append(SolrContents.Index_Fields.Q_GAMEID);
queryBuffer.append(SolrContents.DOUBLE_MARKS);
// queryBuffer.append(q);
queryBuffer.append(gameId);
}
// solrQuery.setQuery(queryBuffer.toString());
solrQuery.setParam("q", queryBuffer.toString());
// 执行solr查询
HttpSolrServer httpSolrServer = SolrUtils.getSolrServer();
QueryResponse queryResponse = httpSolrServer.query(solrQuery);
return queryResponse;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* 拆词搜索,支持AND和OR两种查询
*/
private QueryResponse tokenizeSearch(String q, String gameId,
Integer pageNum, Integer pageSize, String sort)
{
if (StringUtils.isEmpty(q))
{
return null;
}
try
{
// 设置solr查询
SolrQuery solrQuery = new SolrQuery();
// solrQuery.setSort(SortClause.asc(sort));
solrQuery.setSort(SortClause.desc(sort));
solrQuery.setStart((pageNum - 1) * pageSize);
solrQuery.setRows(pageSize);
// 高亮
// solrQuery.setHighlight(true);
// solrQuery.addHighlightField(SolrContents.Index_Fields.Q_TITLE);
// yangjian modify
// solrQuery.addHighlightField(SolrContents.Index_Fields.Q_TITLE_BAK);
// solrQuery.setHighlightSimplePre("<font color=\"red\">")
// .setHighlightSimplePost("</font>");// 渲染标签
StringBuffer queryBuffer = new StringBuffer();
queryBuffer.append(SolrContents.Index_Fields.Q_TITLE);
queryBuffer.append(SolrContents.DOUBLE_MARKS);
queryBuffer.append(q);
if (StringUtils.isNotEmpty(gameId))
{
queryBuffer.append(" AND ");
queryBuffer.append(SolrContents.Index_Fields.Q_GAMEID);
queryBuffer.append(SolrContents.DOUBLE_MARKS);
queryBuffer.append(gameId);
}
// solrQuery.setQuery(queryBuffer.toString());
solrQuery.setParam("q", queryBuffer.toString());
// 执行solr查询
HttpSolrServer httpSolrServer = SolrUtils.getSolrServer();
QueryResponse queryResponse = httpSolrServer.query(solrQuery);
return queryResponse;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/service/impl/KeyWordsRateServiceImpl.java
package com.downjoy.iask.service.impl;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.downjoy.iask.dao.KeyWordsDao;
import com.downjoy.iask.dao.basedao.BaseDao;
import com.downjoy.iask.domain.DynamicSqlParameter;
import com.downjoy.iask.domain.KeyWords;
import com.downjoy.iask.exception.BaseException;
import com.downjoy.iask.service.KeyWordsRateService;
import com.downjoy.iask.service.baseservice.BaseAbstractService;
import com.downjoy.iask.util.PaginationResult;
/**
* @Description: 关键词业务逻辑类
* @author <EMAIL>
* @date 2014年9月2日 上午9:42:13
* @version 1.0
*/
@Service("keyWordsRateService")
public class KeyWordsRateServiceImpl extends
BaseAbstractService<KeyWords, Long> implements KeyWordsRateService
{
Logger logger = Logger.getLogger(KeyWordsRateServiceImpl.class);
@Autowired
@Qualifier("keyWordsDao")
private KeyWordsDao keyWordsDao;
@Override
public int insert(KeyWords entity) throws BaseException
{
return 0;
}
@Override
public int update(KeyWords entity) throws BaseException
{
// TODO Auto-generated method stub
return 0;
}
@Override
public int update(DynamicSqlParameter param) throws BaseException
{
// TODO Auto-generated method stub
return 0;
}
@Override
public int delete(Long primaryKey) throws BaseException
{
// TODO Auto-generated method stub
return 0;
}
@Override
public int delete(DynamicSqlParameter param) throws BaseException
{
// TODO Auto-generated method stub
return 0;
}
@Override
public int truncate() throws BaseException
{
// TODO Auto-generated method stub
return 0;
}
@Override
public int count() throws BaseException
{
// TODO Auto-generated method stub
return 0;
}
@Override
public int count(Object param) throws BaseException
{
// TODO Auto-generated method stub
return 0;
}
@Override
public KeyWords get(Long primaryKey) throws BaseException
{
// TODO Auto-generated method stub
return null;
}
@Override
public List<KeyWords> select() throws BaseException
{
// TODO Auto-generated method stub
return keyWordsDao.select();
}
@Override
public List<KeyWords> select(DynamicSqlParameter param)
throws BaseException
{
// TODO Auto-generated method stub
return null;
}
@Override
public PaginationResult<KeyWords> selectPagination(DynamicSqlParameter param)
throws BaseException
{
// TODO Auto-generated method stub
return null;
}
@Override
public List<KeyWords> selectFk(DynamicSqlParameter param)
throws BaseException
{
// TODO Auto-generated method stub
return null;
}
@Override
public PaginationResult<KeyWords> selectFkPagination(
DynamicSqlParameter param) throws BaseException
{
// TODO Auto-generated method stub
return null;
}
@Override
public void batchInsert(List<KeyWords> list) throws BaseException
{
// TODO Auto-generated method stub
}
@Override
public void batchUpdate(List<KeyWords> list) throws BaseException
{
// TODO Auto-generated method stub
}
@Override
public void batchDelete(List<Long> list) throws BaseException
{
// TODO Auto-generated method stub
}
public BaseDao<KeyWords, Long> getDao()
{
return keyWordsDao;
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/service/InformService.java
package com.downjoy.iask.service;
import com.downjoy.iask.domain.Inform;
import com.downjoy.iask.service.baseservice.BaseService;
public interface InformService extends BaseService<Inform, Long> {
public void uploadInformInfo(Inform inform);
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/service/LogService.java
package com.downjoy.iask.service;
import com.downjoy.iask.domain.Log;
import com.downjoy.iask.service.baseservice.BaseService;
/**
* 日志
*/
public interface LogService extends BaseService<Log, Long> {
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/service/GameQuestionService.java
package com.downjoy.iask.service;
import com.downjoy.iask.domain.Questions;
import com.downjoy.iask.service.baseservice.BaseService;
/**
* @Description: TODO(这里用一句话描述这个类的作用)
* @author <EMAIL>
* @date 2014年9月9日 下午4:03:13
* @version 1.0
*/
public interface GameQuestionService extends BaseService<Questions, Long>
{
public int searchQuestionByGameId(String gameId);
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/dao/impl/LogCatDaoImpl.java
package com.downjoy.iask.dao.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.downjoy.iask.dao.LogCatDao;
import com.downjoy.iask.dao.basedao.BaseMybatisDao;
import com.downjoy.iask.domain.DynamicSqlParameter;
import com.downjoy.iask.domain.Log;
import com.downjoy.iask.exception.BaseException;
import com.downjoy.iask.util.PaginationResult;
@Repository("logCatDao")
public class LogCatDaoImpl extends BaseMybatisDao<Log, Long> implements
LogCatDao {
@Override
public void setSqlmapNamespace(String sqlmapNamespace) {
super.setSqlmapNamespace(LogCatDao.class.getName());
}
@Override
public int insert(Log entity) throws BaseException {
super.setSqlmapNamespace(LogCatDao.class.getName());
return super.insert(entity);
}
@Override
public List<Log> selectFk(DynamicSqlParameter param) throws BaseException {
return null;
}
@Override
public PaginationResult<Log> selectFkPagination(DynamicSqlParameter param)
throws BaseException {
return null;
}
}
<file_sep>/iask-web/src/main/webapp/2013/specialtopic/script/fuceng.js
// JavaScript Document
$(function(){
$(window).scroll(function(){
var scrollTop = $(document).scrollTop();
var headheight = 396;
if(scrollTop >= headheight){
$(".contentR").addClass("fixed");
}else{
$(".contentR").removeClass("fixed");
}
})
})<file_sep>/iask-web/src/main/java/com/downjoy/iask/domain/RequestUser.java
package com.downjoy.iask.domain;
public class RequestUser {
private String beginData;
private String endDate;
public String getBeginData() {
return beginData;
}
public void setBeginData(String beginData) {
this.beginData = beginData;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/dao/InformDao.java
package com.downjoy.iask.dao;
import com.downjoy.iask.dao.basedao.BaseDao;
import com.downjoy.iask.domain.Inform;
/**
* 举报信息接口
*/
public interface InformDao extends BaseDao<Inform, Long> {
public void uploadInformInfo(Inform inform);
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/domain/ResponseAnswerResult.java
/**
* Project Name:iask
* File Name:AnswerResult.java
* Package Name:com.downjoy.iask.domain
* Date:2014年8月8日上午8:49:40
* Copyright (c) 2014, <EMAIL> All Rights Reserved.
*
* @author <EMAIL>
* @since JDK 1.6
*/
package com.downjoy.iask.domain;
import java.util.ArrayList;
import java.util.List;
/**
* ClassName: AnswerResult <br/>
* decription: 返回的答案实体类. <br/>
* reason: TODO ADD REASON(可选). <br/>
* date: 2014年8月8日 上午8:49:40 <br/>
*
*/
public class ResponseAnswerResult {
/**
* 问题pv
*/
private String qpv;
/**
* 问题ID
*/
private String qid;
/**
* 问题标题
*/
private String qtitle;
/**
* 问题描述
*/
private String qdescription;
/**
* 问题的发布者
*/
private String qusername;
/**
* 问题的创建时间
*/
private String qcreatetime;
/**
* 回答的内容
*/
private List<ResponseAnswer> acontext = new ArrayList<ResponseAnswer>();
public String getQpv() {
return qpv;
}
public void setQpv(String qpv) {
this.qpv = qpv;
}
public String getQid() {
return qid;
}
public void setQid(String qid) {
this.qid = qid;
}
public String getQtitle() {
return qtitle;
}
public void setQtitle(String qtitle) {
this.qtitle = qtitle;
}
public String getQdescription() {
return qdescription;
}
public void setQdescription(String qdescription) {
this.qdescription = qdescription;
}
public String getQusername() {
return qusername;
}
public void setQusername(String qusername) {
this.qusername = qusername;
}
public String getQcreatetime() {
return qcreatetime;
}
public void setQcreatetime(String qcreatetime) {
this.qcreatetime = qcreatetime;
}
public List<ResponseAnswer> getAcontext() {
return acontext;
}
public void setAcontext(List<ResponseAnswer> acontext) {
this.acontext = acontext;
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/util/IKAnalzyerUtil.java
package com.downjoy.iask.util;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.wltea.analyzer.lucene.IKAnalyzer;
import com.downjoy.iask.domain.KeyWords;
import com.downjoy.ikanalyzer.DictionaryLoader;
public class IKAnalzyerUtil {
static Logger logger = Logger.getLogger(IKAnalzyerUtil.class);
static Analyzer analyzer = new IKAnalyzer(true);
public static List<KeyWords> getTerm(String q) {
List<KeyWords> list = new ArrayList<KeyWords>();
List<KeyWords> words = DictionaryLoader.getSingleton().getWords();
List<String> wordStrs = DictionaryLoader.getSingleton().getWordStrs();
logger.info("words length : " + words.size());
TokenStream ts = null;
try {
logger.info("tokenStream start ");
ts = analyzer.tokenStream("myfield", new StringReader(q));
CharTermAttribute term = (CharTermAttribute) ts
.addAttribute(CharTermAttribute.class);
ts.reset();
String termStr = null;
int index = 0;
while (ts.incrementToken()) {
termStr = term.toString();
if (wordStrs != null && wordStrs.size() > 0
&& wordStrs.contains(termStr)) {
index = wordStrs.indexOf(termStr);
list.add(words.get(index));
}
}
ts.end();
} catch (IOException e) {
e.printStackTrace();
logger.error(e);
} finally {
if (ts != null)
try {
ts.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return list;
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/domain/Inform.java
package com.downjoy.iask.domain;
import com.downjoy.iask.domain.basedomain.BaseDoMain;
/**
* 举报信息实体
*
* @author Administrator
*/
public class Inform extends BaseDoMain {
private long id;
private long questionId;// 问题Id
private long userId; // 用户ID
private String informUrl; // 举报地址
private String informContent;// 举报内容
private String informType; // 举报类型
private int informNum; // 举报数目
public long getQuestionId() {
return questionId;
}
public void setQuestionId(long questionId) {
this.questionId = questionId;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getInformUrl() {
return informUrl;
}
public void setInformUrl(String informUrl) {
this.informUrl = informUrl;
}
public String getInformContent() {
return informContent;
}
public void setInformContent(String informContent) {
this.informContent = informContent;
}
public String getInformType() {
return informType;
}
public void setInformType(String informType) {
this.informType = informType;
}
public int getInformNum() {
return informNum;
}
public void setInformNum(int informNum) {
this.informNum = informNum;
}
@Override
public String toString() {
return "Inform [id=" + id + ", userId=" + userId + ", informUrl="
+ informUrl + ", informContent=" + informContent
+ ", informType=" + informType + ", informNum=" + informNum
+ "]";
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/service/impl/KeyWordRelationServiceImpl.java
package com.downjoy.iask.service.impl;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.downjoy.iask.dao.KeyWordRelationDao;
import com.downjoy.iask.dao.basedao.BaseDao;
import com.downjoy.iask.domain.KeyWordRelation;
import com.downjoy.iask.service.KeyWordRelationService;
import com.downjoy.iask.service.baseservice.BaseAbstractService;
/**
* @author lxw KeyWordRelationService 的实现,
*/
@Service("keyWordRelationService")
public class KeyWordRelationServiceImpl extends
BaseAbstractService<KeyWordRelation, Long> implements
KeyWordRelationService {
@Autowired
private KeyWordRelationDao keyWordRelationDao;
/**
* 获取关键词两项接口一:未指定游戏范围查询
*
* @param game
* @return
*/
public List<KeyWordRelation> getGameKeyWords(String keyWord) {
return keyWordRelationDao.getGameKeyWords(keyWord);
}
/**
* /** 获取关键词两项接口二:指定游戏范围查询
*
* @param game
* @return
*/
public List<KeyWordRelation> getKeyWordKeyWords(String game, String keyWord) {
if (StringUtils.isEmpty(game)) {
return null;
}
List<KeyWordRelation> list = keyWordRelationDao.getKeyWordsByLog(game,
keyWord);
if (list == null || list.size() < 1) {
list = keyWordRelationDao.getKeyWordsByFrequency(game, keyWord);
}
return list;
}
@Override
public BaseDao<KeyWordRelation, Long> getDao() {
return keyWordRelationDao;
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/dao/impl/InformDaoImpl.java
package com.downjoy.iask.dao.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.downjoy.iask.dao.InformDao;
import com.downjoy.iask.dao.basedao.BaseMybatisDao;
import com.downjoy.iask.domain.DynamicSqlParameter;
import com.downjoy.iask.domain.Inform;
import com.downjoy.iask.exception.BaseException;
import com.downjoy.iask.util.PaginationResult;
@Repository("informDao")
public class InformDaoImpl extends BaseMybatisDao<Inform, Long> implements
InformDao {
@Override
public Inform get(Long primaryKey) throws BaseException {
super.setSqlmapNamespace(InformDao.class.getName());
return getSqlSession().selectOne(getSqlmapNamespace() + ".get",
primaryKey);
}
@Override
public int insert(Inform entity) throws BaseException {
super.setSqlmapNamespace(InformDao.class.getName());
return getSqlSession().insert(getSqlmapNamespace() + ".insert", entity);
}
@Override
public int update(Inform entity) throws BaseException {
super.setSqlmapNamespace(InformDao.class.getName());
return getSqlSession().update(getSqlmapNamespace() + ".update", entity);
}
@Override
public List<Inform> selectFk(DynamicSqlParameter param)
throws BaseException {
return null;
}
@Override
public PaginationResult<Inform> selectFkPagination(DynamicSqlParameter param)
throws BaseException {
return null;
}
@Override
public void uploadInformInfo(Inform inform) {
System.out.println("asassa");
super.setSqlmapNamespace(InformDao.class.getName());
System.out.println(getSqlmapNamespace());
getSqlSession().update(getSqlmapNamespace() + ".updateInfo");
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/domain/ResponseKeyWord.java
package com.downjoy.iask.domain;
/**
* @Description: 返回客服端的关键词类
* @author <EMAIL>
* @date 2014年9月3日 上午10:32:35
* @version 1.0
*/
public class ResponseKeyWord
{
/**
* 关键词的Id
*/
private String keyWordId;
/**
* 关键词
*/
private String keyWord;
/**
* 关键词的使用频率
*/
private String frequency;
public String getKeyWordId()
{
return keyWordId;
}
public void setKeyWordId(String keyWordId)
{
this.keyWordId = keyWordId;
}
public String getKeyWord()
{
return keyWord;
}
public void setKeyWord(String keyWord)
{
this.keyWord = keyWord;
}
public String getFrequency()
{
return frequency;
}
public void setFrequency(String frequency)
{
this.frequency = frequency;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result
+ ((frequency == null) ? 0 : frequency.hashCode());
result = prime * result + ((keyWord == null) ? 0 : keyWord.hashCode());
result = prime * result
+ ((keyWordId == null) ? 0 : keyWordId.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ResponseKeyWord other = (ResponseKeyWord) obj;
if (frequency == null)
{
if (other.frequency != null)
return false;
}
else if (!frequency.equals(other.frequency))
return false;
if (keyWord == null)
{
if (other.keyWord != null)
return false;
}
else if (!keyWord.equals(other.keyWord))
return false;
if (keyWordId == null)
{
if (other.keyWordId != null)
return false;
}
else if (!keyWordId.equals(other.keyWordId))
return false;
return true;
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/domain/ResponseGameQuestion.java
package com.downjoy.iask.domain;
/**
* @Description: 游戏问题的Id
* @author <EMAIL>
* @date 2014年9月12日 上午10:16:03
* @version 1.0
*/
public class ResponseGameQuestion
{
/**
* 游戏ID
*/
private String gameId;
/**
* 游戏所拥有的问答数量
*/
private String gameQuestionNum;
public String getGameId()
{
return gameId;
}
public void setGameId(String gameId)
{
this.gameId = gameId;
}
public String getGameQuestionNum()
{
return gameQuestionNum;
}
public void setGameQuestionNum(String gameQuestionNum)
{
this.gameQuestionNum = gameQuestionNum;
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/service/impl/RequestSolrSearchServiceImpl.java
package com.downjoy.iask.service.impl;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.downjoy.iask.domain.ResponseSimiResult;
import com.downjoy.iask.domain.ResponseTitleAnswer;
import com.downjoy.iask.service.RequestSolrSearchService;
import com.downjoy.iask.service.baseservice.SolrSearchService;
/**
* 请求solr服务器进行查询
*
* @author <EMAIL>
*
*/
@Service("requestSolrSearchService")
public class RequestSolrSearchServiceImpl implements RequestSolrSearchService {
Logger logger = Logger.getLogger(RequestSolrSearchServiceImpl.class);
@Autowired
@Qualifier("solrSearchService")
private SolrSearchService solrSearchService;
/**
* @Description: 获取类似问题
* @param questionId
* 问题ID
* @param gameId
* 游戏ID
* @return List<ResponseSimiResult> 返回类似问题
* @throws Exception
*/
@Override
public List<ResponseSimiResult> getSimilarityService(String gameId,
String questionId) throws Exception {
return solrSearchService.getSimilarityService(gameId, questionId);
}
/**
* @Description: 获取类似问题
* @param questionId
* 问题ID
* @param gameId
* 游戏ID
* @param flag
* 问答是否按时间排序
* @return List<ResponseTitleAnswer> 返回类似问题
* @throws Exception
*/
@Override
public List<ResponseTitleAnswer> getSimilarityTitleAnswer(String gameId,
String questionId, String flag) throws Exception {
return solrSearchService.getSimilarityTitleAnswer(gameId, questionId,
flag);
}
@Override
public List<ResponseSimiResult> getUserQuestions(String userId) {
return solrSearchService.getUserQuestions(userId);
}
@Override
public List<ResponseSimiResult> getSimilarityService(String questionId)
throws Exception {
return null;
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/model/Page.java
package com.downjoy.iask.model;
import java.util.List;
/**
* @author lxw
*
* @param <T>
*
* 系统通用分页model
*/
public class Page<T> {
// 当前第几页
private int pageNum;
// 每页显示多少条记录
private int pageSize = 10;
// 共有多少条记录
private long totalItemNumber;
// 当前页的 List
private List<T> list;
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public long getTotalItemNumber() {
return totalItemNumber;
}
public void setTotalItemNumber(long totalItemNumber) {
this.totalItemNumber = totalItemNumber;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
<file_sep>/iask-web/src/main/java/com/downjoy/iask/aop/StatisticsAspect.java
package com.downjoy.iask.aop;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import com.downjoy.iask.domain.Questions;
import com.downjoy.iask.service.QuestionService;
/**
* 页面点击拦截器
*/
@Aspect
public class StatisticsAspect {
private static final int MAX_SIZE = 10;
@Autowired
private QuestionService questionService;
private static Map<String, Integer> map = new ConcurrentHashMap<String, Integer>();
public static final String EDP = "execution(* com.downjoy.iask.service.impl.DownjoySolrServiceImpl.*(..))";
@Around(EDP)
public Object logAround(ProceedingJoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
Object obj = null;
try {
obj = joinPoint.proceed(args);
if (args.length == 1) {
String questionId = (String) args[0];
if (!map.containsKey(questionId)) {
map.put(questionId, 1);
} else {
int num = map.get(questionId);
map.put(questionId, num + 1);
// 当满足条件才进行进行数据插入
if (num > MAX_SIZE) {
Questions questions = new Questions();
questions.setId(Long.valueOf(questionId));
int queryNum = questionService
.queryBrowseNum(questions);
int countNum = map.get(questionId);
int browseNum = (int) (countNum + Long
.valueOf(queryNum));
questions.setQuestionBrowseNum(String
.valueOf(browseNum));
questionService.update(questions);
map.put(questionId, 0);
}
}
}
} catch (Throwable e) {
e.printStackTrace();
}
return obj;
}
}
| 3f77637e222c8ef0fbc800984c618a3981397f7d | [
"JavaScript",
"Java",
"Maven POM"
] | 31 | Maven POM | skyj129/iask-web | f55435015f8c6a47fb5fe5c90de6d3d197900578 | 333791be6c4604e0015a42b1416dee9d3dc92c5c |
refs/heads/master | <file_sep>#!/bin/bash
#Written by <NAME>
green='\e[0;32m'
endcolor='\e[0m'
red='\e[1;31m'
IP=$1
pingresult=$(ping -q -W 2 $IP -c 4 | grep "packets transmitted" | awk '{print $6}' | sed 's/%//')
echo '''
Welcome! This is the DO networking dump utility
'''
echo " Hostname: $IP"
echo " "
if [ "$pingresult" = "0" ]; then
echo -e " Ping test: ${green}Pingable${endcolor}"
else
echo -e " Ping test: ${red}Not Pingable${endcolor}"
fi
echo ' '
curlresult=$(curl -I -s -m 5 $IP | grep "Server:" | sed 's/Server: //')
if [ ! "$curlresult" ]; then
echo -e " Web Server: ${red}None${endcolor}"
else
echo -e " Web Server: ${green}$curlresult${endcolor}"
fi
echo ' '
echo ' Common Ports:'
ftp=$(nc -z -w 2 $IP 21 | awk 'NF>1{print $NF}')
if [ ! "$ftp" ]; then
ftp="${red}Closed${endcolor}"
else
ftp="${green}Open${endcolor}"
fi
echo -e " FTP (21): $ftp"
ssh=$(nc -z -w 2 $IP 22 | awk 'NF>1{print $NF}')
if [ ! "$ssh" ]; then
ssh="${red}Closed${endcolor}"
else
ssh="${green}Open${endcolor}"
fi
echo -e " SSH (22): $ssh"
telnet=$(nc -z -w 2 $IP 23 | awk 'NF>1{print $NF}')
if [ ! "$telnet" ]; then
telnet="${red}Closed${endcolor}"
else
telnet="${green}Open${endcolor}"
fi
echo -e " Telnet (23): $telnet"
smtp=$(nc -z -w 2 $IP 25 | awk 'NF>1{print $NF}')
if [ ! "$smtp" ]; then
smtp="${red}Closed${endcolor}"
else
smtp="${green}Open${endcolor}"
fi
echo -e " SMTP (25): $smtp"
http=$(nc -z -w 2 $IP 80 | awk 'NF>1{print $NF}')
if [ ! "$http" ]; then
http="${red}Closed${endcolor}"
else
http="${green}Open${endcolor}"
fi
echo -e " HTTP (80): $http"
ldap=$(nc -z -w 2 $IP 389 | awk 'NF>1{print $NF}')
if [ ! "$ldap" ]; then
ldap="${red}Closed${endcolor}"
else
ldap="${green}Open${endcolor}"
fi
echo -e " LDAP (389): $ldap"
https=$(nc -z -w 2 $IP 443 | awk 'NF>1{print $NF}')
if [ ! "$https" ]; then
https="${red}Closed${endcolor}"
else
https="${red}Open${endcolor}"
fi
echo -e " HTTPS (443): $https"
httpproxy=$(nc -z -w 2 $IP 8080 | awk 'NF>1{print $NF}')
if [ ! "$httpproxy" ]; then
httpproxy="${red}Closed${endcolor}"
else
httpproxy="${green}Open${endcolor}"
fi
echo -e " HTTP Proxy (8080): $httpproxy"
echo '''
'''
| 860485d6ec3a7fd15c02beb2ee5bd9007113c261 | [
"Shell"
] | 1 | Shell | xdls/bashhost | 43181adbc8f161a4c6c56221ab9537cf84925da2 | 288f90284b056fa7ab8b68b4b0aff7a22388dcc2 |
refs/heads/master | <repo_name>jmcanterafonseca/DevConfFOS<file_sep>/README.md
DevConfFOS
==========
Designing and implementing advanced interactions in Firefox OS
<file_sep>/dragdrop/homescreen/script/homescreen.js
var owd = window.owd || {};
if(!owd.Homescreen) {
(function(doc) {
'use strict';
var apps = [
{name: 'calculator'}, {name: 'clock'}, {name: 'contacts'}, {name: 'dialer'},
{name: 'ereader'}, {name: 'facebook'}, {name: 'gallery'}, {name: 'jajah'},
{name: 'maps'}, {name: 'messages'}, {name: 'penguin'}, {name: 'puzzle'},
{name: 'settings'}, {name: 'torus'}, {name: 'towerjelly'}, {name: 'twitter'},
{name: 'youtube'},
{name: 'calculator'}, {name: 'clock'}, {name: 'contacts'}, {name: 'dialer'},
{name: 'ereader'}, {name: 'facebook'}, {name: 'gallery'}, {name: 'jajah'},
{name: 'maps'}, {name: 'messages'}, {name: 'penguin'}, {name: 'puzzle'},
{name: 'settings'}, {name: 'torus'}, {name: 'towerjelly'}, {name: 'twitter'},
{name: 'youtube'}
];
owd.GridManager.init('.apps', '.counter', apps);
owd.Homescreen = {
install: function(app) {
owd.GridManager.add(app);
},
uninstall: function(app) {
owd.GridManager.remove(app);
},
setMode: function(mode) {
owd.GridManager.setMode(mode);
}
};
})(document);
} | 808019574e15a0302086ca15c0fc6d6bddede4f0 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | jmcanterafonseca/DevConfFOS | 218d765f30262d60675937bef43526caeff94730 | 22c1524b3a94b6cbf801750248fe5cfa948c5180 |
refs/heads/master | <file_sep>const Command = require('./command')
module.exports = class ClearChat extends Command {
static match (message) {
return message.content.startsWith('!clear')
}
static action (message) {
if(hasRole(message.member, "Modérateur" || hasRole(message.member, "Admin"))){
message.channel.fetchMessages(50).then(messages => message.channel.bulkDelete(messages));
message.channel.send('Un petit peu de proprété !')
}else{
return;
}
}
}
function hasRole(meme, role){
if(pluck(meme.roles).includes(role)){
return true;
}else{
return false;
}
}
function pluck(array){
return array.map(function(item) {return item["name"];})
}
<file_sep>const Discord = require('discord.js')
const bot = new Discord.Client()
const Google = require('./commands/google')
const Ping = require('./commands/ping')
const Play = require('./commands/play')
const ClearChat = require('./commands/clearChat')
const Github = require('./commands/github')
const Mod = require('./commands/mod')
const Admin = require('./commands/admin')
const Help = require('./commands/help')
const Invite = require('./commands/invite')
bot.on('ready', function () {
// bot.user.setAvatar('./avatar.png').catch(console.error)
bot.user.setGame('Bonjour Monsieur').catch(console.error)
console.log('ready');
})
bot.on('guildMemberAdd', function (member) {
member.createDM().then(function (channel) {
return channel.send(' :stuck_out_tongue_winking_eye: Bienvenue sur le channel ' + member.displayName)
}).catch(console.error)
})
bot.on('message', function (message) {
let commandUsed =
Ping.parse(message) ||
Play.parse(message) ||
Google.parse(message) ||
ClearChat.parse(message) ||
Github.parse(message) ||
Mod.parse(message) ||
Admin.parse(message) ||
Help.parse(message) ||
Invite.parse(message)
})
bot.login('')
<file_sep>const Command = require('./command')
module.exports = class Help extends Command {
static match (message) {
return message.content.startsWith('!help')
}
static action (message) {
message.delete()
dm(message, "***Commandes disponible***\n\n`!github => Pour suivre l'évolution du développement`\n\n`!google <recherche> => Vous renvoie un lien de recherche`\n\n`!ping => Vous renvoie votre ping`\n\n`!play <lien_streaming> => Permet de lancer une musique dans le channel ***Musique*** (Uniquement disponible pour les Musicien)`")
}
}
function dm(messagedebase, messagesend){
messagedebase.member.createDM().then(function (channel) {
return channel.send(messagesend)
}).catch(console.error)
}
<file_sep>const Command = require('./command')
module.exports = class Invite extends Command {
static match (message) {
return message.content.startsWith('!invite')
}
static action (message) {
message.delete()
message.reply("Invitez dont vos amis :') (https://discord.gg/Vy64Zbr)'")
}
}
<file_sep>const Command = require('./command')
const YoutubeStream = require('ytdl-core')
module.exports = class Play extends Command {
static match (message) {
return message.content.startsWith('!play')
}
static action (message) {
if(hasRole(message.member, "Musicien")){
let voiceChannel = message.guild.channels
.filter(function (channel) { return channel.type === 'voice' })
.first()
let args = message.content.split(' ')
if(!args[1]){
message.reply(':rage: Merci de me donner un lien de musique !')
return;
}
voiceChannel
.join()
.then(function (connection) {
message.delete()
let stream = YoutubeStream(args[1])
stream.on('error', function () {
message.reply(" :interrobang: Je n'ai pas réussi à lire cette vidéo :(")
connection.disconnect()
})
message.delete()
connection
.playStream(stream)
.on('end', function () {
connection.disconnect()
message.channel.send(':musical_note: La music est finis ! :musical_note: ')
})
})
}else{
return;
}
}
}
function hasRole(meme, role){
if(pluck(meme.roles).includes(role)){
return true;
}else{
return false;
}
}
function pluck(array){
return array.map(function(item) {return item["name"];})
}
<file_sep># Discord_bot J.A.R.V.I.S
[](http://forthebadge.com) [](http://forthebadge.com)
This discord bot was made for my own discord, for help people to installing my automatisation home :)
## Before starting
You need to install
- 1) node js: [Download page](https://docs.npmjs.com/getting-started/installing-node)
- 2) run: git clone [Github](https://github.com/zaraakai/discord_bot)
- 3) run: npm install
<file_sep>const Command = require('./command')
module.exports = class Github extends Command {
static match (message) {
return message.content.startsWith('!github')
}
static action (message) {
message.reply("Actuellement sur Github, il y a :\n Le site de jarvis (https://github.com/homejarvis/jarvis-website)\net son api en php (https://github.com/homejarvis/jarvis-api)\nLe code source de Jarvis en lui même n'est pas encore disponible ")
}
}
<file_sep>
Copyright (C) 2017 <NAME>.
<file_sep>const Command = require('./command')
module.exports = class Admin extends Command {
static match (message) {
return message.content.startsWith('!admin')
}
static action (message) {
if(hasRole(message.member, "Admin")){
let args = message.content.split(' ')
if(args[1]){
if(args[1] === "list"){
message.delete()
}
}else{
dm(message, "Utilisation de la commande !admin :\n``")
}
}else{
return;
}
}
}
function hasRole(meme, role){
if(pluck(meme.roles).includes(role)){
return true;
}else{
return false;
}
}
function pluck(array){
return array.map(function(item) {return item["name"];})
}
function dm(messagedebase, messagesend){
messagedebase.member.createDM().then(function (channel) {
return channel.send(messagesend)
}).catch(console.error)
}
| d673878a9193093207910fe753d6a683884e5c18 | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | theopqrs/bot_discord | 47ccddc04fc20cfa55339cfe56a34ed4887a81ef | ae0a5b5675946336f9f20abe649e8ec039d9a85f |
refs/heads/master | <file_sep>
<html>
<head>
<title>
UDWA
</title>
<h2>UNIVERSITY DATABASE WEB APPLICATION</h2>
</head>
<body>
<h2><a href="/php/student.php"> STUDENT</a> </h2>
<h2><a href="/php/prof.php"> PROFESSOR</a></h2>
<?php
//in this class define the structure of the database,
//in other words Data Definition Language of DB university
//reset the variable every time the page refreshes
// $decision = "";
/*Determine which button was selected*
// if(isset($_POST["Professor"]))
// {
// $decision = $_POST['Professor'];
// }
// else if(isset($_POST["Student"]))
// {
// $decision = $_POST['Student'];
// }
//Switch to another php
// if($decision == "Professor")
// {
// header('Location: /php/prof.php');
// }
// else if($decision == "Student")
// {
// header('Location: /php/student.php');
// }
// else GOING BACK DOESNT WORKK FOR ME
?>
<!--create buttons as a menu for the user.-->
<!-- <form action="index.php" method="post">
<input type="submit" name = "Professor" value="Professor">
<input type="submit" name = "Student" value="Student">
</form> -->
</body>
<?php $connect->close(); ?>
</html>
<file_sep>
<!--
Developed by <NAME>, <NAME>, <NAME>
This file will handle the professor interface.
-calls configuration file to create connection.
-->
<!DOCTYPE html>
<html>
<head>
<title>
Professor Interface
</title>
</head>
<body>
<h1>
Welcome Faculty Member!
</h1>
<?php
/*
Given the ssn of a prof, list the titles, classrooms, meeting days and time of classes.
*/
if(isset($_POST["ssn_button"]) && !empty($_POST['prof-input-ssn']))
{
require_once ('../config.php');
$ssn = $_POST['prof-input-ssn'];
$query = "SELECT course_title, classroom, meeting_days, beg_time, end_time
FROM PROFESSOR, SECTION, COURSE
WHERE $ssn = prof_ssn
AND prof_ssn = prof_ssno
AND course_no = course_number";
$response = @mysqli_query($connect, $query);
if($response)
{
echo '<table align = "left"
cellspacing = "5" cellpadding="8">
<tr>
<td align="left"><b>Title</b>
<td align="left"><b>Classroom</b>
<td align="left"><b>Meeting Days</b>
<td align="left"><b>Start Time</b>
<td align="left"><b>End Time</b></tr>';
while($row = mysqli_fetch_array($response))
{
echo '<tr> <td align = "left">' .
$row[course_title] . '</td><td align = "left">'.
$row[classroom] . '</td><td align = "left">'.
$row[meeting_days] . '</td><td align = "left">'.
$row[beg_time] . '</td><td align = "left">'.
$row[end_time] . '</td><td align = "left">' ;
echo '</tr>';
}
echo "</table>";
}
else
{
echo "Couldn't issue database query. <br>";
echo mysqli_error($connect); //issue error
}
mysqli_close($connect);
}
else
{
echo "Please enter your ssn to look at your schedule. <br>";
/**/
}
if(isset($_POST['cs_button']))
{
if(!empty($_POST['prof-input-course']))
{
if(!empty($_POST['prof-input-section']))
{
require_once ('../config.php');
$course = $_POST['prof-input-course'];
$section = $_POST['prof-input-section'];
$query = "SELECT grade, COUNT(*) AS Total
FROM ENROLL
WHERE $section = sec_num
AND $course = crs_num
GROUP BY grade";
$response = @mysqli_query($connect, $query);
if($response)
{
echo '<table align = "left"
cellspacing = "5" cellpadding="8">
<tr>
<td align="left"><b>Letter Grade</b>
<td align="left"><b>Total</b></tr>';
while($row = mysqli_fetch_array($response))
{
echo '<tr> <td align = "left">' .
$row[grade] . '</td><td align = "left">'.
$row[Total] . '</td><td align = "left">';
echo '</tr>';
}
echo "</table>";
}
else
{
echo "Couldn't issue database query.<br>";
echo mysqli_error($connect); //issue error
}
mysqli_close($connect);
}
else
{
echo "Please enter the section number.<br>";
}
}
else
{
echo "Please enter your course number.<br>";
}
}
?>
<form action = "prof.php" method = "POST">
Ssn: <br>
<input type = "text" name = "prof-input-ssn">
<input type = "submit" name = "ssn_button" value = "Professor Schedules">
<br>
<br>
OR
<br>
<br>
Course #:
<input type = "text" name = "prof-input-course">
and Section #:
<input type = "text" name = "prof-input-section">
<input type = "submit" name = "cs_button" value = "Student Grades"><br>
</form>
</body>
</html><file_sep>## University Web Application
This simple project combines php & mysql to create a website and query a database.
This project will allow an easy way to learn the basics of php and mysql.
While it is simple, it enables me to successfully complete a project that is scalable
to be used in data driven companies.
###### Prograd description:
Given the ssn of a prof (not safe in real life unless ecrypted and handled correctly), list the titles, classrooms,
meeting days and time of classes.
Given the course number and section number, list the grades of the students and the total number of students
enrolled.
<file_sep>DROP DATABASE IF EXISTS university;
DROP DATABASE IF EXISTS UNIVERSITY;
CREATE DATABASE UNIVERSITY;
USE UNIVERSITY;
CREATE TABLE STUDENT
(
cwid INT NOT NULL PRIMARY KEY,
student_name VARCHAR(25) NOT NULL,
student_addr VARCHAR(20),
student_phone VARCHAR(15)
);
CREATE TABLE PROFESSOR
(
prof_ssn INT NOT NULL PRIMARY KEY,
prof_name VARCHAR(15),
sex CHAR(1),
salary FLOAT(2),
title VARCHAR(15),
area_code VARCHAR(5),
phone VARCHAR(10),
st_addr VARCHAR(20),
city VARCHAR(20),
state CHAR(2),
zip VARCHAR(5)
);
CREATE TABLE DEGREE
(
degree_title VARCHAR (25) NOT NULL,
degree_ssn INT NOT NULL,
PRIMARY KEY(degree_title, degree_ssn),
FOREIGN KEY (degree_ssn) REFERENCES PROFESSOR(prof_ssn)
);
CREATE TABLE DEPARTMENT
(
dept_no INT NOT NULL PRIMARY KEY,
dept_ssn INT NOT NULL,
dept_name VARCHAR(20) NOT NULL,
dept_phone VARCHAR(10),
dept_loc VARCHAR(20),
FOREIGN KEY(dept_ssn)
REFERENCES PROFESSOR(prof_ssn)
);
CREATE TABLE COURSE
(
course_no INT NOT NULL PRIMARY KEY,
course_dept_no INT NOT NULL,
course_title VARCHAR(15),
textbook VARCHAR(40),
units INT,
FOREIGN KEY(course_dept_no) REFERENCES DEPARTMENT(dept_no)
);
CREATE TABLE SECTION
(
section_no INT NOT NULL PRIMARY KEY,
prof_ssno INT NOT NULL,
course_number INT NOT NULL,
classroom VARCHAR(10),
beg_time VARCHAR(10),
end_time VARCHAR(10),
seat_count INT,
meeting_days VARCHAR(10),
FOREIGN KEY (prof_ssno) REFERENCES PROFESSOR(prof_ssn),
FOREIGN KEY (course_number) REFERENCES COURSE(course_no)
);
CREATE TABLE MAJOR
(
student_major_id INT NOT NULL,
dept_major_id INT NOT NULL,
PRIMARY KEY(student_major_id,dept_major_id),
FOREIGN KEY (student_major_id) REFERENCES STUDENT(cwid),
FOREIGN KEY (dept_major_id) REFERENCES DEPARTMENT(dept_no)
);
CREATE TABLE MINOR
(
student_minor_id INT NOT NULL,
dept_minor_id INT NOT NULL,
PRIMARY KEY(student_minor_id,dept_minor_id),
FOREIGN KEY(student_minor_id) REFERENCES STUDENT(cwid),
FOREIGN KEY(dept_minor_id) REFERENCES DEPARTMENT(dept_no)
);
CREATE TABLE PREREQUISITE
(
crs_no INT NOT NULL,
prereq_title VARCHAR(15),
PRIMARY KEY(crs_no,prereq_title),
FOREIGN KEY(crs_no) REFERENCES COURSE (course_no)
);
CREATE TABLE ENROLL
(
grade CHAR(2),
id INT NOT NULL,
crs_num INT NOT NULL,
sec_num INT NOT NULL,
PRIMARY KEY(crs_num, sec_num, id),
FOREIGN KEY(crs_num) REFERENCES COURSE(course_no),
FOREIGN KEY(sec_num) REFERENCES SECTION(section_no),
FOREIGN KEY(id) REFERENCES STUDENT(cwid)
);
<file_sep><!--
Developed by <NAME>, <NAME>, <NAME>
This file will handle the student interface.
-calls configuration file to create connection.
-->
<!DOCTYPE html>
<html>
<head>
<title>
Student Interface
</title>
</head>
<body>
<h1>Welcome Students!</h1>
<?php
// Given the course number, list course information
/*Determine which button was selected*/
if(isset($_POST["course_button"]) && !empty($_POST['student-input-course']))
{//
require_once ('../config.php');
$course = $_POST['student-input-course'];
$query = "SELECT section_no, classroom, meeting_days, beg_time, end_time, count(*) AS count
FROM SECTION, COURSE
WHERE $course = course_no
AND course_no = course_number
GROUP BY section_no";
$response = @mysqli_query($connect, $query);
if($response)
{
echo '<table align = "left"
cellspacing = "5" cellpadding="8">
<tr><td align="left"><b></b>
<td align="left"><b>Section Number</b>
<td align="left"><b>Classroom</b>
<td align="left"><b>Meeting Days</b>
<td align="left"><b>Start Time</b>
<td align="left"><b>End Time</b>
<td align="left"><b>Students</b></tr>';
while($row = mysqli_fetch_array($response))
{
echo '<tr> <td align = "left">' .'</td><td align = "left">' .
$row[section_no] . '</td><td align = "left">' .
$row[classroom] . '</td><td align = "left">' .
$row[meeting_days] . '</td><td align = "left">'.
$row[beg_time] . '</td><td align = "left">' .
$row[end_time] . '</td><td align = "left">' .
$row[count] . '</td><td align = "left">' ;
echo '</tr>';
}
echo "</table>";
}
else
{
echo "Couldn't issue database query";
echo mysqli_error($connect); //issue error
}
mysqli_close($connect);
}
/**/
if(isset($_POST["cwid_button"]) && !empty($_POST['student-input-cwid']))
{//
require_once ('../config.php');
$cwid = $_POST['student-input-cwid'];
$query = "SELECT course_title, grade
FROM COURSE, SECTION, ENROLL, STUDENT
WHERE $cwid = cwid
AND cwid = id
AND sec_num = section_no
AND course_number = course_no";
$response = @mysqli_query($connect, $query);
if($response)
{
echo '<table align = "left"
cellspacing = "5" cellpadding="8">
<tr><td align="left"><b></b>
<td align="left"><b>Course Title</b>
<td align="left"><b>Letter Grade</b></tr>';
while($row = mysqli_fetch_array($response))
{
echo '<tr> <td align = "left">' .'</td><td align = "left">' .
$row[course_title] . '</td><td align = "left">' .
$row[grade] . '</td><td align = "left">' ;
echo '</tr>';
}
echo "</table>";
}
else
{
echo "Couldn't issue database query";
echo mysqli_error($connect); //issue error
}
mysqli_close($connect);
}
?>
<form action = "student.php" method = "POST">
Course: <br>
<input type = "text" name = "student-input-course">
<input type = "submit" name = "course_button" value = "Available courses">
<br>
<br>
OR
<br>
<br>
Cwid #:
<input type = "text" name = "student-input-cwid">
<input type = "submit" name = "cwid_button" value = "List course history"><br>
</form>
</body>
</html>
<!--
select dept_no, prof_name from DEPARTMENT, PROFESSOR WHERE dept_name = 'Math' AND prof_ssn = 0249; --><file_sep><html>
<head>
<title>
Printing data
</title>
</head>
<body>
<?php
require_once ('../config.php');
$query = "SELECT * FROM STUDENT";
//send the query to the DB
$response = @mysqli_query($connect, $query);
if($response)
{
echo '<table align = "left"
cellspacing = "5" cellpadding="8">
<tr><td align="left"><b>CWID</b>
<td align="left"><b>First Name</b>
<td align="left"><b>Last Name</b>
<td align="left"><b>Address</b>
<td align="left"><b>City
<td align="left"><b>Zip</b></tr>';
while($row = mysqli_fetch_array($response))
{
echo '<tr> <td align = "left">' .
$row[cwid] . '</td><td align = "left">' .
$row[fname] . '</td><td align = "left">' .
$row[lname] . '</td><td align = "left">' .
$row[address] . '</td><td align = "left">' .
$row[city] . '</td><td align = "left">' .
$row[zip] . '</td><td align = "left">' ;
echo '</tr>';
}
echo "</table>";
}
else
{
echo "Couldn't issue database query";
echo mysqli_error($connect); //issue error
}
mysql_close($connect);
?>
</body>
</html><file_sep>
<!--
Developed by <NAME>, <NAME>, <NAME>
Config.php will be called by the index.php first to create a connection with the server.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
/*
Encapsulate sensitive data away from the public data.
*/
$server = "ecs.fullerton.edu";
$username = "cs332g42";
$password = "<PASSWORD>";
//create connection
$connect = @mysqli_connect($server, $username, $password, '<PASSWORD>');
//check connection
if(!$connect)
die("connection failed:" . mysqli_connect_error());
echo "Connected successfully <br>";
?>
</body>
</html>
| a84be11adddc79d90b79735710f2f19e09baa68f | [
"Markdown",
"SQL",
"PHP"
] | 7 | PHP | elasanchez/UniversityWebApplication | b952c85ea41be64e8aba212a4a2a8410f30fefbe | 9f5ddcf92c38176dff1e4861471132fcc2f9b3ae |
refs/heads/main | <repo_name>griego62/my-first-theme<file_sep>/packages/my-first-theme/src/components/index.js
// File: /packages/my-first-theme/src/components/index.js
import React from "react"
import { connect } from "frontity"
import Link from "@frontity/components/link"
const Root = ({ state }) => {
return (
<>
<h1>Hello Frontity</h1>
<p>Current URL: {state.router.link}</p>
<nav>
<Link link="/">Home</Link>
<br/>
<Link link="/page/2">More posts</Link>
<br/>
<Link link="/about-us">About Us</Link>
</nav>
</>
)
}
export default connect(Root) | 513b6a85aea70c00b00aeb9a61a681fe866ca6a4 | [
"JavaScript"
] | 1 | JavaScript | griego62/my-first-theme | fed2cfef1ec2227b2a18fee1e7508bac86740646 | 93b1e68cb3fcc7a75d870621af45a04f20b30493 |
refs/heads/master | <file_sep>const log4js = require('log4js')
const poll = require('./poll')
const logger = log4js.getLogger()
module.exports = controller => {
controller.on('slash_command', (bot, msg) => {
logger.info('slash_command', msg.command)
if (msg.command === '/poll') {
poll(bot, msg)
}
})
}
<file_sep>const logger = require('log4js').getLogger()
const poll = require('./poll')
module.exports = controller => {
controller.on('interactive_message_callback', (bot, msg) => {
logger.info('interactive_message_callback callback_id', msg.callback_id)
if (msg.callback_id === 'poll') {
poll(bot, msg)
}
})
}
<file_sep>const config = require('config')
const log4js = require('log4js')
const Botkit = require('botkit')
const slash = require('./src/slash')
const interactive = require('./src/interactive')
log4js.configure(config.log4js)
async function setTeam(controller, bot) {
const res = await new Promise((resolve, reject) => {
bot.api.team.info({}, (err, res) => {
if (err) reject(err)
else resolve(res)
})
})
await new Promise((resolve, reject) => {
controller.storage.teams.save(
{
id: res.team.id,
bot: {
user_id: bot.identity.id,
name: bot.identity.name
}
},
err => {
if (err) reject(err)
else resolve()
}
)
})
}
function startWebServer(controller, port) {
return new Promise((resolve, reject) => {
controller.setupWebserver(port, (err, webserver) => {
if (err) {
reject(err)
} else {
controller.createWebhookEndpoints(webserver)
resolve()
}
})
})
}
async function setup() {
const controller = Botkit.slackbot({
debug: process.env.DEBUG,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
clientSigningSecret: process.env.CLIENT_SIGNING_SECRET
})
const bot = controller.spawn({
token: process.env.TOKEN
})
await setTeam(controller, bot)
slash(controller)
interactive(controller)
const port = process.env.PORT || 8080
await startWebServer(controller, port)
}
setup()
<file_sep># Slack Poll
Slack poll app

## Usage
### Required Environments
* CLIENT_ID
* CLIENT_SECRET
* CLIENT_SIGNING_SECRET
* TOKEN
### Start
```
yarn start
```
| 6220d1993f654c4370a14c335a5e0b6ece03b25e | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | maruware/slack-poll | 38bc5927a1dc8ba0a2907535cd60049414408dc1 | 9b5ee6341babbb2b6a8c2d300085a35924b430ec |
refs/heads/master | <repo_name>jelmervos/energy-reader<file_sep>/EnergyReader/Producer/UdpSource.cs
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EnergyReader.Producer
{
class UdpSource : ITelegramProducer
{
public event EventHandler<TelegramEventArgs> NewTelegram;
private UdpClient udpClient;
private const int UdpPort = 9433;
private readonly ILogger<UdpSource> logger;
private CancellationTokenSource cts;
private Task receiveTask;
public UdpSource(ILogger<UdpSource> logger)
{
this.logger = logger;
}
public void Start()
{
cts = new CancellationTokenSource();
udpClient = new UdpClient();
udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, UdpPort));
receiveTask = Task.Run(() => Receive(cts.Token));
}
private void Receive(CancellationToken cancelToken)
{
var from = new IPEndPoint(0, 0);
try
{
while (!cancelToken.IsCancellationRequested)
{
var buffer = udpClient.Receive(ref from);
logger.LogInformation($"Received {buffer.Length} bytes from {from}");
NewTelegram?.Invoke(this, new TelegramEventArgs(buffer));
}
}
catch (SocketException) { }
catch (ObjectDisposedException) { }
catch (OperationCanceledException) { }
}
public void Stop()
{
cts.Cancel();
udpClient.Dispose();
receiveTask.Wait(TimeSpan.FromSeconds(5));
}
}
}
<file_sep>/EnergyReader/Producer/ITelegramProducer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EnergyReader.Producer
{
public class TelegramEventArgs
{
public byte[] Data { get; }
public TelegramEventArgs(byte[] data)
{
Data = data;
}
}
interface ITelegramProducer
{
void Start();
void Stop();
event EventHandler<TelegramEventArgs> NewTelegram;
}
}
<file_sep>/EnergyReader/Producer/SerialPortSource.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
namespace EnergyReader.Producer
{
class SerialPortSource : ITelegramProducer
{
public event EventHandler<TelegramEventArgs> NewTelegram;
private SerialPort serialPort;
private readonly Encoding encoding = Encoding.ASCII;
private const string LineSeperator = "\r\n";
private List<string> inputBuffer;
private readonly ILogger logger;
private const string PortName = "/dev/ttyUSB0";
private const int BaudRate = 115200;
private CancellationTokenSource cts;
private BlockingCollection<byte[]> queue;
private Task consumerTask;
private Task producerTask;
public SerialPortSource(ILogger<SerialPortSource> logger)
{
this.logger = logger;
}
public void Start()
{
queue = new BlockingCollection<byte[]>();
serialPort = new SerialPort(PortName, BaudRate)
{
Encoding = encoding,
NewLine = LineSeperator
};
inputBuffer = new List<string>();
serialPort.Open();
cts = new CancellationTokenSource();
var cancelToken = cts.Token;
consumerTask = Task.Factory.StartNew(() => ProcessSerialPortData(cancelToken), cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
producerTask = Task.Factory.StartNew(async () => await ReadFromSerialPort(cancelToken), cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
private async Task ReadFromSerialPort(CancellationToken cancelToken)
{
var buffer = new byte[1024];
while (!cancelToken.IsCancellationRequested)
{
try
{
var bytesRead = await serialPort.BaseStream.ReadAsync(buffer.AsMemory(0, buffer.Length), cancelToken);
var data = new byte[bytesRead];
Buffer.BlockCopy(buffer, 0, data, 0, data.Length);
queue.Add(data, cancelToken);
}
catch (IOException ex)
{
logger.LogError(ex, "Exception reading from serial port");
}
catch (OperationCanceledException) { }
}
}
private void ProcessSerialPortData(CancellationToken cancelToken)
{
try
{
foreach (var data in queue.GetConsumingEnumerable(cancelToken))
{
inputBuffer.Add(encoding.GetString(data));
CheckForTelegrams();
}
}
catch (OperationCanceledException) { }
}
private void CheckForTelegrams()
{
while (FindTelegramInBuffer(out var telegram))
{
NewTelegram?.Invoke(this, new TelegramEventArgs(encoding.GetBytes(telegram)));
}
}
private bool FindTelegramInBuffer(out string telegram)
{
var data = string.Join(string.Empty, inputBuffer);
var startIndex = data.IndexOf('/');
var crcMatch = Regex.Match(data, $"(![A-Z0-9]{{4}}{LineSeperator})");
if (startIndex > -1 && crcMatch.Success)
{
var endIndex = crcMatch.Index + crcMatch.Length;
var length = endIndex - startIndex;
telegram = data.Substring(startIndex, length);
inputBuffer.Clear();
var left = data.Remove(0, endIndex);
if (!string.IsNullOrEmpty(left))
{
inputBuffer.Add(left);
}
logger.LogInformation($"Telegram found, size: {telegram.Length}, left in buffer: {inputBuffer.Sum(x => x.Length)}");
return true;
}
telegram = null;
return false;
}
public void Stop()
{
logger.LogInformation("Stop");
queue.CompleteAdding();
cts.Cancel();
producerTask.Wait(TimeSpan.FromSeconds(5));
consumerTask.Wait(TimeSpan.FromSeconds(5));
serialPort.Close();
serialPort.Dispose();
cts.Dispose();
queue.Dispose();
}
}
}
<file_sep>/EnergyReader/Consumer/InfluxDbWriter.cs
using DSMRParser;
using DSMRParser.Models;
using InfluxDB.LineProtocol.Client;
using InfluxDB.LineProtocol.Payload;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EnergyReader.Consumer
{
class InfluxDbWriter : ITelegramConsumer
{
private DateTimeOffset lastWrite;
private readonly ILogger<InfluxDbWriter> logger;
private readonly TimeSpan writeEvery = TimeSpan.FromMinutes(1);
private const string Uri = "http://raspberrypi.:8086";
private const string DatabaseName = "energy";
public InfluxDbWriter(ILogger<InfluxDbWriter> logger)
{
lastWrite = DateTimeOffset.MinValue;
this.logger = logger;
}
private async Task CheckForWritableTelegrams(List<Telegram> telegrams, CancellationToken cancelToken)
{
var now = DateTimeOffset.Now;
var lastWriteAge = now - lastWrite;
if ((telegrams.Count > 0) && (lastWriteAge >= writeEvery))
{
var batch = telegrams.Where(t => t.TimeStamp >= lastWrite);
if (batch.Any())
{
var list = batch.ToList();
await WriteTelegrams(list, cancelToken);
telegrams.RemoveAll(t => batch.Contains(t));
}
lastWrite = now;
}
}
private async Task WriteTelegrams(List<Telegram> telegrams, CancellationToken cancelToken)
{
logger.LogInformation($"Write {telegrams.Count} telegrams");
LineProtocolPayload payload;
payload = new LineProtocolPayload();
payload.Add(GetElectricityPoint(telegrams));
payload.Add(GetGasPoint(telegrams));
var client = new LineProtocolClient(new Uri(Uri), DatabaseName);
var writeResult = await client.WriteAsync(payload, cancelToken);
logger.LogInformation($"WriteResult: {writeResult.Success} {writeResult.ErrorMessage}");
}
private static LineProtocolPoint GetGasPoint(List<Telegram> telegrams)
{
var timeStamp = telegrams.Max(t => t.GasDelivered.DateTime.Value);
var delivered = telegrams.Max(t => t.GasDelivered.Value.Value);
return new LineProtocolPoint(
"gas", //Measurement
new Dictionary<string, object> //Fields
{
{ "delivered", delivered },
},
new Dictionary<string, string> { }, //Tags
timeStamp.UtcDateTime); //Timestamp
}
private static LineProtocolPoint GetElectricityPoint(List<Telegram> telegrams)
{
var timeStamp = telegrams.Max(t => t.TimeStamp.Value);
var deliveredTariff1 = telegrams.Max(t => t.EnergyDeliveredTariff1.Value);
var deliveredTariff2 = telegrams.Max(t => t.EnergyDeliveredTariff2.Value);
var returnedTariff1 = telegrams.Max(t => t.EnergyReturnedTariff1.Value);
var returnedTariff2 = telegrams.Max(t => t.EnergyReturnedTariff2.Value);
var voltageL1 = telegrams.Average(t => t.VoltageL1.Value);
return new LineProtocolPoint(
"electricity", //Measurement
new Dictionary<string, object> //Fields
{
{ "DeliveredTariff1", deliveredTariff1 },
{ "DeliveredTariff2", deliveredTariff2 },
{ "ReturnedTariff1", returnedTariff1 },
{ "ReturnedTariff2", returnedTariff2 },
{ "VoltageL1", voltageL1 },
},
new Dictionary<string, string> { }, //Tags
timeStamp.UtcDateTime); //Timestamp
}
public async Task StartConsumingAsync(BlockingCollection<byte[]> queue, CancellationToken cancelToken)
{
var telegrams = new List<Telegram>();
var parser = new DSMRTelegramParser();
foreach (var data in queue.GetConsumingEnumerable(cancelToken))
{
var telegram = parser.Parse(new Span<byte>(data));
if (telegram.TimeStamp != null)
{
telegrams.Add(telegram);
}
await CheckForWritableTelegrams(telegrams, cancelToken);
}
}
}
}
<file_sep>/EnergyReader/ConsumerQueue.cs
using EnergyReader.Consumer;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace EnergyReader
{
class ConsumerQueue
{
private BlockingCollection<byte[]> queue;
private Task consumerTask;
private readonly ITelegramConsumer consumer;
private readonly ILogger logger;
private CancellationTokenSource cts;
public ConsumerQueue(ITelegramConsumer consumer, ILogger logger)
{
this.consumer = consumer;
this.logger = logger;
}
public void Start()
{
cts = new CancellationTokenSource();
queue = new BlockingCollection<byte[]>();
var cancelToken = cts.Token;
StartConsumer(cancelToken);
}
private void StartConsumer(CancellationToken cancelToken)
{
consumerTask = Task.Factory.StartNew(async () => await StartConsumingAsync(cancelToken), cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
consumerTask.ContinueWith(t => RestartConsumer(t, cancelToken), cancelToken, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default);
}
private async Task StartConsumingAsync(CancellationToken cancelToken)
{
logger.LogInformation("Start consuming");
try
{
await consumer.StartConsumingAsync(queue, cancelToken);
}
catch (OperationCanceledException) { }
}
private void RestartConsumer(Task task, CancellationToken cancelToken)
{
if (task?.Exception != null)
{
logger.LogError(task.Exception, "Consumer faulted");
}
else
{
logger.LogError("Consumer faulted");
}
if (!cancelToken.IsCancellationRequested)
{
logger.LogError("Restarting consumer");
StartConsumer(cancelToken);
}
}
public void Stop()
{
logger.LogInformation("Stop consumer");
cts.Cancel();
queue.CompleteAdding();
consumerTask.Wait(TimeSpan.FromSeconds(5));
queue.Dispose();
}
public void Enqueue(byte[] data)
{
queue.Add(data);
}
}
}
<file_sep>/EnergyReader/Program.cs
using EnergyReader.Consumer;
using EnergyReader.Producer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace EnergyReader
{
internal sealed class Program
{
private static async Task Main(string[] args)
{
await Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
})
.ConfigureServices((_, services) => services
.AddLogging()
.AddHostedService<ConsoleHostedService>()
.AddSingleton(typeof(TelegramMessageBus))
#if (DEBUG)
.AddTransient<ITelegramProducer, UdpSource>()
.AddTransient<ITelegramConsumer, FileWriter>())
#else
.AddTransient<ITelegramProducer, SerialPortSource>()
.AddTransient<ITelegramConsumer, FileWriter>()
.AddTransient<ITelegramConsumer, UdpBroadcaster>()
.AddTransient<ITelegramConsumer, InfluxDbWriter>())
#endif
.RunConsoleAsync();
}
}
internal sealed class ConsoleHostedService : IHostedService
{
private readonly ILogger logger;
private readonly IHostApplicationLifetime appLifetime;
private readonly TelegramMessageBus messageBus;
private readonly AutoResetEvent applicationShutdownEvent;
public ConsoleHostedService(ILogger<ConsoleHostedService> logger, IHostApplicationLifetime appLifetime, TelegramMessageBus messageBus)
{
this.logger = logger;
this.appLifetime = appLifetime;
this.messageBus = messageBus;
applicationShutdownEvent = new AutoResetEvent(false);
}
public Task StartAsync(CancellationToken cancellationToken)
{
appLifetime.ApplicationStarted.Register(() =>
{
Task.Run(() =>
{
try
{
messageBus.Start();
applicationShutdownEvent.WaitOne();
messageBus.Stop();
}
catch (Exception ex)
{
logger.LogError(ex, "Unhandled exception!");
}
finally
{
appLifetime.StopApplication();
}
});
});
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
applicationShutdownEvent.Set();
return Task.CompletedTask;
}
}
}
<file_sep>/EnergyReader/Consumer/FileWriter.cs
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EnergyReader.Consumer
{
class FileWriter : ITelegramConsumer
{
private readonly ILogger<FileWriter> logger;
private const string DestinationFileName = "telegram.txt";
public FileWriter(ILogger<FileWriter> logger)
{
this.logger = logger;
}
public async Task StartConsumingAsync(BlockingCollection<byte[]> queue, CancellationToken cancelToken)
{
foreach (var data in queue.GetConsumingEnumerable(cancelToken))
{
var fileName = Path.Combine(AppContext.BaseDirectory, DestinationFileName);
using (var fileStream = File.Open(fileName, FileMode.Create))
{
fileStream.Seek(0, SeekOrigin.End);
await fileStream.WriteAsync(data.AsMemory(0, data.Length), cancelToken);
}
logger.LogInformation($"Written {data.Length} bytes to {fileName}");
}
}
}
}
<file_sep>/EnergyReader/TelegramMessageBus.cs
using EnergyReader.Consumer;
using EnergyReader.Producer;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EnergyReader
{
class TelegramMessageBus
{
private readonly List<ConsumerQueue> consumerQueues;
private readonly ITelegramProducer producer;
public TelegramMessageBus(ILoggerFactory logger, ITelegramProducer producer, IEnumerable<ITelegramConsumer> consumers)
{
this.producer = producer;
consumerQueues = new List<ConsumerQueue>(consumers.Select(c => new ConsumerQueue(c, logger.CreateLogger(c.GetType().Name))));
}
public void Start()
{
Parallel.ForEach(consumerQueues, c => c.Start());
producer.NewTelegram += NewTelegram;
producer.Start();
}
private void NewTelegram(object sender, TelegramEventArgs e)
{
Parallel.ForEach(consumerQueues, c => c.Enqueue(e.Data));
}
public void Stop()
{
producer.Stop();
producer.NewTelegram -= NewTelegram;
Parallel.ForEach(consumerQueues, t => t.Stop());
}
}
}
<file_sep>/EnergyReader/Consumer/UdpBroadcaster.cs
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EnergyReader.Consumer
{
class UdpBroadcaster : ITelegramConsumer
{
private const int UdpPort = 9433;
private readonly ILogger logger;
public UdpBroadcaster(ILogger<UdpBroadcaster> logger)
{
this.logger = logger;
}
public async Task StartConsumingAsync(BlockingCollection<byte[]> queue, CancellationToken cancelToken)
{
using var udpClient = new UdpClient();
var broadcastIpAddress = IPAddress.Broadcast.ToString();
foreach (var data in queue.GetConsumingEnumerable(cancelToken))
{
await udpClient.SendAsync(data, data.Length, broadcastIpAddress, UdpPort);
logger.LogInformation($"Broadcasted data, size: {data.Length}, port: {UdpPort}");
}
}
}
}
<file_sep>/EnergyReader/Consumer/ITelegramConsumer.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EnergyReader.Consumer
{
interface ITelegramConsumer
{
Task StartConsumingAsync(BlockingCollection<byte[]> queue, CancellationToken cancelToken);
}
}
| 6fa1aaf9089a4157b6a2e9a7ace75151fd7711af | [
"C#"
] | 10 | C# | jelmervos/energy-reader | 9ac238e386caa2320135d30242b184bfdfd413bc | 17a97290eef081c258029a456280ae634478fe0b |
refs/heads/main | <file_sep>"""
Examen 3D Recuperacion
<NAME>
"""
import matplotlib.pyplot as plt
import numpy as np
from math import sqrt
import sys
import keyboard
#Declaracion del arrgelo
x=[30,40,80,10,40]
y=[10,60,60,10,75]
z=[-10,10,10,0,0]
#funcion del ploteo de la figura
def plotPlaneLine(xg,yg,zg,bandera,areaBase,area1,area2):
#Tamaño del grid
plt.title('<NAME>')
plt.axis([0,150,100,0])
plt.axis('on')
plt.grid(True)
plt.xlabel('Eje x')
plt.ylabel('Eje y')
#Triangulo base
plt.plot([x[0],x[1]],[y[0],y[1]],color='k')
plt.plot([x[1],x[2]],[y[1],y[2]],color='k')
plt.plot([x[2],x[0]],[y[2],y[0]],color='k')
#Triangulos lados
plt.plot([x[0],x[3]],[y[0],y[3]],linestyle=':',color='r')
plt.plot([x[3],x[1]],[y[3],y[1]],linestyle=':',color='g')
plt.plot([x[3],x[2]],[y[3],y[2]],linestyle=':',color='y')
#Linea de interseccion
plt.plot([x[3],x[4]],[y[3],y[4]],color='b')
if(bandera==True):
plt.text(100,60,'Hitpoint dentro del plano')
else:
plt.text(100,60,'Hitpoint fuera del plano')
areaBase = int(areaBase)
area1 = int(area1)
area2 = int(area2)
plt.text(100,25,'Area base=')
plt.text(125,25,areaBase)
plt.text(100,35,'Area1=')
plt.text(120,35,area1)
plt.text(100,40,'Area2=')
plt.text(120,40,area2)
plt.text(100,50,'Area1+Area2=')
plt.text(135,50,area1+area2)
plt.show()
def hitpoint(x,y,z):
#Triangulo base
#Distancia de 0 a 1
a=x[1]-x[0]
b=y[1]-y[0]
c=z[1]-z[0]
D01=sqrt(a*a+b*b+c*c)
#Distancia de 1 a 2
a=x[2]-x[1]
b=y[2]-y[1]
c=z[2]-z[1]
D12=sqrt(a*a+b*b+c*c)
#Distancia de 0 a 2
a=x[2]-x[0]
b=y[2]-y[0]
c=z[2]-z[0]
D02=sqrt(a*a+b*b+c*c)
#Calcular area con formula de Heron
s=(D01+D12+D02)/2
areaBase=sqrt(s*(s-D01)*(s-D12)*(s-D02))
#Triangulo 1
#Distancia de 0 a 1
a=x[1]-x[0]
b=y[1]-y[0]
c=z[1]-z[0]
D01=sqrt(a*a+b*b+c*c)
#Distancia de 1 a 3
a=x[3]-x[1]
b=y[3]-y[1]
c=z[3]-z[1]
D13=sqrt(a*a+b*b+c*c)
#Distancia de 0 a 3
a=x[3]-x[0]
b=y[3]-y[0]
c=z[3]-z[0]
D03=sqrt(a*a+b*b+c*c)
#Calcular area con formula de Heron
s=(D01+D13+D03)/2
area1=sqrt(s*(s-D01)*(s-D13)*(s-D03))
#Triangulo 2
#Distancia de o a 2
a=x[2]-x[0]
b=y[2]-y[0]
c=z[2]-z[0]
D02=sqrt(a*a+b*b+c*c)
#Distancia de 2 a 3
a=x[3]-x[2]
b=y[3]-y[2]
c=z[3]-z[2]
D23=sqrt(a*a+b*b+c*c)
#Distancia de 0 a 3
a=x[3]-x[0]
b=y[3]-y[0]
c=z[3]-z[0]
D03=sqrt(a*a+b*b+c*c)
#Calcular area con formula de Heron
s=(D02+D23+D03)/2
area2=sqrt(s*(s-D02)*(s-D23)*(s-D03))
#Verificacion del hitpoint
sumaAreas = area1+area2
bandera = True
if(areaBase>sumaAreas):
bandera = True
else:
bandera = False
#Manda a plotear la figura y etiquetas
plotPlaneLine(x,y,z,bandera,areaBase,area1,area2)
#inserccion de datos y hitpoint
print("pulsa Enter para continuar o ESC para salir")
while True:
if keyboard.is_pressed('Esc'):
sys.exit(0)
if keyboard.is_pressed('ENTER'):
tecla=input('-----')
hx=input("Hitpoint x:")
hy=input("Hitpoint y:")
#Asignacion de los arreglos
x[3]=int(hx)
y[3]=int(hy)
hitpoint(x,y,z)
print("pulsa Enter para continuar o ESC para salir")
plt.show() | bdbedb7a7987d6a4ffa4807166bc31e65ef4399c | [
"Python"
] | 1 | Python | alexis-saul/examen_recuperacion3d | 6ede99bec872bc71528edde5cc017eee46cf61d2 | e89d1ae7947632cee4f63c7180a6e16a754a1f1c |
refs/heads/master | <repo_name>AKincel18/Burglar-alarm-simulator<file_sep>/KEYPAD/diode.h
/*
* diode atmega16 F_CPU = 8000000 Hz
*
* Created on: 02.01.2019
* Author: admin
*/
#ifndef DIODE_
#define DIODE_
void switchOnDiode(int);
void switchOffDiode(int);
void resetDiode();
#endif /* DIODE_ */<file_sep>/INIT/init.c
/*
* init.c atmega16 F_CPU = 8000000 Hz
*
* Created on: 02.01.2019
* Author: admin
*/
#include <avr/io.h>
#include "init.h"
void init ()
{
//DIODY
//dioda niebieska -> uzbrojenie alarmu
DDRC |= ( 1 << PC6 ); //wyjscie
PORTC |= ( 1 << PC6 ); //stan wysoki -> nie swieci
//dioda zielona - swieci ciagle -> zasilanie
DDRB |= ( 1 << PB2 ); //wyjscie
PORTB &= ~( 1 << PB2 ); //stan niski -> swieci zielona
//RGB -> zielona PC0, czerwona PC1 -> poprawnosc kodu
DDRC |= (1<<PC0) | 1<<PC1 ;
PORTC &= ~( (1<<PC0) | 1<<PC1);
//czerwone
DDRD |= ( 1 << PD6 );
PORTD |= ( 1 << PD6 );
DDRD |= ( 1 << PD5 );
PORTD |= ( 1 << PD5 );
DDRD |= ( 1 << PD4 );
PORTD |= ( 1 << PD4 );
DDRD |= ( 1 << PD3 );
PORTD |= ( 1 << PD3 );
//zolta - jest wprowadzany kod
DDRD |= ( 1 << PD2 );
PORTD |= ( 1 << PD2 );
//PRZYCISKI
DDRB &= ~ ( 1 << PB1 ); //uzbrojenie alarmu
PORTB |= ( 1 << PB1 );
DDRB &= ~ ( 1 << PB0 ); //resetowanie urzadzenia po wprowadzniu kodu
PORTB |= ( 1 << PB0 );
//CZUJNIK DZWIEKU
DDRA &= ~( 1 << PA7 ); //wejscie
//BUZZER
DDRD |= ( 1 << PD0 );
PORTD |= ( 1 << PD0 ); //wyjscie
}<file_sep>/KEYPAD/diode.c
/*
* diode.c atmega16 F_CPU = 8000000 Hz
*
* Created on: 02.01.2019
* Author: admin
*/
#include <avr/io.h>
#include "diode.h"
void switchOnDiode(int pos)
{
switch(pos)
{
case 0:
PORTD &= ~( 1 << PD6 );
break;
case 1:
PORTD &= ~( 1 << PD5 );
break;
case 2:
PORTD &= ~( 1 << PD4 );
break;
case 3:
PORTD &= ~( 1 << PD3 );
break;
}
}
void switchOffDiode(int pos)
{
switch(pos)
{
case 0:
PORTD |= ( 1 << PD6 );
break;
case 1:
PORTD |= ( 1 << PD5 );
break;
case 2:
PORTD |= ( 1 << PD4 );
break;
case 3:
PORTD |= ( 1 << PD3 );
break;
}
}
void resetDiode()
{
PORTD |= ( 1 << PD6 );
PORTD |= ( 1 << PD5 );
PORTD |= ( 1 << PD4 );
PORTD |= ( 1 << PD3 );
}<file_sep>/KEYPAD/keypad.c
/*
* keypad.c atmega16 F_CPU = 8000000 Hz
*
* Created on: 02.01.2019
* Author: admin
*/
#include <avr/io.h>
#include <util/delay.h>
#include "keypad.h"
#include "diode.h"
int tab[4]; //tablica reprezentujaca kod wpisany z klawiatury
int sec; //ilosc sekund ktore minely przy wpisywaniu kodu
uint8_t GetKeyPressed() { //obsluga klawiatury, zwraca kod klawisza
uint8_t r, c;
PORTA |= 0x0F;
for ( c = 0;c < 3;c++ ) {
DDRA &= ~( 0x7F );
DDRA |= ( 0x40 >> c );
for ( r = 0;r < 4;r++ ) {
if ( !( PINA & ( 0x08 >> r ) ) ) { //sprawdzenie czy nastapilo nacisniecie klawisza
return ( r*3 + c +1); //zwracanie kodu klawisza: 1->1, 2->2, ..., 10->'*', 11->0, 12->"#"
}
}
}
return 0xFF;//zwracanie 255 gdy klawisz nie zostal wcisniety
}
int checkPassword() //password= <PASSWORD>
{
if ( tab[0] == 1 && tab[1] == 2 && tab[2] == 3 && tab[3] == 4 )
return 1;
else
return 0;
}
int timeOut()
{
if (TCNT1 >= 15625) //15625 - jedna sekunda
{
TCNT1 = 0; //Zerowanie Timera
sec++;
if (sec >= 10)
{
return 1;
}
}
return 0;
}
void setWrongPassword()
{
tab[0] = 0;
tab[1] = 0;
tab[2] = 0;
tab[3] = 0;
}
void getPassword() {
int key; //kod klawisza
int pos = 0; //ktora pozycja jest wpisywana
int enterCode = 0; //czy wprowadzany jest kod
TCNT1 = 0; //Zerowanie Timera
sec = 0;
while ( enterCode == 0)
{
if (timeOut() == 0)
{
while ( GetKeyPressed() != 255 )
{
if (timeOut() == 0) //czas sie nie skonczyl
{
key = GetKeyPressed();
if ( (key < 10 || key == 11) && (pos<4) )
{
switchOnDiode(pos);
tab[pos] = key;
pos++;
_delay_ms( 50 );
}
else if (key == 10) //kasowanie znaku
{
if (pos != 0)
{
pos=pos-1;
switchOffDiode(pos);
_delay_ms( 50 );
}
}
else if (pos == 4 && key==12) //zatwierdzenie kodu
{
enterCode = 1;
}
}
else //czas sie skonczyl
{
enterCode = 1;
setWrongPassword();
}
}
}
else
{
enterCode = 1;
setWrongPassword();
}
}
_delay_ms( 50 );
resetDiode();
}
<file_sep>/INIT/init.h
/*
* init atmega16 F_CPU = 8000000 Hz
*
* Created on: 02.01.2019
* Author: admin
*/
#ifndef INIT_
#define INIT_
void init();
#endif /* INIT_ */<file_sep>/README.md
# Burglar alarm simulator
## Description
Project which goal is simulation burglar alarm on Atmega16. The alarm simulator detects the sound. After arming the alarm, the user has 10 seconds to enter the correct code to disarm the alarm. After turning the power supply on, the green diode lights, which indicates the power supply. The user can arm the alarm with one of the buttons. After a while, the alarm is ready for operation. Then, when it detects a sound, the yellow LED lights up. The user has 10 seconds to enter the correct code from the keyboard. If the user enters the correct code, the green diode is turned on, otherwise there will be an acoustic signal (buzzer) and a light signal (red diode).
## Elements
* AVR - ATmega16A-PU - DIP
* Breadboard
* Sound sensor
* Buzzer
* Membrane keyboard
* Buttons
* Diodes
* Cordset
* Resistors
## Schematic diagram




## Printed circuit board

## Pictures of the burglar alarm simulator




<file_sep>/main.c
/*
* main.c ATmega16 F_CPU = 8000000 Hz
*
* Created on: 17.11.2018
* Author: admin
*/
// dołączanie systemowych plików nagłówkowych
#include <avr/io.h>
#include <util/delay.h>
#include "INIT/init.h"
#include "KEYPAD/keypad.h"
int main( void ) {
init(); // sekcja inicjalizacji peryferiów
//zmienne sterujace prace programu
int beep = 0;
int alarm = 0;
int end = 0;
TCCR1B |= ((1 << CS10) | (1 << CS11)); //Ustawia timer z preskalerem Fcpu/64
while ( 1 ) {
if ( !( PINB & ( 1 << PB1 ) ) ) { //uzbrojenie alarmu
_delay_ms( 200 ); //czas na uzbrojenie alarmu
PORTC &= ~( 1 << PC6 ); //zalaczenie diody niebieskiej
alarm = 0;
while ( alarm == 0 ) {
if ( !( PINA & ( 1 << PA7 ) ) ) { //jesli wystapi dzwiek
PORTC |= ( 1 << PC6 ); //wylaczenie diody niebieskiej -> koniec uzbrojenia alarmu
PORTD &= ~( 1 << PD2); //dioda zolta -> czas na wpisanie alarmu
getPassword(); //wpisanie hasla
PORTD |= ( 1 << PD2); //wylaczenie diody zoltej
if ( checkPassword() == 1 ) { //dobre haslo
PORTC |= (1<<PC0); //dioda zielona -> dobre haslo
end = 0;
while (end == 0)
{
if ( !( PINB & ( 1 << PB0 ) ) ) { // po nacisnieciu przycisku powrot do stanu poczatkowego
PORTC &= ~( (1<<PC0));
end=1;
}
}
} else { //zle haslo
PORTC |= 1<<PC1; //dioda czerwona
beep = 1;
PORTD &= ~( 1 << PD0 ); //wlaczenie buzzera
while ( beep == 1 ) {
if ( !( PINB & ( 1 << PB0 ) ) ) { //po nacisnieciu przycisku powrot do stanu poczatkowego
PORTD |= ( 1 << PD0 );
beep = 0;
PORTC &= ~( 1<<PC1);
}
}
}
alarm = 1;
}
}
}
PORTC |= ( 1 << PC6 ); //wylaczenie diody niebieskiej
}
}<file_sep>/KEYPAD/keypad.h
/*
* keypad atmega16 F_CPU = 8000000 Hz
*
* Created on: 02.01.2019
* Author: admin
*/
#ifndef KEYPAD_
#define KEYPAD_
uint8_t GetKeyPressed();
int checkPassword();
int timeOut();
void setWrongPassword();
void getPassword();
#endif /* KEYPAD_ */ | 86e315af2ad09dabce31ff8bf74b78bcdb301d61 | [
"Markdown",
"C"
] | 8 | C | AKincel18/Burglar-alarm-simulator | f86b0dfad30ccfc4d93c047002da9951c3d58985 | 20fefcbc54b2b02c91828d7552fb866e9324b9be |
refs/heads/master | <file_sep><?php
namespace spec\Hexmedia\Crontab\Parser\Json;
use dev\Hexmedia\Crontab\PhpSpec\Parser\AbstractJsonParserObjectBehavior;
use Prophecy\Argument;
class PhpParserSpec extends AbstractJsonParserObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Parser\Json\PhpParser');
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Parser\Ini;
use Hexmedia\Crontab\Exception\ParsingException;
use Hexmedia\Crontab\Parser\AbstractParser;
use Hexmedia\Crontab\Parser\ParserInterface;
/**
* Class AustinHydeParser
*
* @package Hexmedia\Crontab\Parser\Ini
*/
class AustinHydeParser extends AbstractParser implements ParserInterface
{
/**
* @return \ArrayObject
*
* @throws ParsingException
*/
public function parse()
{
{
$this->setTemporaryErrorHandler();
$parser = new \IniParser($this->getFile());
/** @var \ArrayObject $parsed */
$parsed = $parser->parse();
$this->restoreErrorHandler();
}
$parsed = $this->transformToArray($parsed);
return $parsed;
}
/**
* @return bool
*/
public static function isSupported()
{
return class_exists('\\IniParser');
}
/**
* @param \ArrayObject $arrayObject
*
* @return array
*/
private function transformToArray(\ArrayObject $arrayObject)
{
$array = $arrayObject->getArrayCopy();
foreach ($array as $key => $value) {
if ($value instanceof \ArrayObject) {
$array[$key] = $this->transformToArray($value);
}
}
return $array;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab\Writer;
use dev\Hexmedia\Crontab\PhpSpec\SystemAwareObjectBehavior;
use Hexmedia\Crontab\Crontab;
use Hexmedia\Crontab\System\Unix;
use Hexmedia\Crontab\Task;
use Hexmedia\Crontab\Variables;
use Prophecy\Argument;
class SystemWriterSpec extends SystemAwareObjectBehavior
{
private function prepareTask(&$task, $variables, $notManaged = false)
{
$task->getCommand()->willReturn("test");
$task->getMonth()->willReturn("*");
$task->getDayOfMonth()->willReturn("*");
$task->getDayOfWeek()->willReturn("*");
$task->getHour()->willReturn("*");
$task->getMinute()->willReturn("*/10");
$task->getLogFile()->willReturn("some_log_file.log");
$task->getBeforeComment()->willReturn("This is some comment with \n two lines");
$task->isNotManaged()->willReturn($notManaged);
$task->getVariables()->willReturn($variables);
$task->getName()->willReturn("synchronize1");
}
function let(Crontab $crontab, Task $nmTask1, Task $nmTask2, Task $task1, Task $task2, Variables $variables1)
{
$this->prepareTask($task1, $variables1);
$this->prepareTask($task2, $variables1);
$this->prepareTask($nmTask1, $variables1, true);
$this->prepareTask($nmTask2, $variables1, true);
$crontab->getName()->willReturn("TestAopTest");
$crontab->getManagedTasks()->willReturn(array($task1, $task2));
$crontab->getNotManagedTasks()->willReturn(array($nmTask1, $nmTask2));
}
function it_is_initializable()
{
if (Unix::isUnix()) { //Currently this will work only on *nix
$this->shouldHaveType('Hexmedia\Crontab\Writer\SystemWriter');
}
}
function it_is_properly_writing($crontab)
{
$this->isSystemSupported();
$this->write($crontab)->shouldReturn(true);
}
function it_is_properly_preparing_content($crontab)
{
$this->isSystemSupported();
$this->getContent($crontab)->shouldContain("test");//shouldReturn($shouldBe);
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
/**
* Class ReaderFactorySpec
*
* @package spec\Hexmedia\Crontab
*
* @covers Hexmedia\Crontab\ReaderFactory
*/
class ReaderFactorySpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\ReaderFactory');
}
// function it_is_not_created_without_type() {
// $this->shouldThrow()->during('create', array(array()));
// }
function it_is_able_to_create_yaml_reader()
{
$this::create(array('type' => 'yaml', 'file' => 'aa'))->shouldHaveType('Hexmedia\Crontab\Reader\YamlReader');
}
}
<file_sep><?php
namespace spec\Hexmedia\Crontab\Parser\Json;
use dev\Hexmedia\Crontab\PhpSpec\Parser\FactoryObjectBehavior;
use Prophecy\Argument;
class ParserFactorySpec extends FactoryObjectBehavior
{
protected function getType()
{
return "Json";
}
protected function getWorkingParser()
{
return 'PhpParser';
}
protected function getParsersCount()
{
return 1;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Parser;
use Hexmedia\Crontab\Exception\NoSupportedParserException;
use Hexmedia\Crontab\Exception\UnexistingParserException;
/**
* Class ParserFactoryAbstract
*
* @package Hexmedia\Crontab\Parser
*/
abstract class AbstractParserFactory
{
/**
* @var array|mixed
*/
protected $parsers = array();
/**
* ParserFactoryAbstract constructor.
*
* @param string|null $preferred
*/
public function __construct($preferred = null)
{
$this->parsers = $this->getDefaultParsers();
$this->sortWithPreferred($preferred);
}
/**
* @return array
*/
abstract public function getDefaultParsers();
/**
* @param string $className
*
* @return $this
* @throws UnexistingParserException
*/
public function addParser($className)
{
if (!class_exists($className)) {
throw new UnexistingParserException(sprintf('Parser %s does not exists!', $className));
}
$this->parsers[] = $className;
return $this;
}
/**
* @param string $className
*
* @return bool
*/
public function removeParser($className)
{
$key = $this->searchForKey($className);
if (false !== $key) {
unset($this->parsers[$key]);
return true;
}
return false;
}
/**
* @param string $content
* @param string|null $file
*
* @return ParserInterface
* @throws NoSupportedParserException
*/
public function create($content, $file)// = null)
{
foreach ($this->parsers as $parserName) {
if (call_user_func($parserName . '::isSupported')) {
return new $parserName($content, $file);
}
}
throw new NoSupportedParserException(
sprintf('There is no supported parser for this type or operating system (your is "%s").', PHP_OS)
);
}
/**
* @return array
*/
public function getParsers()
{
return $this->parsers;
}
/**
* @return $this;
*/
public function clearParser()
{
$this->parsers = array();
return $this;
}
/**
* @param string $searched
*
* @return string
*/
protected function searchForKey($searched)
{
$key = false;
$searchedUnified = $this->unify($searched);
foreach ($this->parsers as $key2 => $parser) {
if ($searchedUnified == $this->unify($parser)) {
$key = $key2;
break;
}
}
if (false === $key) {
foreach ($this->parsers as $key2 => $parser) {
if (preg_match('/\\\\([A-Za-z0-9]*)$/', $parser, $matches)) {
if ($matches[1] == $searched) {
return $key2;
}
}
}
}
return $key;
}
/**
* @param string $preferred
*/
private function sortWithPreferred($preferred)
{
if ($preferred) {
$key = $this->searchForKey($preferred);
if (false !== $key) {
$preferred = $this->parsers[$key];
unset($this->parsers[$key]);
array_unshift($this->parsers, $preferred);
}
}
}
/**
* Unifying class name for search
*
* @param string $className
*
* @return string
*/
private function unify($className)
{
$className = trim($className, "\\/ \n");
return preg_replace("/[^a-zA-Z0-9]*/", "/", $className);
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Parser\Yaml;
use Hexmedia\Crontab\Exception\ParsingException;
use Hexmedia\Crontab\Parser\AbstractParser;
use Hexmedia\Crontab\Parser\ParserInterface;
use Symfony\Component\Yaml\Exception\ParseException;
/**
* Class SymfonyParser
*
* @package Hexmedia\Crontab\Parser\Yaml
*/
class SymfonyParser extends AbstractParser implements ParserInterface
{
/**
* @return array
*
* @throws ParsingException
*/
public function parse()
{
try {
$parser = new \Symfony\Component\Yaml\Parser();
$parsed = $parser->parse($this->getContent());
} catch (ParseException $e) {
throw new ParsingException("Cannot parse this file: " . $e->getMessage(), 0, $e);
}
return $parsed;
}
/**
* @return bool
*/
public static function isSupported()
{
return class_exists('\\Symfony\\Component\\Yaml\\Parser');
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\System;
use Hexmedia\Crontab\Exception\SystemOperationException;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\ProcessBuilder;
/**
* Class Unix
*
* @package Hexmedia\Crontab\System
*/
class Unix
{
/**
* @var string|null
*/
private static $temporaryDir = null;
/**
* @var ProcessBuilder
*/
private static $processBuilder = null;
/**
* @var array
*/
private static $unixes = array('Linux', 'FreeBSD', 'OsX');
/**
* @param ProcessBuilder|null $processBuilder
*/
public static function setProcessBuilder(ProcessBuilder $processBuilder = null)
{
self::$processBuilder = $processBuilder;
}
/**
* @return ProcessBuilder
*/
public static function getProcessBuilder()
{
if (null === self::$processBuilder) {
self::$processBuilder = new ProcessBuilder();
}
return self::$processBuilder;
}
/**
* @param null|string $user
*
* @return string
* @throws SystemOperationException
*/
public static function get($user = null)
{
$processArgs = array('-l');
if (null !== $user) {
$processArgs[] = '-u';
$processArgs[] = $user;
}
$process = self::getProcessBuilder()
->setPrefix('crontab')
->setArguments($processArgs)
->getProcess();
$process->run();
if ($process->getErrorOutput()) {
if (false === strpos($process->getErrorOutput(), 'no crontab for')) {
throw new SystemOperationException(sprintf('Executing error: %s', trim($process->getErrorOutput())));
}
return false;
}
return $process->getOutput();
}
/**
* @param string $content
* @param string|null $user
*
* @return bool
* @throws SystemOperationException
*/
public static function save($content, $user = null)
{
$temporaryFile = self::getTemporaryDir() . '/' . md5(rand(0, 10000)) . '.cron';
$fileHandler = fopen($temporaryFile, 'w');
flock($fileHandler, LOCK_EX);
fwrite($fileHandler, $content);
flock($fileHandler, LOCK_UN);
fclose($fileHandler);
$processArgs = array();
if (null !== $user) {
$processArgs[] = '-u';
$processArgs[] = $user;
}
$processArgs[] = $temporaryFile;
$process = self::getProcessBuilder()
->setPrefix('crontab')
->setArguments($processArgs)
->getProcess();
$process->run();
if ($process->getErrorOutput()) {
throw new SystemOperationException(sprintf('Executing error: %s', trim($process->getErrorOutput())));
}
if ($process->getOutput()) {
throw new SystemOperationException(sprintf('Unexpected output: %s', trim($process->getOutput())));
}
return true;
}
/**
* @param string|null $user
*
* @return bool
* @throws SystemOperationException
*/
public static function clear($user = null)
{
$processArgs = array();
if (null !== $user) {
$processArgs[] = '-u';
$processArgs[] = $user;
}
$processArgs[] = '-r';
$process = self::getProcessBuilder()
->setPrefix('crontab')
->setArguments($processArgs)
->getProcess();
$process->run();
if ($process->getErrorOutput()) {
if (false === strpos($process->getErrorOutput(), 'no crontab for')) {
throw new SystemOperationException(sprintf('Executing error: %s', trim($process->getErrorOutput())));
}
return true; //It means that it's clear so true should be returned.
}
if ($process->getOutput()) {
throw new SystemOperationException(sprintf('Unexpected output: %s', trim($process->getOutput())));
}
return true;
}
/**
* @param null $user
*
* @return bool
* @throws SystemOperationException
*/
public static function isSetUp($user = null)
{
return false !== self::get($user);
}
/**
* @return string
*/
public static function getTemporaryDir()
{
return self::$temporaryDir ?: sys_get_temp_dir();
}
/**
* @param string $temporaryDirectory
*/
public static function setTemporaryDir($temporaryDirectory)
{
self::$temporaryDir = $temporaryDirectory;
}
/**
* @param string|null $osName Default: PHP_OS
*
* @return bool
*/
public static function isUnix($osName = null)
{
if (null === $osName) {
$osName = PHP_OS;
}
return in_array($osName, self::$unixes);
}
/**
* @return array
*/
public static function getUnixList()
{
return self::$unixes;
}
/**
* @param string $name
*
* @return bool
*/
public static function addUnix($name)
{
if (false === in_array($name, self::$unixes)) {
self::$unixes[] = $name;
return true;
}
return false;
}
/**
* @param string $name
*
* @return bool
*/
public static function removeUnix($name)
{
$key = array_search($name, self::$unixes);
if (false !== $key) {
unset(self::$unixes[$key]);
return true;
}
return false;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab;
use Hexmedia\Crontab\Exception\NotManagedException;
use Hexmedia\Crontab\Task;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
/**
* Class CrontabSpec
*
* @package spec\Hexmedia\Crontab
*
* @covers Hexmedia\Crontab\Crontab
*/
class CrontabSpec extends ObjectBehavior
{
public $name = "aaa";
function let()
{
$this->beConstructedWith(null, $this->name);
}
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Crontab');
}
function it_is_possible_to_add_and_remove_managed_task(Task $task)
{
$task->isNotManaged()->willReturn(false);
$task->getName()->willReturn("name");
$this->addTask($task);
$this->getManagedTasks()->shouldHaveCount(1);
$this->removeTask($task);
$this->getManagedTasks()->shouldHaveCount(0);
}
function it_is_possible_to_add_not_managed_task(Task $task)
{
$task->isNotManaged()->willReturn(true);
$task->getName()->willReturn("name");
$this->addTask($task);
$this->getNotManagedTasks()->shouldHaveCount(1);
}
function it_is_possible_to_clear_tasks(Task $task)
{
$task->isNotManaged()->willReturn(false);
$task->getName()->willReturn("name");
$this->addTask($task);
$this->getManagedTasks()->shouldHaveCount(1);
$this->clearManagedTasks();
$this->getManagedTasks()->shouldHaveCount(0);
}
function it_is_correctly_returing_name()
{
$this->getName()->shouldReturn($this->name);
}
function it_is_allowing_to_remove_taks(Task $task)
{
$task->isNotManaged()->willReturn(false);
$task->getName()->willReturn("Some Name");
$this->getManagedTasks()->shouldHaveCount(0);
$this->addTask($task);
$this->getManagedTasks()->shouldHaveCount(1);
$this->removeTask($task)->shouldReturn($this);
$this->getManagedTasks()->shouldHaveCount(0);
}
function it_is_not_allowing_to_remove_non_existing_task(Task $task)
{
$task->isNotManaged()->willReturn(false);
$task->getName()->willReturn("Some Name");
$this->getManagedTasks()->shouldHaveCount(0);
$this->removeTask($task)->shouldReturn($this);
$this->getManagedTasks()->shouldHaveCount(0);
}
function it_is_not_allowing_to_remove_not_managed_task(Task $task)
{
$task->isNotManaged()->willReturn(true);
$task->getName()->willReturn("Some Name");
$this->getNotManagedTasks()->shouldHaveCount(0);
$this->addTask($task);
$this->getNotManagedTasks()->shouldHaveCount(1);
$this
->shouldThrow(new NotManagedException("This task is not managed by this application so you cannot remove it!"))
->duringRemoveTask($task);
}
function it_is_returning_user()
{
$this->getUser()->shouldReturn(null);
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project name="hexmedia/crontab" default="build" phingVersion=">=2">
<!-- This variables should be provided by user with -D options. I'm thinking about disallowing to build without them -->
<property name="deps" value="normal"/>
<property name="citool" value="local"/>
<property name="phpversion" value="${php.version}"/>
<property name="coveralls" value="false"/>
<property name="build.report.dir" value="./build/report"/>
<property name="build.report.dir.phpmd" value="${build.report.dir}/phpmd"/>
<property name="build.report.dir.phpspec" value="${build.report.dir}/phpspec/"/>
<property name="build.report.dir.phpcs" value="${build.report.dir}/phpcs"/>
<property name="build.report.dir.phploc" value="${build.report.dir}/phploc"/>
<property name="build.report.dir.phpdcd" value="${build.report.dir}/phpdcd"/>
<property name="build.report.dir.behat" value="${build.report.dir}/behat"/>
<property name="build.phpcs.standard"
value="${project.basedir}/vendor/hexmedia/code-style/src/Hexmedia/"/>
<property name="build.config.dir" value="${build.dir}/config"/>
<property name="build.config.file.phpmd" value="${build.config.dir}/phpmd.xml"/>
<property name="build.config.file.phpspec" value="${build.config.dir}/phpspec.yml"/>
<property name="vendor" value="${project.basedir}/vendor"/>
<property name="bin" value="${vendor}/bin"/>
<property name="src" value="${project.basedir}/src"/>
<property name="build.dir" value="${project.basedir}/build"/>
<property name="composer.file" value="composer.phar"/><!-- For windows -->
<property environment="env"/>
<php expression="include('vendor/autoload.php');" level="debug"/>
<fileset id="project" dir="${src}">
<include name="**/*.php"></include>
</fileset>
<target name="composer-check">
<if>
<not>
<os family="windows"></os>
</not>
<then>
<exec executable="which" outputProperty="composer.file">
<arg line="composer"/>
</exec>
<if>
<available file="${composer.file}" property="composer.exists"/>
<then>
</then>
<else>
<if>
<equals arg1="${citool}" arg2="local"/>
<then>
<input message="Enter path to your composer file: " propertyName="composer.file"/>
</then>
</if>
</else>
</if>
</then>
</if>
</target>
<target name="do-composer">
<if>
<equals arg1="${citool}" arg2="appveyor"/>
<then>
<echo message="Cannot call composer on AppVeyor"/>
</then>
<else>
<composer command="${composer.temporary.command}" composer="${composer.file}"/>
</else>
</if>
</target>
<target name="composer" depends="composer-check">
<phingcall target="do-composer">
<param name="composer.temporary.command" value="update"/>
</phingcall>
<composer command="install" composer="${composer.file}"/>
</target>
<target name="prepare">
<echo msg="Creating build directories..."/>
<delete includeemptydirs="true">
<fileset dir="${build.report.dir}" includes="**/*"/>
</delete>
<mkdir dir="${build.report.dir}"/>
<mkdir dir="${build.report.dir.phpcs}"/>
<mkdir dir="${build.report.dir.phpmd}"/>
<mkdir dir="${build.report.dir.phploc}"/>
<mkdir dir="${build.report.dir.phpspec}"/>
<mkdir dir="${build.report.dir.phpdcd}"/>
<mkdir dir="${build.report.dir.behat}"/>
</target>
<target name="rename-configuration-file">
<property name="exists" value="false"/>
<available file="${file}.${citool}" type="file" property="exists"/>
<if>
<istrue value="${exists}"/>
<then>
<delete file="${file}"/>
<copy file="${file}.${citool}" tofile="${file}"/>
</then>
</if>
</target>
<target name="configuration-files">
<!-- especially for travis -->
<if>
<and>
<equals arg1="${citool}" arg2="travis"/>
<equals arg1="${deps}" arg2="normal"/>
<equals arg1="${coveralls}" arg2="true"/>
</and>
<then>
<delete file="${build.config.file.phpspec}.travis"/>
<copy file="${build.config.file.phpspec}.normal.travis"
tofile="${build.config.file.phpspec}.travis"/>
</then>
</if>
<phingcall target="rename-configuration-file">
<property name="file" value="${build.config.file.phpmd}"/>
<property name="citool" value="${citool}"/>
</phingcall>
<phingcall target="rename-configuration-file">
<property name="file" value="${build.config.file.phpspec}"/>
<property name="citool" value="${citool}"/>
</phingcall>
</target>
<target name="phpspec" depends="configuration-files">
<exec dir="${project.basedir}" executable="${bin}/phpspec" checkreturn="true" passthru="true">
<arg line="--config=${build.config.file.phpspec}"/>
<arg line="run"/>
<arg line="-vvv"/>
</exec>
</target>
<target name="phpspec-local">
<exec dir="${project.basedir}" executable="${bin}/phpspec" output="${build.report.dir.phpspec}/report.xml"
checkreturn="true">
<arg line="run"/>
<arg line="-c"/>
<arg path="${build.config.file.phpspec}"/>
</exec>
</target>
<target name="behat">
<if>
<not>
<equals arg1="${citool}" arg2="appveyor"/>
</not>
<then>
<if>
<equals arg1="${citool}" arg2="travis"/>
<then>
<exec dir="${project.basedir}" executable="${bin}/behat" checkreturn="true" passthru="true">
<arg value="-s"/>
<arg value="travis"/>
</exec>
</then>
</if>
<exec dir="${project.basedir}" executable="${bin}/behat" checkreturn="true" passthru="true">
<arg value="-s"/>
<arg value="default"/>
</exec>
</then>
</if>
</target>
<target name="phpmd" depends="configuration-files">
<exec dir="${project.basedir}" executable="${bin}/phpmd" output="${build.report.dir.phpmd}/report.xml"
checkreturn="true">
<arg line="${src}"/>
<arg line="xml"/>
<arg line="${build.config.file.phpmd}"/>
</exec>
</target>
<target name="phpmd-local">
<exec dir="${project.basedir}" executable="${bin}/phpmd" output="${build.report.dir.phpmd}/report.html"
checkreturn="true"
passthru="true">
<arg line="${src}"/>
<arg line="html"/>
<arg line="${build.config.file.phpmd}"/>
</exec>
</target>
<target name="phpcs">
<phpcodesniffer haltonerror="true" haltonwarning="true" verbosity="1" standard="${build.phpcs.standard}">
<formatter type="full" outfile="${build.report.dir.phpcs}/report.txt"/>
<fileset refid="project"/>
</phpcodesniffer>
</target>
<target name="phpcbf">
<exec dir="${project.basedir}" executable="${bin}/phpcbf">
<arg line="-w"/>
<arg line="--standard=${build.phpcs.standard}"/>
<arg line="${src}"/>
</exec>
</target>
<target name="phploc">
<phploc reportDirectory="${build.report.dir.phploc}" reportType="xml" reportName="report">
<fileset refid="project"/>
</phploc>
</target>
<target name="phploc-local">
<phploc reportDirectory="${build.report.dir.phploc}" reportType="txt" reportName="report">
<fileset refid="project"/>
</phploc>
</target>
<target name="phpcpd">
<phpcpd>
<fileset refid="project"/>
</phpcpd>
</target>
<target name="phpdcd">
<exec dir="${project.basedir}" command="${bin}/phpdcd" output="${build.report.dir.phpdcd}/report.txt">
<arg line="${src}"/>
</exec>
</target>
<target name="jsonlint-file">
<echo message="Checking file: ${absname}" level="debug"/>
<exec executable="${bin}/jsonlint" dir="${project.basedir}">
<arg line="${absname}"/>
</exec>
</target>
<target name="yamllint-file">
<echo message="Checking file: ${absname}" level="debug"/>
<exec executable="${bin}/yaml-lint" dir="${project.basedir}" outputProperty="response">
<arg line="${absname}"/>
</exec>
<if>
<contains string="${response}" substring="Unable to parse"/>
<then>
<echo message="${response}"/>
<fail message="Error linting yaml file: ${absname}."/>
</then>
</if>
</target>
<target name="xmllint-file">
<echo message="Checkint file: ${absname}" level="debug"/>
<exec executable="xmllint" dir="${project.basedir}" outputProperty="response">
<arg line="${absname}"/>
</exec>
<if>
<contains string="${response}" substring="parser error"/>
<then>
<echo message="${response}" level="error"/>
<fail message="Error linting xml file ${absname}."/>
</then>
</if>
</target>
<target name="lint-files">
<echo message="Running ${target-task} for ${project.basedir} with **/*.${target-extension}" level="info"/>
<foreach param="${project.basedir}" absparam="absname" target="${target-task}">
<fileset dir="${project.basedir}">
<type type="file"/>
<include name="**/*.${target-extension}"/>
<exclude name="vendor/**/*"/>
<exclude name="build.xml"/>
</fileset>
</foreach>
</target>
<target name="jsonlint">
<phingcall target="lint-files">
<param name="target-task" value="jsonlint-file"/>
<param name="target-extension" value="json"/>
</phingcall>
</target>
<target name="yamllint">
<echo message="Running yamllint files."/>
<phingcall target="lint-files">
<param name="target-task" value="yamllint-file"/>
<param name="target-extension" value="yaml"/>
</phingcall>
<phingcall target="lint-files">
<param name="target-task" value="yamllint-file"/>
<param name="target-extension" value="yml"/>
</phingcall>
</target>
<target name="xmllint">
<if>
<and>
<os family="Unix"></os>
<!--<available property="xmllint.available" file="${env.PATH}/xmllint"/>-->
</and>
<then>
<phingcall target="lint-files">
<param name="target-task" value="xmllint-file"/>
<param name="target-extension" value="xml"/>
</phingcall>
</then>
<else>
<echo message="Trying to run xmllint on non Unix system. Or without xmllint installed." level="error"/>
</else>
</if>
</target>
<target name="travislint">
<if>
<and>
<os family="Unix"></os>
<not>
<equals arg1="${citool}" arg2="travis"/>
</not>
</and>
<then>
<exec executable="which" outputProperty="travis.command">
<arg line="travis"/>
</exec>
<echo message="Travis command is: '${travis.command}'"/>
<if>
<and>
<not>
<equals arg1="${travis.command}" arg2=""/>
</not>
<available property="travis.exists" file="${travis.command}"/>
</and>
<then>
<exec executable="${travis.command}" checkreturn="true" outputProperty="travis.output">
<arg line="lint"/>
</exec>
<if>
<contains string="${travis.output}" substring="Warnings for .travis.yml"
casesensitive="true"/>
<then>
<echo message="${travis.output}" level="warning"/>
<fail message="Travis crontab is wrong!"/>
</then>
</if>
</then>
<else>
<echo message="Will not check travis."/>
</else>
</if>
</then>
<else>
<echo message="Will not check travis."/>
</else>
</if>
</target>
<target name="composerlint" depends="composer-check">
<phingcall target="do-composer">
<param name="composer.temporary.command" value="validate"/>
</phingcall>
</target>
<!-- Full tasks -->
<target name="lint" depends="composerlint,travislint,jsonlint,yamllint,xmllint"/>
<target name="tests" depends="phpmd, phpcs, phploc, phpcpd, phpspec, behat"/>
<target name="tests-local" depends="phpmd-local, phpspec-local, behat, phpcs, phploc-local, phpcpd"/>
<target name="build" depends="prepare,lint,tests-local"/>
<target name="continous" depends="prepare,lint,tests"/>
</project>
<file_sep><?php
namespace spec\Hexmedia\Crontab\Parser\Xml;
use dev\Hexmedia\Crontab\PhpSpec\Parser\AbstractXmlParserObjectBehavior;
use Prophecy\Argument;
class PhpParserSpec extends AbstractXmlParserObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Parser\Xml\PhpParser');
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Parser;
use Hexmedia\Crontab\Exception\ParsingException;
/**
* Class ParserAbstract
*
* @package Hexmedia\Crontab\Parser
*/
abstract class AbstractParser implements ParserInterface
{
/**
* @var string
*/
private $content;
/**
* @var string
*/
private $file;
/**
* AbstractParser constructor.
*
* @param string $content
* @param string $file
*/
public function __construct($content, $file)
{
$this->content = $content;
$this->file = $file;
}
/**
* @return string
*/
protected function getContent()
{
return $this->content;
}
/**
* @return string
*/
protected function getFile()
{
return $this->file;
}
/**
*
*/
protected function setTemporaryErrorHandler()
{
set_error_handler(
function ($errorNumber, $errorString) {
throw new ParsingException(sprintf('Cannot parse this file: (%d) %s', $errorNumber, $errorString));
},
E_ALL
);
}
/**
*
*/
protected function restoreErrorHandler()
{
restore_error_handler();
}
}
<file_sep>#!/usr/bin/env php
<?php
require dirname(__DIR__) . "/vendor/autoload.php";
$application = new \Hexmedia\Crontab\Application();
$application->run();
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Parser\Xml;
use Hexmedia\Crontab\Exception\ParsingException;
use Hexmedia\Crontab\Parser\AbstractParser;
/**
* Class PhpParser
*
* @package Hexmedia\Crontab\Parser\Xml
*/
class PhpParser extends AbstractParser
{
/**
* @return array
*
* @throws ParsingException
*/
public function parse()
{
try {
$xml = new \SimpleXMLElement($this->getContent());
} catch (\Exception $e) {
throw new ParsingException("Cannot parse this file: " . $e->getMessage());
}
$parsed = $this->convertToArray($xml);
return $parsed;
}
/**
* @return bool
*/
public static function isSupported()
{
return true; //This is supported in php
}
/**
* @param \SimpleXMLElement $xml
*
* @return array
*/
private function convertToArray($xml)
{
$responseArray = array();
foreach ($xml->task as $task) {
$responseArray[(string) $task->name] = $this->taskToArray($task);
}
return $responseArray;
}
/**
* @param \SimpleXMLElement $task
*
* @return array
*/
private function taskToArray($task)
{
$taskArray = array();
$taskArray['command'] = (string) $task->command;
$taskArray['month'] = (string) $task->month;
$taskArray['day_of_month'] = (string) $task->dayOfMonth;
$taskArray['day_of_week'] = (string) $task->dayOfWeek;
$taskArray['hour'] = (string) $task->hour;
$taskArray['minute'] = (string) $task->minute;
$taskArray['machine'] = (string) $task->machine;
if ((string) $task->comment) {
$taskArray['comment'] = (string) $task->comment;
}
if ((string) $task->logFile) {
$taskArray['log_file'] = (string) $task->logFile;
}
if ($task->variables) {
$taskArray['variables'] = $this->parseVariables($task->variables->variable);
}
return $taskArray;
}
/**
* @param \SimpleXMLElement[] $variables
*
* @return array
*/
private function parseVariables($variables)
{
$variablesArray = array();
/** @var \SimpleXMLElement $variable */
foreach ($variables as $variable) {
$variablesArray[(string) $variable->attributes()->name] = (string) $variable;
}
return $variablesArray;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab\Reader;
use dev\Hexmedia\Crontab\PhpSpec\SystemAwareObjectBehavior;
use Prophecy\Argument;
/**
* Class UnixSystemReaderSpec
* @package spec\Hexmedia\Crontab\Reader
*
* @method string read()
* @method static bool isSupported()
* @method static $this addSupportedOs(string $name)
* @method static $this removeSupportedOs(string $name)
* @method static array getSupportedOses()
*/
class UnixSystemReaderSpec extends SystemAwareObjectBehavior
{
function let()
{
$this->isSystemSupported();
$this->beConstructedWith(null, null);
}
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Reader\UnixSystemReader');
$this->shouldImplement('Hexmedia\Crontab\Reader\AbstractUnixReader');
}
function it_is_supported()
{
$this::isSupported()->shouldReturn(in_array(PHP_OS, array('Linux', "FreeBSD")));
}
function it_allows_to_read()
{
$readed = $this->read();
$readed->shouldHaveType('Hexmedia\Crontab\Crontab');
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab\System;
use Hexmedia\Crontab\Exception\SystemOperationException;
use Hexmedia\Crontab\System\Unix;
use PhpSpec\ObjectBehavior;
use PhpSpec\Wrapper\Subject;
use Prophecy\Argument;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\ProcessBuilder;
/**
* Class SaverToolSpec
*
* @package spec\Hexmedia\Crontab\Writer\System\Unix
*
* This class cannot be tested without calling real save.
*/
class UnixSpec extends ObjectBehavior
{
function let(ProcessBuilder $processBuilder, Process $process)
{
$processBuilder->setPrefix("crontab")->willReturn($processBuilder);
$processBuilder->getProcess()->willReturn($process);
$process->run()->willReturn(true);
$this::setProcessBuilder($processBuilder);
}
function letGo()
{
$this::setProcessBuilder(null);
}
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\System\Unix');
}
function it_has_default_porcess_builder()
{
$this::getProcessBuilder()->shouldHaveType('Symfony\Component\Process\ProcessBuilder');
}
function it_does_not_allow_to_add_second_time()
{
$this::addUnix("Foo")->shouldReturn(true);
$this::addUnix("Foo")->shouldReturn(false);
$this::removeUnix("Foo");
}
function it_allows_to_check_if_custom_name_is_unix()
{
$this::isUnix("WINNT")->shouldReturn(false);
$this::isUnix("FreeBSD")->shouldReturn(true);
$this::isUnix("Linux")->shouldReturn(true);
}
function it_can_check_if_it_is_unix()
{
if (PHP_OS === "Linux" || PHP_OS === "FreeBSD") {
$this::isUnix()->shouldReturn(true);
} else {
$this::isUnix()->shouldReturn(false);
}
}
function it_is_allowed_to_get($processBuilder, $process)
{
$processBuilder->setArguments(array("-l"))->willReturn($processBuilder);
$process->run()->willReturn(null);
$process->getErrorOutput()->willReturn(null);
$process->getOutput()->willReturn("#some response");
$this::get()->shouldReturn("#some response");
}
function it_is_not_allowed_to_get_for_wrong_user($processBuilder, $process)
{
$processBuilder->setArguments(array("-l", "-u", "sdg4o"))->willReturn($processBuilder);
$process->getErrorOutput()->willReturn("crontab: user `sdg4o' unknown");
$process->getOutput()->shouldNotBeCalled();
$process->run()->wilLReturn(true);
$this
->shouldThrow(new SystemOperationException("Executing error: crontab: user `sdg4o' unknown"))
->during('get', array("sdg4o"));
}
function it_is_returning_false_when_there_is_no_crontab_for_user($processBuilder, $process)
{
$processBuilder->setArguments(array("-l"))->willReturn($processBuilder);
$process->run()->willReturn(null);
$process->getErrorOutput()->willReturn("no crontab for user kkuczek");
$process->getOutput()->shouldNotBeCalled();
$this::get()->shouldReturn(false);
}
function it_is_allowing_to_save($processBuilder, $process)
{
$content = "#TEST";
$processBuilder->setArguments(
Argument::that(
function ($argument) use ($content) {
return
1 === sizeof($argument)
&& 0 == strpos("/tmp/", $argument[0])
//Checking content of temporary file;
&& file_exists($argument[0])
&& file_get_contents($argument[0]) === $content;
}
)
)->willReturn($processBuilder); //Maybe we should do better test here
$process->run()->willReturn(true);
$process->getErrorOutput()->willReturn(null);
$process->getOutput()->willReturn('');
$this::save($content)->shouldReturn(true);
}
function it_throws_exception_when_unknown_output($processBuilder, $process)
{
$content = "#TEST";
$processBuilder->setArguments(
Argument::that(
function ($argument) use ($content) {
return
1 === sizeof($argument)
&& 0 == strpos("/tmp/", $argument[0])
//Checking content of temporary file;
&& file_exists($argument[0])
&& file_get_contents($argument[0]) === $content;
}
)
)->willReturn($processBuilder); //Maybe we should do better test here
$process->run()->willReturn(true);
$process->getErrorOutput()->willReturn(null);
$process->getOutput()->willReturn('some error');
$this->shouldThrow(new SystemOperationException("Unexpected output: some error"))
->duringSave($content);
}
function it_is_not_allowing_to_save_unknown_user($processBuilder, $process)
{
$content = "# some content";
$processBuilder->setArguments(
Argument::that(
function ($argument) use ($content) {
return
3 === sizeof($argument)
&& "-u" === $argument[0]
&& "sdg4o" === $argument[1]
&& 0 == strpos("/tmp/", $argument[2])
//Checking content of temporary file;
&& file_exists($argument[2])
&& file_get_contents($argument[2]) === $content;
}
)
)->willReturn($processBuilder);
$process->getErrorOutput()->willReturn("crontab: user `sdg4o' unknown");
$this
->shouldThrow(new SystemOperationException("Executing error: crontab: user `sdg4o' unknown"))
->during('save', array($content, 'sdg4o'));
}
function it_is_allowed_to_clear_whole_crontab($processBuilder, $process)
{
$processBuilder->setArguments(array("-r"))->willReturn($processBuilder);
$process->getErrorOutput()->willReturn(false);
$process->getOutput()->willReturn('');
$this::clear();
}
function it_is_not_allowed_to_clear_for_unexisting_user($processBuilder, $process)
{
$processBuilder->setArguments(array('-u', 'sdg4o', '-r'))->willReturn($processBuilder);
$process->getErrorOutput()->willReturn("crontab: user `sdg4o' unknown");
$process->run()->willReturn('');
$this
->shouldThrow(new SystemOperationException("Executing error: crontab: user `sdg4o' unknown"))
->during('clear', array('sdg4o'));
}
function it_is_returning_true_when_trying_to_clear_cleared_crontab($processBuilder, $process)
{
$processBuilder->setArguments(array('-r'))->willReturn($processBuilder);
$process->getErrorOutput()->willReturn("no crontab for user a");
$process->getOutput()->shouldNotBeCalled();
$this::clear()->shouldReturn(true);
}
function it_throws_exception_when_clear_will_return_unexpected_output($processBuilder, $process)
{
$content = "#TEST";
$processBuilder->setArguments(array("-r"))->willReturn($processBuilder); //Maybe we should do better test here
$process->run()->willReturn(true);
$process->getErrorOutput()->willReturn(null);
$process->getOutput()->willReturn('some error');
$this->shouldThrow(new SystemOperationException("Unexpected output: some error"))
->duringClear();
}
function it_has_default_temporary_directory()
{
$this::getTemporaryDir()->shouldReturn(sys_get_temp_dir());
}
function it_is_able_to_set_temporary_directory()
{
$this::setTemporaryDir("/tmp2");
$this::getTemporaryDir()->shouldReturn("/tmp2");
$this::setTemporaryDir(null);
$this::getTemporaryDir()->shouldReturn(sys_get_temp_dir());
}
function it_allows_to_get_all_supported_os()
{
$this::getUnixList()->shouldHaveCount(3);
}
function it_allows_to_add_supported_os()
{
$this::addUnix("Foo")->shouldReturn(true);
$this::getUnixList()->shouldHaveCount(4);
}
function it_allows_to_remove_supported_os()
{
$this::removeUnix("Foo")->shouldReturn(true);
$this::getUnixList()->shouldHaveCount(3);
}
function it_do_not_allows_to_remove_unexisting_supported_os()
{
$this::removeUnix("WinNT")->shouldReturn(false);
$this::getUnixList()->shouldHaveCount(3);
}
function it_allows_to_set_temporary_dir()
{
$dir = "/var/tmp";
$this::setTemporaryDir($dir);
$this::getTemporaryDir()->shouldReturn($dir);
}
function it_allows_to_check_if_crontab_is_setup($processBuilder, $process)
{
$processBuilder->setArguments(array("-l"))->willReturn($processBuilder);
$process->run()->willReturn(null);
$process->getErrorOutput()->willReturn(null);
$process->getOutput()->willReturn("#some response");
$this::isSetUp()->shouldReturn(true);
}
function it_allows_to_check_if_crontab_is_not_setup($processBuilder, $process)
{
$processBuilder->setArguments(array("-l"))->willReturn($processBuilder);
$process->run()->willReturn(null);
$process->getErrorOutput()->willReturn(null);
$process->getOutput()->willReturn(false);
$this::isSetUp()->shouldReturn(false);
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Parser\Ini;
use Hexmedia\Crontab\Parser\AbstractParserFactory;
/**
* Class ParserFactory
*
* @package Hexmedia\Crontab\Parser\Ini
*/
class ParserFactory extends AbstractParserFactory
{
/**
* @return array
*/
public function getDefaultParsers()
{
$supported = array();
if (!defined("HHVM_VERSION")) {
$supported[] = '\Hexmedia\Crontab\Parser\Ini\Zend2Parser';
$supported[] = '\Hexmedia\Crontab\Parser\Ini\ZendParser';
}
$supported[] = '\Hexmedia\Crontab\Parser\Ini\AustinHydeParser';
return $supported;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace dev\Hexmedia\Crontab\PhpSpec\Parser;
/**
* Class AbstractYamlParserObjectBehavior
*
* @package dev\Hexmedia\Crontab\PhpSpec\Parser
*/
class AbstractYamlParserObjectBehavior extends AbstractParserObjectBehavior
{
protected function getFileName()
{
return __DIR__ . '/../../../Tests/example_configurations/test.yml';
}
}
<file_sep>Crontab
=======
[](https://travis-ci.org/Hexmedia/Crontab) [](https://ci.appveyor.com/project/kuczek/crontab/history) [](https://insight.sensiolabs.com/projects/bb22e198-7f34-4a13-a70c-03442493f827) [](https://coveralls.io/github/Hexmedia/Crontab?branch=master)
[](https://packagist.org/packages/hexmedia/crontab) [](https://packagist.org/packages/hexmedia/crontab) [](https://packagist.org/packages/hexmedia/crontab) [](https://packagist.org/packages/hexmedia/crontab)
Library for managing crontab on your system.
Currently supports only FreeBSD and Linux devices, for other devices see section: [Other Unix Like crontab systems](#other-unix-like-crontab-systems)
Installation
------------
### Phar file
add instruction
### Global composer
composer.phar global require hexmedia/crontab
### For project
composer.phar require hexmedia/crontab
Usage
-----
### Other Unix Like crontab systems
If your system is not identified as Linux or FreeBSD, you can easily add support for them by adding this code to
your application:
```
Hexmedia\Crontab\Reader\SystemUnixReader::addSupportedOs("FreeBSD");
```
Known problems
--------------
* Does not support special crontab values like @daily, @yearly
* Does not support correctly comments between variables
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace dev\Hexmedia\Crontab\PhpSpec\Parser;
/**
* Class AbstractIniParserObjectBehavior
*
* @package Hexmedia\CrontabDev\PhpSpec\Parser
*/
abstract class AbstractIniParserObjectBehavior extends AbstractParserObjectBehavior
{
protected function getFileName()
{
return __DIR__ . '/../../../Tests/example_configurations/test.ini';
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Reader;
use Hexmedia\Crontab\Parser\Xml\ParserFactory;
/**
* Class XmlReader
*
* @package Hexmedia\Crontab\Reader
*/
class XmlReader extends AbstractFileReader implements ReaderInterface
{
/**
* @return array
*/
protected function getParserFactory()
{
return new ParserFactory();
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Reader;
use Hexmedia\Crontab\Crontab;
use Hexmedia\Crontab\Exception\ClassNotExistsException;
use Hexmedia\Crontab\Exception\NotReaderFoundForOSException;
/**
* Class SystemReader
*
* @package Hexmedia\Crontab\Reader
*/
class SystemReader implements ReaderInterface
{
private $readers = array(
'\\Hexmedia\\Crontab\\Reader\\UnixSystemReader',
);
/**
* @var string
*/
private $user;
/**
* @var Crontab
*/
private $crontab;
/**
* @var ReaderInterface
*/
private $reader;
/**
* SystemReader constructor.
*
* @param string $user
* @param Crontab|null $crontab
*/
public function __construct($user, Crontab $crontab = null)
{
$this->user = $user;
$this->crontab = $crontab;
$this->reader = $this->getSystemReader();
}
/**
* @return Crontab
*/
public function read()
{
return $this->reader->read();
}
/**
* @return array
*/
public function getReaders()
{
return $this->readers;
}
/**
* @param string $reader
*
* @return $this ;
* @throws ClassNotExistsException
*/
public function addReader($reader)
{
$reader = $this->fixReaderName($reader);
if (false === class_exists($reader)) {
throw new ClassNotExistsException(
sprintf("Class %s does not exists. Cannot be added as Reader.", $reader)
);
}
if (false === in_array($reader, $this->readers)) {
$this->readers[] = $reader;
$this->readers = array_values($this->readers); //FIXME: Why this is needed?
}
return $this;
}
/**
* @param string $reader
*
* @return $this;
*/
public function removeReader($reader)
{
$key = array_search($this->fixReaderName($reader), $this->readers);
if (false !== $key) {
unset($this->readers[$key]);
}
return $this;
}
/**
* @return ReaderInterface
* @throws NotReaderFoundForOSException
*/
private function getSystemReader()
{
foreach ($this->readers as $reader) {
if (false !== call_user_func($reader . '::isSupported')) {
return new $reader($this->user, $this->crontab);
}
}
throw new NotReaderFoundForOSException(sprintf("There is no reader for your operating system '%s'", PHP_OS));
}
/**
* @param string $name
*
* @return string
*/
private function fixReaderName($name)
{
return '\\' . trim($name, '\\');
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Parser\Json;
use Hexmedia\Crontab\Exception\ParsingException;
use Hexmedia\Crontab\Parser\AbstractParser;
/**
* Class PhpParser
*
* @package Hexmedia\Crontab\Parser\Json
*/
class PhpParser extends AbstractParser
{
/**
* @return array
*
* @throws ParsingException
*/
public function parse()
{
$this->setTemporaryErrorHandler();
$parsed = json_decode($this->getContent(), true);
if (null === $parsed) {
throw new ParsingException("Cannot parse file!");
}
$this->restoreErrorHandler();
return $parsed;
}
/**
* @return bool
*/
public static function isSupported()
{
return true; //This is supported in php
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab\Parser\Yaml;
use dev\Hexmedia\Crontab\PhpSpec\Parser\FactoryObjectBehavior;
use Prophecy\Argument;
class ParserFactorySpec extends FactoryObjectBehavior
{
protected function getType()
{
return "Yaml";
}
protected function getWorkingParser()
{
return "SymfonyParser";
}
protected function getParsersCount()
{
if (defined("HHVM_VERSION")) {
return 1;
}
return 2;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab;
use Hexmedia\Crontab\Exception\NotManagedException;
/**
* Class Crontab
*
* @package Hexmedia\Crontab
*/
class Crontab
{
/**
* @var string Unique hash for this crontab list
*/
private $name;
/**
* @var Task[]
*/
private $managedTasks = array();
/**
* @var Task[]
*/
private $notManagedTasks = array();
/**
* @var string|null
*/
private $user = null;
/**
* @param string|null $user
* @param string|null $name
*/
public function __construct($user = null, $name = null)
{
$this->user = $user;
$this->name = $name;
}
/**
* @return null|string
*/
public function getName()
{
return $this->name;
}
/**
* @param Task $task
*
* @return $this
*/
public function addTask(Task $task)
{
if ($task->isNotManaged()) {
$this->notManagedTasks[] = $task;
} else {
$this->managedTasks[$task->getName()] = $task;
}
return $this;
}
/**
* @param Task $task
*
* @return $this
* @throws NotManagedException
*/
public function removeTask(Task $task)
{
if ($task->isNotManaged()) {
throw new NotManagedException('This task is not managed by this application so you cannot remove it!');
}
foreach ($this->managedTasks as $key => $taskIteration) {
if ($taskIteration->getName() === $task->getName()) {
unset($this->managedTasks[$key]);
}
}
return $this;
}
/**
* @return \Hexmedia\Crontab\Task[]
*/
public function getManagedTasks()
{
return $this->managedTasks;
}
/**
* @return \Hexmedia\Crontab\Task[]
*/
public function getNotManagedTasks()
{
return $this->notManagedTasks;
}
/**
* @return $this
*/
public function clearManagedTasks()
{
$this->managedTasks = array();
return $this;
}
/**
* @return null|string
*/
public function getUser()
{
return $this->user;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Console;
use Hexmedia\Crontab\Crontab;
use Hexmedia\Crontab\Reader\SystemReader;
use Hexmedia\Crontab\Writer\SystemWriter;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class ClearCommand
*
* @package Hexmedia\Crontab\Console
*/
class ClearCommand extends AbstractCommand
{
/**
* @param OutputInterface $output
* @param Crontab $crontab
* @param string|null $user
*
* @return mixed
*/
public function output(OutputInterface $output, Crontab $crontab, $user = null)
{
$crontab->clearManagedTasks();
$writer = new SystemWriter(array('user' => $user));
$writer->write($crontab);
$output->writeln('Your crontab was updated!');
}
/**
*
*/
protected function configureName()
{
$this
->setName('clear')
->setDescription('Clear this project crontabs from this machine');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*
* @return null
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$name = $input->getArgument('name');
$user = $input->getOption('user');
$crontab = new Crontab($user, $name);
$systemReader = new SystemReader($user, $crontab);
$systemReader->read();
$crontab->clearManagedTasks();
$this->output($output, $crontab, $user);
}
/**
*
*/
protected function configureArguments()
{
$this
->addArgument('name', InputArgument::REQUIRED, 'Name of project')
->addArgument('configuration-file', InputArgument::OPTIONAL, 'Configuration file');
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Reader;
use Hexmedia\Crontab\Crontab;
/**
* Interface ReaderInterface
*
* @package Hexmedia\Crontab\Reader
*/
interface ReaderInterface
{
/**
* @return Crontab
*/
public function read();
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab;
/**
* Class Task
*
* @package Hexmedia\Crontab
*/
class Task
{
/**
* @var array
*/
private $variables = array();
/**
* @var string
*/
private $minute = '*';
/**
* @var string
*/
private $hour = '*';
/**
* @var string
*/
private $dayOfMonth = '*';
/**
* @var string
*/
private $month = '*';
/**
* @var string
*/
private $dayOfWeek = '*';
/**
* @var string
*/
private $command;
/**
* @var string
*/
private $beforeComment;
/**
* @var string
*/
private $logFile;
/**
* @var string
*/
private $name;
/**
* @var bool
*/
private $notManaged;
/**
* @return Variables[]
*/
public function getVariables()
{
return $this->variables;
}
/**
* @param Variables $variables
*
* @return $this
*/
public function setVariables(Variables $variables)
{
$this->variables = $variables;
return $this;
}
/**
* @return string
*/
public function getCommand()
{
return $this->command;
}
/**
* @param string $command
*
* @return $this;
*/
public function setCommand($command)
{
$this->command = $command;
return $this;
}
/**
* @return string
*/
public function getDayOfMonth()
{
return $this->dayOfMonth;
}
/**
* @param string $dayOfMonth
*
* @return $this;
*/
public function setDayOfMonth($dayOfMonth)
{
$this->dayOfMonth = $dayOfMonth;
return $this;
}
/**
* @return string
*/
public function getDayOfWeek()
{
return $this->dayOfWeek;
}
/**
* @param string $dayOfWeek
*
* @return $this;
*/
public function setDayOfWeek($dayOfWeek)
{
$this->dayOfWeek = $dayOfWeek;
return $this;
}
/**
* @return string
*/
public function getHour()
{
return $this->hour;
}
/**
* @param string $hour
*
* @return $this;
*/
public function setHour($hour)
{
$this->hour = $hour;
return $this;
}
/**
* @return string
*/
public function getLogFile()
{
return $this->logFile;
}
/**
* @param string $logFile
*
* @return $this;
*/
public function setLogFile($logFile)
{
$this->logFile = $logFile;
return $this;
}
/**
* @return string
*/
public function getMinute()
{
return $this->minute;
}
/**
* @param string $minute
*
* @return $this;
*/
public function setMinute($minute)
{
$this->minute = $minute;
return $this;
}
/**
* @return string
*/
public function getMonth()
{
return $this->month;
}
/**
* @param string $month
*
* @return $this;
*/
public function setMonth($month)
{
$this->month = $month;
return $this;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*
* @return $this;
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return boolean
*/
public function isNotManaged()
{
return $this->notManaged;
}
/**
* @param boolean $notManaged
*
* @return $this;
*/
public function setNotManaged($notManaged)
{
$this->notManaged = true === $notManaged;
return $this;
}
/**
* @param string $name
*/
public function setMd5Name($name)
{
$this->setName(substr(md5($name), 10));
}
/**
* @return string
*/
public function getBeforeComment()
{
return $this->beforeComment;
}
/**
* @param string $beforeComment
*
* @return $this;
*/
public function setBeforeComment($beforeComment)
{
$this->beforeComment = $beforeComment;
return $this;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab\Parser\Unix;
use Hexmedia\Crontab\Exception\ParseException;
use Hexmedia\Crontab\Parser\Unix\UnixParser;
use Hexmedia\Crontab\Parser\Unix\UnixParserAbstract;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class UnixParserSpec extends ObjectBehavior
{
function let()
{
$file = __DIR__ . '/../../../example_configurations/test.unix';
$content = file_get_contents($file);
$this->beConstructedWith($content, null);
}
function it_is_not_working_with_wrong_file()
{
$file = __DIR__ . '/../../../example_configurations/test.ini';
$content = file_get_contents($file);
$this->beConstructedWith($content, null);
$this->shouldThrow(new ParseException('Cannot match this file error: \'wrong file format\''))->duringParse();
}
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Parser\Unix\UnixParser');
// $this->shouldImplement('Hexmedia\Crontab\Parser\Unix\AbstractParser');
}
function it_is_loading_file_correctly()
{
$parsed = $this->parse();
$parsed->shouldHaveCount(4);
$commands = array(
'./mwe:photo:s3 asgasg afasf',
'./crobtabaction.php -- -pht',
'ant build',
'. ./do some thing98',
);
$minutes = array('*/26', "13", '50', "*");
$hours = array('*/14', "23", "13", "*");
$dayOfMonth = array('*/2', "18", "*/10", "*");
$month = array('12', "8", "*/3", "*");
$dayOfWeek = array('*/3', "0", "5", "*");
$variables = array(
array(
'AND_SOME_VAR_FOR_NOT_MANAGED' => '1',
'AND_ANOTHER_VAR' => '2',
),
array(),
array(
'MAILTO' => '<EMAIL>',
),
array(
'MAILTO' => '<EMAIL>',
),
);
$comments = array(
"Some comment before variables\nAnd some after",
"",
"------------ CURRENTLY MANAGED by Test --------------\n" .
"Rule below is managed by CrontabLibrary by Hexmedia - Do not modify it! 0cbc6611f502690a30dc24bcc1148cfa",
"Rule below is managed by CrontabLibrary by Hexmedia - Do not modify it! 0cbc6611f5f04eb5607f81bdf9c11ffe\n" .
"Send to test1\n" .
"Or not... //only the second one will be saved :)",
);
for ($i = 0; $i < 4; $i++) {
$parsed[$i]->shouldHaveCount(9);
$parsed[$i]['command']->shouldReturn($commands[$i]);
$parsed[$i]['log_file']->shouldReturn(sprintf("./logs/schema_validate%d.log", $i + 1));
$parsed[$i]['minute']->shouldReturn($minutes[$i]);
$parsed[$i]['hour']->shouldReturn($hours[$i]);
$parsed[$i]['day_of_week']->shouldReturn($dayOfWeek[$i]);
$parsed[$i]['day_of_month']->shouldReturn($dayOfMonth[$i]);
$parsed[$i]['month']->shouldReturn($month[$i]);
$parsed[$i]['variables']->shouldReturn($variables[$i]);
$parsed[$i]['comment']->shouldReturn($comments[$i]);
}
}
function it_is_returning_null_when_there_is_no_system_crontab()
{
$this->beConstructedWith(false, null);
$this->parse()->shouldReturn(null);
}
}
<file_sep><?php
namespace spec\Hexmedia\Crontab\Parser\Xml;
use dev\Hexmedia\Crontab\PhpSpec\Parser\FactoryObjectBehavior;
use Prophecy\Argument;
class ParserFactorySpec extends FactoryObjectBehavior
{
protected function getType()
{
return "Xml";
}
protected function getWorkingParser()
{
return 'PhpParser';
}
protected function getParsersCount()
{
return 1;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab\Parser\Ini;
use dev\Hexmedia\Crontab\PhpSpec\Parser\AbstractIniParserObjectBehavior;
use PhpSpec\Exception\Example\SkippingException;
use Prophecy\Argument;
/**
* Class ZendParserSpec
*
* @package spec\Hexmedia\Crontab\Parser\Ini
*/
class ZendParserSpec extends AbstractIniParserObjectBehavior
{
function let() {
if (defined('HHVM_VERSION')) {
throw new SkippingException("Zend is not compatible with HHVM.");
}
parent::let();
}
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Parser\Ini\ZendParser');
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace dev\Hexmedia\Crontab\Behat;
use Behat\Behat\Context\Context;
use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Gherkin\Node\PyStringNode;
use Hexmedia\Crontab\Application;
use Hexmedia\Crontab\System\Unix;
use Hexmedia\Symfony\FakeProcess\FakeProcessBuilder;
use PhpSpec\Matcher\MatchersProviderInterface;
use Symfony\Component\Console\Tester\ApplicationTester;
use PHPUnit_Framework_Assert as Assertions;
/**
* Class CommandFeatureContext
*
* @package dev\Hexmedia\Crontab\Behat
*/
class ApplicationContext implements Context, MatchersProviderInterface, SnippetAcceptingContext
{
/**
* @var ApplicationTester
*/
private $tester;
/**
* @var Application
*/
private $application;
/**
* @var int
*/
private $lastExitCode;
/**
* @var string
*/
private $lastDisplay;
/**
* @var FakeProcessBuilder
*/
private $processBuilder;
/**
* @var string
*/
private $currentCrontab;
/**
* @return array
*/
public function getMatchers()
{
return array();
}
/**
* @beforeScenario
*/
public function initApplication()
{
$this->application = new Application();
$this->application->setAutoExit(false);
$this->tester = new ApplicationTester($this->application);
}
/**
* @param string $command
* @param string $file
* @param PyStringNode $options
*
* @When /^I run (?P<command>[a-zA-Z0-9\.\:]*) command with file \"(?P<file>[^\"]*)\"$/
* @When /^I run (?P<command>[a-zA-Z0-9\.\:]*) command with file \"(?P<file>[^\"]*)\" and options:$/
*/
public function iRunCommand($command, $file = null, PyStringNode $options = null)
{
$arguments = array(
'command' => $command,
'name' => 'Test',
);
$arguments['configuration-file'] = __DIR__ . "/../../" . $file;
$options = $this->parseOptions($options);
$arguments += $options;
$runOptions = array('interactive' => false, 'decorated' => false);
$this->lastExitCode = $this->tester->run($arguments, $runOptions);
$this->lastDisplay = $this->tester->getDisplay();
}
/**
* @param int $response
*
* @throws \Exception
*
* @Then /The exit code should be (\d+)/
*
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function theExitCodeShouldBe($response)
{
if ((int) $response !== $this->lastExitCode) {
throw new \Exception($this->lastDisplay);
}
Assertions::assertSame((int) $response, $this->lastExitCode);
}
/**
* @param PyStringNode $content
*
* @Then Crontab should contain:
*
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function crontabShouldContain(PyStringNode $content)
{
$crontab = $this->currentCrontab;
Assertions::assertNotFalse($crontab);
if ("" == $content->getRaw()) {
Assertions::assertEquals("", $crontab);
} else {
Assertions::assertContains($content->getRaw(), $crontab);
}
}
/**
* @param PyStringNode $content
*
* @Then Crontab should be:
*
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function crontabShouldBe(PyStringNode $content)
{
$crontab = $this->currentCrontab;
Assertions::assertNotFalse($crontab);
if ("" == $content->getRaw()) {
Assertions::assertEquals("", $crontab);
} else {
Assertions::assertEquals($content->getRaw(), $crontab);
}
}
/**
* @param PyStringNode $display
*
* @Then The display should be:
*
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function theDisplayShouldBe(PyStringNode $display)
{
Assertions::assertSame($display->getRaw(), $this->lastDisplay);
}
/**
* @param PyStringNode $display
*
* @Then The display should contain:
*
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function theDisplayShouldContain(PyStringNode $display)
{
Assertions::assertContains($display->getRaw(), $this->lastDisplay);
}
/**
* @Then The display should be empty
*
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function theDisplayShouldBeEmpty()
{
Assertions::assertEquals('', $this->lastDisplay);
}
/**
* @Given The process builder is fake
*
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function theProcessBuilderIsFake()
{
$this->processBuilder = new FakeProcessBuilder();
Unix::setProcessBuilder($this->processBuilder);
}
/**
* @Given /^\"(?P<command>[^\"]*)\" command will have (?P<code>\d+) as exit code$/
* @Given /^\"(?P<command>[^\"]*)\" command will have (?P<code>\d+) as exit code and will return:/
*
* @param string $command
* @param string $code
* @param PyStringNode $string
*/
public function commandWillHaveAsExitCodeAndWillReturn($command, $code, PyStringNode $string = null)
{
$this->processBuilder->addCommand(
$command,
function ($command) use ($string) {
if (null !== $string) {
return $string->getRaw();
}
return '';
},
$code
);
}
/**
* @Given Crontab save will be called
*/
public function crontabSaveShouldBeCalled()
{
$command = "'crontab' '/tmp/.*'";
$content = '';
$this->currentCrontab = &$content;
$content = '1';
$this->processBuilder->addCommand(
$command,
function ($command) use (&$content) {
if (preg_match("#'crontab' '(/tmp/.*)'#", $command, $matches)) {
$content = file_get_contents($matches[1]);
}
},
0
);
}
/**
* @param PyStringNode $options
*
* @return array
*/
private function parseOptions(PyStringNode $options)
{
$return = array();
foreach ($options->getStrings() as $option) {
if (preg_match('/(?P<option>\-\-[a-zA-Z0-9\-]*)((\=|\s)(?P<value>[^\n\s]*))?/', $option, $matches)) {
$return[$matches['option']] = isset($matches['value']) ? $matches['value'] : true;
}
if (preg_match('/(?P<option>\-[a-zA-Z0-9\-]*) (?P<value>[^\n\s]*)?/', $option, $matches)) {
$return[$matches['option']] = isset($matches['value']) ? $matches['value'] : true;
}
}
return $return;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab;
use Hexmedia\Crontab\Reader\IniReader;
use Hexmedia\Crontab\Reader\JsonReader;
use Hexmedia\Crontab\Reader\ReaderInterface;
use Hexmedia\Crontab\Reader\UnixSystemReader;
use Hexmedia\Crontab\Reader\XmlReader;
use Hexmedia\Crontab\Reader\YamlReader;
use Hexmedia\Crontab\Exception\FactoryException;
/**
* Class ReaderFactory
*
* @package Hexmedia\Crontab
*/
class ReaderFactory
{
/**
* @param array $configuration
*
* @return ReaderInterface
* @throws FactoryException
* @throws \Exception
*/
public static function create($configuration)
{
//TODO: HERE WE CAN ADD TYPE DETECTOR ON FILE NAME
if (!isset($configuration['type'])) {
throw new FactoryException('No type defined, cannot use.');
}
switch ($configuration['type']) {
case 'json':
return self::createJson($configuration);
case 'yaml':
case 'yml':
return self::createYaml($configuration);
case 'ini':
return self::createIni($configuration);
case 'xml':
return self::createXml($configuration);
case 'unix':
return self::createUnix($configuration);
default:
throw new FactoryException(sprintf("Unknown type '%s'", $configuration['type']));
}
}
/**
* @param array $configuration
*
* @return JsonReader
* @throws FactoryException
*/
private static function createJson(array $configuration)
{
if (!isset($configuration['file'])) {
throw new FactoryException('File needs to be defined for type json');
}
$file = $configuration['file'];
$machine = self::configurationGetOrDefault($configuration, 'machine', null);
$crontab = self::configurationGetOrDefault($configuration, 'crontab', null);
$reader = new JsonReader($file, $crontab, $machine);
return $reader;
}
/**
* @param array $configuration
*
* @return YamlReader
* @throws FactoryException
*/
private static function createYaml(array $configuration)
{
if (!isset($configuration['file'])) {
throw new FactoryException('File needs to be defined for type yaml');
}
$file = $configuration['file'];
$machine = self::configurationGetOrDefault($configuration, 'machine', null);
$crontab = self::configurationGetOrDefault($configuration, 'crontab', null);
$reader = new YamlReader($file, $crontab, $machine);
return $reader;
}
/**
* @param array $configuration
*
* @return IniReader
* @throws FactoryException
*/
private static function createIni($configuration)
{
if (!isset($configuration['file'])) {
throw new FactoryException('File needs to be defined for type yaml');
}
$file = $configuration['file'];
$machine = self::configurationGetOrDefault($configuration, 'machine', null);
$crontab = self::configurationGetOrDefault($configuration, 'crontab', null);
$reader = new IniReader($file, $crontab, $machine);
return $reader;
}
/**
* @param array $configuration
*
* @return XmlReader
* @throws FactoryException
*/
private static function createXml($configuration)
{
if (!isset($configuration['file'])) {
throw new FactoryException('File needs to be defined for type yaml');
}
$file = $configuration['file'];
$machine = self::configurationGetOrDefault($configuration, 'machine', null);
$crontab = self::configurationGetOrDefault($configuration, 'crontab', null);
$reader = new XmlReader($file, $crontab, $machine);
return $reader;
}
/**
* @param array $configuration
*
* @return UnixReader
*/
private static function createUnix($configuration)
{
$user = self::configurationGetOrDefault($configuration, 'user', null);
$crontab = self::configurationGetOrDefault($configuration, 'crontab', null);
$reader = new UnixSystemReader($user, $crontab);
return $reader;
}
/**
* @param array $configuration
* @param mixed $index
* @param mixed $default
*
* @return mixed
*/
private static function configurationGetOrDefault($configuration, $index, $default)
{
return isset($configuration[$index]) ? $configuration[$index] : $default;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab\Reader;
use dev\Hexmedia\Crontab\PhpSpec\SystemAwareObjectBehavior;
use Prophecy\Argument;
class UnixFileReaderSpec extends SystemAwareObjectBehavior
{
function let()
{
$this->isSystemSupported();
$this->beConstructedWith("./Tests/example_configurations/test.unix");
}
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Reader\UnixFileReader');
$this->shouldImplement('Hexmedia\Crontab\Reader\AbstractUnixReader');
}
function it_is_readable() {
$readed = $this->read();
$readed->shouldHaveType('Hexmedia\Crontab\Crontab');
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Reader;
use Hexmedia\Crontab\Crontab;
/**
* Class FileReaderAbstract
*
* @package Hexmedia\Crontab\Reader
*/
abstract class AbstractFileReader extends AbstractArrayReader
{
/**
* @var string
*/
private $file;
/**
* FileReader constructor.
*
* @param null $file
* @param Crontab|null $crontab
* @param null $machine
*/
public function __construct($file = null, Crontab $crontab = null, $machine = null)
{
parent::__construct($crontab, $machine);
$this->file = $file;
}
/**
* @return array
*/
public function prepareArray()
{
$parsed = $this->parse();
return $parsed;
}
/**
* Reads all crons from given file, and puts them into crontab.
*
* @return Crontab
*/
public function read()
{
$parsed = $this->parse();
return $this->readArray($parsed);
}
/**
* @return string
*/
protected function getFile()
{
return $this->file;
}
/**
* @return string
*/
protected function getContent()
{
return file_get_contents($this->getFile());
}
/**
* @return array
* @throws \Hexmedia\Crontab\Exception\NoSupportedParserException
*/
protected function parse()
{
$parserFactory = $this->getParserFactory();
$parser = $parserFactory->create($this->getContent(), $this->getFile());
return $parser->parse();
}
/**
* @return array
*/
abstract protected function getParserFactory();
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab\Parser\Unix;
use dev\Hexmedia\Crontab\PhpSpec\Parser\FactoryObjectBehavior;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
/**
* Class ParserFactorySpec
*
* @package spec\Hexmedia\Crontab\Parser\Unix
*/
class ParserFactorySpec extends FactoryObjectBehavior
{
protected function getType()
{
return "Unix";
}
protected function getWorkingParser()
{
return "UnixParser";
}
protected function getParsersCount()
{
return 1;
}
function it_returns_correct_praser()
{
$this->isSystemSupported();
$this->create('', '/tmp/file')->shouldImplement('Hexmedia\Crontab\Parser\ParserInterface');
}
function it_is_constructing_with_prefered_full_name()
{
$this->isSystemSupported();
$this->beConstructedWith($this->getFullWorkingParserName());
$this->create('[some]', '/tmp/file')->shouldHaveType($this->getFullWorkingParserName());
}
function it_is_constructing_with_prefered_only_class_name()
{
$this->isSystemSupported();
$this->beConstructedWith($this->getWorkingParser());
$this->create('[some]', '/tmp/file')->shouldHaveType($this->getFullWorkingParserName());
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab\Writer\System;
use dev\Hexmedia\Crontab\PhpSpec\SystemAwareObjectBehavior;
use Hexmedia\Crontab\Crontab;
use Hexmedia\Crontab\System\Unix;
use Hexmedia\Crontab\Task;
use Hexmedia\Crontab\Variables;
use Hexmedia\Symfony\FakeProcess\FakeProcessBuilder;
use PhpSpec\Exception\Example\FailureException;
use Prophecy\Argument;
class UnixWriterSpec extends SystemAwareObjectBehavior
{
private $defaultContent = <<<CONTENT
#WARNING!!!
#This crontab file it at least partially managed by Crontab by Hexmedia, please check all restrictions that comes with that library at: https://github.com/Hexmedia/Crontab/blob/master/README.md
#EOT
#This is some comment with
#two lines
*/10 * * * * test > some_log_file.log
#This is some comment with
#two lines
*/10 * * * * test > some_log_file.log
# ------------ CURRENTLY MANAGED by TestAopTest --------------
#DO NOT MODIFY! This task is managed by Crontab library by Hexmedia bb83a7fd849c0ab6ec0cfb38d3db6a2
#This is some comment with
#two lines
*/10 * * * * test > some_log_file.log
#DO NOT MODIFY! This task is managed by Crontab library by Hexmedia bb83a7fd849c0ab6ec0cfb38d3db6a2
#This is some comment with
#two lines
*/10 * * * * test > some_log_file.log
CONTENT;
private function prepareTask(&$task, $variables, $notManaged = false, $comment = true)
{
$task->getCommand()->willReturn("test");
$task->getMonth()->willReturn("*");
$task->getDayOfMonth()->willReturn("*");
$task->getDayOfWeek()->willReturn("*");
$task->getHour()->willReturn("*");
$task->getMinute()->willReturn("*/10");
$task->getLogFile()->willReturn("some_log_file.log");
$task->getBeforeComment()->willReturn($comment ? "This is some comment with \ntwo lines" : '');
$task->isNotManaged()->willReturn($notManaged);
$task->getVariables()->willReturn($variables);
$task->getName()->willReturn("synchronize1");
}
function let(Crontab $crontab, Task $nmTask1, Task $nmTask2, Task $task1, Task $task2, Variables $variables1)
{
$this->isSystemSupported();
$this->prepareTask($task1, $variables1);
$this->prepareTask($task2, $variables1);
$this->prepareTask($nmTask1, $variables1, true);
$this->prepareTask($nmTask2, $variables1, true);
$crontab->getName()->willReturn("TestAopTest");
$crontab->getManagedTasks()->willReturn(array($task1, $task2));
$crontab->getNotManagedTasks()->willReturn(array($nmTask1, $nmTask2));
}
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Writer\System\UnixWriter');
$this->shouldImplement('Hexmedia\Crontab\Writer\System\WriterInterface');
}
function it_is_able_to_get_content($crontab)
{
$this
->getContent($crontab)
->shouldReturn($this->defaultContent);
}
function it_has_support_for_variables(Task $task3, Variables $variables3, Crontab $crontab2)
{
$this->prepareTask($task3, $variables3);
$variables3->current()->willReturn('value');
$variables3->key()->willReturn('key');
$variables3->rewind()->shouldBeCalled();
$variables3->valid()->willReturn(true, false);
$variables3->next()->shouldBeCalled();
$crontab2->getName()->willReturn("TestAopTest");
$crontab2->getManagedTasks()->willReturn(array($task3));
$crontab2->getNotManagedTasks()->willReturn(array());
$this
->getContent($crontab2)
->shouldReturn(
<<<CONTENT
#WARNING!!!
#This crontab file it at least partially managed by Crontab by Hexmedia, please check all restrictions that comes with that library at: https://github.com/Hexmedia/Crontab/blob/master/README.md
#EOT
# ------------ CURRENTLY MANAGED by TestAopTest --------------
#DO NOT MODIFY! This task is managed by Crontab library by Hexmedia bb83a7fd849c0ab6ec0cfb38d3db6a2
#This is some comment with
#two lines
key=value
*/10 * * * * test > some_log_file.log
CONTENT
);
}
function it_works_with_crons_without_comments(Task $taskWC, Variables $variablesWC, Crontab $crontabWC)
{
$this->prepareTask($taskWC, $variablesWC, true, false);
$variablesWC->current()->willReturn('value');
$variablesWC->key()->willReturn('key');
$variablesWC->rewind()->shouldBeCalled();
$variablesWC->valid()->willReturn(true, false);
$variablesWC->next()->shouldBeCalled();
$crontabWC->getName()->willReturn("TestAopTest");
$crontabWC->getManagedTasks()->willReturn(array($taskWC));
$crontabWC->getNotManagedTasks()->willReturn(array());
// echo($this->getContent($crontabWC)->getWrappedObject());
// die();
$this
->getContent($crontabWC)
->shouldReturn(
<<<CONTENT
#WARNING!!!
#This crontab file it at least partially managed by Crontab by Hexmedia, please check all restrictions that comes with that library at: https://github.com/Hexmedia/Crontab/blob/master/README.md
#EOT
# ------------ CURRENTLY MANAGED by TestAopTest --------------
key=value
*/10 * * * * test > some_log_file.log
CONTENT
);
}
function it_allows_to_write($crontab)
{
$processBuilder = new FakeProcessBuilder();
$shouldBe = $this->defaultContent;
$processBuilder->addCommand(
"'crontab' '(/var)?/tmp/.*'",
function ($command) use ($shouldBe) {
if (preg_match("#'crontab' '((/var)?/tmp/.*)'#", $command, $matches)) {
$content = file_get_contents($matches[1]);
if ($content !== $shouldBe) {
throw new FailureException("Content in not correct");
}
}
},
1
);
Unix::setProcessBuilder($processBuilder);
$this->write($crontab)->shouldReturn(true);
Unix::setProcessBuilder(null);
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab;
use Hexmedia\Crontab\Console\ClearCommand;
use Hexmedia\Crontab\Console\EchoCommand;
use Hexmedia\Crontab\Console\SynchronizeCommand;
use Symfony\Component\Console\Application as BaseApplication;
/**
* Class Application
*
* @package Hexmedia\Crontab
*/
class Application extends BaseApplication
{
/**
* {@inheritdoc}
*/
public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
{
parent::__construct($name, $version);
$this->add(new SynchronizeCommand());
$this->add(new EchoCommand());
$this->add(new ClearCommand());
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Console;
use Hexmedia\Crontab\Crontab;
use Hexmedia\Crontab\Writer\SystemWriter;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class SynchronizeCommand
*
* @package Hexmedia\Crontab\Console
*/
class SynchronizeCommand extends AbstractCommand
{
/**
* @param OutputInterface $output
* @param Crontab $crontab
* @param string|null $user
*
* @return mixed
*/
public function output(OutputInterface $output, Crontab $crontab, $user = null)
{
$writer = new SystemWriter(array('user' => $user));
//Checking if we do want to save something if not it's better to left file as is
if ($crontab->getManagedTasks()) {
$writer->write($crontab);
$output->writeln('Your crontab has been updated!');
} else {
$output->writeln('Your crontab does not need to be updated!');
}
}
/**
*
*/
protected function configureName()
{
$this
->setName('synchronize')
->setDescription('Synchronizes with system crontab');
}
}
<file_sep>[command1]
command = ./some/command1
minute = */13
hour = *
day_of_month = *
day_of_week = *
month = *
log_file = ./logs/some_log1.log
machine = www*
variables.MAILTO = <EMAIL>
comment = "this is some comment for this crontab"
[command2]
command = ./some/command2
minute = *
hour = *
day_of_month = *
day_of_week = *
month = *
log_file = ./logs/some_log2.log
machine = www103
variables.MAILTO = <EMAIL>
variables.NO_VALIDATE = true
[command_without_log_file]
command = ./some/command_without_log_file
minute = *
hour = *
day_of_month = *
day_of_week = *
month = *
machine = www103
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Parser\Yaml;
use Hexmedia\Crontab\Parser\AbstractParserFactory;
/**
* Class ParserFactory
* @package Hexmedia\Crontab\Parser\Yaml
*/
class ParserFactory extends AbstractParserFactory
{
/**
* @return array
*/
public function getDefaultParsers()
{
$supported = array('\\Hexmedia\\Crontab\\Parser\\Yaml\\SymfonyParser');
if (!defined('HHVM_VERSION')) {
$supported[] = '\\Hexmedia\\Crontab\\Parser\\Yaml\\ZendParser';
}
return $supported;
}
}
<file_sep><?php
namespace spec\Hexmedia\Crontab\Parser\Yaml;
use dev\Hexmedia\Crontab\PhpSpec\Parser\AbstractYamlParserObjectBehavior;
use PhpSpec\Exception\Example\SkippingException;
use Prophecy\Argument;
class ZendParserSpec extends AbstractYamlParserObjectBehavior
{
function let() {
if (defined('HHVM_VERSION')) {
throw new SkippingException("Zend is not compatible with HHVM.");
}
parent::let();
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab\Writer\System;
use dev\Hexmedia\Crontab\PhpSpec\SystemAwareObjectBehavior;
use Hexmedia\Crontab\Crontab;
use Hexmedia\Crontab\Exception\NoWriterForSystemException;
use Hexmedia\Crontab\Exception\WriterNotExistsException;
use Hexmedia\Crontab\System\Unix;
use PhpSpec\Exception\Example\SkippingException;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class WriterFactorySpec extends SystemAwareObjectBehavior
{
/**
* @var string
*/
private $linuxWriterClass = 'Hexmedia\Crontab\Writer\System\UnixWriter';
/**
* @var array
*/
private $orginalWriters;
function let()
{
$this->orginalWriters = $this->getWriters();
}
function letgo()
{
$this->setWriters($this->orginalWriters);
}
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Writer\System\WriterFactory');
}
function it_is_able_to_create_writer(Crontab $crontab)
{
$this->isSystemSupported();
$created = $this::create($crontab);
$created->shouldImplement('Hexmedia\Crontab\Writer\System\WriterInterface');
if (true === Unix::isUnix()) {
$created->shouldImplement('Hexmedia\Crontab\Writer\System\UnixWriter');
}
}
function it_returns_writers()
{
$this::getWriters()->shouldHaveCount(1);
}
function it_is_able_to_remove_writer()
{
$this::removeWriter($this->linuxWriterClass);
$this::getWriters()->shouldHaveCount(sizeof($this->orginalWriters) - 1);
}
function it_is_returning_false_when_trying_to_remove_unexisting_writer()
{
$this::removeWriter("test")->shouldReturn(false);
}
function it_is_able_to_add_writer()
{
$this::addWriter($this->linuxWriterClass);
$writers = $this::getWriters();
$writers->shouldHaveCount(sizeof($this->orginalWriters) + 1);
$writers[1]->shouldReturn('Hexmedia\Crontab\Writer\System\UnixWriter');
}
function it_is_throwing_error_when_trying_to_add_unexisting_writter()
{
$this->shouldThrow(
new WriterNotExistsException(
sprintf("Writer with given name %s does not exists.", 'test')
)
)->during('addWriter', array('test'));
}
function it_is_throwin_exception_when_there_is_no_supporting_system(Crontab $crontab)
{
$this::removeWriter($this->linuxWriterClass);
$this::getWriters()->shouldHaveCount(0);
$this->shouldThrow(
new NoWriterForSystemException(
sprintf("Writer for your operating system '%s' was not found!", PHP_OS)
)
)->duringCreate("test", array($crontab));
}
function it_allows_to_set_writers()
{
$this->isSystemSupported();
$this::setWriters(array());
$this::getWriters()->shouldReturn(array());
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Parser\Unix;
use Hexmedia\Crontab\Parser\AbstractParserFactory;
/**
* Class ParserFactory
*
* @package Hexmedia\Crontab\Parser\Unix
*/
class ParserFactory extends AbstractParserFactory
{
/**
* @return array
*/
public function getDefaultParsers()
{
return array(
'\\Hexmedia\\Crontab\\Parser\\Unix\\UnixParser',
);
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Writer\System;
use Hexmedia\Crontab\Crontab;
use Hexmedia\Crontab\System\Unix;
use Hexmedia\Crontab\Task;
/**
* Class UnixWriter
*
* @package Hexmedia\Crontab\Writer\System
*/
class UnixWriter implements WriterInterface
{
/**
* @param Crontab $crontab
*
* @return string
*/
public function write(Crontab $crontab)
{
$content = $this->prepareContent($crontab);
return $this->saveCrontab($content);
}
/**
* @param Crontab $crontab
*
* @return string
*/
public function getContent(Crontab $crontab)
{
$content = $this->prepareContent($crontab);
return $content;
}
/**
* @return bool
*
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public static function isSupported()
{
return Unix::isUnix();
}
/**
* @param string $content
*
* @return bool
*
* @SuppressWarnings(PHPMD.StaticAccess)
*/
protected function saveCrontab($content)
{
Unix::save($content);
return true;
}
private function prepareContent(Crontab $crontab)
{
$content = "#WARNING!!!\n";
$content .= '#This crontab file it at least partially managed by Crontab by Hexmedia, please check all ' . "restrictions that comes with that library at: https://github.com/Hexmedia/Crontab/blob/master/README.md\n";
$content .= "#EOT\n\n";
foreach ($crontab->getNotManagedTasks() as $task) {
$content .= "\n" . $this->prepareTask($task, $crontab);
}
$content .= sprintf("\n\n# ------------ CURRENTLY MANAGED by %s --------------\n", $crontab->getName());
/** @var Task $task */
foreach ($crontab->getManagedTasks() as $task) {
$content .= "\n" . $this->prepareTask($task, $crontab);
}
$content .= "\n";
return $content;
}
/**
* @param string $comment
*
* @return string
*/
private function prepareComment($comment)
{
$exp = explode("\n", $comment);
$exp = array_map(
function ($com) {
return rtrim($com);
},
$exp
);
$comment = trim(implode("\n#", $exp));
if ($comment) {
return "#" . $comment . "\n";
}
return null;
}
/**
* @param Task $task
* @param string $crontabName
*
* @return string
*/
private function prepareTaskNameLine(Task $task, $crontabName)
{
return sprintf(
"DO NOT MODIFY! This task is managed by Crontab library by Hexmedia %s\n",
$this->prepareTaskHash($task->getName(), $crontabName)
);
}
/**
* @param string $taskName
* @param string $crontabName
*
* @return string
*/
private function prepareTaskHash($taskName, $crontabName)
{
return substr(md5($crontabName), 0, 10) . substr(md5($taskName), 11);
}
/**
* @param Task $task
*
* @return string
*/
private function prepareTask(Task $task, Crontab $crontab)
{
$log = $task->getLogFile() ? '> ' . $task->getLogFile() : '';
if ($task->isNotManaged()) {
$comment = $task->getBeforeComment();
} else {
$comment = $this->prepareTaskNameLine($task, $crontab->getName()) . $task->getBeforeComment();
}
$comment = $this->prepareComment($comment);
$variables = '';
if ($task->getVariables() instanceof \Iterator) {
foreach ($task->getVariables() as $name => $value) {
$variables .= sprintf("%s=%s\n", $name, $value);
}
}
return trim(
sprintf(
'%s%s%s %s %s %s %s %s %s',
$comment,
$variables,
$task->getMinute(),
$task->getHour(),
$task->getDayOfMonth(),
$task->getMonth(),
$task->getDayOfWeek(),
$task->getCommand(),
$log,
" "
)
);
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab;
use Hexmedia\Crontab\Exception\UnsupportedVariableException;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
/**
* Class VariablesSpec
*
* @package spec\Hexmedia\Crontab
*
* @covers Hexmedia\Variables
*/
class VariablesSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith(array(
'FIRST' => '1111',
'SECOND' => '222',
'THIRD' => '33'
));
}
function it_is_initializable()
{
$this->shouldHaveType('\Hexmedia\Crontab\Variables');
$this->shouldImplement('\Iterator');
}
function it_can_get_current()
{
$this->current()->shouldReturn('1111');
}
function it_can_go_next()
{
$this->next();
$this->current()->shouldReturn('222');
}
function it_can_rewind()
{
$this->rewind();
$this->current()->shouldReturn('1111');
}
function it_has_working_validation()
{
$this->next();
$this->valid()->shouldReturn(true);
$this->next();
$this->next();
$this->next();
$this->valid()->shouldReturn(false);
}
function it_is_returning_correct_keys()
{
$this->rewind();
$this->key()->shouldReturn("FIRST");
$this->next();
$this->key()->shouldReturn("SECOND");
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace dev\Hexmedia\Crontab\PhpSpec\Parser;
use PhpSpec\Exception\Example\FailureException;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
/**
* Class AbstractParserObjectBehavior
*
* @package Hexmedia\CrontabDev\PhpSpec\Parser
*/
abstract class AbstractParserObjectBehavior extends ObjectBehavior
{
abstract protected function getFileName();
/**
* @return array
*/
public function getMatchers()
{
//Fix for php5.3
$that = $this;
return array(
'beProperlyParsed' => function ($subject) use ($that) {
if (!is_array($subject)) {
throw new FailureException("Returned value should be an array!");
}
if (sizeof($subject) != 3) {
throw new FailureException("Returned array should have 2 elements!");
}
if (!isset($subject['command1'])) {
throw new FailureException('Index "command1" should be defined.');
}
if (!isset($subject['command2'])) {
throw new FailureException('Index "command2" should be defined.');
}
$that->checkCommand(
$subject['command1'],
10,
'./some/command1',
'*/13',
'*',
'*',
'*',
'*',
'./logs/some_log1.log',
'www*',
'this is some comment for this crontab',
array('MAILTO' => '<EMAIL>')
);
$that->checkCommand(
$subject['command2'],
9,
'./some/command2',
'*',
'*',
'*',
'*',
'*',
'./logs/some_log2.log',
'www103',
null,
array('MAILTO' => '<EMAIL>', 'NO_VALIDATE' => '1')
);
$that->checkCommand(
$subject['command_without_log_file'],
7,
'./some/command_without_log_file',
'*',
'*',
'*',
'*',
'*',
null,
'www103',
null,
null
);
return true;
},
);
}
/**
* @return string
*/
public function getWrongFileName()
{
$extension = pathinfo($this->getFileName(), PATHINFO_EXTENSION);
$mapping = array(
'ini' => 'yml',
'yml' => 'json',
'yaml' => 'json',
'json' => 'xml',
'xml' => 'ini',
);
return str_replace($extension, $mapping[$extension], $this->getFileName());
}
/**
* @param array $subject
* @param string $count
* @param string $command
* @param string $minute
* @param string $hour
* @param string $dayOfMonth
* @param string $dayOfWeek
* @param string $month
* @param string $logFile
* @param string $machine
* @param string $comment
* @param string $variables
*
* @throws FailureException
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function checkCommand(
array $subject,
$count,
$command,
$minute,
$hour,
$dayOfMonth,
$dayOfWeek,
$month,
$logFile,
$machine,
$comment,
$variables
) {
if (sizeof($subject) != $count) {
throw new FailureException(
sprintf(
"This command array should have %d elements, %d given",
$count,
sizeof($subject)
)
);
}
$this->compareAndThrow("Command", $subject['command'], $command);
$this->compareAndThrow("Minute", $subject['minute'], $minute);
$this->compareAndThrow('Hour', $subject['hour'], $hour);
$this->compareAndThrow('Day_of_month', $subject['day_of_month'], $dayOfMonth);
$this->compareAndThrow('Day_of_week', $subject['day_of_week'], $dayOfWeek);
$this->compareAndThrow('Month', $subject['month'], $month);
if (null !== $logFile) {
$this->compareAndThrow('Log_file', $subject['log_file'], $logFile);
}
$this->compareAndThrow('Machine', $subject['machine'], $machine);
if (isset($subject['comment'])) {
$this->compareAndThrow('Comment', $subject['comment'], $comment);
} elseif (null !== $comment) {
throw new FailureException(sprintf("Expecting comment to be %s, none given", $comment));
}
if ($variables) {
if ($subject['variables'] != $variables) {
$failure = new FailureException(
sprintf(
"Variables should be:\n %s \n-------\n %s",
var_export($variables, true),
var_export($subject['variables'], true)
)
);
throw $failure;
}
}
}
/**
* @param string $name
* @param string $shouldBe
* @param string $currentValue
*
* @throws FailureException
*/
private function compareAndThrow($name, $shouldBe, $currentValue)
{
if ($shouldBe !== $currentValue) {
throw new FailureException(sprintf('%s should be "%s", "%s" given', $name, $currentValue, $shouldBe));
}
}
function let()
{
$file = $this->getFileName();
$this->beConstructedWith(file_get_contents($file), $file);
}
function it_should_be_supported()
{
$this->isSupported()->shouldReturn(true);
}
function it_is_parsing_file_correctly()
{
$parsed = $this->parse();
$parsed->shouldHaveCount(3);
$parsed->shouldBeProperlyParsed();
}
function it_should_throw_ParsingException_when_wrong_file()
{
$file = $this->getWrongFileName();
$this->beConstructedWith(file_get_contents($file), $file);
$this->shouldThrow('Hexmedia\Crontab\Exception\ParsingException')->duringParse();
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Console;
use Hexmedia\Crontab\Crontab;
use Hexmedia\Crontab\Writer\SystemWriter;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class EchoCommand
*
* @package Hexmedia\Crontab\Console
*/
class EchoCommand extends AbstractCommand
{
/**
* @param OutputInterface $output
* @param Crontab $crontab
* @param string|null $user
*
* @return mixed
*/
public function output(OutputInterface $output, Crontab $crontab, $user = null)
{
$writer = new SystemWriter(array('user' => $user));
$output->writeln('<info>Your crontab will look like:</info>');
$output->write('<comment>' . $writer->getContent($crontab) . '</comment>');
}
/**
*
*/
protected function configureName()
{
$this
->setName('echo')
->setDescription('Displays prepared crontable');
}
}
<file_sep><?php
namespace spec\Hexmedia\Crontab\Parser\Yaml;
use dev\Hexmedia\Crontab\PhpSpec\Parser\AbstractYamlParserObjectBehavior;
use Prophecy\Argument;
class SymfonyParserSpec extends AbstractYamlParserObjectBehavior
{
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab;
use Hexmedia\Crontab\Variables;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
/**
* Class TaskSpec
*
* @package spec\Hexmedia\Crontab
*
* @covers Hexmedia\Reader\Task
*/
class TaskSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Task');
}
function it_allows_to_set_is_not_managed()
{
$this->setNotManaged(true)->shouldReturn($this);
$this->isNotManaged()->shouldReturn(true);
$this->setNotManaged("aaa")->shouldReturn($this);
$this->isNotManaged()->shouldReturn(false);
}
function it_allows_to_set_name()
{
$this->setName("name")->shouldReturn($this);
$this->getName()->shouldReturn("name");
}
function it_allows_to_set_month()
{
$this->setMonth("*")->shouldReturn($this);
$this->getMonth()->shouldReturn("*");
}
function it_allows_to_set_minute()
{
$this->setMinute("*")->shouldReturn($this);
$this->getMinute()->shouldReturn("*");
}
function it_allows_to_set_hour()
{
$this->setHour("*")->shouldReturn($this);
$this->getHour()->shouldReturn("*");
}
function it_allows_to_set_log_file()
{
$this->setLogFile("/var/log_file")->shouldReturn($this);
$this->getLogFile()->shouldReturn("/var/log_file");
}
function it_allows_to_set_day_of_month()
{
$this->setDayOfMonth("*")->shouldReturn($this);
$this->getDayOfMonth()->shouldReturn("*");
}
function it_allows_to_set_day_of_week()
{
$this->setDayOfWeek("*")->shouldReturn($this);
$this->getDayOfWeek()->shouldReturn("*");
}
function it_allows_to_set_before_comment()
{
$this->setBeforeComment("Some Comment")->shouldReturn($this);
$this->getBeforeComment()->shouldReturn("Some Comment");
}
function it_allows_to_set_variables(Variables $variables)
{
$this->setVariables($variables)->shouldReturn($this);
$this->getVariables()->shouldReturn($variables);
}
function it_allows_to_set_command()
{
$this->setCommand("acme:bundle")->shouldReturn($this);
$this->getCommand()->shouldReturn("acme:bundle");
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Parser\Yaml;
use Hexmedia\Crontab\Exception\ParsingException;
use Hexmedia\Crontab\Parser\AbstractParser;
use Hexmedia\Crontab\Parser\ParserInterface;
/**
* Class ZendParser
*
* @package Hexmedia\Crontab\Parser\Yaml
*/
class ZendParser extends AbstractParser implements ParserInterface
{
/**
* @return array
*
* @throws ParsingException
*/
public function parse()
{
try {
$parser = new \Zend_Config_Yaml($this->getFile());
} catch (\Zend_Config_Exception $e) {
throw new ParsingException("Cannot parse this file: " . $e->getMessage(), 0, $e);
}
return $parser->toArray();
}
/**
* @return bool
*/
public static function isSupported()
{
return class_exists('\\Zend_Config_Yaml');
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace dev\Hexmedia\Crontab\PhpSpec\Parser;
/**
* Class AbstractXmlParserObjectBehavior
*
* @package dev\Hexmedia\Crontab\PhpSpec\Parser
*/
abstract class AbstractXmlParserObjectBehavior extends AbstractParserObjectBehavior
{
protected function getFileName()
{
return __DIR__ . '/../../../Tests/example_configurations/test.xml';
}
}
<file_sep><?php
namespace spec\Hexmedia\Crontab;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
/**
* Class ApplicationSpec
*
* @package spec\Hexmedia\Crontab
*
* @covers Hexmedia\Crontab\Application
*/
class ApplicationSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Application');
$this->shouldImplement('Symfony\Component\Console\Application');
}
function it_has_added_all_commands()
{
$this->all()->shouldHaveCount(5);
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Reader;
use Hexmedia\Crontab\Crontab;
use Hexmedia\Crontab\Exception\FileNotFoundException;
/**
* Class UnixFileReader
*
* @package Hexmedia\Crontab\Reader
*/
class UnixFileReader extends AbstractUnixReader
{
/**
* @var string
*/
private $file;
/**
* UnixFileReader constructor.
*
* @param string $file
* @param Crontab|null $crontab
*/
public function __construct($file, Crontab $crontab = null)
{
$this->file = $file;
parent::__construct($crontab);
}
/**
* @return mixed
* @throws FileNotFoundException
*/
protected function getContent()
{
if (false === file_exists($this->file)) {
throw new FileNotFoundException(sprintf("File '%s' was not found!", $this->file));
}
return file_get_contents($this->file);
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Reader;
use Hexmedia\Crontab\Crontab;
use Hexmedia\Crontab\Task;
use Hexmedia\Crontab\Variables;
/**
* Class ArrayReaderAbstract
*
* @package Hexmedia\Crontab\Reader
*/
abstract class AbstractArrayReader implements ReaderInterface
{
/**
* @var Crontab
*/
private $crontab;
/**
* @var string|null
*/
private $machine = null;
/**
* @var bool
*/
private $notManaged = false;
/**
* ArrayReader constructor.
*
* @param Crontab|null $crontab
* @param string|null $machine
*/
public function __construct(Crontab $crontab = null, $machine = null)
{
$this->crontab = ($crontab ?: new Crontab());
$this->machine = $machine;
}
/**
* @return boolean
*/
public function isNotManaged()
{
return $this->notManaged;
}
/**
* @param boolean $notManaged
*/
public function setNotManaged($notManaged)
{
$this->notManaged = $notManaged;
}
/**
* @return Crontab
*/
public function read()
{
$array = $this->prepareArray();
if (is_array($array)) {
return $this->readArray($array);
}
return $this->crontab;
}
/**
* @param array $array
*
* @return Crontab
*/
protected function readArray(array $array)
{
foreach ($array as $name => $task) {
if (true === $this->checkIfForThisMachine(isset($task['machine']) ? $task['machine'] : null)) {
$task = $this->createTaskFromConfig($name, $task);
$this->crontab->addTask($task);
}
}
return $this->crontab;
}
/**
* @return array
*/
abstract protected function prepareArray();
/**
* @param string $name
* @param array $taskArray
*
* @return Task
*/
private function createTaskFromConfig($name, array $taskArray)
{
$task = new Task();
$task->setMd5Name($name);
$task->setNotManaged($this->notManaged);
$task->setCommand($taskArray['command']);
$task->setMinute($taskArray['minute']);
$task->setDayOfMonth($taskArray['day_of_month']);
$task->setDayOfWeek($taskArray['day_of_week']);
$task->setMonth($taskArray['month']);
if (isset($taskArray['variables'])) {
$task->setVariables(new Variables($taskArray['variables']));
}
if (isset($taskArray['log_file'])) {
$task->setLogFile($taskArray['log_file']);
}
return $task;
}
/**
* @param string $machine
*
* @return bool
*/
private function checkIfForThisMachine($machine)
{
if (null === $this->machine) {
return true;
}
//It means that it was read from this device, or has no marked device so should be installed on all of them
if (null === $machine) {
return true;
}
$pattern = str_replace(array('*', '?'), array('.*', '.'), $machine);
if (preg_match(sprintf('/%s/', $pattern), $this->machine)) {
return true;
}
return false;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Parser\Xml;
use Hexmedia\Crontab\Parser\AbstractParserFactory;
/**
* Class ParserFactory
* @package Hexmedia\Crontab\Parser\Xml
*/
class ParserFactory extends AbstractParserFactory
{
/**
* @return array
*/
public function getDefaultParsers()
{
return array(
'\\Hexmedia\\Crontab\\Parser\\Xml\\PhpParser',
);
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Parser\Ini;
use Hexmedia\Crontab\Exception\ParsingException;
use Hexmedia\Crontab\Parser\AbstractParser;
use Hexmedia\Crontab\Parser\ParserInterface;
use Zend\Config\Exception\RuntimeException;
/**
* Class Zend2Parser
*
* @package Hexmedia\Crontab\Parser\Ini
*/
class Zend2Parser extends AbstractParser implements ParserInterface
{
/**
* @return array
*
* @throws ParsingException
*/
public function parse()
{
try {
$parser = new \Zend\Config\Reader\Ini();
$config = $parser->fromFile($this->getFile());
} catch (RuntimeException $e) {
throw new ParsingException("Cannot parse this file: " . $e->getMessage(), 0, $e);
}
return $config;
}
/**
* @return bool
*/
public static function isSupported()
{
return class_exists('\\Zend\\Config\\Reader\\Ini');
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace dev\Hexmedia\Crontab\PhpSpec\Parser;
use dev\Hexmedia\Crontab\PhpSpec\SystemAwareObjectBehavior;
use Hexmedia\Crontab\Exception\NoSupportedParserException;
use Hexmedia\Crontab\Exception\UnexistingParserException;
use Hexmedia\Crontab\System\Unix;
use PhpSpec\Exception\Example\FailureException;
use PhpSpec\ObjectBehavior;
/**
* Class FactoryObjectBehavior
*/
abstract class FactoryObjectBehavior extends SystemAwareObjectBehavior
{
private $notWorkingParser = 'Hexmedia\Crontab\Parser\Ini\SomeParser';
abstract protected function getType();
abstract protected function getWorkingParser();
abstract protected function getParsersCount();
protected function getFullWorkingParserName()
{
return 'Hexmedia\Crontab\Parser\\' . $this->getType() . '\\' . $this->getWorkingParser();
}
function it_is_correctly_defined_working_parser()
{//Test for tests:P
if (!class_exists($this->getFullWorkingParserName())) {
throw new FailureException("Working class does not exists. Tests will not work!");
}
}
function it_has_all_default_parser_that_exists()
{
foreach ($this->getParsers()->getWrappedObject() as $parser) {
if (!class_exists($parser)) {
throw new FailureException(
sprintf("Parser %s does not exists. And is defined as default!", $parser)
);
}
}
}
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Parser\\' . $this->getType() . '\ParserFactory');
$this->shouldImplement('Hexmedia\Crontab\Parser\AbstractParserFactory');
}
function it_is_able_to_add_supported_parser()
{
$this->addParser($this->getFullWorkingParserName())->shouldReturn($this);
}
function it_is_not_able_to_add_unexisting_class_as_parser()
{
$this->shouldThrow(
new UnexistingParserException(sprintf('Parser %s does not exists!', $this->notWorkingParser))
)
->duringAddParser($this->notWorkingParser);
}
function it_is_able_to_remove_existing_parser()
{
$this->removeParser($this->getFullWorkingParserName())->shouldReturn(true);
$this->getParsers()->shouldHaveCount($this->getParsersCount() - 1);
}
function it_is_not_able_to_remove_unexisting_parser()
{
$this->removeParser($this->notWorkingParser)->shouldReturn(false);
$this->getParsers()->shouldHaveCount($this->getParsersCount());
}
function it_returns_correct_praser()
{
$this->create('', '/tmp/file')->shouldImplement('Hexmedia\Crontab\Parser\ParserInterface');
}
function it_is_constructing_with_prefered_full_name()
{
$this->beConstructedWith($this->getFullWorkingParserName());
$this->create("[some]", '/tmp/file')->shouldHaveType($this->getFullWorkingParserName());
}
function it_is_constructing_with_prefered_only_class_name()
{
$this->beConstructedWith($this->getWorkingParser());
$this->create("[some]", '/tmp/file')->shouldHaveType($this->getFullWorkingParserName());
}
function it_is_allowing_to_get_parsers()
{
$this->getParsers()->shouldHaveCount($this->getParsersCount());
}
function it_is_throwing_when_there_is_no_parser()
{
$wasUnix = false;
if (true === Unix::isUnix()) {
$wasUnix = true;
Unix::removeUnix(PHP_OS);
}
$this->clearParser()->shouldReturn($this);
$this->getParsers()->shouldHaveCount(0);
$this
->shouldThrow(
new NoSupportedParserException(
sprintf('There is no supported parser for this type or operating system (your is "%s").', PHP_OS)
)
)
->duringCreate('some text', '/tmp/file');
if ($wasUnix) {
Unix::addUnix(PHP_OS);
}
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab\Parser\Ini;
use dev\Hexmedia\Crontab\PhpSpec\Parser\AbstractIniParserObjectBehavior;
use Prophecy\Argument;
/**
* Class AustinHydeParserSpec
*
* @package spec\Hexmedia\Crontab\Parser\Ini
*/
class AustinHydeParserSpec extends AbstractIniParserObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Parser\Ini\AustinHydeParser');
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab\Reader;
use dev\Hexmedia\Crontab\PhpSpec\SystemAwareObjectBehavior;
use Hexmedia\Crontab\Exception\ClassNotExistsException;
use Prophecy\Argument;
/**
* Class SystemReaderSpec
*
* @package spec\Hexmedia\Crontab\Reader
*
* @covers Hexmedia\Crontab\Reader\SystemReader
*/
class SystemReaderSpec extends SystemAwareObjectBehavior
{
function let()
{
$this->beConstructedWith(null, null);
}
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Reader\SystemReader');
$this->shouldImplement('Hexmedia\Crontab\Reader\ReaderInterface');
}
function it_is_working_only_on_linux_and_bsd_currently()
{
if (in_array(PHP_OS, array('Linux', 'FreeBSD'))) {
}
}
function it_has_readers()
{
$this->isSystemSupported();
$this->getReaders()->shouldHaveCount(1);
}
function it_is_able_to_remove_and_add_reader()
{
$this->isSystemSupported();
$reader = "Hexmedia\\Crontab\\Reader\\UnixSystemReader";
$this->getReaders()->shouldHaveCount(1);
$this->removeReader($reader)->shouldReturn($this);
$this->getReaders()->shouldHaveCount(0);
$this->addReader($reader)->shouldReturn($this);
$readers = $this->getReaders();
$readers->shouldHaveCount(1);
$readers[0]->shouldReturn('\\' . $reader);
}
function it_is_not_able_to_add_non_existing_class()
{
$this->isSystemSupported();
$reader = "\\Hexmedia\\Crontab\\Reader\\WindowsSystemReader";
$this
->shouldThrow(
new ClassNotExistsException(
sprintf("Class %s does not exists. Cannot be added as Reader.", $reader)
)
)->duringAddReader($reader);
}
function it_is_not_able_to_remove_unexisting_reader()
{
$this->isSystemSupported();
$reader = "Hexmedia\\Crontab\\Reader\\AndroidReader";
$this->removeReader($reader)->shouldReturn($this);
$this->getReaders()->shouldHaveCount(1);
}
function it_is_able_to_remove_reader()
{
$this->isSystemSupported();
$reader = "Hexmedia\\Crontab\\Reader\\WindowsSystemReader";
$this->removeReader($reader)->shouldReturn($this);
$readers = $this->getReaders();
$readers->shouldHaveCount(1);
}
function it_is_able_to_read()
{
$this->isSystemSupported();
$readed = $this->read();
$readed->shouldHaveType('Hexmedia\Crontab\Crontab');
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab;
/**
* Class Variables
*
* @package Hexmedia\Crontab
*/
class Variables implements \Iterator
{
/**
* @var int
*/
private $currentIndex = 0;
/**
* @var array
*/
private $values = array();
/**
* @var array
*/
private $keys = array();
/**
* Variables constructor.
*
* @param array $variables
*/
public function __construct(array $variables)
{
$this->values = $variables;
$this->keys = array_keys($variables);
}
/**
* Return the current element
*
* @link http://php.net/manual/en/iterator.current.php
*
* @return mixed Can return any type.
* @since 5.0.0
*/
public function current()
{
return $this->values[$this->keys[$this->currentIndex]];
}
/**
* Move forward to next element
*
* @link http://php.net/manual/en/iterator.next.php
*
* @return void Any returned value is ignored.
* @since 5.0.0
*/
public function next()
{
$this->currentIndex++;
}
/**
* Return the key of the current element
*
* @link http://php.net/manual/en/iterator.key.php
*
* @return mixed scalar on success, or null on failure.
* @since 5.0.0
*/
public function key()
{
return $this->keys[$this->currentIndex];
}
/**
* Checks if current position is valid
*
* @link http://php.net/manual/en/iterator.valid.php
*
* @return boolean The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure.
* @since 5.0.0
*/
public function valid()
{
return isset($this->keys[$this->currentIndex]) && isset($this->values[$this->keys[$this->currentIndex]]);
}
/**
* Rewind the Iterator to the first element
*
* @link http://php.net/manual/en/iterator.rewind.php
*
* @return void Any returned value is ignored.
* @since 5.0.0
*/
public function rewind()
{
$this->currentIndex = 0;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Writer;
use Hexmedia\Crontab\Crontab;
use Hexmedia\Crontab\Writer\System\WriterFactory;
/**
* Class SystemWriter
*
* @package Hexmedia\Crontab\Writer
*/
class SystemWriter implements WriterInterface
{
/** @var System\WriterInterface|null writer */
private $writer;
/**
* SystemWriter constructor.
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function __construct()
{
$this->writer = WriterFactory::create();
}
/**
* @param Crontab $crontab
*
* @return bool
*/
public function write(Crontab $crontab)
{
return $this->writer->write($crontab);
}
/**
* @param Crontab $crontab
*
* @return string
*/
public function getContent(Crontab $crontab)
{
return $this->writer->getContent($crontab);
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Parser;
/**
* Interface ParserInterface
*
* @package Hexmedia\Crontab\Parser
*/
interface ParserInterface
{
/**
* @return array
*/
public function parse();
/**
* @return bool
*/
public static function isSupported();
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Exception;
/**
* Class FileNotFoundException
*
* @package Hexmedia\Crontab\Exception
*/
class FileNotFoundException extends \Exception
{
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Console;
use Hexmedia\Crontab\Crontab;
use Hexmedia\Crontab\Exception\ParsingException;
use Hexmedia\Crontab\Reader\ReaderInterface;
use Hexmedia\Crontab\Reader\SystemReader;
use Hexmedia\Crontab\ReaderFactory;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class CommandAbstract
*
* @package Hexmedia\Crontab\Console
*/
abstract class AbstractCommand extends Command
{
/**
* @param OutputInterface $output
* @param Crontab $crontab
* @param string|null $user
*
* @return mixed
*/
abstract public function output(OutputInterface $output, Crontab $crontab, $user = null);
/**
*
*/
protected function configure()
{
$this
->addOption('machine', 'm', InputOption::VALUE_OPTIONAL, 'Machine name to synchronize')
->addOption('user', 'u', InputOption::VALUE_OPTIONAL, 'Username for synchronization (crontab -u)')
->addOption('type', 't', InputOption::VALUE_REQUIRED, 'Type of parsed file, if not given system will guess')
->addOption('dry-run', null, InputOption::VALUE_OPTIONAL, 'Do not write crontab file');
$this->configureArguments();
$this->configureName();
}
/**
* @return mixed
*/
abstract protected function configureName();
/**
*
*/
protected function configureArguments()
{
$this
->addArgument('configuration-file', InputArgument::REQUIRED, 'Configuration file')
->addArgument('name', InputArgument::REQUIRED, 'Name of project');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*
* @return null
* @SuppressWarnings(PHPMD.StaticAccess)
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$name = $input->getArgument('name');
$user = $input->getOption('user');
$crontab = new Crontab($user, $name);
$systemReader = new SystemReader($user, $crontab);
$systemReader->read();
$configuration = $this->prepareConfiguration($input);
$configuration['crontab'] = $crontab;
/** @var ReaderInterface $reader */
$reader = ReaderFactory::create($configuration);
try {
$crontab = $reader->read();
} catch (ParsingException $e) {
$output->writeln(
sprintf(
"<error>File '%s' does not have --type=%s or has error in formatting.</error>",
$configuration['file'],
$configuration['type']
)
);
return 1;
}
$this->output($output, $crontab, $user);
}
/**
* @param InputInterface $input
*
* @return array
*/
protected function prepareConfiguration(InputInterface $input)
{
$configuration = array();
$configuration['user'] = $input->getOption('user');
$configuration['type'] = $input->getOption('type');
$configuration['file'] = $input->getArgument('configuration-file');
$configuration['name'] = $input->getArgument('name');
$configuration['machine'] = $input->getOption('machine');
return $configuration;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Parser\Unix;
use Hexmedia\Crontab\Exception\ParseException;
use Hexmedia\Crontab\Parser\AbstractParser;
use Hexmedia\Crontab\Parser\ParserInterface;
use Hexmedia\Crontab\System\Unix;
/**
* Class UnixParser
*
* @package Hexmedia\Crontab\Parser\Unix
*/
class UnixParser extends AbstractParser implements ParserInterface
{
/**
* @return array
* @throws ParseException
*/
public function parse()
{
$content = $this->getContent();
if (false === $content || "" === $content) {
return null;
}
$content = "\n" . $content; //a little trick to allow allow only rules that begins at the begining of line
if (!preg_match_all('/' . $this->getCrontabRegexRule() . '/', $content, $matches, PREG_SET_ORDER)) {
throw new ParseException(
sprintf("Cannot match this file error: '%s'", (preg_last_error() ?: "wrong file format"))
);
}
$return = array();
foreach ($matches as $match) {
$return[] = $this->parseOneMatch($match);
}
return $return;
}
/**
* @return bool
*
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public static function isSupported()
{
return Unix::isUnix();
}
/**
* @param array $match
*
* @return array
*/
private function parseOneMatch(array $match)
{
$array = array();
if (isset($match['logFile'])) {
$array['log_file'] = $match['logFile'];
}
$array['command'] = trim($match['command']);
$array['day_of_week'] = $match['dayOfWeek'];
$array['day_of_month'] = $match['dayOfMonth'];
$array['hour'] = $match['hours'];
$array['minute'] = $match['minutes'];
$array['month'] = $match['month'];
$vAndC = $this->parseVariablesAndComments($match['vandc']);
$array['comment'] = $vAndC['comment'];
$array['variables'] = $vAndC['variables'];
return $array;
}
/**
* @param string $match
*
* @return array
*/
private function parseVariablesAndComments($match)
{
$match = trim($match);
$comment = '';
$variables = array();
if ($match) {
if (preg_match_all('/' . $this->getVariableRule() . '/', $match, $matches, PREG_SET_ORDER)) {
foreach ($matches as $m) {
$variables[$m['variable']] = $m['value'];
}
}
if (preg_match_all('/' . $this->getCommentRule() . '/', $match, $matches, PREG_SET_ORDER)) {
foreach ($matches as $m) {
$comment .= trim($m['comment']) . "\n";
}
}
}
return array(
'comment' => trim($comment),
'variables' => $variables,
);
}
/**
* @return string
*/
private function getCrontabRegexRule()
{
$crontabRule = '\n(?<minutes>([0-9]{1,2}|\*|\*\/[0-9]{1,2}))[\t\s]+' . '(?<hours>([0-9]{1,2}|\*|\*\/[0-9]{1,2}))[\t\s]+(?<dayOfMonth>([0-9]{1,2}|\*|\*\/[0-9]{1,2}))[\t\s]+' . '(?<month>([0-9]{1,2}|\*|\*\/[0-9]{1,2}))[\t\s]+(?<dayOfWeek>([0-9]{1,2}|\*|\*\/[0-9]{1,2}))[\t\s]+' . '(?<command>[^>]*)[\t\s]+(>[>\s\t]?(?<logFile>[a-zA-Z0-9\/\-\_:\.]*))?';
$variableRule = sprintf('(%s\n?){0,}', $this->getVariableRule());
$commentRule = sprintf('(%s\n?){0,}', $this->getCommentRule());
$cAndVRule = '(?<vandc>(' . $commentRule . $variableRule . '){0,})';
$rule = '(?<rule>' . $cAndVRule . $crontabRule . ')';
return $rule;
}
/**
* @return string
*/
private function getCommentRule()
{
return '(#(?<comment>.*))';
}
/**
* @return string
*/
private function getVariableRule()
{
return '(?<variable>[A-Za-z0-9_]*)=(?<value>.*)';
}
}
<file_sep>Tests:
------
* Configure at least one osx(travis) environment to test if it is working on osx.
This version
------------
* System reader should also use factory.
* Readers needs to be checked and refactored
* Check names of all systems that should be supported. All Unix like.
* Add specs to existing commands
* Try integration with Symfony CrontabBundle. This will need some commands to be rewritten
* Unify exception names.
* Change beforeComment to comment
* Add protection for special strings in unix, if they exists, this should not work.
Next Versions
-------------
* support for special strings in unix cron, and possibility to setup cron for startup.
* support for comments in variables, currently, all comments between variables will be ignored, and removed.
* add support for importing tasks from crontab to file, should be interactive command.
In future
---------
* support for windows Tasks (more info: http://stackoverflow.com/questions/132971/what-is-the-windows-version-of-cron, https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357(v=vs.85).aspx)
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace dev\Hexmedia\Crontab\PhpSpec;
use Hexmedia\Crontab\System\Unix;
use PhpSpec\Exception\Example\SkippingException;
use PhpSpec\ObjectBehavior;
/**
* Class SystemAwareObjectBehavior
*
* @package dev\Hexmedia\Crontab\PhpSpec
*/
class SystemAwareObjectBehavior extends ObjectBehavior
{
protected function isSystemSupported()
{
if (false === Unix::isUnix()) {
throw new SkippingException(
sprintf('Your os "%s" is currently not supported.', PHP_OS)
);
}
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab\Console;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class SynchronizeCommandSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Console\SynchronizeCommand');
$this->shouldHaveType('Symfony\Component\Console\Command\Command');
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
/**
* @(c) 2013-2015 Hexmedia.pl <<EMAIL>>
*/
namespace Hexmedia\Crontab\Writer\System;
use Hexmedia\Crontab\Exception\NoWriterForSystemException;
use Hexmedia\Crontab\Exception\WriterNotExistsException;
/**
* Class WriterFactory
*
* @package Hexmedia\Crontab\Writer\System
*/
class WriterFactory
{
/**
* @var array
*/
private static $writers = array('Hexmedia\Crontab\Writer\System\UnixWriter');
/**
* @return WriterInterface|null
* @throws NoWriterForSystemException
*/
public static function create()
{
foreach (self::getWriters() as $writer) {
if (true === call_user_func($writer . '::isSupported')) {
return new $writer();
}
}
throw new NoWriterForSystemException(
sprintf("Writer for your operating system '%s' was not found!", PHP_OS)
);
}
/**
* @param string $writer
*
* @return bool
*/
public static function removeWriter($writer)
{
$key = array_search($writer, self::$writers);
if (false !== $key) {
unset(self::$writers[$key]);
return true;
}
return false;
}
/**
* @param string $writer
*
* @throws WriterNotExistsException
*/
public static function addWriter($writer)
{
if (false === class_exists($writer)) {
throw new WriterNotExistsException(sprintf('Writer with given name %s does not exists.', $writer));
}
self::$writers[] = $writer;
}
/**
* @return array
*/
public static function getWriters()
{
return self::$writers;
}
/**
* @param array $writers
*/
public static function setWriters($writers)
{
self::$writers = $writers;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Reader;
use Hexmedia\Crontab\Crontab;
use Hexmedia\Crontab\System\Unix;
/**
* Class UnixSystemReader
*
* @package Hexmedia\Crontab\Reader
*/
class UnixSystemReader extends AbstractUnixReader
{
/**
* @var array
*/
private static $supportedOses = array('Linux', 'FreeBSD');
/**
* @var string
*/
private $user;
/**
* UnixSystemReader constructor.
*
* @param string $user
* @param Crontab|null $crontab
*/
public function __construct($user, Crontab $crontab = null)
{
$this->user = $user;
parent::__construct($crontab);
}
/**
* @return bool
*/
public static function isSupported()
{
return in_array(PHP_OS, self::$supportedOses);
}
/**
* @return array
*/
public static function getSupportedOses()
{
return self::$supportedOses;
}
/**
* @param string $name
*
* @return bool
*/
public function addSupportedOs($name)
{
self::$supportedOses[] = $name;
return true;
}
/**
* @param string $name
*
* @return bool
*/
public function removeSupportedOs($name)
{
$key = array_search($name, self::$supportedOses);
if (false !== $key) {
unset(self::$supportedOses[$key]);
return true;
}
return false;
}
/**
* @return string
*
* @SuppressWarnings(PHPMD.StaticAccess)
*/
protected function getContent()
{
$result = Unix::get($this->user);
return $result;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace spec\Hexmedia\Crontab\Reader;
use Hexmedia\Crontab\Crontab;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class YamlReaderSpec extends ObjectBehavior
{
function let(Crontab $crontab)
{
$file = "./Tests/example_configurations/test.yml";
$machine = "www101";
$this->beConstructedWith($file, $crontab, $machine);
}
function it_is_initializable()
{
$this->shouldHaveType('Hexmedia\Crontab\Reader\YamlReader');
}
function it_is_returning_correct_value()
{
$read = $this->read();
$read->shouldHaveType('Hexmedia\Crontab\Crontab');
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* @copyright 2013-2016 Hexmedia.pl
* @license @see LICENSE
*/
namespace Hexmedia\Crontab\Reader;
use Hexmedia\Crontab\Crontab;
use Hexmedia\Crontab\Parser\Unix\ParserFactory;
use Hexmedia\Crontab\Parser\Unix\UnixParser;
/**
* Class UnixReaderAbstract
*
* @package Hexmedia\Crontab\Reader
*/
abstract class AbstractUnixReader extends AbstractArrayReader
{
/**
* UnixReader constructor.
*
* @param Crontab|null $crontab
*/
public function __construct(Crontab $crontab = null)
{
parent::__construct($crontab, null);
$this->setNotManaged(true);
}
/**
* @return array
*/
protected function prepareArray()
{
$content = $this->getContent();
$factory = new ParserFactory();
$parser = $factory->create($content, null);
return $parser->parse();
}
/**
* @return mixed
*/
abstract protected function getContent();
}
| 084237478837439d25d5f1e68b25fd8217cc353f | [
"Ant Build System",
"Markdown",
"PHP",
"INI"
] | 73 | PHP | kuczek/Crontab | 07f91339ade2d13a5044c5c2957583646f5c3271 | 07a15526d0e0a036a1ce8ccd7f3a5a1d712b7b8a |
refs/heads/master | <file_sep>package com.example.acer.testgraph;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class GraphFragment extends Fragment {
View thisview;
MyGraph newView;
public GraphFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("testing");
System.out.println(strtext);
// Inflate the layout for this fragment
thisview = inflater.inflate(R.layout.fragment_graph, container, false);
newView = new MyGraph(this);
LinearLayout pagelay = (LinearLayout) thisview.findViewById(R.id.pagelayout);
newView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
(pagelay).addView(newView);
return thisview;
}
}
<file_sep>package com.example.acer.testgraph;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by Acer on 11/16/2016.
*/
public class MyGraph extends View {
public MyGraph(Context context) {
super(context);
}
public MyGraph(Fragment fragment){
super(fragment.getContext());
}
public MyGraph(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyGraph(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//set the coordinates and variables
int xAxisStart = canvas.getWidth()*2/16;
int xAxisEnd = canvas.getWidth()*14/16;
int yAxisStart = canvas.getHeight()*3/4;
int yAxisEnd = canvas.getHeight()*1/4;
int delta = canvas.getWidth()*1/32;
int firstLim = xAxisStart;
int firstBarStart = firstLim + 1*delta;
int firstBarEnd = firstBarStart + 6*delta;
int secondLim = firstBarEnd + delta;
int secondBarStart = secondLim + delta;
int secondBarEnd = secondBarStart + 6*delta;
int thirdLim = secondBarEnd + delta;
int thirdBarStart = thirdLim + delta;
int thirdBarEnd = thirdBarStart + 6*delta;
int thirdBarTop = (yAxisStart-yAxisEnd)*1/4 + yAxisEnd;
int secondBarTop = (yAxisStart-yAxisEnd)*2/4 + yAxisEnd;
int firstBarTop = (yAxisStart-yAxisEnd)*3/4 + yAxisEnd;
//draw the text
Paint text = new Paint();
text.setColor(Color.BLACK);
text.setTextSize(40);
canvas.drawText("Date 1",firstBarStart+delta,yAxisStart+3*delta,text);
canvas.drawText("Date 2",secondBarStart+delta,yAxisStart+3*delta,text);
canvas.drawText("Date 3",thirdBarStart+delta,yAxisStart+3*delta,text);
canvas.drawText("75",xAxisStart-3*delta,thirdBarTop,text);
canvas.drawText("50",xAxisStart-3*delta,secondBarTop,text);
canvas.drawText("25",xAxisStart-3*delta,firstBarTop,text);
text.setTextSize(30);
canvas.drawText("minutes",xAxisStart-3*delta,yAxisEnd,text);
text.setTextSize(80);
text.setTextAlign(Paint.Align.CENTER);
text.setFakeBoldText(true);
canvas.drawText("Chart Title",secondBarStart+3*delta,yAxisEnd*3/4,text);
//draw the lines
Paint line = new Paint();
line.setColor(Color.BLACK);
line.setStrokeWidth(3);
canvas.drawLine(xAxisStart,yAxisStart,xAxisEnd,yAxisStart,line);
canvas.drawLine(xAxisStart,yAxisStart,xAxisStart,yAxisEnd,line);
canvas.drawLine(secondLim,yAxisStart+delta/4,secondLim,yAxisStart-delta/4,line);
canvas.drawLine(thirdLim,yAxisStart+delta/4,thirdLim,yAxisStart-delta/4,line);
canvas.drawLine(xAxisStart-delta/4,firstBarTop,xAxisStart+delta/4,firstBarTop,line);
canvas.drawLine(xAxisStart-delta/4,thirdBarTop,xAxisStart+delta/4,thirdBarTop,line);
canvas.drawLine(xAxisStart-delta/4,secondBarTop,xAxisStart+delta/4,secondBarTop,line);
//draw the bars
//first bar
Paint green = new Paint();
green.setColor(Color.GREEN);
green.setStyle(Paint.Style.FILL);
Rect firstRect = new Rect();
firstRect.set(firstBarStart,firstBarTop,firstBarEnd,yAxisStart);
canvas.drawRect(firstRect,green);
//second bar
Paint cyan = new Paint();
cyan.setColor(Color.CYAN);
cyan.setStyle(Paint.Style.FILL);
Rect secondRect = new Rect();
secondRect.set(secondBarStart,thirdBarTop,secondBarEnd,yAxisStart);
canvas.drawRect(secondRect,cyan);
//third bar
Paint magenta = new Paint();
magenta.setColor(Color.MAGENTA);
magenta.setStyle(Paint.Style.FILL);
Rect thirdRect = new Rect();
thirdRect.set(thirdBarStart,secondBarTop,thirdBarEnd,yAxisStart);
canvas.drawRect(thirdRect,magenta);
}
}
| f217b4c68e6848d914533b33f2081112e0481bf7 | [
"Java"
] | 2 | Java | raghid91/TestGraph | c7523870e54806f357c4b407af0b5413aaf4a215 | 6076c14a6bcd424d2f0d081cf2ebe004a80cdfc8 |
refs/heads/master | <repo_name>rjpatraining/rjpard-discoveryclient-verb<file_sep>/src/main/java/com/rjpard/discoveryclient/verb/RjpardDiscoveryclientVerbApplication.java
package com.rjpard.discoveryclient.verb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class RjpardDiscoveryclientVerbApplication {
public static void main(String[] args) {
SpringApplication.run(RjpardDiscoveryclientVerbApplication.class, args);
}
}
| 709b881d25b9b0f79e2c662707a2b83f87bf78e7 | [
"Java"
] | 1 | Java | rjpatraining/rjpard-discoveryclient-verb | 45aaba673dadbfff05b53c1b61f37adb3fef1a18 | 156a84b9a58a40bf3d959cac701d96a896504959 |
refs/heads/master | <repo_name>ninjaboynaru/lnet<file_sep>/entity_neuron_test.go
package main
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewNeuronPanics(t *testing.T) {
var assert *assert.Assertions = assert.New(t)
assert.Panics(func() { newNeuron(-1) }, "Should panic with negative input count")
assert.Panics(func() { newNeuron(-1) }, "Should panic with input count 0")
}
func TestNewNeuronWeightLength(t *testing.T) {
const inputCount int = 3
var neuron neuron = newNeuron(inputCount)
require.Len(t, neuron.weights, inputCount, "Neuron has incorrect amount of weights for given input size")
}
<file_sep>/entity_softmax_test.go
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSoftmaxForward(t *testing.T) {
var input matrix = matrix{
{2, 5, 6},
{4, 4, 6},
}
var expectedOutput matrix = matrix{
{0.013212886953789417, 0.265387928772242, 0.7213991842739688},
{0.10650697891920076, 0.10650697891920076, 0.7869860421615986},
}
var s softmax
var actualOutput matrix = s.forward(input)
assert.Equal(t, actualOutput, expectedOutput, "Softmax forward returns wrong value")
}
func TestSoftmaxBackwardPanics(t *testing.T) {
var assert *assert.Assertions = assert.New(t)
var s softmax
var mockForwardInputDerivatives matrix
var inputs matrix
var doPanic func() = func() { s.backward(mockForwardInputDerivatives) }
s = softmax{}
mockForwardInputDerivatives = matrix{{1, 1, 1}, {1, 1, 1}}
assert.Panics(doPanic, "Should panic on back propigate when forward has not yet ben called")
s = softmax{}
inputs = matrix{{1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 1, 1}}
mockForwardInputDerivatives = matrix{{1, 1, 1}, {1, 1, 1}}
s.forward(inputs)
assert.Panics(doPanic, "Should panic on back propigate when forward derivatives length does not match previous output/input length")
s = softmax{}
inputs = matrix{{1, 1, 1}, {1, 1, 1}}
mockForwardInputDerivatives = matrix{{1, 1}, {1, 1, 1, 1, 1}}
s.forward(inputs)
assert.Panics(doPanic, "Should panic on back propigate when forward derivatives row length does not match previous output/input row length")
}
func TestSoftmaxBackwardDerivativeInput(t *testing.T) {
var s softmax = softmax{}
var inputs matrix = matrix{
{6, 2, 2},
{4, 3, 2},
}
var mockForwardInputDerivatives matrix = matrix{
{1, 0, 0},
{1, 2, 0},
}
s.forward(inputs)
s.backward(mockForwardInputDerivatives)
var expectedInputDerivatives matrix = matrix{
{0.034088151482230225, -0.017044075741115054, -0.017044075741115054},
{-0.10291137744498538, 0.20686949103015304, -0.1039581135851675},
}
var actualInputDerivatives matrix = s.getInputDerivatives()
assert.Equal(t, expectedInputDerivatives, actualInputDerivatives, "Softmax backwards produces wrong input derivatives")
}
<file_sep>/entity_crossentropy.go
package main
import (
"fmt"
"math"
)
type crossentropy struct {
lastInput matrix
lastTargets []int
lastOutput vector
inputDerivatives matrix
}
func (c *crossentropy) forward(input matrix, targets []int) vector {
var inputLen int = len(input)
var targetsLen int = len(targets)
if inputLen != targetsLen {
panic(fmt.Sprintf(
"Crossentropy targets length %d does not match input batch size %d. There must be one target value per row in the inputs batch matrix",
inputLen, targetsLen,
))
}
const safetyMargin float64 = 1e-7
var output vector = make(vector, inputLen)
for index, inputRow := range input {
var targetIndex int = targets[index]
var rowLength int = len(inputRow)
if targetIndex <= -1 || targetIndex >= rowLength {
panic(fmt.Sprintf("A crossentropy target index %d is out of bounds of its corresponding input row length %d", targetIndex, rowLength))
}
var targetValue float64 = inputRow[targetIndex]
var loss float64 = clip(safetyMargin, 1-safetyMargin, targetValue)
loss = -1 * math.Log(loss)
output[index] = loss
}
c.lastInput = input
c.lastTargets = targets
c.lastOutput = output
return output
}
func (c crossentropy) getInputDerivatives() matrix {
return c.inputDerivatives
}
func (c *crossentropy) backward() {
var lastInputLen int = len(c.lastInput)
var lastTargetsLen int = len(c.lastTargets)
if lastInputLen == 0 {
panic("Crossentropy has no previous input. Can not back propigate")
}
if lastTargetsLen == 0 {
panic("Crossentropy has no previous targets. Can not back propigate")
}
var inputDerivatives matrix = make(matrix, lastInputLen)
for inputDerivativeIndex := range inputDerivatives {
var inputRow vector = c.lastInput[inputDerivativeIndex]
var derivativeRow vector = make(vector, len(inputRow))
var targetIndex int = c.lastTargets[inputDerivativeIndex]
for derivativeRowIndex := range derivativeRow {
if targetIndex == derivativeRowIndex {
derivativeRow[derivativeRowIndex] = -1 / inputRow[derivativeRowIndex]
} else {
derivativeRow[derivativeRowIndex] = 0
}
}
inputDerivatives[inputDerivativeIndex] = derivativeRow
}
c.inputDerivatives = inputDerivatives
}
func (c crossentropy) calculateAverageLoss() float64 {
if len(c.lastOutput) == 0 {
panic("Crossentropy has not previous output. Can not calculate average loss")
}
var averageLoss float64 = 0
for _, sampleLossValue := range c.lastOutput {
averageLoss += sampleLossValue
}
averageLoss = averageLoss / float64(len(c.lastOutput))
return averageLoss
}
<file_sep>/entity_crossentropy_test.go
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCrossentropyForwardPanics(t *testing.T) {
var input matrix
var targets []int
var assert *assert.Assertions = assert.New(t)
var tryForward func() = func() {
var c crossentropy
c.forward(input, targets)
}
input = matrix{{1, 2}, {1, 2}}
targets = []int{1}
assert.Panics(tryForward, "Should panic with mismatch between input and targets length")
targets = []int{0, 2}
assert.Panics(tryForward, "Should panic with targets value out of bounds of corresponding input row")
targets = []int{0, -1}
assert.Panics(tryForward, "Should panic with targets value out of bounds of corresponding input row")
}
func TestCrossentropyForward(t *testing.T) {
var input matrix = matrix{
{0.1, 0.5, 0.4},
{0.2, 0.3, 0.6},
{0.03, 0.4985, 0.4985},
}
var targets []int = []int{1, 2, 0}
var expectedOutput vector = vector{
0.6931471805599453,
0.5108256237659907,
3.506557897319982,
}
var c crossentropy
var actualOutput = c.forward(input, targets)
assert.Equal(t, actualOutput, expectedOutput, "Crossentropy forward returns wrong value")
}
func TestCrossentropyBackwardPanics(t *testing.T) {
var assert *assert.Assertions = assert.New(t)
var c crossentropy
var doPanic func() = func() { c.backward() }
c = crossentropy{}
assert.Panics(doPanic, "Should panic on back propigate with no previous input")
}
func TestCrossentropyBackwardDerivativeInput(t *testing.T) {
var c crossentropy = crossentropy{}
var inputs matrix = matrix{
{0.7, 0.2, 0.1},
{0.4, 0.5, 0.1},
}
var targets []int = []int{0, 2}
c.forward(inputs, targets)
c.backward()
var expectedInputDerivatives = matrix{
{-1.4285714285714286, 0, 0},
{0, 0, -10},
}
var actualInputDerivatives = c.getInputDerivatives()
assert.Equal(t, expectedInputDerivatives, actualInputDerivatives, "Crossentropy back propigate produces wrong input derivatives")
}
<file_sep>/entity_neuron.go
package main
import "fmt"
type neuron struct {
weights vector
bias float64
derivativeInputs matrix
derivativeWeights vector
derivativeBias float64
}
func newNeuron(inputCount int) neuron {
if inputCount <= 0 {
panic(fmt.Sprintf("Can not create neuron with input count %d", inputCount))
}
var bias float64 = randRangeFloat64(0, 1)
var weights []float64 = make(vector, inputCount)
for index := range weights {
weights[index] = randRangeFloat64(0.1, 1)
}
return neuron{weights: weights, bias: bias}
}
<file_sep>/entity_reluActivation_test.go
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestReluForwad(t *testing.T) {
var input matrix = matrix{
{12, -5, 5},
{-2, -2, 0.012},
}
var expectedOutput matrix = matrix{
{12, 0, 5},
{0, 0, 0.012},
}
var r reluActivation = reluActivation{}
var actualOutput matrix = r.forward(input)
assert.Equal(t, actualOutput, expectedOutput, "Relu forward returns wrong value")
}
func TestReluBackwardPanics(t *testing.T) {
var assert *assert.Assertions = assert.New(t)
var r reluActivation
var input matrix
var mockForwardInputDerivatives matrix
var doPanic func() = func() {
r.backward(mockForwardInputDerivatives)
}
r = reluActivation{}
assert.Panics(doPanic, "Should panic on back propigation with no previous input")
input = matrix{{1, 1, 1}, {1, 1, 1}}
mockForwardInputDerivatives = matrix{{1, 1, 1}}
r = reluActivation{}
r.forward(input)
assert.Panics(doPanic, "Should panic on back propigation when forward input derivatives length does not match previous input length")
input = matrix{{1, 1, 1}, {1, 1, 1}}
mockForwardInputDerivatives = matrix{{1, 1, 1}, {1}}
r = reluActivation{}
r.forward(input)
assert.Panics(doPanic, "Shoudl panic on back propigation when forward input derivatives contains rows whose length do not match previous input row lengths")
}
func TestReluBackwardDerivativeInput(t *testing.T) {
var input matrix = matrix{
{1, 1, 1},
{-1, 1, -1},
}
var mockForwardInputDerivatives matrix = matrix{
{2, 2, 2},
{2, 2, 2},
}
var r reluActivation = reluActivation{}
r.forward(input)
r.backward(mockForwardInputDerivatives)
var expectedInputDerivatives matrix = matrix{
{2, 2, 2},
{0, 2, 0},
}
var actualInputDerivatives = r.getInputDerivatives()
assert.Equal(t, expectedInputDerivatives, actualInputDerivatives, "RELU Activation back propigate produces wrong input derivatives")
}
<file_sep>/main.go
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UTC().UnixNano())
var inputs, targets = extractIrisSmall()
var l1 layer = newLayer(10, 4)
var relu1 reluActivation = reluActivation{}
var l2 layer = newLayer(3, 10)
var relu2 reluActivation = reluActivation{}
var softmaxActivation softmax = softmax{}
var crossentropyLoss crossentropy = crossentropy{}
const epochs int = 10000
const learningRateStart float64 = 1
const learningRateDecay float64 = 0.00000001
const logRate int = 100
var learningRate float64 = learningRateStart
var currentEpoch int = 0
var forward func() = func() {
var l1Output matrix = l1.forward(inputs)
var relu1Output matrix = relu1.forward(l1Output)
var l2Output matrix = l2.forward(relu1Output)
var relu2Output matrix = relu2.forward(l2Output)
var softmaxOutput matrix = softmaxActivation.forward(relu2Output)
crossentropyLoss.forward(softmaxOutput, targets)
}
var backward func() = func() {
crossentropyLoss.backward()
var crossentropyInputDerivatives matrix = crossentropyLoss.getInputDerivatives()
softmaxActivation.backward(crossentropyInputDerivatives)
var softmaxInputDerivatives matrix = softmaxActivation.getInputDerivatives()
relu2.backward(softmaxInputDerivatives)
var relu2InputDerivatives matrix = relu2.getInputDerivatives()
l2.backward(relu2InputDerivatives)
var l2InputDerivatives matrix = l2.getInputDerivatives()
relu1.backward(l2InputDerivatives)
var relu1InputDerivatives matrix = relu1.getInputDerivatives()
l1.backward(relu1InputDerivatives)
}
var optimizeLayer func(*layer) = func(l *layer) {
for index := range l.neurons {
var n *neuron = &l.neurons[index]
for weightIndex, derivativeValue := range n.derivativeWeights {
n.weights[weightIndex] = n.weights[weightIndex] + (-1 * derivativeValue * learningRate)
}
n.bias = n.bias + (-1 * n.derivativeBias * learningRate)
}
}
var optimize func() = func() {
optimizeLayer(&l1)
optimizeLayer(&l2)
}
var updateLearningRate func() = func() {
learningRate = learningRateStart * (1 / (1 + learningRateDecay*float64(currentEpoch)))
}
for i := 0; i < epochs; i++ {
currentEpoch = i + 1
updateLearningRate()
forward()
backward()
optimize()
if i%logRate == 0 {
var averageLoss float64 = crossentropyLoss.calculateAverageLoss()
fmt.Printf("Learning Rate: %f\nEpoch %d Average Loss: %f\n\n", learningRate, currentEpoch, averageLoss)
}
}
}
<file_sep>/entity_reluActivation.go
package main
import (
"fmt"
"math"
)
type reluActivation struct {
lastInput matrix
inputDerivatives matrix
}
func (r *reluActivation) forward(input matrix) matrix {
var output matrix = make(matrix, len(input))
for inputRowIndex, inputRow := range input {
output[inputRowIndex] = make(vector, len(inputRow))
for inputValueIndex, inputValue := range inputRow {
output[inputRowIndex][inputValueIndex] = math.Max(0, inputValue)
}
}
r.lastInput = input
return output
}
func (r reluActivation) getInputDerivatives() matrix {
return r.inputDerivatives
}
func (r *reluActivation) backward(forwardInputDerivatives matrix) {
var lastInputLen int = len(r.lastInput)
var forwardDerivativesLen int = len(forwardInputDerivatives)
if lastInputLen == 0 {
panic("RELU Activation has not previous input. Can not back propigate")
}
if lastInputLen != forwardDerivativesLen {
panic(fmt.Sprintf(
"Forward derivatives length %d does not match previous input length %d. There must be a row in the forward derivatives matrix for each input sample in the previous input",
forwardDerivativesLen, lastInputLen,
))
}
for forwardDerivativeRowIndex := range forwardInputDerivatives {
var derivativeRowLen int = len(forwardInputDerivatives[forwardDerivativeRowIndex])
var inputRowLen int = len(r.lastInput[forwardDerivativeRowIndex])
if derivativeRowLen != inputRowLen {
panic(fmt.Sprintf(
"The passed forward input derivative containes a row whose length %d does not match the length %d of its corresponding input row",
derivativeRowLen, inputRowLen,
))
}
}
var inputDerivatives matrix = make(matrix, forwardDerivativesLen)
for rowIndex := range inputDerivatives {
var inputRow vector = r.lastInput[rowIndex]
var forwardDerivativeRow vector = forwardInputDerivatives[rowIndex]
var inputDerivativeRow vector = make(vector, len(inputRow))
for valueIndex := range inputDerivativeRow {
if inputRow[valueIndex] <= 0 {
inputDerivativeRow[valueIndex] = 0
} else {
inputDerivativeRow[valueIndex] = forwardDerivativeRow[valueIndex]
}
}
inputDerivatives[rowIndex] = inputDerivativeRow
}
r.inputDerivatives = inputDerivatives
}
<file_sep>/README.md
# LNET
Convocational neural network implemented in Go as a learning project.
Built in order to test my understanding after reading ["Neural Networks From Scratch"](https://nnfs.io/) by [Setndex](https://www.youtube.com/channel/UCfzlCWGWYyIQ0aLC5w48gBQ).
## Barebones Approach
Where as most neural network implementations use a matrix of weight values and a vector of biases to represent a layer, I opted to separate neurons and layers into their own abstractions/structs.
That is, in my implementation a `layer` owns many `neurons` and a `neuron` owns a `bias` value and an array of `weights`. `input` is passed to a `layer` which then passed it to each of its `neurons` to be processed by them.
This approach is less performant and results in more code than the traditional approach does, but forces one to attain a deeper understanding of each and every operation that occurs at every level and phase of the network.<file_sep>/dataExtract.go
package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
const irisSmallCsvPath string = `C:\Users\THPC\Main\Development\Go\lnet\data\iris_small.csv`
func extractIrisSmall() (matrix, []int) {
var file *os.File
var err error
file, err = os.Open(irisSmallCsvPath)
if err != nil {
log.Fatal(err)
}
defer file.Close()
var reader *csv.Reader = csv.NewReader(file)
var rawCsvData [][]string
rawCsvData, err = reader.ReadAll()
if err != nil {
log.Fatal(err)
}
var rawCsvDataLen int = len(rawCsvData)
if rawCsvDataLen <= 1 {
log.Fatal("Small Iris CSV data file contains no rows or only the header row. Can not extract data")
}
var inputs matrix = make(matrix, rawCsvDataLen - 1)
var targets []int = make([]int, rawCsvDataLen - 1)
for recrodIndex, record := range rawCsvData {
if recrodIndex == 0 {
continue
}
var recrodLen int = len(record)
if recrodLen != 7 {
log.Fatal("Small Iris CSV data file contains rows with less or more than 7 values. All rows must have exactly 7 values")
}
var inputSample vector = make(vector, recrodLen - 3)
var sampleTarget int = -1
for recrodValueIndex, recrodValue := range record {
if recrodValueIndex == 0 || recrodValueIndex == 1 || recrodValueIndex == 2 || recrodValueIndex == 3 {
floatValue, err := strconv.ParseFloat(recrodValue, 64)
if err != nil {
log.Fatal(err)
}
inputSample[recrodValueIndex] = floatValue
continue
}
floatValue, err := strconv.ParseFloat(recrodValue, 64)
var intValue int = int(floatValue)
if err != nil {
log.Fatal(err)
}
if intValue != 1 && intValue != 0 {
log.Fatal("All row values from indexes 4 through 6 must be integers 0 or 1")
}
if recrodValueIndex == 4 && intValue == 1 {
sampleTarget = 0
}
if recrodValueIndex == 5 && intValue == 1 {
sampleTarget = 1
}
if recrodValueIndex == 6 && intValue == 1 {
sampleTarget = 2
}
}
if sampleTarget == -1 {
log.Fatal("A row does not contain a value of 1 in any of the label cloumns")
}
inputs[recrodIndex - 1] = inputSample
targets[recrodIndex - 1] = sampleTarget
}
return inputs, targets
}
<file_sep>/entity_softmax.go
package main
import (
"fmt"
"math"
)
type softmax struct {
lastOutput matrix
inputDerivatives matrix
}
func (s softmax) singleInputForward(input vector) vector {
var output vector = make(vector, len(input))
var exponentialSum float64 = 0
for index, value := range input {
var exponentialValue float64 = math.Exp(value)
exponentialSum += exponentialValue
output[index] = exponentialValue
}
for index, value := range output {
output[index] = value / exponentialSum
}
return output
}
func (s *softmax) forward(input matrix) matrix {
var output matrix = make(matrix, len(input))
for inputRowIndex, inputRow := range input {
output[inputRowIndex] = s.singleInputForward(inputRow)
}
s.lastOutput = output
return output
}
func (s softmax) getInputDerivatives() matrix {
return s.inputDerivatives
}
func (s softmax) singleSampleBackward(forwardInputDerivativeRow vector, outputRow vector) vector {
var derivativeRowLen int = len(forwardInputDerivativeRow)
var outputRowLen int = len(outputRow)
if derivativeRowLen != outputRowLen {
panic(fmt.Sprintf(
"The passed forward input derivative containes a row whose length %d does not match the length %d of its corresponding output row",
derivativeRowLen, outputRowLen,
))
}
var sampleInputDerivative vector = make(vector, outputRowLen)
for currentValueIndex := range sampleInputDerivative {
var currentValueOutput = outputRow[currentValueIndex]
var currentValueDerivative vector = make(vector, outputRowLen)
for outputIndex, outputValue := range outputRow {
var derivativeValue float64
if outputIndex == currentValueIndex {
derivativeValue = outputValue * (1 - outputValue)
} else {
derivativeValue = (-1 * outputValue) * currentValueOutput
}
var matchingForwardDerivativeValue float64 = forwardInputDerivativeRow[outputIndex]
derivativeValue *= matchingForwardDerivativeValue
currentValueDerivative[outputIndex] = derivativeValue
}
var finalDerivativeValue float64 = vectorSum(currentValueDerivative)
sampleInputDerivative[currentValueIndex] = finalDerivativeValue
}
return sampleInputDerivative
}
func (s *softmax) backward(forwardInputDerivatives matrix) {
var lastOutputLen int = len(s.lastOutput)
var forwardDerivativesLen int = len(forwardInputDerivatives)
if lastOutputLen == 0 {
panic("Softmax has no previous output. Can not back propigate")
}
if forwardDerivativesLen != lastOutputLen {
panic(fmt.Sprintf(
"Forward derivatives length %d does not match softmax last output length %d. There must be a row in the forward derivatives matrix for each output sample",
forwardDerivativesLen, lastOutputLen,
))
}
var inputDerivatives matrix = make(matrix, lastOutputLen)
for sampleIndex := range inputDerivatives {
var sampleOutput vector = s.lastOutput[sampleIndex]
var sampleForwardDerivative vector = forwardInputDerivatives[sampleIndex]
var sampleInputDerivative vector = s.singleSampleBackward(sampleForwardDerivative, sampleOutput)
inputDerivatives[sampleIndex] = sampleInputDerivative
}
s.inputDerivatives = inputDerivatives
}
<file_sep>/entity_layer_test.go
package main
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewLayerPanics(t *testing.T) {
var assert *assert.Assertions = assert.New(t)
assert.Panics(func() { newLayer(-1, 1) }, "Should panic with negative layer size")
assert.Panics(func() { newLayer(0, 1) }, "Should panic with layer size 0")
assert.Panics(func() { newLayer(1, -1) }, "Should panic with negative input count")
assert.Panics(func() { newLayer(1, 0) }, "Should panic with input count 0")
var weights matrix
var biases vector
var tryNewLayerExplicit func() = func() {
newLayerExplicit(weights, biases)
}
weights = matrix{}
biases = vector{1.0, 2.0}
assert.Panics(tryNewLayerExplicit, "Should panic with 0 neurons")
weights = matrix{{1.0}, {2.0}}
biases = vector{}
assert.Panics(tryNewLayerExplicit, "Should panic with 0 biases")
weights = matrix{}
biases = vector{}
assert.Panics(tryNewLayerExplicit, "Should panic with both 0 neurons and biases")
weights = matrix{{1.0}, {2.0}}
biases = vector{1.0}
assert.Panics(tryNewLayerExplicit, "Should panic with mismatch between neuron and bias counts")
weights = matrix{{1.0}, {2.0}}
biases = vector{1.0}
assert.Panics(tryNewLayerExplicit, "Should panic with mismatch between neuron and bias counts")
weights = matrix{
{1.0, 2.0, 3.0},
{1.1, 2.2, 5.4},
{1.2},
}
biases = vector{1.0, 1.0, 1.0}
assert.Panics(tryNewLayerExplicit, "Should panic with neurons that have different input counts")
}
func TestNewLayerLengths(t *testing.T) {
const layerSize int = 2
const inputCount int = 3
var require *require.Assertions = require.New(t)
var layer layer = newLayer(layerSize, inputCount)
require.Len(layer.neurons, layerSize, "Layer has incorrect amount of neurons")
for _, n := range layer.neurons {
require.Len(n.weights, inputCount, "Neuron in layer has incorrect ammount of weights for given input size")
}
require.Equal(layerSize, layer.layerSize, "Incorrect layerSize value")
require.Equal(inputCount, layer.inputCount, "Incorrect inputCount value")
}
func TestNewLayerExplicitLengths(t *testing.T) {
const neuronCount = 2
const inputCount = 3
var weights matrix = matrix{
{1, 2, 3},
{4, 5, 6},
}
var biases vector = vector{
1,
1,
}
var require *require.Assertions = require.New(t)
var layer layer = newLayerExplicit(weights, biases)
require.Equal(neuronCount, layer.layerSize, "Incorrect layerSize value")
require.Equal(inputCount, layer.inputCount, "Incorrect inputCount value")
require.Len(layer.neurons, neuronCount, "Layer has incorrect amount of neurons")
for index, n := range layer.neurons {
require.Equal(weights[index], n.weights, "Neuron weights incorrect")
require.Equal(biases[index], n.bias, "Neuron bias incorrect")
}
}
func TestLayerForward(t *testing.T) {
var inputs matrix
var expectedOutput matrix
var actualOutput matrix
var assert *assert.Assertions = assert.New(t)
var biases vector = vector{1, 2, 4}
var weights matrix = matrix{
{2, 2, 4},
{6, 4, 8},
{12, 1, 1},
}
var l layer = newLayerExplicit(weights, biases)
inputs = matrix{{1, 3, 2}}
expectedOutput = matrix{{17, 36, 21}}
actualOutput = l.forward(inputs)
assert.Equal(expectedOutput, actualOutput, "Layer forward returns wrong output for single input row")
inputs = matrix{
{2, 2, 2},
{1, 3, 2},
}
expectedOutput = matrix{
{17, 38, 32},
{17, 36, 21},
}
actualOutput = l.forward(inputs)
assert.Equal(expectedOutput, actualOutput, "Layer forward returns wrong output for multiple input rows")
}
func TestLayerBackwardPanics(t *testing.T) {
var l layer
var doPanicFunc func()
var mockForwardInputDerivatives matrix
var input matrix
l = newLayer(3, 3)
mockForwardInputDerivatives = matrix{{1}, {1}, {1}}
doPanicFunc = func() {
l.backward(mockForwardInputDerivatives)
}
assert.Panics(t, doPanicFunc, "Should panic on back propigate with no previous input")
l = newLayer(3, 3)
input = matrix{{1, 1, 1}, {1, 1, 1}}
mockForwardInputDerivatives = matrix{{1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 1, 1}}
l.forward(input)
doPanicFunc = func() {
l.backward(mockForwardInputDerivatives)
}
assert.Panics(t, doPanicFunc, "Should panic on back propigate with forward derivative length not matching input length")
l = newLayer(3, 3)
input = matrix{{1, 1, 1}, {1, 1, 1}}
mockForwardInputDerivatives = matrix{{1, 1, 1}, {1, 1, 1, 1, 1, 1}}
l.forward(input)
doPanicFunc = func() {
l.backward(mockForwardInputDerivatives)
}
assert.Panics(t, doPanicFunc, "Should panic on back propigate with forward derivative row length not matching layer size")
}
func TestLayerBackwardDerivativeInput(t *testing.T) {
var biases vector = vector{1, 2, 4}
var weights matrix = matrix{
{2, 2, 4},
{6, 4, 8},
{12, 1, 1},
}
var l layer = newLayerExplicit(weights, biases)
var inputs matrix = matrix{
{2, 2, 2},
{1, 3, 2},
}
var mockForwardInputDerivatives = matrix{
{1, 1, 1},
{2, 1, 1},
}
l.forward(inputs)
l.backward(mockForwardInputDerivatives)
var expectedInputDerivatives matrix = matrix{
{20, 7, 13},
{22, 9, 17},
}
var actualInputDerivatives matrix = l.getInputDerivatives()
assert.Equal(t, expectedInputDerivatives, actualInputDerivatives, "Layer backwards produces wrong input derivatives for multiple input rows")
}
func TestLayerBackwardDerivativeWeights(t *testing.T) {
var biases vector = vector{1, 2, 4}
var weights matrix = matrix{
{2, 2, 4},
{6, 4, 8},
{12, 1, 1},
}
var l layer = newLayerExplicit(weights, biases)
var inputs matrix = matrix{
{2, 2, 2},
{1, 3, 2},
}
var mockForwardInputDerivatives = matrix{
{1, 1, 1},
{2, 1, 1},
}
l.forward(inputs)
l.backward(mockForwardInputDerivatives)
var expectedNeuronDerivativeWeights matrix = matrix{
{2, 4, 3},
{1.5, 2.5, 2},
{1.5, 2.5, 2},
}
require.Equal(t, expectedNeuronDerivativeWeights[0], l.neurons[0].derivativeWeights, "Layer backwards produces wrong derivative weights for neuron 1")
require.Equal(t, expectedNeuronDerivativeWeights[1], l.neurons[1].derivativeWeights, "Layer backwards produces wrong derivative weights for neuron 2")
require.Equal(t, expectedNeuronDerivativeWeights[2], l.neurons[2].derivativeWeights, "Layer backwards produces wrong derivative weights for neuron 3")
}
<file_sep>/entity_layer.go
package main
import (
"fmt"
)
type layer struct {
layerSize int
inputCount int
lastInput matrix
neurons []neuron
}
func newLayer(layerSize, inputCount int) layer {
if layerSize <= 0 {
panic(fmt.Sprintf("Can not create layer with size %d", layerSize))
}
if inputCount <= 0 {
panic(fmt.Sprintf("Can not create layer with input count %d", inputCount))
}
var neurons []neuron = make([]neuron, layerSize)
for index := range neurons {
neurons[index] = newNeuron(inputCount)
}
return layer{layerSize: layerSize, inputCount: inputCount, neurons: neurons}
}
func newLayerExplicit(weights matrix, biases vector) layer {
var neuronCount = len(weights)
var biasCount = len(biases)
if neuronCount == 0 {
panic("Can not create layer with 0 neurons")
}
if biasCount == 0 {
panic("Can not create layer with 0 biases")
}
if neuronCount != biasCount {
panic(fmt.Sprintf("Layer neuron count %d does not match layer bias count %d", neuronCount, biasCount))
}
var firstWeightSetLen int = len(weights[0])
for index := range weights {
var currentWeightSet vector = weights[index]
if len(currentWeightSet) != firstWeightSetLen {
panic("Found neurons in layer with differint input counts")
}
}
var l layer = newLayer(neuronCount, firstWeightSetLen)
l.layerSize = neuronCount
l.inputCount = firstWeightSetLen
for index := range l.neurons {
var n *neuron = &l.neurons[index]
n.weights = weights[index]
n.bias = biases[index]
}
return l
}
func (l layer) singleInputForward(input vector) vector {
if l.inputCount != len(input) {
panic(fmt.Sprintf("Layer input count %d does not match len of provided input %d", l.inputCount, len(input)))
}
var output vector = make(vector, l.layerSize)
for neuronIndex, n := range l.neurons {
var neuronOutput float64
for weightIndex, weight := range n.weights {
neuronOutput += weight * input[weightIndex]
}
output[neuronIndex] = neuronOutput + n.bias
}
return output
}
func (l *layer) forward(input matrix) matrix {
if len(input) == 0 {
panic("Can not forward layer with empty input batch")
}
var output matrix = make(matrix, len(input))
for rowIndex, inputSample := range input {
output[rowIndex] = l.singleInputForward(inputSample)
}
l.lastInput = input
return output
}
// getLayerInputDerivatives pprocesses all the layers neurons input derivatives into a single matrix.
func (l layer) getInputDerivatives() matrix {
var inputDerivatives matrix = make(matrix, len(l.lastInput))
for sampleIndex := range inputDerivatives {
var inputDerivativeForSample vector = make(vector, l.inputCount)
for inputDerivativeIndex := range inputDerivativeForSample {
for _, n := range l.neurons {
inputDerivativeForSample[inputDerivativeIndex] = inputDerivativeForSample[inputDerivativeIndex] + n.derivativeInputs[sampleIndex][inputDerivativeIndex]
}
}
inputDerivatives[sampleIndex] = inputDerivativeForSample
}
return inputDerivatives
}
func (l *layer) backward(forwardInputDerivatives matrix) {
var lastInputLen int = len(l.lastInput)
var forwardInputDerivativesLen int = len(forwardInputDerivatives)
if lastInputLen == 0 {
panic("Layer has not previous input. Can not backpropigate")
}
if forwardInputDerivativesLen != lastInputLen {
panic(fmt.Sprintf(
"Forward derivatives length %d does not match previous inputs length %d. There must be a row in the forward derivatives matrix for each input sample in the previous input",
forwardInputDerivativesLen, lastInputLen,
))
}
for _, forwardDerivativeRow := range forwardInputDerivatives {
var forwardDerivativeRowLen int = len(forwardDerivativeRow)
if forwardDerivativeRowLen != l.layerSize {
panic(fmt.Sprintf("The passed forward input derivative contains a row whose length %d does not match the layer size %d", forwardDerivativeRowLen, l.layerSize))
}
}
for neuronIndex := range l.neurons {
var n *neuron = &l.neurons[neuronIndex]
n.derivativeWeights = make(vector, len(n.weights))
for weightIndex := range n.derivativeWeights {
for inputSampleIndex, inputSample := range l.lastInput {
var forwardDerivativeForSample vector = forwardInputDerivatives[inputSampleIndex]
var forwardDerivativeValueForSample float64 = forwardDerivativeForSample[neuronIndex]
var inputValueForWeight float64 = inputSample[weightIndex]
var derivativeWeightForSample float64 = inputValueForWeight * forwardDerivativeValueForSample
derivativeWeightForSample /= float64(lastInputLen)
n.derivativeWeights[weightIndex] = n.derivativeWeights[weightIndex] + derivativeWeightForSample
}
}
n.derivativeInputs = make(matrix, lastInputLen)
for inputSampleIndex := range l.lastInput {
var sampleDerivativeInput vector = make(vector, len(n.weights))
for derivativeIndex := range sampleDerivativeInput {
var matchingWeightValue float64 = n.weights[derivativeIndex]
var matchingForwardInputDerivative float64 = forwardInputDerivatives[inputSampleIndex][neuronIndex]
sampleDerivativeInput[derivativeIndex] = matchingWeightValue * matchingForwardInputDerivative
}
n.derivativeInputs[inputSampleIndex] = sampleDerivativeInput
}
n.derivativeBias = 0
for _, forwardDerivativeSample := range forwardInputDerivatives {
n.derivativeBias += (1 * forwardDerivativeSample[neuronIndex])
}
n.derivativeBias = n.derivativeBias / float64(len(forwardInputDerivatives))
}
}
| 08a592d8eab5b06f19b1a1f5a835656027f90bd7 | [
"Markdown",
"Go"
] | 13 | Go | ninjaboynaru/lnet | b4db042492d2de68084ffd7ddab420a6268f82e1 | 59f65db7dd6d611a47ff9e87a52188f4688184f3 |
refs/heads/master | <repo_name>salecharohit/secerts-management-hashicorp-vault<file_sep>/README.md
# Secrets Management using Hashicorp Vault Webinar for Nullcon
# Recording of the Webinar
[Secrets Management using Hashicorp Valut](https://youtu.be/tEmadhKh-1A)
# Slides
[Slides](./Slides.pdf)
# Instructions for Setting Vault Machine
- Download Vagrant 2.2.6+
- Download Virtualbox 6.0+
- git clone [<EMAIL>:salecharohit/secerts-management-hashicorp-vault.git](<EMAIL>:salecharohit/secerts-management-hashicorp-vault.git)
- cd secerts-management-hashicorp-vault
- vagrant up
<file_sep>/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Please install Vagrant latest version
# https://www.vagrantup.com/downloads.html
# After installing Vagrant Please install the following Plugins by executing the below commands
# vagrant plugin install vagrant-cachier vagrant-clean vagrant-disksize vagrant-vbguest
Vagrant.configure(2) do |config|
# Check for missing plugins
required_plugins = %w(vagrant-disksize vagrant-vbguest vagrant-clean)
plugin_installed = false
required_plugins.each do |plugin|
unless Vagrant.has_plugin?(plugin)
system "vagrant plugin install #{plugin}"
plugin_installed = true
end
end
# If new plugins installed, restart Vagrant process
if plugin_installed === true
exec "vagrant #{ARGV.join' '}"
end
config.vm.box = "ubuntu/bionic64"
config.vm.network "private_network", ip: "192.168.30.110"
config.vm.hostname = "vault"
config.disksize.size = '10GB'
config.vm.provision "file", source: "config.json", destination: "/tmp/config.json"
config.vm.provision "file", source: "vault.service", destination: "/tmp/vault.service"
config.vm.provider "virtualbox" do |vb|
vb.name = 'vault'
vb.memory = 2048
vb.cpus = 4
vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
vb.customize ["modifyvm", :id, "--natdnsproxy1", "on"]
vb.customize ["modifyvm", :id, "--ioapic", "on"]
vb.gui = false
end
config.vm.provision "shell",privileged: true, inline: <<-SHELL
apt-get install curl jq unzip -y
cd /opt/
# wget https://releases.hashicorp.com/vault/1.0.3/vault_1.0.3_linux_amd64.zip
wget https://releases.hashicorp.com/vault/1.4.2/vault_1.4.2_linux_amd64.zip
unzip vault_*.zip
cp vault /usr/bin/
mkdir /etc/vault
mkdir /vault-data
mkdir -p /logs/vault/
mv /tmp/config.json /etc/vault/
mv /tmp/vault.service /etc/systemd/system/
echo 'export VAULT_ADDR=http://127.0.0.1:8200' >> /home/vagrant/.bashrc
source /home/vagrant/.bashrc
systemctl start vault.service
systemctl enable vault.service
vault --version
SHELL
end
| eb8ddde33e14348a10680680655a0c02dc4778c3 | [
"Markdown",
"Ruby"
] | 2 | Markdown | salecharohit/secerts-management-hashicorp-vault | b1b9c2f43fc08fa39fe356dbdff7ade62a9c2fd0 | 230dfa68f7f68e2d57db411e58516339f1d1a194 |
refs/heads/master | <repo_name>xiyaowong/save-file-to-github<file_sep>/config.ini
owner =
repo =
token =
<file_sep>/util.go
package main
import (
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
)
// PathExists 文件存在检测
func PathExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return false
}
// BuildDir 创建目录
func BuildDir(abs_dir string) error {
return os.MkdirAll(path.Dir(abs_dir), os.ModePerm) //生成多级目录
}
// RemoveFile 删除文件或文件夹
func RemoveFile(abs_dir string) error {
return os.RemoveAll(abs_dir)
}
// GetPathDirs 获取目录所有文件夹
func GetPathDirs(abs_dir string) (re []string) {
if PathExists(abs_dir) {
files, _ := ioutil.ReadDir(abs_dir)
for _, f := range files {
if f.IsDir() {
re = append(re, f.Name())
}
}
}
return
}
// GetPathFiles 获取目录所有文件
func GetPathFiles(abs_dir string) (re []string) {
if PathExists(abs_dir) {
files, _ := ioutil.ReadDir(abs_dir)
for _, f := range files {
if !f.IsDir() {
re = append(re, f.Name())
}
}
}
return
}
// GetCurrentDir 获取程序运行路径
func GetCurrentDir() string {
dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
return strings.Replace(dir, "\\", "/", -1)
}
// GetExeDir 获取可执行文件的路径文件夹
func GetExeDir() (dir string, err error) {
path, err := os.Executable()
if err != nil {
return
}
dir = filepath.Dir(path)
return
}
<file_sep>/main.go
// Package main provides ...
package main
import (
"fmt"
"os"
"runtime"
)
func main() {
InitConfig()
var filePath string
if len(os.Args) == 1 {
fmt.Printf("输入文件路径: ")
fmt.Scanf("%s\n", &filePath)
} else {
filePath = os.Args[1]
}
if !PathExists(filePath) {
fmt.Println("文件不存在")
os.Exit(1)
}
url, err := Upload(filePath)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(url)
}
if runtime.GOOS == "windows" {
fmt.Println("按回车退出...")
fmt.Scanln()
}
}
<file_sep>/upload.go
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"path/filepath"
"strconv"
"time"
)
type Payload struct {
Message string `json:"message"`
Content string `json:"content"`
}
func Upload(filePath string) (url string, err error) {
fileName := fmt.Sprintf("%s-%s", strconv.Itoa(int(time.Now().Unix())), filepath.Base(filePath))
api := fmt.Sprintf("https://api.github.com/repos/%s/%s/contents/%s", Owner, Repo, fileName)
fileData, err := ioutil.ReadFile(filePath)
if err != nil {
return
}
payload := &Payload{
Message: fmt.Sprintf("Create file: %s", fileName),
Content: base64.StdEncoding.EncodeToString(fileData),
}
reqData, err := json.Marshal(payload)
if err != nil {
return
}
req, err := http.NewRequest("PUT", api, bytes.NewReader(reqData))
if err != nil {
return
}
req.Header.Add("Authorization", fmt.Sprintf("token %s", Token))
var client = &http.Client{
Timeout: 1 * time.Minute,
}
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
response := &CreateResponseJson{}
err = json.Unmarshal(body, &response)
if err != nil {
return
}
// fmt.Printf("%v %d", response, resp.StatusCode)
if resp.StatusCode != 201 {
err = fmt.Errorf("返回码错误: %d", resp.StatusCode)
return
}
url = fmt.Sprintf("https://cdn.jsdelivr.net/gh/%s/%s/%s", Owner, Repo, fileName)
return
}
<file_sep>/config.go
// Package main provides ...
package main
import (
"fmt"
"os"
"path/filepath"
"gopkg.in/ini.v1"
)
var (
Owner string
Repo string
Token string
)
func InitConfig() {
exeDir, err := GetExeDir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
cfg, err := ini.ShadowLoad(filepath.Join(exeDir, "config.ini"))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
sec, _ := cfg.GetSection(ini.DEFAULT_SECTION)
Owner = sec.Key("owner").String()
Repo = sec.Key("repo").String()
Token = sec.Key("token").String()
if Owner == "" || Repo == "" || Token == "" {
fmt.Println("请配置")
os.Exit(1)
}
}
<file_sep>/responseJson.go
package main
import "time"
type CreateResponseJson struct {
Content struct {
Name string `json:"name"`
Path string `json:"path"`
Sha string `json:"sha"`
Size int `json:"size"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
GitURL string `json:"git_url"`
DownloadURL string `json:"download_url"`
Type string `json:"type"`
Links struct {
Self string `json:"self"`
Git string `json:"git"`
HTML string `json:"html"`
} `json:"_links"`
} `json:"content"`
Commit struct {
Sha string `json:"sha"`
NodeID string `json:"node_id"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
Author struct {
Date time.Time `json:"date"`
Name string `json:"name"`
Email string `json:"email"`
} `json:"author"`
Committer struct {
Date time.Time `json:"date"`
Name string `json:"name"`
Email string `json:"email"`
} `json:"committer"`
Message string `json:"message"`
Tree struct {
URL string `json:"url"`
Sha string `json:"sha"`
} `json:"tree"`
Parents []struct {
URL string `json:"url"`
HTMLURL string `json:"html_url"`
Sha string `json:"sha"`
} `json:"parents"`
Verification struct {
Verified bool `json:"verified"`
Reason string `json:"reason"`
Signature interface{} `json:"signature"`
Payload interface{} `json:"payload"`
} `json:"verification"`
} `json:"commit"`
}
<file_sep>/README.md
# 通过 github api 上传到文件仓库,用 jsdelivr 的免费 cdn 用于个人日常使用的文件直链服务
给自己用的,如果你懒得自己写了,可以用一用
首先配置好 config.ini 文件, 相关内容自行了解 github 上传文件的文档
1. 直接运行的话,会提示输入文件路径
2. 也可以直接在命令行中将文件路径作为第二个参数调用
3. 在 windows 上可以直接把文件拖到该可执行文件上, 提示用该程序打开即可
| 3ea830f4ea78300780c0633d78e8e3dde32ed7f8 | [
"Markdown",
"Go",
"INI"
] | 7 | INI | xiyaowong/save-file-to-github | ab800076d76591123c1ab717b38352141016032b | 7b65add7e34678a7d91256ecb355378a98d23e39 |
refs/heads/master | <file_sep>#Create the data set
NEI <- readRDS("summarySCC_PM25.rds")
SCC <- readRDS("Source_Classification_Code.rds")
#subset data for Baltimore City from the dataset
dat = subset(NEI, fips=='24510')
#Create a new dataframe to do a summary
tab = aggregate(Emissions~type+year,data=dat,sum)
# Change numeric valur of the year to factors
tab$year = as.factor(tab$year)
#plot
library(ggplot2)
png(file="plot3.png")
ggplot(tab, aes(year, Emissions))+geom_bar(stat="identity")+facet_grid(.~type)+
labs( x="Baltimore City", y="Emissions")
dev.off()
<file_sep>#Create the data set
NEI <- readRDS("summarySCC_PM25.rds")
SCC <- readRDS("Source_Classification_Code.rds")
#subset data for Baltimore City from the dataset
dat = subset(NEI, fips=='24510')
#Create an array to do a summary
tab = tapply(dat$Emissions, dat$year, sum)
#Convert the array to a dataframe
tab = as.data.frame.table(tab)
#plot
png(file="plot2.png")
barplot(Freq ~ Var1, data = tab,, xlab="Baltimore City", ylab = 'Total PM2.5 Emmission')
dev.off()
<file_sep>#Create the data set
NEI <- readRDS("summarySCC_PM25.rds")
SCC <- readRDS("Source_Classification_Code.rds")
#Create an array to do a summary
tab = tapply(NEI$Emissions, NEI$year, sum)
#Convert the array to a dataframe
tab = as.data.frame.table(tab)
#plot
png(file="plot1.png")
barplot(Freq ~ Var1, data = tab,, xlab="year", ylab = 'Total PM2.5 Emmission')
dev.off()
<file_sep>#Create the data set
NEI <- readRDS("summarySCC_PM25.rds")
SCC <- readRDS("Source_Classification_Code.rds")
#subset SCC for coal combustion-related sources from the dataset
SCC2=subset(SCC, grepl('Comb.*Coal|Coal.*Comb',Short.Name))
#Create a vector haveing all the SCC code
code = SCC2$SCC
#subset the data containing coal combustion related code
dat = subset(NEI, NEI$SCC %in% code)
# get the sum of emmision for every year
tab= aggregate(Emissions~year, data=dat,sum)
#plot
library(ggplot2)
png(file="plot4.png")
ggplot(tab, aes(factor(year), Emissions))+geom_bar(stat="identity")+
labs( x="year", y="Coal Combustion-relatedEmissions in US")
dev.off()
<file_sep>#Create the data set
NEI <- readRDS("summarySCC_PM25.rds")
SCC <- readRDS("Source_Classification_Code.rds")
#subset SCC for motor vehicle sources from the dataset
SCC2=subset(SCC, grepl('Vehicle|Highway Veh',Short.Name))
SCC3= subset(SCC2, EI.Sector!='Mobile - Non-Road Equipment - Diesel'&
EI.Sector!='Mobile - Non-Road Equipment - Gasoline'&
EI.Sector!='Mobile - Non-Road Equipment - Other' &
EI.Sector!='Solvent - Industrial Surface Coating & Solvent Use' &
EI.Sector!='Miscellaneous Non-Industrial NEC' )
#Create a vector haveing all the SCC code
code = SCC3$SCC
#subset the data containing motor vehicle related code and city is Baltimore
dat = subset(NEI, NEI$SCC %in% code & fips=="24510")
# get the sum of emmision for every year
tab= aggregate(Emissions~year, data=dat,sum)
#plot
library(ggplot2)
png(file="plot5.png")
ggplot(tab, aes(factor(year), Emissions))+geom_bar(stat="identity")+
labs( x="year", y="Baltimore Vehicle-related Emissions")
dev.off()
| 666e6c47e82e53e706076c86881d8ba6789f068b | [
"R"
] | 5 | R | ludejia/Exploratory_data_analysis_project2 | dd354f7c9d49372f6fc60909dd607334c53d32b0 | e10899a69da1f0732ab2a7032706d57d6f30f744 |
refs/heads/master | <file_sep>var allData=[];
var category="general";
getData(category)
var links=Array.from(document.querySelectorAll(".nav-link"));
for(var i=0;i<links.length;i++)
{
links[i].addEventListener("click",function(e){
category=(e.target.text);
getData(category)
})
}
function getData(category){
var httpReq= new XMLHttpRequest();
httpReq.open("GET","http://newsapi.org/v2/top-headlines?country=eg&category="+category+"&apiKey=4433c45cb21646b8a2285f5e46e5c5a5");
httpReq.send();
httpReq.onreadystatechange=function()
{
if(httpReq.readyState==4 && httpReq.status==200){
allData=JSON.parse(httpReq.response).articles;
display()
console.log(allData)
}
}} ;
function display()
{
var temp=``;
for(var i=0 ; i<allData.length;i++)
{
temp +=`
<div class="col-lg-4 col-md-6 py-3">
<div class="item">
<img class="img-fluid" src="`+allData[i].urlToImage+`">
<a href="`+allData[i].url+`"><h4>`+allData[i].title+`</h4></a>
<p>`+allData[i].description+`</p>
</div>
</div>
`
}
document.getElementById("rowData").innerHTML=temp
}
function search(term)
{
var temp=``;
for(var i=0 ; i<allData.length;i++)
{
if(allData[i].title.includes(term))
temp +=`
<div class="col-md-4 py-3">
<div class="item">
<img class="img-fluid" src="`+allData[i].urlToImage+`">
<a href="`+allData[i].url+`"><h4>`+allData[i].title+`</h4></a>
<p>`+allData[i].description+`</p>
</div>
</div>
`
}
document.getElementById("rowData").innerHTML=temp
} | c5ef6432ebf6b8dda085a9885eedf31f6e7fee7d | [
"JavaScript"
] | 1 | JavaScript | Hassan-El-Sobky/httpRequestwebservice | 6bdfcd0611498c65a7eac152256ff5095a8522f0 | 74fb3b3b2c525581ab03f61db2019c842af5bb90 |
refs/heads/master | <repo_name>mpangilinan/home-screen-algorithm<file_sep>/src/main/java/homeScreenAlgorithm/ListOfEPGRecords.java
package homeScreenAlgorithm;
/**
* ListOfEPGRecords.java creates a REST template and collects lists of
* records with a given receiver ID.
* @author pangmel
*/
import java.util.List;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ListOfEPGRecords {
public List<EPGRecord> epgrecords;
@JsonCreator
public ListOfEPGRecords(@JsonProperty("epgrecords")List<EPGRecord> epgrecords) {
this.epgrecords = epgrecords;
}
public void setRecords(List<EPGRecord> epgrecords) {
this.epgrecords = epgrecords;
}
public List<EPGRecord> getEPGRecords() {
return epgrecords;
}
public static void main(String[] args) {
RestTemplate rest = new RestTemplate();
ListOfEPGRecords list = rest.getForObject("http://10.76.243.80/epg/seriesFutureShowings.pl?series=134219535", ListOfEPGRecords.class);
// for (EPGRecord r : list.getEPGRecords())
// System.out.println(r.get);
System.out.println(list.getEPGRecords());
}
}<file_sep>/src/main/java/homeScreenAlgorithm/ListOfWhatsHotCheck.java
package homeScreenAlgorithm;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.springframework.web.client.RestTemplate;
@XmlRootElement(name="TopInDMA")
public class ListOfWhatsHotCheck {
private List<WhatsHotCheck> whatsHotCheckItems;
public List<WhatsHotCheck> getWhatsHotCheckItems() {
return whatsHotCheckItems;
}
@XmlElement(name="Row")
public void setWhatsHotCheckItems(List<WhatsHotCheck> whatsHotCheckItems) {
this.whatsHotCheckItems = whatsHotCheckItems;
}
public static void main(String[] args) {
RestTemplate rest = new RestTemplate();
ListOfWhatsHotCheck list = rest.getForObject("http://vmeasuredl.dishaccess.tv/Now/National/Drama.xml", ListOfWhatsHotCheck.class);
System.out.println(list.getWhatsHotCheckItems());
}
}
<file_sep>/src/main/java/homeScreenAlgorithm/ListOfRecords.java
package homeScreenAlgorithm;
/**
* ListOfRecords.java creates a REST template and collects lists of
* records with a given receiver ID.
* @author pangmel
*/
import java.util.List;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ListOfRecords {
public List<Record> records;
@JsonCreator
public ListOfRecords(@JsonProperty("records")List<Record> records) {
this.records = records;
}
public void setRecords(List<Record> records) {
this.records = records;
}
public List<Record> getRecords() {
return records;
}
public static void main(String[] args) {
RestTemplate rest = new RestTemplate();
ListOfRecords list = rest.getForObject("http://10.76.243.80/stb/seriesHistory.pl?recId=28a0a95baa35ea0d72d265f93346456673f13496fc25", ListOfRecords.class);
//for (Record r : list.getRecords())
//System.out.println(r.getRecords());
System.out.println(list.getRecords());
}
}<file_sep>/README.md
Home Screen Intelligent Viewing Algorithm
HSIVA was my Summer 2014 Intern Project in which I wrote an AI program that tracked set-top box viewer history
and analyzed viewer trends. Depending on such trends, my program would then return which series viewers should
watch the next time they tuned into their televisions depending on the time of day.
<file_sep>/src/main/java/homeScreenAlgorithm/WhatsHotCheck.java
package homeScreenAlgorithm;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
public class WhatsHotCheck {
long series;
int episode;
long count;
String title;
public long getSeries() {
return series;
}
@XmlElement
public void setSeries(long series) {
this.series = series;
}
public int getEpisode() {
return episode;
}
@XmlElement
public void setEpisode(int episode) {
this.episode= episode;
}
public long getCount() {
return count;
}
@XmlElement
public void setCount(long count) {
this.count = count;
}
public String getTitle() {
return title;
}
@XmlElement
public void setTitle(String title) {
this.title = title;
}
}
| 5be87a569f913e8f2d53d4e8ac2a90cfb9cf9365 | [
"Markdown",
"Java"
] | 5 | Java | mpangilinan/home-screen-algorithm | 8b9d237028e5f34dfba4e94735846d67a2819ec2 | 20a436f1046642a5d7efa1f317c7bcddc8f2bde1 |
refs/heads/master | <repo_name>inier/vue-component-demo<file_sep>/README.md
# vue-component-demo
vue 封装一些常见类型的组件
### 运行
npm install
### 目录
/src/component - 全局组件
/src/pages/ - 封装常用的组件
- handleButton 类似 toolbar 的操作按钮组件<file_sep>/src/router/route.js
import index from '../pages/index'
import handleButton from '../pages/handleButton/handleButtonDemo'
import tableController from '../pages/tableController/tableController'
export default [
{
path: '/',
redirect: '/index'
},
{
path: '/index',
component: index
},
{
path: '/handleButton',
component: handleButton
},
{
path: '/tableController',
component: tableController
}
]
| f721ed64dc3f0b2d5fdbbe22c6e75d253f17c69e | [
"Markdown",
"JavaScript"
] | 2 | Markdown | inier/vue-component-demo | bcab0cb3d9547824079666013d2ff12bcae77aeb | 81cd63bce235cc4c82b9098f77524837ca944a96 |
refs/heads/master | <repo_name>Nessiec86/MapFrontEnd<file_sep>/src/pages/ProfileEdit.js
import React, { Component } from "react";
import { withAuth } from "../lib/AuthProvider";
import Navbar from "../components/Navbar";
import LoadingDots from "../components/LoadingDots";
import AuthService from "../lib/auth-service";
class ProfileEdit extends Component {
state = {
user: [],
status: "loaded"
};
handleChange = event => {
const { name, value } = event.target;
this.setState({ [name]: value });
};
handleEdit = (state) => {
AuthService.update(state)
this.props.history.push("/profile")
};
componentWillMount(){
this.setState({
user: this.props.user,
});
};
render() {
const { username, surname } = this.state.user;
switch (this.state.status) {
case "loading":
return <LoadingDots/>;
case "loaded":
return (
<div className="myContainer">
<div className="profile-background">
<img src="/Images/profile-placeholder@3x.png" alt="face"/>
<div className="profile-name">
<h1>{username}</h1>
<h1>{surname}</h1>
</div>
</div>
<section style={{margin:'1rem 0 0 0'}}>
<h3>Personal information</h3>
<div className="profile">
<img src="/Images/profile-placeholder@3x.png" alt="face"/>
<button onClick={() => this.handleEdit (this.state)}>
<p>Confirm</p>
</button>
</div>
<ul className="profile-ul">
<li className="profile-list">
<div className="profile-data">
<h3>Name</h3>
<input
type="text"
name="username"
onChange={this.handleChange}
/>
</div>
</li>
<li className="profile-list">
<div className="profile-data">
<h3>Surname</h3>
<input
type="text"
name="surname"
onChange={this.handleChange}
/>
</div>
</li>
<li className="profile-list">
<div className="profile-data">
<h3>Age</h3>
<input
type="number"
name="age"
onChange={this.handleChange}
/>
</div>
</li>
<li className="profile-list">
<div className="profile-data">
<h3>Email</h3>
<input
type="text"
name="email"
onChange={this.handleChange}
/>
</div>
</li>
</ul>
</section>
<Navbar/>
</div>
);
case "error":
return "error!!!! ";
default:
break;
}
}
}
export default withAuth(ProfileEdit);
<file_sep>/src/pages/Signup.js
import React, { Component } from "react";
import { withAuth } from "../lib/AuthProvider";
import SignupForm from "../components/SignupForm";
class Signup extends Component {
state = {
username: "",
surname: "",
password: ""
};
handleFormSubmit = event => {
event.preventDefault();
const { username, surname, password } = this.state;
this.props.signup({ username, surname, password });
};
handleChange = event => {
const { name, value } = event.target;
this.setState({ [name]: value });
};
render() {
return (
<SignupForm/>
);
}
}
export default withAuth(Signup);
<file_sep>/src/pages/Login.js
import React, { Component } from "react";
import { withAuth } from "../lib/AuthProvider";
import LoginForm from "../components/LoginForm";
class Login extends Component {
state = {
username: "",
password: ""
};
handleFormSubmit = event => {
event.preventDefault();
const { username, password } = this.state;
this.props.login({ username, password });
};
handleChange = event => {
const { name, value } = event.target;
this.setState({ [name]: value });
};
render() {
return (
<LoginForm/>
);
}
}
export default withAuth(Login);
<file_sep>/src/pages/Edit.js
import React, { Component } from "react";
import { withAuth } from "../lib/AuthProvider";
import Navbar from "../components/Navbar";
import TicketService from "../lib/ticket-service";
class Edit extends Component {
handleDelete(ticketId){
TicketService.delete(ticketId)
TicketService.joined()
this.props.history.push("/private")
}
render() {
const list = [this.props.location.state.list];
return (
<div className="myContainer">
<div className="home-background">
<img src="../Images/bg-image@3x.jpg" alt="bcn" />
<h1>Your Smar-T</h1>
</div>
{list && list.map(list => {
return <li key={list}>
<div className="edit">
<img src="../Images/trash-alt-solid.svg" alt="trash" onClick={() => this.handleDelete(list._id)}></img>
</div>
<div className="ticket-background-ok">
<img src={list.tkImage} alt="Tk"></img>
</div>
</li>
})
}
<div style={{margin:'-1rem 0 0 0'}}>
<Navbar/>
</div>
</div>
);
}
}
export default withAuth(Edit);<file_sep>/src/App.js
import React, { Component } from "react";
import AuthProvider from "./lib/AuthProvider";
import { Switch, Route } from "react-router-dom";
import PrivateRoute from "./components/PrivateRoute";
import AnonRoute from "./components/AnonRoute";
import Home from "./pages/Home";
import Private from "./pages/Private";
import Signup from "./pages/Signup";
import Login from "./pages/Login";
import Profile from "./pages/Profile";
import ProfileEdit from "./pages/ProfileEdit";
import Tickets from "./pages/Tickets";
import PayMethod from "./pages/PayMethod";
import MyCards from "./pages/MyCards";
import Payment from "./pages/Payment";
import Edit from "./pages/Edit";
import MyTickets from "./pages/MyTickets";
import NotFound from "./components/NotFound";
import Config from "./pages/Config";
import "./App.css";
class App extends Component {
render() {
return (
<AuthProvider>
<Switch>
<AnonRoute exact path="/" component={Home} />
<AnonRoute exact path="/login" component={Login} />
<AnonRoute exact path="/signup" component={Signup} />
<PrivateRoute exact path="/private" component={Private} />
<PrivateRoute exact path="/profile" component={Profile} />
<PrivateRoute exact path="/profile/edit" component={ProfileEdit} />
<PrivateRoute exact path="/tickets" component={Tickets} />
<PrivateRoute exact path="/tickets/payMethod" component={PayMethod} />
<PrivateRoute exact path="/tickets/myCards" component={MyCards} />
<PrivateRoute exact path="/tickets/pay" component={Payment} />
<PrivateRoute exact path="/tickets/edit" component={Edit} />
<PrivateRoute exact path="/MyTickets" component={MyTickets} />
<PrivateRoute exact path="/Config" component={Config}/>
<Route path='*' exact={true} component={NotFound} />
</Switch>
</AuthProvider>
);
}
}
export default App;<file_sep>/src/lib/ticket-service.js
import axios from "axios";
class Ticket {
constructor() {
this.Ticket = axios.create({
baseURL: process.env.REACT_APP_PUBLIC_DOMAIN,
withCredentials: true
});
}
create () {
return this.Ticket
.post("tickets/new")
.then(({ data }) => data);
}
read () {
return this.Ticket
.get("tickets/list")
.then(({ data }) => data);
}
ticket () {
return this.Ticket
.get("tickets/list/:id")
.then(({ data }) => data);
}
join (ticketId) {
return this.Ticket
.put(`tickets/list/${ticketId}`)
.then(({ data }) => data);
}
joined () {
return this.Ticket
.get("tickets/joined")
.then(({ data }) => data);
}
delete (ticketId) {
return this.Ticket
.post(`tickets/edit/${ticketId}`)
.then(({ data }) => data);
}
}
const ticket = new Ticket();
export default ticket;
<file_sep>/README.md
# Project Name
SMART-T
## Description
It is the best way to get around the city, it helps you to choose the different tickets of public transport. Configure your Smar-t on your mobile, travel without worrying about fares and save money.
## User Stories
- **404:** As an anon/user I can see a 404 page if I try to reach a page that does not exist so that I know it's my fault
- **500** - As a user I want to see a nice error page when the super team screws it up so that I know that it is not my fault.
- **Signup:** As an anon I can sign up in the platform so that I can start saving favorite restaurants
- **Login:** As a user I can login to the platform so that I can see my favorite restaurants
- **Logout:** As a user I can logout from the platform so no one else can use it
- **Configure your Profile** As a user I can create my profile
- **Configure your ticket** As a user I can configure my ticket with de best offers
- **Select your fare** As a user I can discover the best fare in 3 steps(Set transport use, zones, type of passenger)or Set manually your ticket
- **Best fares for you** As a user I can select my recommended fare
- **Choose pay metod** As a user I can pay with 3 platforms(Credit Card, Bank Account and Paypal)
- **Payment Screen** As a user I can confirm the purchase
- **See My Smar-t** As a user I can see and use my differents Tickets
- **My purchases log** As a user I can see my Log with all trips spent by ticket
- **Map with filters by transport category** As a user I can choose the transport category and see her own lines or stops
- **Select the Stop to begin the route** As a user I can see the stops by line and select the stop destination to see the route.
## Backlog
Add more differents transport tickets.
Geo Location:
- Add geolocation.
Add API's:
- Connect with Bicing, Bus, Ferro, Tram, Parkings, Renfe and show the stops and routes information on MapBox.
Routes:
- Calculate routes.
Update profile:
- Change image profile.
- Update your data.
# Client
## Pages
## Routes
| URL | Public | Funcionality |
|--------|------|-------------|
| `/home` | true | renders the homepage |
| `/login` | true | renders login form and redirects to /signup if user don't have account |
| `/signup` | true | renders signup form and redirects to /:userid if user logged in |
| `/logout` | false | logout |
| `/:userid` | false |renders the userpage |
| `/:userid/log` | false | render the log page and select by day, month or year log |
| `/:userid/tkconfig` | false | render the configuration page and enter your tickets especifications |
| `/:userid/tkconfig/pay` | false | render the payment page and enter your payment information and purchase |
| `/:userid/profile` | false | render the user profile page and update your profile page |
## Services
- Auth Service
- auth.login(user)
- auth.signup(user)
- auth.logout()
- auth.me()
- auth.getUser() // synchronous
# Server
## Models
User model
```
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { ObjectId } = Schema.Types;
const userSchema = new Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
lastName: { type: String },
email: { type: String },
myTickets: [{type: ObjectId, ref: 'Ticket'}],
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: 'updated_at'
},
});
const User = mongoose.model('User', userSchema);
module.exports = User;
```
Ticket Model
```
const mongoose = require('mongoose');
const { Schema } = mongoose;
const { ObjectId } = Schema.Types;
const ticketSchema = new Schema({
tkName: { type: String},
tkCategory: { type: String },
tkZones: Number,
tkDuration: Number,
description: String,
tkPrice: Number,
userID: {
type: ObjectId,
ref: 'User',
},
});
const Ticket = mongoose.model('Ticket', ticketSchema);
module.exports = Ticket;
```
Log Model
```
const mongoose = require('mongoose');
const { Schema } = mongoose;
const { ObjectId } = Schema.Types;
const logSchema = new Schema({
Date: Number,
Trip: Number,
tkPrice: Number,
TicketID: {
type: ObjectId,
ref: 'Ticket',
},
});
const Log = mongoose.model('Log', logSchema);
module.exports = Log;
```
## API routes:
### auth
| Method | Route | Functionality |
|---|---|---|
| GET | api/me |Check session status|
| POST | api/signup |Log in user to app and set user to session (Body: username, <PASSWORD>)|
| POST | api/login |Register user to app and set user to session (Body: username, password)|
| POST | api/logout |Log out user from app and remove session|
| GET | api/:userid/tkconfig | Render the configuration form |
| POST | api/:userid/tkconfig | Configure your ticket |
| GET | api/:userid/tkconfig/pay | Render the payment form |
| POST | api/:userid/tkconfig/pay | Configure your purchase |
| GET | api/:userid/log | Render the log of your trips by ticket |
| POST | api/:userid/log | Select by day, week or month |
| GET | api/:userid/profile | Render the user profile |
| POST | api/:userid/profile | Update user information |
## Links
### Trello/Kanban
[Link to your trello board](https://trello.com/b/kHDEnnDt/map)
### Git
The URL to your repository and to your deployed project
[Client repository Link](https://github.com/Nessiec86/MapFrontEnd)
[Server repository Link](https://github.com/Nessiec86/MapBackEnd)
[Deploy Link Backend](https://smar-t.herokuapp.com/)
[Deploy Link Frontend](https://smar-t.firebaseapp.com/)
### Slides
The url to your presentation slides
[Slides Link](http://slides.com)
### Wire-Frames InVision
https://projects.invisionapp.com/share/9KGOMY7384Q
<file_sep>/src/pages/Tickets.js
import React, { Component } from "react";
import { withAuth } from "../lib/AuthProvider";
import TicketService from "../lib/ticket-service";
import Card from "../lib/card-service";
import Navbar from "../components/Navbar";
import LoadingDots from "../components/LoadingDots";
import { Link } from "react-router-dom";
class Tickets extends Component {
state = {
list: [],
card: [],
status: "loading"
};
componentDidMount(){
TicketService.read()
.then((list) => {
this.setState({
list,
});
Card.read()
.then((card) => {
this.setState({
card,
status: "loaded"
});
})
})
.catch(error => {
this.setState({
status: "error"
});
});
};
handleSelect = (ticketId) => {
TicketService.join(ticketId)
};
render() {
const card = this.state.card
switch (this.state.status) {
case "loading":
return <LoadingDots/>;
case "loaded":
return (
<div className="myContainer">
<h1 className="cards-h1">Select your fare</h1>
<section className="cards">
{this.state.list.map((list, index) => {
return <div key={index} className="cards--content">
<li className="card--content--li" >{list.tkName}
<img src={list.tkImage} alt="Tk"></img>
<div>
<p>Trips {list.tkTrips}</p>
<p>{list.tkPrice}€</p>
<div className="card--select">
<button onClick={() => this.handleSelect(list._id)} style={{display: "flex"}}>
<Link to={{
pathname: `/tickets/paymethod`,
state: {
list,
card
}}}>SELECT THIS FARE<img src="../Images/back@3x.png" alt="arrow" style={{margin: "0px 0rem 1px 6px"}}/></Link>
</button>
</div>
</div>
</li>
</div>
})
}
</section>
<div style={{ margin:'-3.5rem 0 0 0' }}>
<Navbar/>
</div>
</div>
);
case "error":
return "error!!!! ";
default:
break;
}
}
}
export default withAuth(Tickets);
<file_sep>/src/pages/MyTickets.js
import React, { Component } from "react";
import { withAuth } from "../lib/AuthProvider";
import Navbar from "../components/Navbar";
import TicketService from "../lib/ticket-service";
import LoadingDots from "../components/LoadingDots";
class Tickets extends Component {
state = {
list: {},
status: "loading"
}
componentDidMount(){
TicketService.joined()
.then((list) => {
this.setState({
list,
status: "loaded"
});
})
.catch(error => {
this.setState({
status: "error"
});
});
}
render() {
switch (this.state.status) {
case "loading":
return <LoadingDots/>;
case "loaded":
return (
<div className="App">
<Navbar/>
<h1>MyTickets</h1>
{this.state.list.map(list => {
return <li key={list._id}>{list.tkName}<img src={list.tkImage} alt="Tk"></img></li>;
})}
</div>
);
case "error":
return "error!!!! ";
default:
break;
}
}
}
export default withAuth(Tickets);
<file_sep>/src/components/Navbar.js
import React, { Component } from "react";
import { withAuth } from "../lib/AuthProvider";
import { withRouter } from "react-router-dom";
import { Link } from "react-router-dom";
class Navbar extends Component {
render() {
const { logout, isLoggedin } = this.props;
return (
<div className="Navbar">
{isLoggedin ? (
<>
<nav>
<div>
<img src="../Images/expenses@3x.png" alt="log" style={{width: '3rem'}}></img>
</div>
<div>
<Link to="/Private/" >
<img src="../Images/mysmar-t@3x.png" alt="my smar-t" style={{width: '3rem'}}></img>
</Link>
</div>
<div>
<Link to="/Profile/" >
<img src="../Images/account@3x.png" alt="my smar-t" style={{width: '3rem'}}></img>
</Link>
</div>
<div>
<button onClick={logout}><img src="../Images/shut-down.svg" alt="log" style={{width: '2.5rem'}}/></button>
</div>
</nav>
</>
) : (
<>
</>
)}
</div>
);
}
}
export default withRouter(withAuth(Navbar));
<file_sep>/src/pages/Private.js
import React, { Component } from "react";
import { withAuth } from "../lib/AuthProvider";
import TicketService from "../lib/ticket-service";
import LoadingDots from "../components/LoadingDots";
import WithTicket from "../components/WithTicket";
import WhithoutTicket from "../components/WithoutTicket";
import AuthService from "../lib/auth-service";
class Private extends Component {
state = {
user: {},
list: [],
isLoading: true,
status: "loading"
};
componentDidMount(){
TicketService.joined()
.then((list) => {
AuthService.me()
.then((user) => {
this.setState({
user,
list,
status: "loaded",
isLoading: false
});
})
})
.catch(error => {
this.setState({
status: "error",
isLoading: false
});
});
};
render () {
const { isLoading } = this.state;
const { list } = this.state;
const { user } = this.state;
return isLoading ?
<LoadingDots/> :
list.length !== 0 ?
<WithTicket tickets={ list } usertickets={ user } />
:
<WhithoutTicket />
}
}
export default withAuth(Private);
<file_sep>/src/pages/MyCards.js
import React, { Component } from "react";
import { withAuth } from "../lib/AuthProvider";
import { Link } from "react-router-dom";
import Navbar from "../components/Navbar";
class Payment extends Component {
render() {
const card = this.props.location.state.card
const ticket = this.props.location.state.ticket
return (
<div className="myContainer">
<h1 className="cards-h1">Select your Card</h1>
<section className="cards">
{card ? card.map((card, index) => {
return <div key={index} className="cards--content">
<li className="card--select--li" key={card._id}>{}
<div className="apple-card">
<p style={{margin: "7rem 0 0 0.8rem"}}>{card.cardname}</p>
<p style={{margin: "-1.5rem 0 0 2rem"}}>{card.cardnum}</p>
</div>
<div className="card--select">
<button style={{display: "flex"}}>
<Link to={{
pathname: '/private',
}}>SELECT THIS CARD TO PAY<img src="../Images/back@3x.png" alt="arrow" style={{margin: "0px 0rem 1px 6px"}}/></Link>
</button>
</div>
</li>
</div>
}) :
<>
<p>No cards</p>
<div className="card--select" style={{display: "flex"}}>
<button>
<Link to={{
pathname: `/tickets/pay`,
state: {
ticket,
}}}>New Credit Card<img src="../Images/back@3x.png" alt="arrow" style={{margin: "0px 0rem 1px 6px"}}/></Link>
</button>
</div>
</>
}
</section>
<div style={{margin: '-3.5rem 0 0 0'}}>
<Navbar/>
</div>
</div>
);
}
}
export default withAuth(Payment);<file_sep>/src/pages/Config.js
import React, { Component } from "react";
import { withAuth } from "../lib/AuthProvider";
import { Link } from "react-router-dom";
import Navbar from "../components/Navbar";
class Config extends Component {
render() {
return (
<div className="myContainer">
<div>
<Link to="/tickets/" >Tickets</Link>
</div>
<div>
<Link to="/MyTickets/" >MyTickets</Link>
</div>
<Navbar/>
</div>
);
}
}
export default withAuth(Config);<file_sep>/src/pages/PayMethod.js
import React, { Component } from "react";
import { withAuth } from "../lib/AuthProvider";
import { Link } from "react-router-dom";
class Payment extends Component {
render() {
const card = this.props.location.state.card
const ticket = this.props.location.state.list
return (
<>
<div className="myContainer-sesion">
<h2>Selected!</h2>
<div className="tk-info">
<img src={ticket.tkImage} alt="ticket"></img>
<div>
<p>{ticket.tkName}</p>
<p>{ticket.tkZones}Zone</p>
<p>{ticket.tkPrice}€</p>
</div>
</div>
<div className="line-grey"></div>
<div className="select-pay">
<h2>Select payment method</h2>
<p>We will renovate automatically your ticket when it is over. You can change your fare & payment method whenever you want or unsuscribe</p>
</div>
<li style={{listStyle: "none", margin: "2rem 0 0 0"}}>
<div className="card--select" style={{display: "flex"}}>
<button>
<Link to={{
pathname: `/tickets/pay`,
state: {
ticket,
}}}>New Credit Card<img src="../Images/back@3x.png" alt="arrow" style={{margin: "0px 0rem 1px 6px"}}/></Link>
</button>
</div>
<div className="card--select" style={{display: "flex"}}>
<button>
<Link to={{
pathname: `/tickets/myCards`,
state: {
card,
}}}>My credit Cards<img src="../Images/back@3x.png" alt="arrow" style={{margin: "0px 0rem 1px 6px"}}/>
</Link>
</button>
</div>
</li>
</div>
</>
);
}
}
export default withAuth(Payment);<file_sep>/src/components/Counter.js
import React, { Component } from 'react';
import { Link } from "react-router-dom";
import TicketService from "../lib/ticket-service";
import authService from "../lib/auth-service";
class Counter extends Component {
state = {
counter: this.props.trips,
ticketId: this.props.ticketId,
};
handleDelete(ticketId){
TicketService.delete(ticketId)
}
handleDecrease = (trips, ticketId) => {
this.setState({
counter: trips - 1,
});
this.props.getTrips(trips)
authService.updateTrip(this.state)
};
render() {
const tripsRemaining = this.state.counter
const ticketId = this.state.ticketId
if (tripsRemaining === 0) {
this.handleDelete(ticketId)
}
return (
tripsRemaining !== 0 ?
<div>
<div className="ticket-config" style={{margin: "-2.5rem auto 1rem auto"}}>
<button onClick={() => this.handleDecrease(tripsRemaining, ticketId)} style={{display:"flex"}}>
<img src="../Images/final-nfc-vector-black@3x.png" alt="nfc"/>
<p style={{margin: "0.5rem 3rem 0 0"}}>PAY</p>
</button>
</div>
<div className="travels">
<p>Travels:{tripsRemaining}</p>
<p>Expires: 31 Dic 2019</p>
</div>
</div>
:
<div className="ticket-config" style={{margin: "-1.5rem auto 1rem auto"}}>
<Link to="/tickets/" onClick={() => this.handleDelete(ticketId)} style={{margin:"1rem 0 0 0"}}><p>BUY!</p></Link>
</div>
);
}
}
export default Counter;
<file_sep>/src/components/SignupForm.js
import React, { Component } from "react";
import { Form } from "react-bootstrap";
import { withAuth } from "../lib/AuthProvider";
import { Link } from "react-router-dom";
class SignupForm extends Component {
constructor(...args) {
super(...args);
this.state = {
validated: false,
username: "",
surname: "",
password: ""
};
};
handleSubmit = event => {
const form = event.currentTarget;
const { username, surname, password } = this.state;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
} else {
event.preventDefault();
this.props.signup({ username, surname, password });
}
this.setState({ validated: true });
}
handleChange = event => {
const { name, value } = event.target;
this.setState({ [name]: value });
};
render() {
const { username, surname, password, validated } = this.state;
return (
<div className="myContainer-sesion">
<Form
noValidate
validated={validated}
onSubmit={e => this.handleSubmit(e)}
className="text-center"
>
<h2 className="center-log">Sign up</h2>
<div className="sign_profile">
<img src="../Images/avatar@2x.png" width="74px" height="74px" alt="avatar"></img>
<div className="data">
<p>{username}</p>
<p>{surname}</p>
</div>
</div>
<Form.Group controlId="validationCustom01" className="sign">
<Form.Label style={{margin: "2rem 0 -1rem -19rem"}}>Name</Form.Label>
<Form.Control
className="sign"
required
type="text"
name="username"
value={username}
onChange={this.handleChange}
/>
<div className="line"></div>
<Form.Control.Feedback type="invalid">
Name is required.
</Form.Control.Feedback>
<Form.Control.Feedback>Nice Name!</Form.Control.Feedback>
</Form.Group>
<Form.Group controlId="validationCustom02" className="sign">
<Form.Label style={{margin: "1rem 0px 0.5rem -18rem"}}>Surname</Form.Label>
<Form.Control
required
type="text"
name="surname"
value={surname}
onChange={this.handleChange}
/>
<div className="line"></div>
<Form.Control.Feedback type="invalid">
Surname is required.
</Form.Control.Feedback>
<Form.Control.Feedback>Well done!</Form.Control.Feedback>
</Form.Group>
<Form.Group controlId="validationCustom03" className="sign">
<Form.Label style={{margin:"1rem 0 0 -17rem"}}>Password:</Form.Label>
<Form.Control
required
type="password"
name="<PASSWORD>"
value={<PASSWORD>}
onChange={this.handleChange}
/>
<div className="line"></div>
<Form.Control.Feedback type="invalid">
Password is required.
</Form.Control.Feedback>
<Form.Control.Feedback>Well done!</Form.Control.Feedback>
</Form.Group>
<div className="btn-signup">
<input type="submit" value="NEXT" />
</div>
<p>
Already have account?
<button><Link to={"/login"}>Login</Link></button>
</p>
</Form>
</div>
);
}
}
export default withAuth(SignupForm);
| a432d5470033ba016a0c5533bd3320173d28884b | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | Nessiec86/MapFrontEnd | 9bde5e2c5aa7bbcb38bbbe906a4cb5f8d552f783 | cd1f5c1ee15b371ee62b94865242ec1b19c57cb0 |
refs/heads/main | <repo_name>maciejszulia/zrob-je-wszystkie<file_sep>/4.c
#include <stdio.h>
#include <stdlib.h>
struct element{
int i;
struct element* next;
};
void wyswietlListeBezGlowy(struct element*Lista)
{
struct element * wsk = Lista;
if (wsk == NULL)
{
printf("Lista jest pusta\n");
}
while(wsk!=NULL)
{
printf("%p\n",wsk);
wsk=wsk->next;
}
printf("---\n");
}
int len(struct element*Lista)
{
struct element * wsk = Lista;
int i=0;
while(wsk!=NULL)
{
i++;
wsk=wsk->next;
}
return i;
}
int main()
{
//pusta lista bez glowy
struct element * Lista1 = NULL;
wyswietlListeBezGlowy(Lista1);
printf("%d\n",len(Lista1));
// dodanie elementu 4 na liste bez glowy
struct element * wsk = malloc(sizeof(struct element));
wsk->i=4;
wsk->next= NULL;
Lista1=wsk;
wyswietlListeBezGlowy(Lista1);
printf("%d \n",len(Lista1));
//puste lista z glowa
struct element * Lista2 = malloc(sizeof(struct element));
Lista2->next=NULL;
return 0;
}
<file_sep>/wariant-2/main.c
#include <stdio.h>
#include <stdlib.h>
void wypisz(int tab[10])
{
for (int i = 0; i < 10; i++)
{
if (i % 2 == 1)
{
printf("index: %i wartosc: %i\n", tab[i], i);
}
}
}
int main(int argc, char** argv)
{
int i;
int* tab = malloc(sizeof(int) * 10);
for (i = 0; i < 10; i++)
tab[i] = 0;
//for (i = 0; i < 10; i++)
// printf("index: %i wartosc: %i\n", i, tab[i]);
wypisz(tab);
return 0;
}<file_sep>/wariant-jakis/4.c
#include <stdio.h>
#include <stdlib.h>
#define TYDZIEN 7
struct dzienZKalendarza
{
int miesiac;
int dzien;
float sredniaTemperatura;
};
void wczytajDzienZKaledarza(struct dzienZKalendarza* dzien)
{
int wejscie;
do
{
printf("Podaj miesiac ");
scanf("%d", &wejscie);
} while (wejscie < 1 wejscie > 12);
dzien->miesiac = wejscie;
do
{
printf("Podaj dzien ");
scanf("%d", &wejscie);
} while (wejscie < 1 wejscie > 31);
dzien->dzien = wejscie;
float temp;
printf("Podaj srednia temperature ");
scanf("%f", &temp);
dzien->sredniaTemperatura = temp;
}
void wczytajDniZKaledarza(struct dzienZKalendarza* dzien, int ilosc)
{
int i;
for (i = 0; i < ilosc; i++)
{
wczytajDzienZKaledarza(&dzien[i]);
}
}
float sredniaWMiesiacu(struct dzienZKalendarza* dni, int ilosc, int miesiac)
{
float suma = 0;
int licznik = 0;
int i;
for (i = 0; i < ilosc; i++)
{
if (dni[i].miesiac == miesiac)
{
suma += dni[i].sredniaTemperatura;
licznik++;
}
}
if (licznik != 0)
return suma / (float)licznik;
return 0.0;
}
int main()
{
struct dzienZKalendarza tablicaDni[TYDZIEN];
wczytajDniZKaledarza(tablicaDni, TYDZIEN);
int i;
for (i = 1; i < 13; i++)
printf("%f\n", sredniaWMiesiacu(tablicaDni, TYDZIEN, i));
return 0;
}<file_sep>/3.c
#include <stdio.h>
#include <stdlib.h>
struct car{
char model[50],marka[50];
int cena;
};
void add_auto(struct car* samochod){
printf("Podaj markę:\n");
scanf("%50s", samochod->marka);
printf("Podaj model:\n");
scanf("%50s", samochod->model);
printf("Podaj cene:\n");
scanf("%d", samochod->cena);
}
void show(struct car in){
printf("Marka: %s\n",in.marka);
printf("Model: %s\n",in.model);
printf("Cena: %d\n",in.cena);
}
void show_brand(struct car*komis,char*brand,int n){
for(int i=0;i<n;i++){
int test=1;
for(int j=0;brand[j]!=0;j++){
if(brand[j]!=komis[i].marka[j]){
test=0;
break;
}
}
if(test==1){
show(komis[i]);
}
}
}
void show_cheaper(struct car*komis,int price,int n){
for(int i=0;i<n;i++){
if(price>komis[i].cena){
show(komis[i]);
}
}
return 0;
}
main(){
struct car c1,c2;
struct car ko[2]={c1,c2};
//show(ko[0]);
add_auto(&ko[0]);
//add_auto(ko,1);
return 0;
}
<file_sep>/wariant z dzisiaj/4.c
#include <stdio.h>
#include <stdlib.h>
struct element
{
int i;
struct element * next;
};
struct element * utworz()
{
return NULL;
};
struct element* dnk(struct element* list, int a)
{
struct element* wsk;
if(list == NULL)
{
wsk = malloc(sizeof(struct element));
list = wsk;
}
else
{
wsk = list;
while(wsk->next != NULL)
{
wsk = wsk->next;
}
wsk->next = malloc(sizeof(struct element));
wsk = wsk->next;
}
wsk->i = a;
wsk->next = NULL;
return list;
};
struct element* usun(struct element* list, int a)
{
struct element* wsk = list;
if(list->i == a)
{
list = list->next;
free(wsk);
}
struct element* wsk1 = list;
while(wsk1->next != NULL)
{
if(wsk1->next->i == a)
{
struct element* us = wsk1->next;
wsk1->next = us->next;
free(us);
}
else
{
wsk1 = wsk1->next;
}
}
struct element* tmp = list;
if(tmp == NULL)
{
printf("Lista jest pusta\n");
}
while(tmp != NULL)
{
printf("%d\n", tmp->i);
tmp = tmp->next;
}
printf("======\n");
};
int main()
{
struct element* l1 = utworz();
l1 = dnk(l1, 5);
l1 = dnk(l1, 4);
l1 = dnk(l1, 3);
l1 = dnk(l1, 4);
l1 = dnk(l1, 5);
usun(l1, 4);
return 0;
}<file_sep>/wariant-3/4.c
//zad 4
//nie wiem czy to ejst dobrze
#include <stdlib.h>
#include <stdio.h>
int main()
{
//int* lista;
//lista = (int*)calloc(256, sizeof(int));
int lista[256]; //tutaj mozna uzyc malloc? chyba....
for (int i = 0; i < (sizeof(lista) / sizeof(int)); i++)
{
printf("%p\n", lista + i);
}
int iloscElem = 0;
for (int i = 0; i < (sizeof(lista) / sizeof(int)); i++)
{
if ((lista + i) != NULL)
iloscElem++;
}
printf("\n ilosc elementow w liscie: %d \n", iloscElem);
return 0;
}<file_sep>/wariant3_2.c
#include<stdlib.h>
#include<stdio.h>
void show(int**tablica,int n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
printf("%d ",tablica[i][j]);
}
printf("\n");
}
}
void wczytaj(int**tablica,int n){
tablica=malloc(n*sizeof(int*));
for(int i=0;i<n;i++){
tablica[i]=malloc(n*sizeof(int));
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d", &tablica[i][j]);
}
}
}
void dodaj(int**tab1,int**tab2,int n){
int**out=malloc(n*sizeof(int*));
for(int i=0;i<n;i++){
out[i]=malloc(n*sizeof(int));
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
out[i][j]=tab1[i][j]+tab2[i][j];
}
}
show(out,n);
}
int main(){
int n=11;
int **tab1,**tab2;
while (n > 10){
scanf("%d", &n);
if(n>10)
printf("zla liczba!\n");
}
wczytaj(tab1,n);
wczytaj(tab2,n);
dodaj(tab1,tab2,n);
return 0;
}
<file_sep>/wariant-jakis/2.c
#include <stdio.h>
#include <stdlib.h>
void wczytaj(int n, int tab[][n]) {
printf("Podaj wartosci do tablicy o wymiarach %d x %d: ", n, n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &tab[i][j]);
}
}
}
void maxim(int n, int tab[][n]) {
int maks, nr_kolumny;
for (int i = 0; i < n; i++) {
int suma = 0;
for (int j = 0; j < n; j++) {
suma += tab[j][i];
if (i == 0) {
maks = suma;
nr_kolumny = i;
}
if (suma > maks) {
maks = suma;
nr_kolumny = i;
}
}
}
printf("Suma: %d, indeks kolumny: %d", maks, nr_kolumny);
}
int main() {
int n;
printf("Podaj n: ");
scanf("%d", &n);
while (n > 10) {
printf("!! n nie moze byc wiekszy niz 10, podaj n jeszcze raz: ");
scanf("%d", &n);
}
int tab[n][n];
wczytaj(n, tab);
maxim(n, tab);
return 0;
}<file_sep>/wariant-jakis/1.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a, b, x;
char c;
printf("Podaj pierwsza liczbe : \n");
scanf("%d", &a);
printf("Podaj druga: \n");
scanf("%d", &b);
getchar();
printf("Podaj znak( - + * / ): \n");
scanf("%c", &c);
switch (c)
{
case '-': x = a - b;
printf("Wynik to: %d\n", x);
break;
case '+': x = a + b;
printf("Wynik to: %d\n", x);
break;
case '': x = ab;
printf("Wynik to: %d\n", x);
break;
case '/':
printf("Wynik to: %d\n", x);
if (b == 0)
{
printf("NIE MOZNA DZIELIC PRZEZ 0 !!! ");
}
else
{
'/'; x = a / b;
printf("Wynik to: %d\n", x);
}
break;
}
return 0;
}<file_sep>/wariant-jakis/3.c
#include <stdio.h>
#include <stdlib.h>
struct element
{
int i;
struct element* next;
};
struct element* utworz()
{
struct element* temp = malloc(sizeof(struct element));
temp->next = NULL;
return temp;
};
void dodaj(struct element* Lista, int a)
{
struct element* wsk = Lista;
while (wsk->next != NULL)
{
wsk = wsk->next;
}
wsk->next = malloc(sizeof(struct element));
wsk = wsk->next;
wsk->i = a;
wsk->next = NULL;
}
void wyswietlListeZGlowa(struct element* Lista)
{
struct element* temp = Lista->next;
if (temp == NULL)
{
printf("Lista jest pusta\n");
}
while (temp != NULL)
{
printf("%d\n", temp->i);
temp = temp->next;
}
printf("----\n");
}
void wypiszwskazniki(struct element* Lista)
{
struct element* temp = Lista->next;
if (temp == NULL)
{
printf("Lista jest pusta\n");
}
printf("\n----\n");
while (temp != NULL)
{
printf("\n%p\n", temp);
temp = temp->next;
}
printf("----\n");
}
int ilosc(struct element* Lista)
{
int ile = 0;
struct element* temp = Lista->next;
if (temp == NULL)
{
printf("Lista jest pusta\n");
}
while (temp != NULL)
{
temp = temp->next;
ile++;
}
return ile;
}
int main()
{
struct element* lista1 = utworz();
wyswietlListeZGlowa(lista1);
dodaj(lista1, 2);
dodaj(lista1, -4);
dodaj(lista1, 45);
wyswietlListeZGlowa(lista1);
printf("Elementow w liscie jest: %d", ilosc(lista1));
wypiszwskazniki(lista1);
return 0;
}<file_sep>/wariant z dzisiaj/3.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define rozmiar 20
struct Auto {
char model[rozmiar];
char marka[rozmiar];
float cena;
};
void wczytaj(struct Auto tab2[2])
{
for(int i = 0; i < 2; i++)
{
printf("Podaj model: ");
scanf("%s", tab2[i].model);
printf("Podaj marke: ");
scanf("%s", tab2[i].marka);
printf("Podaj cene: ");
scanf("%f", &tab2[i].cena);
printf("\n");
}
}
void wyszukajMarka(struct Auto tab2[2])
{
char mareczka[rozmiar];
printf("Podaj model do wyszukania: ");
scanf("%s", mareczka);
printf("Model\tMarka\tCena\n");
for(int i = 0; i < 2; i++)
{
if(strcmp(tab2[i].marka, marki) == 0)
{
printf("%s\t%s\t%f\n", tab2[i].model, tab2[i].marka, tab2[i].cena);
}
else
{
printf("===\t===\t===\n");
}
}
printf("\n");
}
void wyszukajCena(struct Auto tab2[2])
{
float cenki;
printf("Podaj cene do wyszukania ponizej: ");
scanf("%f", &cenki);
printf("Model\tMarka\tCena\n");
for(int i = 0; i < 2; i++)
{
if(tab2[i].cena < cenki)
{
printf("%s\t%s\t%f\n", tab2[i].model, tab2[i].marka, tab2[i].cena);
}
else
{
printf("===\t===\t===\n");
}
}
printf("\n");
}
void wyszukajModel(struct Auto tab2[2])
{
char modelki[rozmiar];
printf("Podaj model do wyszukania: ");
scanf("%s", modelki);
printf("Model\tMarka\tCena\n");
for(int i = 0; i < 2; i++)
{
if(strcmp(tab2[i].model, modelki) == 0)
{
printf("%s\t%s\t%f\n", tab2[i].model, tab2[i].marka, tab2[i].cena);
}
}
printf("\n");
}
int main()
{
struct Auto tab2[2];
wczytaj(tab2);
wyszukajMarka(tab2);
wyszukajCena(tab2);
wyszukajModel(tab2);
return 0;
}<file_sep>/wariant-3/1.c
#include <stdlib.h>
#include <stdio.h>
void policz(char napis[])
{
int i = 0, a = 0, b = 0;
while (napis[i] != '\0')
{
if (napis[i] == 'a')
a++;
if (napis[i] == 'b')
b++;
i++;
}
printf("ilosc a: %d ilosc b: %d", a, b);
}
//void policz(char napis[])
//{
// int temp[1000];
// int i = 0;
// while (napis[i] != '\0')
// {
// if(napis[sizeof(napis)-i] == )
//
// }
//}
int main()
{
char napis[] = "aba";
policz(napis);
return 0;
}<file_sep>/README.md
# zrob-je-wszystkie
pomocy<file_sep>/wariant2_2.c
#include<stdlib.h>
#include<stdio.h>
void wypisz(int*tablica){
for(int i=0;i<11;i+=2){
printf("%d ",tablica[i]);
}
}
int main(){
int tab[11]={1,2,3,4,5,6,7,8,9,10};
wypisz(tab);
return 0;
}
<file_sep>/wariant z dzisiaj/1.c
#include <stdio.h>
#include <stdlib.h>
void zamiana(int* a, int* b)
{
if(*b < *a)
{
int temp = *a;
*a = *b;
*b = temp;
}
printf("Pierwsza liczba: %d\nDruga liczba: %d", *a, *b);
}
int main()
{
int a, b;
printf("Podaj 2 liczby typu int,\njesli druga bedzie mniejsza, zostana zamienione:\n");
scanf("%d %d", &a, &b);
zamiana(&a, &b);
return 0;
}<file_sep>/wariant-1/main.c
#include<stdlib.h>
#include<stdio.h>
int main()
{
unsigned int n = 1;
scanf_s("%u", &n);
if (n > 10)
{
while (n > 10)
{
scanf_s("%u", &n);
printf("\n zla liczba!\n");
}
}
//int A[n][n];
//int B[n][n];
// nie umiem dwu-wymiarowych tablic sory
return 0;
} | 09a3612455a2c3cdf58279cae73453d2a48fa924 | [
"Markdown",
"C"
] | 16 | C | maciejszulia/zrob-je-wszystkie | 42b68a47cd5b3ee93937b9522db665f5a3d0929b | 555f34a3d58f341664a3872234feefac3263f549 |
refs/heads/master | <file_sep>---
title: "Keras Example : Subtype Classification"
author: "<NAME>"
output:
html_document:
df_print: paged
code_folding: show
fig_height: 6
fig_width: 10
highlight: textmate
toc: no
toc_depth: 4
toc_float: yes
word_document: default
github_document:
toc: yes
toc_depth: 4
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T, eval = F)
```
## Library
```{r message=F, warning=F}
library(data.table)
library(tidyverse)
library(caret)
library(keras)
library(tensorflow)
```
## Install Keras in r (windows)
**Keras는 Python으로 구현된 쉽고 간결한 딥러닝 라이브러리이다.**
[케라스 이야기 - 깃헙 블로그](https://tykimos.github.io/2017/01/27/Keras_Talk/)
<br>
먼저 **Anaconda**를 설치하고, `devtools::install_github("rstudio/keras")`를 통해 keras를 설치한다.
tensorflow역시 마찬가지이다. `devtools::install_github("rstudio/tensorflow")`
<br>
이후, library(keras), library(tensorflow)불러온뒤, `install_tensorflow()`를 통해 설치하면 끝이 난다.
꽤 쉬운 설치방법이라 생각했지만, error를 마주치게 된다면 여기서 밑의 방법을 써보자.
며칠을 고생한 뒤 에러가 나지 않는 방법으로 설치를 성공했다.
-----------
박찬엽님의 블로그 글을 참조했다.
[(conda4r) R을 위해서 conda를 설치해보자](https://mrchypark.github.io/post/conda4r-r%EC%9D%84-%EC%9C%84%ED%95%B4%EC%84%9C-conda%EB%A5%BC-%EC%84%A4%EC%B9%98%ED%95%B4%EB%B3%B4%EC%9E%90/)
### My method
```{r}
remotes::install_github("mrchypark/multilinguer")
multilinguer::install_conda()
install.packages("reticulate")
reticulate::install_miniconda()
library(reticulate)
library(multilinguer)
# has_conda()
remotes::install_github("haven-jeon/KoSpacing")
devtools::install_github("nathan-russell/hashmap")
```
KoSpacing을 하기 위한 작업이다.(이 패키지에 대한 소개는 블로그를 참조)
혹시 대비해서 Anaconda Navigator에서도 Rstudio를 설치했다.
```{r}
library(KoSpacing)
library(reticulate)
packageVersion("KoSpacing")
KoSpacing::set_env()
spacing("김형호영화시장분석가는'1987'의네이버영화정보네티즌10점평에서언급된단어들을지난해12월27일부터올해1월10일까지통계프로그램R과KoNLP패키지로텍스트마이닝하여분석했다.")
# install_tensorflow()
# reticulate::conda_version()
# reticulate::conda_list()
```

나도 모르게 곧바로 set_env()를 실행하고 진행하면 에러가 나서, 띄워쓰기 함수를 한번 실행했어야 했다.(아마 keras, tensorflow를 백앤드로 사용한 것이라고 이해하고 있다.)
set_env()를 통해 환경세팅을 해준뒤, keras패키지의 함수들은 정상적으로 돌아갔다.(나의 경우)
결론적으로 설치가 완료되었다.(안정적인 방법은 더 찾고 있다)
MNIST를 불러오면서 확인을 함과 동시에 example을 진행해보면 좋을 것이다.
밑의 예제는 유방암의 4가지 아형분류에 대한 예제를 keras를 이용하여 진행해보려고 한다.
<br>
<br>
## Data
```{r}
data <- fread("mrna.csv", data.table = F)
meta_dat <- fread("meta_dat.csv", header = T,data.table = F)
rownames(data) <- data$V1
data$V1 <- NULL
rownames(meta_dat) <- meta_dat$V1
meta_dat$V1 <- NULL
```
물론 tibble::rownames_to_columns()함수도 유용하게 사용될 수 있다.
```{r}
data_mat <- as.matrix(data)
dimnames(data_mat) <- NULL
```
## Data Partition
```{r}
set.seed(100)
index <- createDataPartition(1:630, p = 0.8, list = F)
train_x <- data_mat[index,]
train_y <- meta_dat[index,]
test_x <- data_mat[-index,]
test_y <- meta_dat[-index,]
```
seed를 박아서 재현성을 유지한다.
```{r}
train_x %>% class; train_y %>% class
test_x %>% class; test_y %>% class
```

## One-hot encoding
```{r}
# HER2 Luminal A LuminalB TNBC
as.numeric(as.factor(train_y))[1:20]
# One-hot encoding : training labels
train_y_labels <- to_categorical(as.numeric(as.factor(train_y))-1)
# One-hot encoding : validation labels
test_y_labels <- to_categorical(as.numeric(as.factor(test_y))-1)
train_y_labels %>% head
test_y_labels %>% head
```

0아니면 1으로 만들어주기 위해 -1을 한다.
## Model
```{r}
use_session_with_seed(100)
# initial model
model <- keras_model_sequential()
# add the layer
# 96 inputs(independent var) -> [30 hidden nodes] ->
# [[30 hidden nodes]] -> 4 outputs
model %>%
layer_dense(units = 30, activation = 'relu', input_shape = c(96)) %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 30, activation = 'relu') %>%
layer_dense(units = 4, activation = 'softmax')
# inspect the model
summary(model)
# compile the model
model %>% compile(
loss = 'categorical_crossentropy',
optimizer = 'adam',
metrics = 'accuracy'
)
history <- model %>% fit(
train_x,
train_y_labels,
epochs = 30,
batch_size = 2,
validation_split = 0.2
)
```

<br>

모델의 정보, 훈련과정을 확인가능하다. 훈련과정 일부만 사진으로 들고왔다.
input shape에서 96은 투입되는 feature갯수를 의미한다.
첫번째 hidden layer에 node는 30개, 두번째 hidden layer에 node도 30개로 설정했다.
relu함수와 drop out에 대해서는 링크를 참조하자.
<br>

```{r}
plot(history)
```

어느 epoch시점부터 과적합이 일어나고 있다.
과적합의 조짐이 일어나기 전에 훈련을 stop 하는방법 등을 더 찾아봐야겠다.
## Evaluation
```{r}
model %>% evaluate(test_x, test_y_labels)
model %>% predict_classes(test_x)
table(prediction = model %>% predict_classes(test_x),
actual = as.numeric(as.factor(test_y))-1)
```

유방암 subtype을 분류하는 이전에 적합했던 기계학습 모형(Random Forest)과 비교해서 확인해볼 수 있다.
다음에는 더 이해할 수 있는 공부를 해볼예정이다.
<br>
<br>
## Reference
[dropout - Dive into Deep Learning (책)](https://ko.d2l.ai/chapter_deep-learning-basics/dropout.html)
[Relu - tstory blog](https://pythonkim.tistory.com/40)
[신경망이란 무엇인가? - 3Blue1Brown](https://www.youtube.com/watch?v=aircAruvnKk)
[optimizor - tstory blog](https://nittaku.tistory.com/271)
------------
<br>
[배치사이즈와 에포크](https://tykimos.github.io/2017/03/25/Fit_Talk/)
[keras : Deep Learning in R (DataCamp)](https://www.datacamp.com/community/tutorials/keras-r-deep-learning)
[Binary Classification using Keras in R](https://heartbeat.fritz.ai/binary-classification-using-keras-in-r-ef3d42202aaa)
<file_sep>
# library -----------------------------------------------------------------
library(tidyverse)
library(data.table)
library(glmnet)
library(caret)
library(Metrics)
library(doParallel)
doParallel::registerDoParallel(3)
load("D:/Jae Kwan/4학년여름/연구생/연구주제/glm.RData")
# one_hot_encoding --------------------------------------------------------
one_hot_meta_dat <- model.matrix(~.-1, meta_dat)
colnames(one_hot_meta_dat) <- one_hot_meta_dat %>% colnames %>%
str_remove(.,"condition")
# dummyVars(" ~ .", data = meta_dat)->kkkk
# predict(kkkk,meta_dat) %>% data.frame
# cancer ------------------------------------------------------------------
normal_t <- normal %>% t %>% as.matrix
normal_t[1:3,1:2]
dim(normal_t)
cancer_fit <- glmnet(x = normal_t,
y = one_hot_meta_dat,
family = "multinomial",
type.multinomial = "grouped",
alpha = 1) # alpha=1 : lasso
par(mfrow=c(2,2))
plot(cancer_fit)
cancer_fit$npasses
cancer_fit$lambda
# cv fit ------------------------------------------------------------------
set.seed(100)
cv_fit <-
cv.glmnet(x = normal_t,
y = one_hot_meta_dat,
family = "multinomial",
type.multinomial = "grouped",
alpha = 1,
parallel = T)
par(mfrow=c(1,1))
plot(cv_fit)
par(mfrow=c(2,2))
plot(cv_fit$glmnet.fit, xvar="lambda")
plot(cv_fit$glmnet.fit, xvar="norm")
par(mfrow=c(1,1))
cv_fit$lambda.1se
cv_fit$lambda.min
# predict(cv_fit, newx = normal_t, s = "lambda.1se", type = "class") -> a
#
# table(a, meta_dat$condition)
# mean(a==meta_dat)
# cancer_fit coef --------------------------------------------------------
# temp <- predict(cancer_fit, newx = normal_t,
# s = cv_fit$lambda.min,
# type = "class") # s : lambda
#
# temp %>% head
# temp %>% tail
#
# mean(temp==meta_dat)
# table(prediction = temp, actual = meta_dat$condition)
tmp_coeffs <- coef(cancer_fit, s = cv_fit$lambda.1se)
data.frame(name = tmp_coeffs[[1]]@Dimnames[[1]][tmp_coeffs[[1]]@i + 1], coefficient = tmp_coeffs[[1]]@x) -> k1
data.frame(name = tmp_coeffs[[2]]@Dimnames[[1]][tmp_coeffs[[2]]@i + 1], coefficient = tmp_coeffs[[2]]@x) -> k2
data.frame(name = tmp_coeffs[[3]]@Dimnames[[1]][tmp_coeffs[[3]]@i + 1], coefficient = tmp_coeffs[[3]]@x) -> k3
data.frame(name = tmp_coeffs[[4]]@Dimnames[[1]][tmp_coeffs[[4]]@i + 1], coefficient = tmp_coeffs[[4]]@x) -> k4
all(k1$name==k2$name)
all(k2$name==k3$name)
all(k3$name==k4$name)
k1 %>%
left_join(k2, by = "name") %>%
left_join(k3, by = "name") %>%
left_join(k3, by = "name")
# normalized count & gene condition ---------------------------------------
normal_temp <- normal %>% t %>% data.frame
normal_temp[1:2,1:2]
normal_z <- scale(normal_temp, center = T, scale = T)
normal_z <- normal_z %>% t %>% data.frame
normal_z[1:2,1:2]
sig_gene <- k1 %>%
select(name) %>%
left_join(normal_z %>% rownames_to_column(var="name"), by = c("name"))
sig_gene <- sig_gene[-1,]
sig_gene[1:2,1:3]
rownames(sig_gene) <- sig_gene[,1]
sig_gene <- sig_gene[,-1]
sig_gene <- sig_gene %>% t %>% data.frame
sig_gene <- sig_gene %>% rownames_to_column(var = "name")
sig_gene$name <- gsub(pattern = "\\.",replacement = "-",x = sig_gene$name)
sig_gene <- sig_gene %>% left_join(meta_dat %>% rownames_to_column("name"), by = c("name"))
colnames(sig_gene)
work <- sig_gene %>% select(1:11,"condition")
work %>% colnames
sig_gene %>% dim
work[1:2,1:4]
work_temp <-
work %>%
pivot_longer(cols = -c(condition, name),
names_to = "gene", values_to = "count")
work_temp %>% head
work_temp$count <- as.numeric(work_temp$count)
library(hrbrthemes)
library(viridis)
work_temp %>%
ggplot(aes(x=gene,y=count,fill=condition))+
geom_boxplot() +
scale_fill_viridis(discrete = TRUE, alpha=0.8) +
geom_jitter(color="black", size=0.06, alpha=0.2)+
theme_ipsum() +
theme(
legend.position=c(.9, .8),
plot.title = element_text(size=11)
) +
ggtitle("A boxplot by subtype") +
xlab("") +
ylab("Normalized Count") +
labs(fill="Subtype") +
scale_x_discrete(guide = guide_axis(n.dodge = 2))
# 4개 중 하나라도 유의한 유전자에 대한 것 중 10개를 도식화 한 것이다.
work_temp %>%
ggplot(aes(x=gene,y=count,fill=condition))+
geom_boxplot() +
scale_fill_viridis(discrete = TRUE, alpha=0.8) +
geom_jitter(color="black", size=0.06, alpha=0.2)+
theme_ipsum() +
theme(
legend.position=c(.9, .8),
plot.title = element_text(size=11)
) +
ggtitle("A boxplot by subtype") +
xlab("") +
ylab("Normalized Count") +
labs(fill="Subtype") +
scale_x_discrete(guide = guide_axis(n.dodge = 2))
# classificatoin ----------------------------------------------------------
set.seed(100)
index <- createDataPartition(1:630, p = 0.8, list = F)
train_x <- normal_temp[index,]
test_x <- normal_temp[-index,]
train_y <- meta_dat[index,]
test_y <- meta_dat[-index,]
trControl <- trainControl(method="cv",
number=5,
allowParallel =TRUE)
Grid <- expand.grid(.alpha = seq(0, 1, 0.1),
.lambda = seq(0.001, 0.1, length.out = 50))
glm_train <- train(x = train_x,
y = train_y,
method = "glmnet",
tuneGrid = Grid,
trControl = trControl,
metric = "accuracy",
verbose = FALSE)
plot(glm_train)
glm_train$bestTune
prediction <- predict(glm_train, newdata = test_x, type="raw")
confusionMatrix(prediction, test_y %>% as.factor)
<file_sep>---
title: "understanding of breast cancer"
author: "<NAME>"
output:
html_document:
fig_height: 6
fig_width: 10
highlight: textmate
toc: no
toc_depth: 4
toc_float: yes
word_document: default
github_document:
toc: yes
toc_depth: 4
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval=T)
```
# comprehension
## Breast Cancer
* `유방암`은 전 세계적으로 여자에게 가장 흔히 나타나는 암(물론 남자도 발병가능)
* 서부 유럽사람들은 유방암 발생률이 가장 높고 20~30년 전 부터 발생률은 서서히 증가하는 추세
* `50~70대 여성`에게 유방암은 발생률이 가장 높음
* 더 좋고 효과적인 screening programs, 치료법의 향상 -> 생존률 상승
<br>
<br>
### Two main types of breast cancer
유방암은 유방의 조직에서 시작
* **Ductal carcinoma**
starts in the tubes (ducts) that move milk from the breast to the nipple. Most breast cancers are of this type.
* **Lobular carcinoma**
starts in the parts of the breast, called lobules, which produce milk.
<img src="https://www.bebig.com/fileadmin/_processed_/csm_5000a57244_f826e1962d.jpg" width="400" height="300" />
※ Ductal :(인체나 식물의)도관
※ Lobular : 소엽의,뇌엽
TCGA focused mainly on two types of invasive breast cancer: ductal carcinoma(도관암) and lobular carcinoma(뇌엽암).
Invasive ductal carcinoma 는 가장 흔한 유방암 type이다.
It comprises about 65–85% of all breast cancer and develops in the milk ducts of the breast.
About 10% of all cases of advanced breast cancer 2 are invasive lobular breast carcinoma.
This cancer develops in the breast milk-producing lobules or glands.
<br>
[breast cancer 설명 출처](https://www.bebig.com/home/patients/breast_cancer/)
[TCGA's Study of Breast Ductal Carcinoma](https://www.cancer.gov/about-nci/organization/ccg/research/structural-genomics/tcga/studied-cancers/breast-ductal)
# 관련자료
## Paper {.tabset .tabset-fade .tabset-pills}
[Classifying Breast Cancer Subtypes Using Multiple Kernel Learning Based on Omics Data](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6471546/#B33-genes-10-00200)
**Omics** : 전체를 뜻하는 말인 `옴(-ome)`과 학문을 뜻하는 접미사 `익스(-ics)`가 결합된 말로, 어떤 특정 학문 분야를 말하기보다는 개별 유전자(gene), 전사물(transcript), 단백질(protein), 대사물(metabolite) 연구에 대비되는 **총체적인 개념의 데이터 세트를 바탕으로 하는 생물학 분야**
### Abstract
유방암 아형의 본질적인 차이를 탐구하는 것은 매우 중요
본질적인 차이는 임상 진단 및 치료 계획의 지정과 밀접하게 관련
생물학적, 의학적 데이터세트가 축적되면서 다양한 측면에서 볼 수 있는 여러 가지 Omics data가 존재
이런 데이터를 결합하면 예측의 정확성을 향상시킬 수 있음
**에스트로겐 수용체(ER)**, **프로게스테론 수용체(PR)**, **사람 표피성장인자 수용체2(HER2)**를 사용하여 유방암 아형을 정의
TCGA로부터 `mRNA data`, `methylation data` and `copy number variation (CNV) data`를 수집해 유방암 아형을 분류
다중 커널 학습(MKL)로 3개의 Omics data를 사용한 결과는 여러 개의 커널에 단일 Omics data를 사용한 결과보다 낫다.
실험에서 제안된 방법은 다른 최첨단 방법보다 뛰어나며 풍부한 생물학적 해석을 가지고 있다.
### Introduction
더욱이 유방암을 앓고 있는 젊은 여성은 삼중 음성이나 HER2 양성 유방암과 같이 보다 공격적인 아형을 갖게 될 가능성이 높으며, 고도 단계로 식별될 가능성이 더 높다
종양 분자 타이핑의 개념은 1999년 국립 암 연구소에 의해 제안
* 미국 스탠퍼드대 페루 외 연구진은 2000년 유방암의 분자분류를 처음 보고
* basal-like subtype, human epidermal growth subtype and normal breast-like subtype 등 4가지 1차 아형이 있다고 결론
* 2003년, Sorlie 외는 추가로 Luminal 하위 유형을 Luminal A와 Luminal B로 나눔눔
유방암의 아형을 규정하는 다른 분류방법이 많지만, 여전히 가장 널리 알려진 방법은 페루와 설리가 제안한 방법
<br>
<br>

<br>
* The Unclear subtypes was the patients which have missing data in ER, PR or HER2
* Luminal A is the most common subtype of breast cancer in clinic, and it is usually an early form of breast cancer.
* the 5-year local recurrence rate of this subtype is significantly lower than other subtypes
* the expression of hormone in patients with Luminal B is lower than Luminal A, while the expression of proliferation markers and histologic grade are higher than Luminal A
* Probably 25% of breast cancer are classified as HER2-positive, and this subtype has always been related to poor prognosis.
* Basle-like/TNBC is currently the most studied subtype, is easy to deteriorate and metastasize, is highly sensitive to chemotherapy
<br>
<br>
많은 유방암 subtype 분류에 대한 연구들이 있다.
hierarchical clustering에 의해 gene expression patterns의 차이에 기초해 유방암 유형을 분리
<br>
SVM : 지도학습모형, 데이터 특징을 선형적으로 분리할 수 있는 더 높은 차원에 매핑한 커널 함수를 통해 비선형 분리 문제를 효과적으로 해결
클래식한 커널함수는 linear kernel, polynomial kernel, gaussian kernel이 존재
이 후, Multiple kernel learining(MKL)을 등장하여 svm의 분류 정확도를 향상시킴
<br>
**우리는 SMO-MKL을 사용할 것(이 방법은 MKL을 사용하는 것보다 더 나을 결과를 도출)**
* SMO-MKL is an improved supervised method based on linear MKL framework fusing heterogeneous omics data of breast cancer from the Cancer Genome Atlas (TCGA)
<br>
1. mRNA, DNA methylation, Copy Number Variation(CNV)데이터를 수집하고 이러한 Omics 데이터와 subtypes(아형) 정보를 동시에 가진 환자들만 선택
2. 이 데이터들을 삭제하고 정규화. Omics 데이터에서 쓸모없느 문제를 해결하기 위해 각각 omics 데이터에 기초해 gene feature selection방법을 사용
3. 그 다음의 모형의 인풋으로 omics 데이터를 사용해 커널을 생성. 그리고 SMO-MKL 모형을 만들어 예측의 분류결과를 얻음
{width=600, height=900}
### Method
mRNA, DNA methylation, Copy number variation 데이터 사용 : 환자 샘플에서 동시에 측정
* the RNA sequencing level 3 data as mRNA data
* DNA Methylation 450k level 3 data as DNA methylation data
* the Affymetrix SNP 6.0 array data with GRCH 38 (hg38) genome data as CNV data.
clinical data로부터 ER, PR and Her2의 정보 사용하여 환자의 암 subtype을 확인
<br>
유방암 별개의 환자 샘플 606명이 포함된 데이터셋은 5개의 subtypes으로 나뉨

### Result
heatmap을 통해 살펴보니 3개의 데이터 중에서는 mRNA데이터에서 유방암 subtypes들이 가장 뚜렷히 분류가 되었다.
random forest, Neural network보다 SMO-MKL의 성능이 더 좋았다.
## Different Gene Expression {.tabset .tabset-fade .tabset-pills}
### Abstract
Bioconductor packages를 이용하여 RNA-seq differential gene expression을 살펴본다.
gene-level의 count dataset을 이용한다.
### Introduction
Bioconductor packages는 많은 것을 할 수 있다.
DESeq2패키지로 분석이 가능
{width=450, height=450}
{width=450, height=450}
{width=450, height=450}
##
**content below tabbed region**
## 나의 생각?
1. mRNA데이터를 통해 유방암 subtype들의 different expression gene을 분석
2. tumor 4가지의 subtype에 대한 QC이 후, DEG를 수행하고 해석도 고려
tumor의 subtype을 분류하는 모형을 구축함에 있어서 DEG나 다른 방법을 통해 발현적으로 유의한 gene들만 선택하는 등 feature selection에 이용할 수도 있을 것
------------
* subtype의 DEG수행 후 특징살피기
* 유방암 subtype에 영향을 미치는 유전자 탐색
* 이 유전자로부터 subtype들의 분류
<br>
<br>
# Data import & Pre-processing {.tabset .tabset-fade .tabset-pills}
## Library
```{r library, message=FALSE, warning=FALSE}
# Data manipulation
library(tidyverse)
library(data.table)
library(plyr)
library(stringr)
library(DT)
# Bio
# BiocManager::install("DESeq2")
# BiocManager::install("DEGseq")
library(BiocManager)
library(DEGseq) # not use
library(DESeq2) # I use this package
library(TCGAbiolinks)
# Visualization
library(patchwork)
library(ggthemes)
```
### function
```{r}
`%notin%` <- Negate(`%in%`)
```
사용자 부정 명령어를 할당
## Download the mRNA - count
```{r eval=FALSE}
query <- GDCquery(project="TCGA-BRCA",
data.category="Transcriptome Profiling",
data.type="Gene Expression Quantification",
workflow.type="HTSeq - Counts")
# 2. Download from GDC repository
GDCdownload(query)
# 3. Make R object from the downloaded data
data <- GDCprepare(query)
# 4. Extract Gene expression matrix
library(SummarizedExperiment)
eset <- assay(data)
```
|Function | Description|
|:---: | :-------:|
|TCGAquery_clinic() | Get the clinical information|
|TCGAquery() | TCGA open-access data providing also latest version of the files.|
|dataBRCA() | TCGA data matrix BRCA|
[Function Description](https://www.rdocumentation.org/packages/TCGAbiolinks/versions/1.2.5)
## Import data
```{r, echo=F}
load("./BRCA객체.RData")
```
```{r echo=FALSE}
load("D:/Jae Kwan/4학년여름/연구생/연구주제/ens_naming까지객체.RData")
```
```{r eval=FALSE}
normal <- eset %>% data.frame
data <- fread("./data/brca_tcga_pub/data_clinical_sample.txt",
data.table = F)
patient <-
data %>%
dplyr::select(`Patient Identifier`, `ER Status`, `PR Status`, `HER2 Status`) %>%
filter(`ER Status` %in% c("Positive","Negative") &
`PR Status` %in% c("Positive","Negative") &
`HER2 Status` %in% c("Positive","Negative"))
```
### naming match
```{r eval=FALSE}
library(biomaRt)
ensembl_ids <- unlist(lapply(rownames(normal), as.character), use.names=FALSE)
ens <- useEnsembl(biomart="ensembl",
dataset="hsapiens_gene_ensembl")
genes.tbl <- getBM(attributes = c("ensembl_gene_id","hgnc_symbol"),
filters = "ensembl_gene_id",
values = ensembl_ids,
mart = ens)
# head(genes.tbl)
# duplicated(genes.tbl$ensembl_gene_id) %>% sum
# duplicated(genes.tbl$hgnc_symbol) %>% sum
```
유전자에 이름을 부여하고 난 뒤에는 18893개가 중복되었다. 중복된 것들은 삭제하고 진행한다.
```{r}
genes.tbl <-
genes.tbl[!duplicated(genes.tbl$hgnc_symbol) &!duplicated(genes.tbl$ensembl_gene_id), ]
genes.tbl %>% dim
genes.tbl %>% head
```
```{r}
rownames(normal) %in% genes.tbl$ensembl_gene_id %>% sum
normal <- normal[rownames(normal) %in% genes.tbl$ensembl_gene_id,]
```
```{r}
normal[1:5,1:2]
```
```{r}
all(rownames(normal)==genes.tbl$ensembl_gene_id)
```
```{r}
rownames(normal) <- genes.tbl$hgnc_symbol
normal[1:5,1:2]
```
### patient
```{r echo=FALSE}
datatable(patient)
```
### normal
```{r echo=FALSE}
knitr::kable(normal[1:5,1:3])
```
## Pre-Process
### normal data
```{r}
normal[1:3,1:3]
normal <- normal[, str_sub(colnames(normal), 14,15) == "01"]
colnames(normal) <- str_sub(colnames(normal),1,15)
colnames(normal) <- gsub(pattern = ".",replacement = "-",
x = colnames(normal), fixed = T)
normal %>% dim
normal <- normal[, !duplicated(colnames(normal))]
normal %>% dim
```
```{r echo=F}
knitr::kable(normal[1:5,1:2])
```
tumor인 사람만 고른 후, patient의 rownames이름 형식과 맞추기 위한 작업을 한다.
단 normal데이터에서 뒤를 날렸기 때문에 중복된 이름이 존재할 수 있다. 이 부분은 그냥 감안하고 중복된 사람은 없애기로 한다.
### patient data
```{r}
colnames(patient) <- c("sample","ER","PR","HER2")
patient <-
patient %>% mutate(condition = case_when(
ER == "Positive" & PR == "Positive" & HER2 == "Negative" ~ "LuminalA",
ER == "Positive" & PR == "Positive" & HER2 == "Positive" ~ "LuminalB",
ER == "Negative" & PR == "Negative" & HER2 == "Negative" ~ "TNBC",
ER == "Negative" & PR == "Negative" & HER2 == "Positive" ~ "HER2"))
patient <- patient %>% arrange(condition)
patient <- patient %>% filter(!is.na(condition))
patient %>% head
patient <- column_to_rownames(patient, "sample")
patient %>% head
normal <- normal[, colnames(normal) %in% rownames(patient)]
patient <- patient[rownames(patient) %in% colnames(normal), ]
dim(normal); dim(patient)
```
공통으로 들어간 환자로 일치시킨다.
### Match
```{r}
match(rownames(patient), colnames(normal)) %>% is.na %>% sum
match_idx <- match(colnames(normal), rownames(patient))
meta_dat <- patient[match_idx,]
meta_dat[1:3, ]
normal[1:3, 1:3]
all(rownames(meta_dat) == colnames(normal))
meta_dat <- meta_dat %>% dplyr::select(condition)
meta_dat %>% head
normal[1:3, 1:3]
```
DESeq2모형에 탑재하기 위해서는 환자의 순서를 통일해준다.
<br>
#### subtype count
```{r echo=FALSE}
knitr::kable(meta_dat %>% dplyr::count(condition))
```
#### NA count
```{r}
map_dbl(meta_dat, ~sum(is.na(.x)))
map_dbl(normal, ~sum(is.na(.x))) %>% sum
```
두 데이터에서 서로 없는 부분이 존재하면 NA가 생기고 sum결과 연산이 되지 않아 NA가 발생할 것
여기서는 0으로 모두 공통으로 존재함
<br>
```{r}
# arrange_index <-
# meta_dat %>%rownames_to_column(var = "gene") %>%
# arrange(condition) %>%
# column_to_rownames(var = "gene") %>%
# rownames %>%
# match(colnames(normal))
#
# meta_dat <-
# meta_dat %>%rownames_to_column(var = "gene") %>%
# arrange(condition) %>%
# column_to_rownames(var = "gene")
#
# normal <- normal[,arrange_index]
# all(rownames(meta_dat)==colnames(normal))
```
# Unsupervised learning
```{r eval=F}
dds <- DESeqDataSetFromMatrix(countData = normal,
colData = meta_dat,
design = ~ condition)
dds
dds_fac <- estimateSizeFactors(dds)
# sizeFactors(dds_fac)
normalized_counts <- counts(dds_fac, normalized=TRUE)
# View(normalized_counts)
vsd <- vst(dds_fac, blind=TRUE)
# Extract the vst matrix from the object
vsd_mat <- assay(vsd)
# Compute pairwise correlation values
vsd_cor <- cor(vsd_mat)
```
```{r echo=FALSE}
load("D:/Jae Kwan/4학년여름/연구생/연구주제/pca까지객체.RData")
```
## Headmap
```{r}
# Load pheatmap libraries
library(pheatmap)
# Plot heatmap
pheatmap(vsd_cor,
cluster_rows = T,
show_rownames = F,
annotation = dplyr::select(meta_dat, condition))
```
## PCA
```{r}
# Plot PCA
plotPCA(vsd, intgroup="condition")
```
<br>
<br>
# DEG analysis
```{r}
# HER2 vs LuminalA
her2_luminalA_meta_dat <-
meta_dat %>%
mutate(number=1:nrow(meta_dat)) %>%
filter(condition %in% c("LuminalA","HER2"))
her2_luminalA_normal <-
normal %>%
dplyr::select(her2_luminalA_meta_dat$number)
all(rownames(her2_luminalA_meta_dat)==colnames(her2_luminalA_normal))
# # HER2 vs Luminal B
#
# her2_luminalB_meta_dat <-
# meta_dat %>%
# mutate(number=1:nrow(meta_dat)) %>%
# filter(condition %in% c("LuminalB","HER2"))
#
# her2_luminalB_normal <-
# normal %>%
# dplyr::select(her2_luminalB_meta_dat$number)
#
# all(rownames(her2_luminalB_meta_dat)==colnames(her2_luminalB_normal))
#
#
#
# # HER2 vs TNBC
#
# her2_TNBC_meta_dat <-
# meta_dat %>%
# mutate(number=1:nrow(meta_dat)) %>%
# filter(condition %in% c("TNBC","HER2"))
#
# her2_TNBC_normal <-
# normal %>%
# dplyr::select(her2_TNBC_meta_dat$number)
#
# all(rownames(her2_TNBC_meta_dat)==colnames(her2_TNBC_normal))
#
#
# # Luminal A vs Luminal B
#
# luminalA_luminalB_meta_dat <-
# meta_dat %>%
# mutate(number=1:nrow(meta_dat)) %>%
# filter(condition %in% c("LuminalA","LuminalB"))
#
# luminalA_luminalB_normal <-
# normal %>%
# dplyr::select(luminalA_luminalB_meta_dat$number)
#
# all(rownames(luminalA_luminalB_meta_dat)==colnames(luminalA_luminalB_normal))
#
#
# # Luminal A vs TNBC
#
# luminalA_TNBC_meta_dat <-
# meta_dat %>%
# mutate(number=1:nrow(meta_dat)) %>%
# filter(condition %in% c("LuminalA","TNBC"))
#
# luminalA_TNBC_normal <-
# normal %>%
# dplyr::select(luminalA_TNBC_meta_dat$number)
#
# all(rownames(luminalA_TNBC_meta_dat)==colnames(luminalA_TNBC_normal))
#
# # Luminal B vs TNBC
#
# luminalB_TNBC_meta_dat <-
# meta_dat %>%
# mutate(number=1:nrow(meta_dat)) %>%
# filter(condition %in% c("LuminalB","TNBC"))
#
# luminalB_TNBC_normal <-
# normal %>%
# dplyr::select(luminalB_TNBC_meta_dat$number)
#
# all(rownames(luminalB_TNBC_meta_dat)==colnames(luminalB_TNBC_normal))
```
각 비교할 type들의 유전자 쌍별로 데이터를 분리하여 DESeq2모형에 넣을 계획이다.
```{r warning=FALSE, message=FALSE}
# HER2 vs LuminalA
dds_HER2_luminalA <-
DESeqDataSetFromMatrix(countData = her2_luminalA_normal,
colData = her2_luminalA_meta_dat,
design = ~ condition)
dds_HER2_luminalA <- estimateSizeFactors(dds_HER2_luminalA)
# # HER2 vs LuminalB
# dds_HER2_luminalB <-
# DESeqDataSetFromMatrix(countData = her2_luminalB_normal,
# colData = her2_luminalB_meta_dat,
# design = ~ condition)
# dds_HER2_luminalB <- estimateSizeFactors(dds_HER2_luminalB)
#
#
# # HER2 vs TNBC
# dds_HER2_TNBC <-
# DESeqDataSetFromMatrix(countData = her2_TNBC_normal,
# colData = her2_TNBC_meta_dat,
# design = ~ condition)
# dds_HER2_TNBC <- estimateSizeFactors(dds_HER2_TNBC)
#
#
# # LuminalA vs LuminalB
# dds_luminalA_luminalB <-
# DESeqDataSetFromMatrix(countData = luminalA_luminalB_normal,
# colData = luminalA_luminalB_meta_dat,
# design = ~ condition)
# dds_luminalA_luminalB <- estimateSizeFactors(dds_luminalA_luminalB)
#
#
#
# # LuminalA vs TNBC
# dds_luminalA_TNBC <-
# DESeqDataSetFromMatrix(countData = luminalA_TNBC_normal,
# colData = luminalA_TNBC_meta_dat,
# design = ~ condition)
# dds_luminalA_TNBC <- estimateSizeFactors(dds_luminalA_TNBC)
#
#
#
# # LuminalB vs TNBC
# dds_luminalB_TNBC <-
# DESeqDataSetFromMatrix(countData = luminalB_TNBC_normal,
# colData = luminalB_TNBC_meta_dat,
# design = ~ condition)
# dds_luminalB_TNBC <- estimateSizeFactors(dds_luminalB_TNBC)
```
```{r eval=FALSE}
# Run analysis
dds_HER2_luminalA_model <- DESeq(dds_HER2_luminalA)
# dds_HER2_luminalB_model <- DESeq(dds_HER2_luminalB)
#
# dds_HER2_TNBC_model <- DESeq(dds_HER2_TNBC)
#
# dds_luminalA_luminalB_model <- DESeq(dds_luminalA_luminalB)
#
# dds_luminalA_TNBC_model <- DESeq(dds_luminalA_TNBC)
#
# dds_luminalA_TNBC_model <- DESeq(dds_luminalB_TNBC)
```
```{r echo=FALSE}
load("D:/Jae Kwan/4학년여름/연구생/연구주제/dds_her2_luminalA객체.RData")
```
## HER2 vs Luminal A
쌍별 유전자 차이에 대한 검정을 하나만 예로 실행해보자.
```{r}
result_HER2_luminalA <-
results(dds_HER2_luminalA_model,
contrast = c("condition", "HER2", "LuminalA"),
alpha = 0.05,
lfcThreshold = 0.2)
# plotDispEsts(dds_HER2_luminalA_model)
mcols(result_HER2_luminalA)
result_HER2_luminalA
```
|||
|:---:|:-------:|
|**baseMean**|mean value across all the samples|
|**lfcSE**|standard error of the fold change estimates|
|**stat**|wald statistics output from the wald test for differential expression|
|**pvalue**|the wald test p-value|
|**padj**|the Benjamini-Hochberg adjusted p-value|
<br>
```{r}
summary(result_HER2_luminalA)
```
log fold change가 threshold보다 큰 값과 작은 값 등을 나타낸다.
<br>
true positives또는 DE라고 불리는 유전자를 잘못된 것으로부터 구별하는 방법은 어려운데, DESeq2는 Benjamini-Hochberg(BH-method) 방법으로 p-value를 조정하고, true positive에 대해 false positive를 제어하기 위해 multiple test correction을 수행한다.
DESeq2는 모든 표본에 걸쳐 zero counts인 유전자, 평균값이 낮은 유전자, extreme 값을 가지는 outlier를 가진 유전자 등 testing전에 실제로 다르게 표현될 가능성이 없는 유전자들을 자동으로 걸러낸다.
`summary()`를 통해 alpha level에 대해 차이를 보이는 유전자의 수와 필터링된 유전자의 수에 대한 정보를 확인할 수 있다.
```{r}
p1 <-
result_HER2_luminalA %>%
data.frame %>%
rownames_to_column(var = "gene") %>%
mutate(threshold = padj < 0.05) %>%
filter(threshold %notin% NA) %>%
ggplot(aes(x = log2FoldChange, y = -log10(padj),
color = threshold)) +
theme_classic() +
geom_point() +
xlab("log2 fold chage") +
ylab("-log10 adjusted p-value") +
theme(legend.position = c(0.2,0.8),
legend.background = element_rect(linetype = "solid",
size = 0.5,
colour = "darkblue"),
plot.title = element_text(size = rel(1.5), hjust = 0.5),
axis.title = element_text(size = rel(1.25))) +
scale_x_continuous(breaks = seq(-12,10,2))
p2 <-
result_HER2_luminalA %>%
data.frame %>%
rownames_to_column(var = "gene") %>%
mutate(threshold = padj < 0.05) %>%
filter(threshold %notin% NA) %>%
ggplot(aes(x = log2FoldChange, y = -log10(padj),
color = threshold)) +
theme_classic() +
geom_point() +
xlab("log2 fold chage") +
ylab("") +
theme(legend.position = "none") +
coord_cartesian(xlim=c(-5, 5),ylim=c(0,25))
plotMA(dds_HER2_luminalA_model, ylim = c(-10,10))
```
MA plot은 유전체 데이터의 시각적 표현을 위해 Bland-Altman plot을 적용한 것
데이터를 M(로그 비율)와 A(mean average)로 변환한 다음 이러한 값을 표시하여 두 표본에서 측정한 측정값 간의 차이를 시각화한다. 원래 두 채널 DNA 마이크로어레이 유전자 발현 데이터의 맥락에서 적용되었지만, MA 플롯은 high-throughput sequencing analysis을 시각화하는 데도 사용된다.
MA plot은 expression change와 condition의 차이에 대한 관계(log ratio, M), 유전자의 평균 변화 강도 그리고 유전자 차이 표현을 감지하는 알고리즘을 전반적으로 제공한다.
유의한 임계값을 통과한 유전자는 파란색으로 표시된다.
<br>
>분석 화학 또는 생물 의학에서의 Bland-Altman plot(difference plot)은 서로 다른 두 분석 사이의 합치를 분석하는 데 사용되는 data plotting 방법이다.
다른 분야에서 알려진 이름인 Tukey mean-difference plot과 동일하지만, <NAME>와 <NAME>에 의해 의료 통계에 대중화되었다.
```{r}
p1 + p2
```
<br>
Fold change : 어떤 유전자에 대하여 실험군에서의 평균발현량이 대조군에서의 평균발현량의 몇 배인지를 나타냄
P-value : 두 군의 평균발현량 차이가 통계적으로 유의미한 값인지를 알려줌.
Volcano plot : Log-scaled fold-change를 X축, -Log-scaled P-value를 Y축으로 갖는 그래프로, 그 모습이 화산 폭발과 비슷하여 볼케이노 플롯이라고 불린다.
0.05를 threshold로 잡고 유의미한 유전자와 아닌 유전자를 색으로 표현
오른쪽 그림은 왼쪽 전체그림 중 중요한 부분만 확대하여 확인한 것
# 연구와는 무관한 필요없는 내용
limma, DEseq 또는 DESeq2패키지로 유전자 발현에 대한 차이를 분석할 수 있다.
```{r}
# str_locate(dataBRCA %>% names, "\\d\\dA")
# str_sub(dataBRCA %>% names,start = 14, end=16)
# index <- str_sub(dataBRCA %>% names,start = 14, end=16)=="01A"
#
#
# cancer <- dataBRCA[,index]
# normal <- dataBRCA[,!index]
```
```{r}
# str_sub(koo %>% names,start = 14, end=16)
# cancer_index <- str_sub(koo %>% names,start = 14, end=15)=="01"
# normal_index <- str_sub(koo %>% names,start = 14, end=15)=="11"
#
# cancer <- koo[,cancer_index]
# normal <- koo[,normal_index]
```
```{r}
# DEGexp(geneExpMatrix1 = normal, geneCol1 = 1, groupLabel1 = "Normal",
# geneExpMatrix2 = cancer, geneCol2 = 1, groupLabel2 = "Cancer",
# method="MARS", output='output')
```
```{r}
# output <- fread("./output/output_score.txt")
#
# head(output)
```
```{r}
# 유전자 이름? 이름이 TCGA랑 다름
# devtools::install_github("stephenturner/annotables")
# library(annotables)
```
# Refer
* [TCGAbiolinks 대략적인 설명 블로그](http://www.incodom.kr/TCGAbiolinks#h_04b78a38c44c25698b471e7ea22434eb)
* [Broad Institute GDAC Firehose](https://m.blog.naver.com/PostView.nhn?blogId=cjh226&logNo=220868113892&proxyReferer=https:%2F%2Fwww.google.com%2F)
* [TCGA Barcode 의미](http://blog.naver.com/PostView.nhn?blogId=cjh226&logNo=220992617831&parentCategoryNo=&categoryNo=18&viewDate=&isShowPopularPosts=false&from=postView)
* [DEG 설명 블로그](https://sosal.kr/848)
<br>
* [biomaRt네이버 블로그](https://m.blog.naver.com/PostView.nhn?blogId=cjh226&logNo=221398384399&targetKeyword=&targetRecommendationCode=1)
* [biomaRt구글링](https://www.bioconductor.org/packages/devel/bioc/vignettes/biomaRt/inst/doc/accessing_ensembl.html)
<br>
<br>
간접적 도움 읽어본 자료
* [Remove rows with all or some NAs in data.frame](https://stackoverflow.com/questions/4862178/remove-rows-with-all-or-some-nas-missing-values-in-data-frame)
* [TCGA BRCA - SOX10](https://www.biostars.org/p/381632/)
* [Matched Paired Tumour-Normal DEA of BRCA using data downloaded using TCGAbiolinks](https://www.biostars.org/p/321918/)
* [Differential Expression and Visualization in R](https://angus.readthedocs.io/en/2019/diff-ex-and-viz.html#differential-expression-with-deseq2)
* [R&DESeq2 - Volcano plot 네이버 블로그](http://blog.naver.com/PostView.nhn?blogId=cjh226&logNo=221360753408&parentCategoryNo=&categoryNo=18&viewDate=&isShowPopularPosts=false&from=postList)
* [TCGA Workflow: Analyze cancer genomics and epigenomics data using Bioconductor packages](https://bioconductor.org/packages/devel/workflows/vignettes/TCGAWorkflow/inst/doc/TCGAWorkflow.html#abstract)
* [Introduction to DGE](https://hbctraining.github.io/DGE_workshop/lessons/05_DGE_DESeq2_analysis2.html)
* [Using DESeq2 for gene-level differential expression analysis - GITHUB](https://github.com/hbctraining/DGE_workshop/blob/master/exercises/DGE_analysis_exercises%20answer_key.md)
* [workflow in DESeq2](http://bioconductor.org/packages/devel/bioc/vignettes/DESeq2/inst/doc/DESeq2.html)
<file_sep>---
title: "어떤 연구가 좋을까?"
author: "<NAME>"
output: slidy_presentation
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T)
```
## Contents
- TCGA in R
- Install
- Example - clinic data
- Download data from GDC(Genomic Data Commons Data Portal)
- 관심이 가는 주제
## TCGA in R
**TCGA(The Cancer Genome Atlas)**
* The Cancer Genome Atlas (TCGA)는 미국 국립보건원(National Institutes of Health, NIH)에서 진행한 프로젝트
* 여러 가지 암종에 대한 유전체/전사체/단백체 데이터를 수집 및 분석하여 암을 분자 수준에서 이해
* 게놈 염기서열 분석과 생물정보학을 이용해 암의 원인이 되는 유전자 돌연변이를 분류하기 위해 2005년부터 시작된 프로젝트. 대부분의 유전체학 연구보다 많은 500개의 환자 샘플을 계획했고, 환자 샘플을 분석하기 위해 다른 기술을 사용했다.
## Install
```{r message=F,warning=FALSE}
# devtools::install_github("halpo/purrrogress")
# devtools::install_github("waldronlab/MultiAssayExperiment")
# devtools::install_github("PoisonAlien/maftools")
if (!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
if (!requireNamespace("ComplexHeatmap", quietly = TRUE))
BiocManager::install("ComplexHeatmap") # from bioconductor
if (!requireNamespace("TCGAbiolinks", quietly = TRUE))
BiocManager::install("BioinformaticsFMRP/TCGAbiolinks") # from github
library(TCGAbiolinks)
library(MultiAssayExperiment)
library(maftools)
library(tidyverse)
library(ComplexHeatmap)
```
## Example - clinic data
```{r}
clinical <- GDCquery_clinic("TCGA-COAD")
DT::datatable(clinical,
options = list(pageLength = 5, autoWidth = TRUE))
```
##
```{r echo=FALSE, fig.width=18, fig.height=10, fig.align='center'}
null_count <- apply(clinical, 2, function(x) sum(is.na(x)))
data <- data.frame(col_names = null_count %>% names, count = null_count)
rownames(data) <- NULL
data %>% ggplot(aes(x = col_names, y = count)) +
geom_bar(stat="identity") +
coord_flip() +
xlab("") +
ylab("") +
theme_bw()
```
## Download data from GDC(Genomic Data Commons Data Portal)
```{r eval=F}
# 1. Search data in GDC
query <- GDCquery(project="TCGA-LIHC", # Liver and intrahepatic bile ducts(간, 간내 담관)
data.category="Transcriptome Profiling",
data.type="Gene Expression Quantification",
workflow.type="HTSeq - Counts")
# 2. Download from GDC repository
GDCdownload(query)
# 3. Make R object from the downloaded data
data <- GDCprepare(query)
# 4. Extract Gene expression matrix
library(SummarizedExperiment)
eset <- assay(data)
# 5. Save the matrix as .csv format
fwrite(x = eset, file = "LIHC.csv") # setwd() location
```
##
```{r eval=T}
TCGAbiolinks:::getGDCprojects()$project_id # possible project name
TCGAbiolinks:::getProjectSummary("TCGA-LIHC")
```
## [관심이 가는 주제](https://ko.ovalengineering.com/quantitative-mri-radiomics-prediction-molecular-classifications-breast-cancer-subtypes-tcgatcia-data-870194#menu-8)
* 유방암은 북미 여성에서 가장 흔히 진단되는 암으로 여성의 암 사망 원인 중 두 번째로 많이 발생
* 수용체 상태에 따라 유방암은 여러 가지 아형으로 분류 될 수 있음.
<br>
<br>
[TCGA Cancers Selected for Study](https://www.cancer.gov/about-nci/organization/ccg/research/structural-genomics/tcga/studied-cancers)
What have TCGA researchers learned about breast cancer?
* The cancer can be categorized into four molecular subtypes: `HER2-enriched`, `Luminal A`, `Luminal B`, and `Basal-like`.
Each subtype is associated with a unique panel of mutated genes.
* Basal-like(기저형 아형) subtype shares many genetic features with high-grade serous ovarian cancer(난소 암), suggesting that the cancers have a common molecular origin and may share therapeutic opportunities, such as:
* A drug that inhibits blood vessel growth, cutting off the blood supply to the tumor.
* Bioreductive drugs, which are inactive drugs that become toxic to cancer cells under low oxygen conditions.
## Refer
* TCGA
* https://bioconductor.org/packages/release/bioc/html/TCGAbiolinks.html
* [National cancer institute GDC Data Portal](https://portal.gdc.cancer.gov/projects)
* https://m.blog.naver.com/PostView.nhn?blogId=cjh226&logNo=221320056674&proxyReferer=https:%2F%2Fwww.google.com%2F
* https://rpubs.com/tiagochst/TCGAworkshop
* [TCGA Barcode](http://blog.naver.com/PostView.nhn?blogId=cjh226&logNo=220992617831&categoryNo=18&parentCategoryNo=0&viewDate=¤tPage=1&postListTopCurrentPage=1&from=postView)
* [TCGA의 간단한 설명을 한 블로그](https://medium.com/biosupermarket/%EB%8D%B0%EC%9D%B4%ED%84%B0-%EB%82%98%EB%93%A4%EC%9D%B4-tcga-target-gtex-1-tcga-target-gtex-32b3a78de709)
* [GDC query](https://rdrr.io/bioc/TCGAbiolinks/man/GDCquery.html)
<file_sep>---
title: "gene subtype classification"
author: "<NAME>"
output:
html_document:
df_print: paged
code_folding: show
fig_height: 6
fig_width: 10
highlight: textmate
word_document: default
github_document:
toc: yes
toc_depth: 4
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = T)
```
## Library
```{r warning=F, message=FALSE}
# Manipulate
library(tidyverse)
library(data.table)
library(glue)
# Model
library(glmnet)
library(caret)
library(Metrics)
library(ROSE) # rose
library(DMwR) # smote
library(ggfortify) # pca
# Parallel
library(doParallel)
# Visualization
library(hrbrthemes)
library(viridis)
library(plotROC) # plot the ROC curve
library(pROC)
library(patchwork)
```
```{r echo=FALSE}
load("D:/Jae Kwan/4학년여름/연구생/연구주제/glm_model_gridsearch.RData")
```
## Parallel processing
```{r}
doParallel::registerDoParallel(3)
```
caret패키지의 모형개발 속도 향상을 위해 병렬처리를 이용한다.
## One hot encoding
```{r}
one_hot_meta_dat <- model.matrix(~.-1, meta_dat)
colnames(one_hot_meta_dat) <- one_hot_meta_dat %>% colnames %>%
str_remove(.,"condition")
```
glmnet함수는 y label값을 수치로 받기 때문에 인코딩을 하는 것이 좋다.
## GLM
```{r}
normal_t <- normal %>% t %>% as.matrix
normal_t[1:3,1:2]
dim(normal_t)
cancer_fit <- glmnet(x = normal_t,
y = one_hot_meta_dat,
family = "multinomial",
type.multinomial = "grouped",
alpha = 1) # alpha=1 : lasso
# par(mfrow=c(2,2))
# plot(cancer_fit)
```
기존의 전처리된 형태의 데이터에 대해 유전자가 열로, 환자는 행으로 위치시킨다.
Ridge regression은 일반적으로 변수들의 서브셋만을 포함하는 모델들을 선택하는 최상의 부분집합 선택과 전진 및 후진 단계적 선택과 달리, Ridge는 최종 모델에 p개 설명변수 모두를 포함할 것이다.(regularized parameter가 inf가 아니면 정확히 0으로 만들 수 없다.)
Lasso는 이러한 Ridge의 단점을 극복한 기법이다.
ridge와 같이 lasso는 계수 추정치들을 0으로 수축하지만, lasso에서 $l_1$ penalty는 hyperparameter lambda가 충분히 클 경우 계수 추정치들의 일부를 정확히 0이 되게 하는 효과를 가진다.
**따라서, 최상의 부분집합 선택처럼 lasso는 변수 선택을 수행한다.**
그 결과 lasso로부터 생성된 모델은 ridge regression에 의해 생성된 것보다 일반적으로 해석하기 훨씬 더 쉽다.
### CV
```{r}
set.seed(100)
cv_fit <-
cv.glmnet(x = normal_t,
y = one_hot_meta_dat,
family = "multinomial",
type.multinomial = "grouped",
alpha = 1,
parallel = T)
# par(mfrow=c(1,1))
# plot(cv_fit)
#
# par(mfrow=c(2,2))
# plot(cv_fit$glmnet.fit, xvar="lambda")
# plot(cv_fit$glmnet.fit, xvar="norm")
# par(mfrow=c(1,1))
cv_fit$lambda.1se
cv_fit$lambda.min
```
알맞은 lambda를 정해주기 위해 cross validation을 수행한다.
cv.glmnet은 기본옵션으로 10-fold이다.
[R documentation - cv.glmnet](https://www.rdocumentation.org/packages/glmnet/versions/4.0-2/topics/cv.glmnet)
## Coefficients
```{r}
tmp_coeffs <- coef(cancer_fit, s = cv_fit$lambda.1se)
data.frame(name = tmp_coeffs[[1]]@Dimnames[[1]][tmp_coeffs[[1]]@i + 1], coefficient = tmp_coeffs[[1]]@x) -> k1
data.frame(name = tmp_coeffs[[2]]@Dimnames[[1]][tmp_coeffs[[2]]@i + 1], coefficient = tmp_coeffs[[2]]@x) -> k2
data.frame(name = tmp_coeffs[[3]]@Dimnames[[1]][tmp_coeffs[[3]]@i + 1], coefficient = tmp_coeffs[[3]]@x) -> k3
data.frame(name = tmp_coeffs[[4]]@Dimnames[[1]][tmp_coeffs[[4]]@i + 1], coefficient = tmp_coeffs[[4]]@x) -> k4
all(k1$name==k2$name)
all(k2$name==k3$name)
all(k3$name==k4$name)
k1 %>%
left_join(k2, by = "name") %>%
left_join(k3, by = "name") %>%
left_join(k4, by = "name")
```
이전에 만든 glmnet모형에 `s = `으로 원하는 lambda를 설정할 수 있다.
다음과 같은 방법으로 4개의 subtype에 대한 coefficient를 뽑아낸다.
여기있는 유전자들은 4개의 subtype에 하나라도 영향을 미치는 유전자라고 생각할 수 있을 것이다.
<br>
물론 cv.glmnet에서 정한 lambda를 통해 새 모형을 만들면 `beta()`함수로 coefficient를 쉽게 뽑아낼 수도 있을 것이다.
## normalized count & gene condition
```{r}
normal_temp <- normal %>% t %>% data.frame
normal_temp[1:2,1:2]
normal_z <- scale(normal_temp, center = T, scale = T)
normal_z <- normal_z %>% t %>% data.frame
normal_z[1:2,1:2]
sig_gene <- k1 %>%
select(name) %>%
left_join(normal_z %>% rownames_to_column(var="name"), by = c("name"))
sig_gene <- sig_gene[-1,]
sig_gene[1:2,1:3]
rownames(sig_gene) <- sig_gene[,1]
sig_gene <- sig_gene[,-1]
sig_gene <- sig_gene %>% t %>% data.frame
sig_gene <- sig_gene %>% rownames_to_column(var = "name")
sig_gene$name <- gsub(pattern = "\\.",replacement = "-",x = sig_gene$name)
sig_gene <- sig_gene %>% left_join(meta_dat %>% rownames_to_column("name"), by = c("name"))
colnames(sig_gene)
```
각 유전자별로 normalization을 수행한다.
<Definition>
Normalization is a process designed to identify and correct technical biases removing the least possible biological signal. This step is technology and platform-dependant.
**Library size**, **genes length**는 실험에서 편향을 가져올 수 있다.
* `genes length` : The raw count of two genes cannot be face off if gene A is twice longer than gene B. Due to its length, the longest gene will have much chance to be sequenced than the short one. And in the end, for the same expression level, the longest gene will get more read than the shortest one
* `library size` : the most well know bias. You create two libraries for two conditions with the same RNA composition. The second library works way better than the first one, you got 12 000 000 reads for condition A and 36 000 000 reads for condition B. You will have three times (36 000 000/12 000 000 = 3) more of each RNA in your condition B than your condition A.
다른 library size로 인해 한 sample이 다른 sample에 비해 더 많은 판독 값이 유전자에 정렬될 수 있다.
## Graph
```{r}
work <- sig_gene %>% select(1:11,"condition")
work %>% colnames
sig_gene %>% dim
work[1:2,1:4]
work_temp <-
work %>%
pivot_longer(cols = -c(condition, name),
names_to = "gene", values_to = "count")
work_temp %>% head
work_temp$count <- as.numeric(work_temp$count)
```
```{r}
work_temp %>%
ggplot(aes(x=gene,y=count,fill=condition))+
geom_boxplot() +
scale_fill_viridis(discrete = TRUE, alpha=0.8) +
geom_jitter(color="black", size=0.06, alpha=0.2)+
theme_ipsum() +
theme(
legend.position=c(.9, .8),
plot.title = element_text(size=11)
) +
ggtitle("A boxplot by subtype") +
xlab("") +
ylab("Normalized Count") +
labs(fill="Subtype") +
scale_x_discrete(guide = guide_axis(n.dodge = 2))
```
4개의 subtype중 하나라도 영향을 미치는 유전자 중 10개에 대해 나타낸 시각화이다.
<br>
이제 4개의 유방암 아형을 classify하는 모형을 구축해보기로 한다.
## Feature Selection with LASSO
```{r}
cv_fit$lambda.min %>% log
cv_fit$lambda.1se %>% log
minus_min_lse <-
cv_fit$lambda.min - (cv_fit$lambda.1se - cv_fit$lambda.min)
cv_fit$lambda.min
cv_fit$lambda.1se
minus_min_lse
plot(cv_fit)
abline(v = log(minus_min_lse), col = "red", lwd = 1.5)
text(-4.5,1.4,
labels = glue("log Lambda = {round(log(minus_min_lse),4)}"),
col="red")
# coef
feature_coef <- coef(cancer_fit, s = minus_min_lse)
data.frame(name = feature_coef[[1]]@Dimnames[[1]][feature_coef[[1]]@i + 1], coefficient = feature_coef[[1]]@x) -> new1
data.frame(name = feature_coef[[2]]@Dimnames[[1]][feature_coef[[2]]@i + 1], coefficient = feature_coef[[2]]@x) -> new2
data.frame(name = feature_coef[[3]]@Dimnames[[1]][feature_coef[[3]]@i + 1], coefficient = feature_coef[[3]]@x) -> new3
data.frame(name = feature_coef[[4]]@Dimnames[[1]][feature_coef[[4]]@i + 1], coefficient = feature_coef[[4]]@x) -> new4
all(new1$name==new2$name)
all(new2$name==new3$name)
all(new3$name==new4$name)
selected_dat <-
new1 %>%
left_join(new2, by = "name") %>%
left_join(new3, by = "name") %>%
left_join(new4, by = "name")
selected_dat <- selected_dat[-1,] # delete intercept row
```
이전에 영향을 미치는 유전자를 찾을때보다는 덜 엄격하게 lambda를 잡아 유전자 변수들이 조금 더 많이 선택될 수 있게 했다.
여기서 정하게 된 lambda의 기준점은 cv.glmnet()에서 도출된 Lasso모형의 lambda minimun과 lambda first standard error의 차이만큼 lambda minimun을 중심으로 반대로 이동한 lambda의 값(lambda minimum - (lambda first se - lambda min)을 취하였다.
## PCA with selected Genes
```{r}
# confirm the 180 genes
normal_z %>%
rownames_to_column(var = "name") %>%
.$name %in% selected_dat$name %>% sum
pca_dat <-
normal_z[normal_z %>% rownames_to_column(var = "name") %>%
.$name %in% selected_dat$name, ] # (180 : genes, 630 : patients)
pca_dat[1:3,1:2]
pca_dat <- pca_dat %>% t %>% data.frame
pca_obj <- prcomp(pca_dat)
pca_obj <- as.data.frame(pca_obj$x)
theme<-
theme(panel.background =
element_blank(),
panel.border=element_rect(fill=NA),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
strip.background=element_blank(),
axis.text.x=element_text(colour="black"),
axis.text.y=element_text(colour="black"),
axis.ticks=element_line(colour="black"),
plot.margin=unit(c(1,1,1,1),"line"),
legend.position=c(0.85,0.8))
ggplot(pca_obj,aes(x=PC1,y=PC2, color=meta_dat$condition)) +
geom_point() +
theme +
labs(color='Subtype')
```
정해진 유전자들을 PCA로 살펴보자
이전에 37600개를 모두 사용한 것보다 더 잘 분리될 것 같다.
## Boruta feature selection
```{r}
library(Boruta)
feature_dat <- pca_dat %>% bind_cols(condition = meta_dat$condition)
feature_dat$condition <- feature_dat$condition %>% as.factor
set.seed(100)
boruta_results <- Boruta(condition ~ .,
data = feature_dat,
maxRuns=100)
boruta_results$finalDecision %>% data.frame %>% table
plot(boruta_results, las = 1, xaxt='n')
```
덜 엄격하게 정해진 유전자변수들로부터 한번 더 걸러내는 작업을 가졌다.
<br>
많은 변수들을 가지는 고차원 데이터는 기계학습문제에서 요즘 증가하는 추세이다. 이 큰 데이터로부터 유용한 정보를 추출하기 위해, 우리는 noise, redundant를 줄이기 위해 통계적 테크닉을 사용해야 한다.
왜냐하면, 우리는 모형을 훈련시키기 위해 우리의 처리에서 모든 변수들을 사용하지는 않을 것이기 때문인데, 여기서 **Feature Selection**이 중요한 역할을 한다.
모형 훈련을 더 빠르게 해주고 모형의 복잡도를 낮춰 더 쉽게 이해할 수 있고, accuracy, precision, recall등 모형 평가의 척도를 향상시킬 수 있다.
<br>
<Boruta algorithm>
Boruta는 데이터 셋에서 변수들의 중요성에 대한 것들을 요청한다.
많든 변수들은 중요한지, 안중요한지, 잠정적인지 분류가 된다.
Tentative features들은 그들의 shadow features라는 것에 가까운 특성을 가져, random forest 실행횟수로는 확신있게 중요한 변수인지 아닌지 결정할 수 없는 변수들을 말한다.
`maxRuns = `를 증가시킴에 따라 tentative features이 남아있는지 여부를 고려할 수 있다.
rf 분류자는 out of bag error의 값이 최소화되는 곳에서 수렴한다.
X축은 변수들을 나타내고, Y축은 섞인 데이터에서 모든 변수들의 Z-score가 위치해 변수의 중요도를 나타낸다.
<br>
* out of bag error : an estimate to measure prediction error of the classifiers which uses bootstrap aggregation to sub sample data samples used for training.
* 보루타 알고리즘은 filter method보다 더 많은 연산이 요구되는 wrapper method알고리즘이다.
* Boruta알고리즘은 rf를 구현한 wrapper이다.
* rf algorithm에서는 평균과 표준편차를 이용한 z score를 활용하지 않는데, 분포가 normal(0,1)을 따르지 않으므로 변수 중요성에 대한 통계적 유의성과 직접적인 관련이 없기 때문이다.
* Boruta algorithm은 rf내의 tree에서 평균 정확도 손실의 fluctuation을 고려하기 위해 중요성을 측정할 때 z-score을 사용한다.
## Data
```{r}
# data <- normal_temp[,selected_dat$name]
# data[1:2,1:2]
good_feature <-
boruta_results$finalDecision %>%
data.frame %>%
filter(.!="Rejected") %>%
rownames
data <- pca_dat[, good_feature]
data[1:2,1:2]
```
## Data partition
```{r}
set.seed(100)
index <- createDataPartition(1:630, p = 0.8, list = F)
train_x <- data[index,]
train_y <- meta_dat[index,]
test_x <- data[-index,]
test_y <- meta_dat[-index,]
```
train과 test의 비율을 80대 20으로 분리한다.
caret::createDataPartition은 기본적으로 각 클래스별 층화추출을 수행한다.
## Imbalance Data
```{r}
prop.table(table(meta_dat))
prop.table(table(train_y))
prop.table(table(test_y))
table(train_y)
```
각 클래스에서 비슷한 갯수들로 추출됨을 확인
LuminalA가 극히 많은 Imbalance data이다.
original 데이터와 3개의 sampling method을 실행한 데이터와의 모형을 적합해 확인해보도록 한다.
sampling method별로 비교할 것이므로 모두 rf모형을 사용했고, tree갯수는 400으로 고정시켰다. mtry만 Grid Search로 탐색하였다.
10-fold 3 repeat cross validation을 수행
## Classification without sampling method
```{r}
set.seed(100)
trControl <- trainControl(method="repeatedcv",
number=10,
repeats = 3,
allowParallel =TRUE)
Grid <- expand.grid(.mtry = 1:20)
rf_train <- train(x = train_x,
y = train_y,
method = "rf",
tuneGrid = Grid,
trControl = trControl,
metric = "Accuracy",
ntree=400,
verbose = FALSE)
rf_train$bestTune
pred_original <- predict(rf_train, newdata = test_x, type="raw")
confusionMatrix(pred_original, test_y %>% as.factor)
```
## Up & Down sampling
```{r}
set.seed(100)
train_y <- train_y %>% data.frame(class=.)
train_y$class <- train_y$class %>% as.factor
x <- caret::upSample(x = train_x, y = train_y$class)
table(x$Class)
x2 <- caret::downSample(x = train_x, y = train_y$class)
table(x2$Class)
```
```{r}
up_train_x <- x %>% select(-"Class")
up_train_y <- x$Class %>% as.character
down_train_x <- x2 %>% select(-"Class")
down_train_y <- x2$Class %>% as.character
train_y <- meta_dat[index,]
```
## SMOTE
```{r}
data_sampling <- train_x %>% bind_cols(train_y %>%
data.frame(class=.))
data_sampling$class <- data_sampling$class %>% as.factor
# sampling_rose <- ROSE(class~., data=data_sampling, seed=100)$data
# The response variable must have 2 levels : regulations
set.seed(100)
sampling_smote <- SMOTE(class~.,
data=data_sampling,
perc.over = 200,
perc.under = 300,
k = 5)
```
비율은 경험적으로 선택하였다.
```{r}
train_y %>% table
sampling_smote$class %>% table
```
[SMOTE](https://medium.com/@hslee09/r-%EB%B6%84%EB%A5%98-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98-%ED%81%B4%EB%9E%98%EC%8A%A4-%EB%B6%88%EA%B7%A0%ED%98%95-f5a260056049)
## Model application
```{r}
set.seed(100)
rf_train_under <- train(x = down_train_x,
y = down_train_y,
method = "rf",
tuneGrid = Grid,
trControl = trControl,
metric = "Accuracy",
ntree=400,
verbose = FALSE)
rf_train_under$bestTune
prediction_under <- predict(rf_train_under, newdata = test_x, type="raw")
confusionMatrix(prediction_under, test_y %>% as.factor)
## oversampling --------------------------------
rf_train_over <- train(x = up_train_x,
y = up_train_y,
method = "rf",
tuneGrid = Grid,
trControl = trControl,
metric = "Accuracy",
ntree=400,
verbose = FALSE)
rf_train_over$bestTune
prediction_over <- predict(rf_train_over, newdata = test_x, type="raw")
confusionMatrix(prediction_over, test_y %>% as.factor)
# SMOTE --------------------------
rf_train_smote <- train(x = sampling_smote %>% select(-class),
y = sampling_smote$class,
method = "rf",
tuneGrid = Grid,
trControl = trControl,
metric = "Accuracy",
ntree=400,
verbose = FALSE)
rf_train_smote$bestTune
prediction_smote <- predict(rf_train_smote, newdata = test_x, type="raw")
confusionMatrix(prediction_smote, test_y %>% as.factor)
```
## 일반적인 성능 평가 지표
```{r}
set.seed(100)
breast_models <- list(original = rf_train,
under = rf_train_under,
over = rf_train_over,
smote = rf_train_smote)
breast_resampling <- resamples(breast_models)
bwplot(breast_resampling)
```
Setting the seed produces paired samples and enables the two models to be compared using the resampling technique described in Hothorn at al, "The design and analysis of benchmark experiments", Journal of Computational and Graphical Statistics(2005)
<br>
$$
\kappa = {P(a)-P(e) \over 1- P(e)}
$$
P(e) : expected accuracy
P(a) : observed accuracy
즉, 실제 정확도와 예측된 정확도를 구분지어 위의 식으로 구한 수치가 Kappa 통계량이다.
Kappa 통계량은 -1부터 1까지의 값을 가지는데, 0의 값을 가지게 되면 관측된 클래스와 예측된 클래스 사이의 합의점이 전혀 없음을 의미한다.
결론적으로 Kappa값이 클수록 좋다.
## Accuracy
```{r}
# Oversampling
confusionMatrix(prediction_over %>% as.factor,
test_y %>% as.factor)$table
confusionMatrix(prediction_over %>% as.factor,
test_y %>% as.factor)$overall[1]
# Undersampling
confusionMatrix(prediction_under %>% as.factor,
test_y %>% as.factor)$table
confusionMatrix(prediction_under %>% as.factor,
test_y %>% as.factor)$overall[1]
# SMOTE
confusionMatrix(prediction_smote %>% as.factor,
test_y %>% as.factor)$table
confusionMatrix(prediction_smote %>% as.factor,
test_y %>% as.factor)$overall[1]
# Original
confusionMatrix(pred_original %>% as.factor,
test_y %>% as.factor)$table
confusionMatrix(pred_original %>% as.factor,
test_y %>% as.factor)$overall[1]
```
## GRID
```{r}
theme_set(new = theme_bw())
p1 <-
ggplot(rf_train) + theme(legend.position = "none",
legend.direction = "vertical") +
labs(title="Grid Search", subtitle="Original Data")
p2 <-
ggplot(rf_train_under) + theme(legend.position = "right",
legend.direction = "vertical") +
labs(title="Grid Search", subtitle="Undersampling Data")
p3 <-
ggplot(rf_train_over) + theme(legend.position = "none",
legend.direction = "vertical") +
labs(title="Grid Search", subtitle="Oversampling Data")
p4 <-
ggplot(rf_train_smote) + theme(legend.position = "right",
legend.direction = "vertical") +
labs(title="Grid Search", subtitle="SMOTE Data")
p1+p2+p3+p4
```
```{r}
grid_data <- data.frame(rf_train$results[1:2],
rf_train_over$results[1:2],
rf_train_under$results[1:2],
rf_train_smote$results[1:2])
ggplot(grid_data, aes(x = mtry)) +
geom_point(aes(y = Accuracy, colour = "Original Data")) +
geom_line(aes(y = Accuracy, colour = "Original Data")) +
geom_point(aes(y = Accuracy.1, colour = "Oversampling Data")) +
geom_line(aes(y = Accuracy.1, colour = "Oversampling Data")) +
geom_point(aes(y = Accuracy.2, colour = "Undersampling Data")) +
geom_line(aes(y = Accuracy.2, colour = "Undersampling Data")) +
geom_point(aes(y = Accuracy.3, colour = "SMOTE Data")) +
geom_line(aes(y = Accuracy.3, colour = "SMOTE Data")) +
scale_x_continuous(breaks=seq(0,20,4)) +
scale_y_continuous(breaks=seq(0.85,1,0.02)) +
theme(legend.title=element_blank(),
legend.position = "bottom") +
ggtitle("Grid Search for sampling methods")
```
## Multiclass ROC CURVE
```{r}
# direction = auto
# Oversampling AUC
over_roc <-
pROC::multiclass.roc(prediction_over %>% as.numeric(),
test_y %>% as.factor %>% as.numeric(),
direction ="<")
# Undersampling AUC
under_roc <-
pROC::multiclass.roc(prediction_under %>% as.factor %>% as.numeric,
test_y %>% as.factor %>% as.numeric,
direction ="<")
# SMOTE AUC
smote_roc <-
pROC::multiclass.roc(prediction_smote %>% as.factor %>% as.numeric,
test_y %>% as.factor %>% as.numeric,
direction ="<")
# Original AUC
original_roc <-
pROC::multiclass.roc(pred_original %>% as.factor %>% as.numeric,
test_y %>% as.factor %>% as.numeric,
direction ="<")
over_roc$auc
under_roc$auc
smote_roc$auc
original_roc$auc
```
<br>
```{r}
over_rc <- over_roc[['rocs']]
under_rc <- under_roc[['rocs']]
smote_rc <- smote_roc[['rocs']]
original_rs <- original_roc[['rocs']]
par(mfrow=c(2,2))
# over
plot.roc(over_rc[[1]], main = "ROC : Oversampling")
sapply(2:length(over_rc),function(i) lines.roc(over_rc[[i]],col=i))
text(0,0.2,labels=glue("AUC : {round(over_roc$auc,4)}"), col="red")
# under
plot.roc(under_rc[[1]], main = "ROC : Undersampling")
sapply(2:length(under_rc),function(i) lines.roc(under_rc[[i]],col=i))
text(0,0.2,labels=glue("AUC : {round(under_roc$auc,4)}"), col="red")
# smote
plot.roc(smote_rc[[1]], main = "ROC : SMOTE")
sapply(2:length(smote_rc),function(i) lines.roc(smote_rc[[i]],col=i))
text(0,0.2,labels=glue("AUC : {round(smote_roc$auc,4)}"), col="red")
# original
plot.roc(original_rs[[1]], main = "ROC : Original")
sapply(2:length(original_rs),function(i) lines.roc(original_rs[[i]],col=i))
text(0,0.2,labels=glue("AUC : {round(original_roc$auc,4)}"),
col="red")
```
<br>
<br>
## Reference
[multiclass ROC curve](https://stackoverflow.com/questions/34169774/plot-roc-for-multiclass-roc-in-proc-package)
[Boruta algorithm](https://www.datacamp.com/community/tutorials/feature-selection-R-boruta#package)
<file_sep># 13주 학부연구생의 생물통계분석
[연구주제 고민](https://koojaekwan.github.io/Researcher_undergraduated/%EC%97%B0%EA%B5%AC%EC%A3%BC%EC%A0%9Chtml.html#(1))
[breast cancer 프로젝트](https://koojaekwan.github.io/Researcher_undergraduated/breast.html)
[gene plot](https://koojaekwan.github.io/Researcher_undergraduated/gene_plot.html)
[keras example in subtype classification](https://koojaekwan.github.io/Researcher_undergraduated/keras_example_R.html)
| e3c5d9be8f81ce5bb99adbfac3af9f09d200eaae | [
"Markdown",
"R",
"RMarkdown"
] | 6 | RMarkdown | koojaekwan/Researcher_undergraduated | ea8a21482a40f7df55972535497c7e1d3af12f05 | dc79e155875a364a9a66cbbe573b48695c9e9c89 |
refs/heads/master | <file_sep>package cn.jhworks.lib_common.event;
import io.reactivex.Flowable;
import io.reactivex.processors.FlowableProcessor;
import io.reactivex.processors.PublishProcessor;
import io.reactivex.subscribers.SerializedSubscriber;
/**
* <p> 基于RxJava的事件分发封装</p>
*
* @author jiahui
* @date 2017/12/12
*/
public class RxBus {
private static volatile RxBus sRxBus;
private final FlowableProcessor<Object> mBus;
private RxBus() {
//toSerialized()保证线程安全
mBus = PublishProcessor.create().toSerialized();
}
public static RxBus get() {
if (sRxBus == null) {
synchronized (RxBus.class) {
if (sRxBus == null) {
sRxBus = new RxBus();
}
}
}
return sRxBus;
}
/**
* 发送消息
*
* @param o
*/
public void post(Object o) {
new SerializedSubscriber<>(mBus).onNext(o);
}
/**
* 确定接收消息类型
*
* @param tClass 消息类型
* @param <T>
* @return
*/
public <T> Flowable<T> toFlowable(Class<T> tClass) {
return mBus.ofType(tClass);
}
/**
* Returns true if the subject has subscribers.
* <p>The method is thread-safe.
*
* @return true if the subject has subscribers
*/
public boolean hasSubscribers() {
return mBus.hasSubscribers();
}
}
<file_sep>include ':app', ':rxnet', ':lib_common'
<file_sep>apply plugin: 'com.android.library'
apply plugin: 'com.novoda.bintray-release'//添加
android {
compileSdkVersion rootProject.ext.android.compileSdkVersion
buildToolsVersion rootProject.ext.android.buildToolsVersion
defaultConfig {
minSdkVersion rootProject.ext.android.minSdkVersion
targetSdkVersion rootProject.ext.android.targetSdkVersion
versionCode rootProject.ext.android.versionCode
versionName rootProject.ext.android.versionName
}
}
//添加
publish {
userOrg = 'jiahui'//bintray.com用户名
repoName = 'jiahui'//要传到的maven的名字。你可能有多个maven,要传哪个写哪个。
groupId = 'org.net.rxnet'//jcenter上的路径
artifactId = 'RxNet'//项目名称
publishVersion = '1.0.2'//版本号
desc = 'Retrofit2,RxJava,Okhttp3简单封装,快速开发项目!'//描述,不重要
website = 'https://github.com/JackLiaoJH'//网站,不重要
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
compile rootProject.ext.dependencies.rxjava2
compile(rootProject.ext.dependencies.rxjava2_android) {
exclude module: "rxjava"
}
/* compile(rootProject.ext.dependencies.rxlifecycle2) {
exclude module: 'rxjava'
exclude module: 'jsr305'
}
compile(rootProject.ext.dependencies.rxlifecycle2_components) {
exclude module: 'support-v4'
exclude module: 'appcompat-v7'
exclude module: 'support-annotations'
exclude module: 'rxjava'
exclude module: 'rxandroid'
exclude module: 'rxlifecycle'
}*/
compile(rootProject.ext.dependencies.retrofit) {
exclude module: 'okhttp'
exclude module: 'okio'
}
compile(rootProject.ext.dependencies.retrofit_converter_gson) {
exclude module: 'gson'
exclude module: 'okhttp'
exclude module: 'okio'
exclude module: 'retrofit'
}
compile(rootProject.ext.dependencies.retrofit_adapter_rxjava2) {
exclude module: 'rxjava'
exclude module: 'okhttp'
exclude module: 'retrofit'
exclude module: 'okio'
}
compile rootProject.ext.dependencies.gson
compile rootProject.ext.dependencies.okhttp3
compile rootProject.ext.dependencies.okhttp3_logging
}
<file_sep>package cn.jhworks.rxnetproject
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import cn.jhworks.lib_common.event.RxBusHelper
import cn.jhworks.rxnetproject.meizi.MeiZiActivity
import cn.jhworks.rxnetproject.meizi.MeiZiEvent
import cn.jhworks.rxnetproject.module.BasicResult
import cn.jhworks.rxnetproject.module.MeiZi
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_main.*
import org.net.rxnet.utils.RxNetLog
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
fab.setOnClickListener { view ->
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show()
//
// RxNet.doGet("/v3/user/3")
// .param("userId",String.valueOf(1))
// .header("cache","sdas")
// .excute(new CallBack());
MeiZiActivity.start(this)
}
RxBusHelper.doOnMainThread(MeiZiEvent().javaClass,
{ res ->
if (res?.mMeiZiList != null)
RxNetLog.i("主页获取数据:%s", res.mMeiZiList)
})
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
}
<file_sep>package cn.jhworks.rxnetproject;
import android.app.Application;
import org.net.rxnet.RxNet;
import org.net.rxnet.model.HttpHeaders;
import org.net.rxnet.model.HttpParams;
/**
* <p> </p>
*
* @author jiahui
* @date 2017/12/4
*/
public class RxNetApp extends Application {
@Override
public void onCreate() {
super.onCreate();
// HttpHeaders httpHeaders = new HttpHeaders();
// for (int i = 0; i < 10; i++) {
// httpHeaders.put("key" + i, "value" + i);
// }
HttpParams httpParams = new HttpParams();
for (int i = 0; i < 10; i++) {
httpParams.put("key" + i, "value" + i);
}
RxNet.init(this)
.debug(BuildConfig.DEBUG)
.setBaseUrl("http://gank.io")
// .setHttpHeaders(httpHeaders)
.setHttpParams(httpParams)
//https
// .certificates()
.build()
;
}
}
<file_sep>package cn.jhworks.lib_common.base.factory;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import cn.jhworks.lib_common.base.AbstractMvpPresenter;
/**
* <p> 标注创建Presenter的注解</p>
*
* @author jiahui
* @date 2017/12/8
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface CreatePresenter {
Class<? extends AbstractMvpPresenter> value();
}
<file_sep># RxNet 网络请求初始化
<file_sep>package cn.jhworks.lib_common.base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import cn.jhworks.lib_common.base.factory.BaseMvpProxy;
import cn.jhworks.lib_common.base.factory.PresenterMvpFactory;
import cn.jhworks.lib_common.base.factory.PresenterMvpFactoryImpl;
import cn.jhworks.lib_common.base.factory.PresenterProxyInterface;
/**
* <p> 1. 子类的Presenter必须继承自AbstractMvpPresenter;
* 2. 子类的View必须继承自IMvpBaseView
* </p>
*
* @author jiahui
* @date 2017/12/7
*/
public abstract class AbstractMvpActivity<V extends IMvpBaseView, P extends AbstractMvpPresenter<V>> extends AppCompatActivity
implements PresenterProxyInterface<V, P> {
protected final String TAG = getClass().getSimpleName();
private static final String KEY_SAVE_PRESENTER = "key_save_presenter";
/** 创建代理对象,传入默认的Presenter工厂 */
private BaseMvpProxy<V, P> mMvpProxy = new BaseMvpProxy<>(PresenterMvpFactoryImpl.<V, P>createFactory(getClass()));
private final String activityName = getClass().getName();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, activityName + " V onCreate...");
Log.e(TAG, activityName + " V onCreate... mProxy=" + mMvpProxy);
Log.e(TAG, activityName + " V onCreate... this=" + this.hashCode());
if (savedInstanceState != null) {
mMvpProxy.onRestoreInstanceState(savedInstanceState.getBundle(KEY_SAVE_PRESENTER));
}
}
@Override
protected void onResume() {
super.onResume();
Log.e(TAG, activityName + " V onResume...");
mMvpProxy.onResume((V) this);
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.e(TAG, activityName + " V onDestroy...");
mMvpProxy.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.e(TAG, activityName + " V onSaveInstanceState...");
outState.putBundle(KEY_SAVE_PRESENTER, mMvpProxy.onSaveInstanceState());
}
@Override
public void setPresenterFactory(PresenterMvpFactory<V, P> presenterFactory) {
Log.e(TAG, activityName + " V setPresenterFactory...");
mMvpProxy.setPresenterFactory(presenterFactory);
}
@Override
public PresenterMvpFactory<V, P> getPresenterFactory() {
Log.e(TAG, activityName + " V getPresenterFactory...");
return mMvpProxy.getPresenterFactory();
}
@Override
public P getMvpPresenter() {
Log.e(TAG, activityName + " V getMvpPresenter...");
return mMvpProxy.getMvpPresenter();
}
}
<file_sep>package cn.jhworks.lib_common.base.factory;
import cn.jhworks.lib_common.base.AbstractMvpPresenter;
import cn.jhworks.lib_common.base.IMvpBaseView;
/**
* <p> Presenter 工厂接口</p>
*
* @author jiahui
* @date 2017/12/7
*/
public interface PresenterMvpFactory<V extends IMvpBaseView, P extends AbstractMvpPresenter<V>> {
/**
* 创建Presenter方法
*
* @return 创建的Presenter
*/
P createMvpPresenter();
}
<file_sep>package cn.jhworks.lib_common.base;
/**
* <p> MVP 模式View 基类</p>
*
* @author jiahui
* @date 2017/12/7
*/
public interface IMvpBaseView {
}
| e6d763146ead07986e408df15d2ae9bc9d082fed | [
"Markdown",
"Java",
"Kotlin",
"Gradle"
] | 10 | Java | JackLiaoJH/RxNet | ca891068ec11152a2a2e8c2c263d0496f887e5da | 1b87d3f4ba72a1a49bb49ec1fba5e4d8f163da76 |
refs/heads/master | <file_sep>import React from 'react';
function Flutter(){
return (<h1>我是FLUTER</h1>)
}
export default Flutter;
<file_sep>import React, { Component } from 'react';
class List extends Component {
constructor(props) {
super(props);
this.state = { }
}
componentDidMount(){
// 打印路由
console.log(this.props.match)
console.log(this.props.match.params.id)
}
render() {
return (
<ul>
<li>10点半睡觉</li>
<li>6点起床</li>
<li>运动</li>
<li>7点洗漱</li>
<li>7点半早餐出门上班</li>
</ul>
);
}
}
export default List;<file_sep>import React from 'react';
import {Route,Link} from 'react-router-dom';
import work1 from './Test1';
import work2 from './Test2';
function Index(){
return (
<div>
<div className="topNav">
<ul>
<li><Link to="/workPlace/test1/">技能1</Link></li>
<li><Link to="/workPlace/test2/">技能2</Link></li>
</ul>
</div>
<div className="videoContent">
<Route path="/workPlace/test1/" component={work1}></Route>
<Route path="/workPlace/test2/" component={work2}></Route>
</div>
</div>
)
}
export default Index;<file_sep>import React, {Component } from 'react';
import {Link,Redirect} from 'react-router-dom';
class Index extends Component {
constructor(props) {
super(props);
this.state = {
list:[
{
cid:1,title:'文章1'
},
{
cid:2,title:'文章2'
},
{
cid:3,title:'文章3'
},
{
cid:4,title:'文章4'
},
{
cid:5,title:'文章5'
},
]
}
this.props.history.push('/home/')
}
render() {
return (
<div>
<ul>
{
this.state.list.map((item,index)=>{
return <li key={index}><Link to={`/list/${item.cid}`}>{item.title}</Link></li>
})
}
</ul>
{/* <Redirect to='/home/'>重定向</Redirect> */}
</div>
);
}
}
export default Index;<file_sep>import React from 'react';
function Test1(){
return (<h2>我是React页面</h2>)
}
export default Test1;<file_sep>import React from 'react';
function work2(){
return (
<h1>天天在学习</h1>
)
}
export default work2;<file_sep>import React from 'react';
function Vue(){
return (<h1>我是 vue</h1>)
}
export default Vue; | 7e831d3fb082318b0029d188849ce0641008ce32 | [
"JavaScript"
] | 7 | JavaScript | MECN/react-router | 6965701143662f2edc8941b29cc27de90fc065e7 | ff162710384110f62ba092d5b5ea61a5a74f631d |
refs/heads/master | <file_sep># XmlParser
Deprecated
<file_sep>import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.awt.*;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
public class Main extends Application
{
private static boolean check = true;
public static void main(String[] args) throws SQLException, IOException
{
/* beginParsing();
HeapSizeChecker checker = new HeapSizeChecker();
checker.start();*/
launch(args);
// String selectTableSQL = "SELECT * FROM test";
// ResultSet rs = statement.executeQuery(selectTableSQL);
//
// while (rs.next())
// {
// String userid = rs.getString("id");
// String username = rs.getString("testcol");
//
// System.out.println("id : " + userid);
// System.out.println("testcol : " + username);
// }
}
@Override
public void start(Stage primaryStage) throws IOException
{
try
{
Parent root = FXMLLoader.load(getClass().getResource("fxml/main.fxml"));
primaryStage.setTitle("Choose a file to parse");
primaryStage.setScene(new Scene(root, 305, 150));
primaryStage.setResizable(false);
root.requestFocus();
primaryStage.show();
ClickController.init(primaryStage);
establishConnection(primaryStage);
} catch (Exception e)
{
e.printStackTrace();
}
}
private void establishConnection(Stage pStage) throws IOException
{
Stage stage = new Stage();
Parent conn = FXMLLoader.load(getClass().getResource("fxml/connection.fxml"));
stage.setResizable(false);
stage.setScene(new Scene(conn));
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(pStage.getScene().getWindow());
conn.requestFocus();
stage.show();
}
private static void beginParsing() throws SQLException
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e)
{
System.out.println(e.getMessage());
}
XmlParser parser = new XmlParser();
java.sql.Connection connection = null;
try
{
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/dbbig", "root", "root");
} catch (SQLException e)
{
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
Statement statement = connection.createStatement();
try
{
/*newTable(statement, "Users", XmlParser.attributesUsers);
ArrayList<HashMap<String, String>> data = parser.parseXmlAttributes("C:\\Users\\Wingfly\\Desktop\\DB\\Users.xml", XmlParser.attributesUsers);
addToDB(statement, "Users", data);
System.out.println("Users finished");
newTable(statement, "Badges", XmlParser.attributesBadges);
addToDB(statement, "Badges", parser.parseXmlAttributes("C:\\Users\\Wingfly\\Desktop\\DB\\Badges.xml", XmlParser.attributesBadges));
System.out.println("Badges finished");
newTable(statement, "Comments", XmlParser.attributesComments);
addToDB(statement, "Comments", parser.parseXmlAttributes("C:\\Users\\Wingfly\\Desktop\\DB\\Comments.xml", XmlParser.attributesComments));
System.out.println("Comments finished");
newTable(statement, "History", XmlParser.attributesHistory);
addToDB(statement, "History", parser.parseXmlAttributes("C:\\Users\\Wingfly\\Desktop\\DB\\PostHistory.xml", XmlParser.attributesHistory));
System.out.println("History finished");
newTable(statement, "PostLinks", XmlParser.attributesPostLinks);
addToDB(statement, "PostLinks", parser.parseXmlAttributes("C:\\Users\\Wingfly\\Desktop\\DB\\PostLinks.xml", XmlParser.attributesPostLinks));
System.out.println("PostLinks finished");*/
// newTable(statement, "Post", XmlParser.attributesPost);
addToDB(statement, "Post", parser.parseXmlAttributes("C:\\Users\\Wingfly\\Desktop\\DB\\Posts.xml", XmlParser.attributesPost));
System.out.println("Post finished");
/* newTable(statement, "Tags", XmlParser.attributesTags);
addToDB(statement, "Tags", parser.parseXmlAttributes("C:\\Users\\Wingfly\\Desktop\\DB\\Tags.xml", XmlParser.attributesTags));
System.out.println("Tags finished");
newTable(statement, "Votes", XmlParser.attributesVotes);
addToDB(statement, "Votes", parser.parseXmlAttributes("C:\\Users\\Wingfly\\Desktop\\DB\\Votes.xml", XmlParser.attributesVotes));
System.out.println("Votes finished");
System.out.println("parsing finished");*/
} catch (OutOfMemoryError error)
{
check = false;
}
}
private static void addToDB(Statement statement, String tableName, ArrayList<HashMap<String, String>> data) throws SQLException
{
try
{
for (HashMap<String, String> str : data)
{
StringBuilder column = new StringBuilder();
StringBuilder val = new StringBuilder();
for (String name : str.keySet())
{
String s = str.get(name);
s = s.replace("'", "")
.replace("`", "")
.replace("\\", "");
column.append("`").append(name).append("`");
val.append("'").append(s).append("'");
// if name equals to last key of map dont append , at the end
if (!name.equals(str.keySet().toArray()[str.size() - 1]))
{
column.append(", ");
val.append(", ");
}
}
String selectTableSQL2 = "INSERT INTO `" + tableName +
"` (" + column.toString() + ") VALUES (" +
val.toString() + ")";
statement.executeUpdate(selectTableSQL2);
System.out.println(selectTableSQL2);
}
} catch (Exception e)
{
check = false;
e.printStackTrace();
}
}
private static void newTable(Statement statement, String tableName, String[] array) throws SQLException
{
StringBuilder builder = new StringBuilder();
builder.append("CREATE table `dbbig`.`")
.append(tableName)
.append("`( `idUsers` INT NOT NULL AUTO_INCREMENT,");
for (int i = 0; i < array.length; i++)
{
builder.append("`" + array[i] + "` TEXT(1000000),");
}
builder.append(" PRIMARY KEY (`idUsers`));");
statement.executeUpdate("DROP TABLE if exists `dbbig`.`" + tableName + "`");
statement.executeUpdate(builder.toString());
}
static class HeapSizeChecker extends Thread
{
@Override
public void run()
{
while (check)
{
try
{
sleep(2000);
System.out.println(Runtime.getRuntime().freeMemory() / 1000000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}<file_sep>import javafx.scene.control.Alert;
public class Error
{
public static void newError(String header)
{
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText(header);
alert.showAndWait();
}
public static void newInfo(String message)
{
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Info");
alert.setHeaderText(message);
alert.showAndWait();
}
}
<file_sep>import com.sun.org.apache.xerces.internal.dom.DeferredAttrImpl;
import javafx.fxml.FXML;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Statement;
public class FIleParser
{
private static final int TABLE_DOES_NOT_EXIST = 1146;
private static String element = null;
private String fileName;
private static Statement statement;
public static FIleParser newInstance(File file, String elementToParse)
{
element = elementToParse;
if (file == null)
return null;
try
{
return new FIleParser(file);
} catch (SAXException e)
{
e.printStackTrace();
} catch (ParserConfigurationException e)
{
e.printStackTrace();
} catch (SQLException e)
{
e.printStackTrace();
if (e.getErrorCode() == TABLE_DOES_NOT_EXIST) createTable(file);
else Error.newError(e.getMessage());
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
private static void createTable(File file)
{
//TODO what now?
System.out.println();
}
public FIleParser(File file) throws SAXException, ParserConfigurationException, SQLException, IOException
{
fileName = file.getAbsoluteFile().getName();
if (fileName.endsWith(".xml"))
{
fileName = fileName.replace(".xml", "");
if (ClickController.checkTableDelete.isEnabled())
{
dropTableRecreate(file);
} else
{
parse(file);
}
}
}
private void parse(File file) throws IOException, SAXException, ParserConfigurationException, SQLException
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName(element);
for (int i = 0; i < nList.getLength(); i++)
{
Node item = nList.item(i);
NamedNodeMap attributes = item.getAttributes();
StringBuilder column = new StringBuilder();
StringBuilder val = new StringBuilder();
for (int j = 0; j < attributes.getLength(); j++)
{
Node attr = attributes.item(j);
String name = ((DeferredAttrImpl) attr).getName();
String value = ((DeferredAttrImpl) attr).getValue();
System.out.println("");
value = value.replace("'", "")
.replace("`", "")
.replace("\\", "");
column.append("`").append(name).append("`");
val.append("'").append(value).append("'");
// if name equals to last key of map dont append , at the end
if (!attr.equals(attributes.item(attributes.getLength() - 1)))
{
column.append(", ");
val.append(", ");
}
}
String selectTableSQL2 = "INSERT INTO `" + fileName +
"` (" + column.toString() + ") VALUES (" +
val.toString() + ")";
getStatement().executeUpdate(selectTableSQL2);
System.out.println(selectTableSQL2);
}
}
private void dropTableRecreate(File file)
{
}
public static Statement getStatement()
{
return statement;
}
public static void setStatement(Statement statement)
{
FIleParser.statement = statement;
}
}<file_sep>import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.stage.Window;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectionController
{
//TODO add port textfield too
@FXML
TextField tfUser = new TextField();
@FXML
TextField tfPassword = new TextField();
@FXML
TextField tfDbName = new TextField();
@FXML
public void connect(ActionEvent actionEvent)
{
try
{
java.sql.Connection connection = null;
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/" + tfDbName.getText(), tfUser.getText(), tfPassword.getText());
FIleParser.setStatement(connection.createStatement());
Error.newInfo("connected successfully");
Stage window = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
window.close();
} catch (SQLException e)
{
Error.newError("connection not established");
e.printStackTrace();
} finally
{
/* Stage window = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
window.close();*/
}
}
}
| 0b71ab66bb824fc45e76439ea2613ad8ae33188a | [
"Markdown",
"Java"
] | 5 | Markdown | WingFlier/XmlParser | b9b801ca7a8790dbfe25cf991abf29191c52b086 | 373cc652c1846f84d188e7cd515932bb39e9fe53 |
refs/heads/master | <repo_name>Molem7b5/test-repo<file_sep>/test_folder/test_2.py
def test(:) | 551894d8cdcfa0b9159f6d4c82066eefb7ca3d61 | [
"Python"
] | 1 | Python | Molem7b5/test-repo | 00fba46002316c317e51d7f6c8ba1e780953ded6 | a4f2c2613faad1a932079c502e8d3827c6c493ce |
refs/heads/master | <file_sep>
//环境切换
let isTest = process.env.isTest;
//api接口
let baseUrl = '';
let apiUrl = "";
let apiTwoUrl = "";
let apiUrlSit = "";
let shop = "";
let weChatPublic = "";
let apiNewYear = "";
let goods = "";
let news = "";
let group = "";
let wxPhone = "";
let djcx = "";
let vb = "";
let qiNiuPhoto = "";
let cdd = "";
switch (isTest) {
//测试环境
case true:
console.log("当前环境:测试");
baseUrl = 'https://bqyx.bqzulin.com';
apiUrl = `${baseUrl}/bqyx/homepage/`;
apiTwoUrl = `${baseUrl}/bqyx/thirdparty/`;
apiUrlSit = `${baseUrl}/bqyx/activity/`;
shop = `${baseUrl}/mall`;
cdd = `${baseUrl}/cdd/`;
//cdd = `http://10.81.2.14:8080/`;
//会佳本地
//shop = "http://10.81.2.201/dist";
weChatPublic = "https://uatwx.bqzulin.com";
// apiNewYear = "http://szxhrzzlit035.bf.cn:8015/"
apiNewYear = "https://bqyx.bqzulin.com/bqyx/activity/";
// apiUrl = "http://10.81.2.218:8012/";
// apiTwoUrl = "http://10.81.2.218:8012/bqyx/";
//apiUrlSit = "http://10.81.2.152:8015/";
goods = `${baseUrl}/bqyx/goods/`;
// weChatPublic = "http://10.81.2.218:8003/bqyx/thirdparty/";
wxPhone = `${baseUrl}/bqyx/thirdparty/crawlType/`;
break;
//生产环境
case false:
console.log("当前环境:生产");
baseUrl = 'https://bqyxapi.bqrzzl.com';
apiUrl = `${baseUrl}/bqyx/homepage/`;
apiTwoUrl = `${baseUrl}/bqyx/thirdparty/`;
apiUrlSit = `${baseUrl}/bqyx/activity/`;
shop = `https://bqyxh5.bqrzzl.com/mall`;
cdd = `https://bqyxh5.bqrzzl.com/cdd/`;
weChatPublic = "https://car.bqrzzl.com";
goods = `${baseUrl}/bqyx/goods/`;
wxPhone = `${baseUrl}/bqyx/thirdparty/crawlType/`;
//七牛云图片配置
qiNiuPhoto = "http://bqyx-qiniu.bqrzzl.com";
break;
}
export const path = {
//热门品牌
hotBrand: apiUrl + "queryRankingsbrandList",
//爆款推荐
carHot: apiUrl + "queryProductInfoByProductStateIdList",
//产品详情
carModelInfo: apiUrl + "queryCarModelInfo",
// 车辆中心列表
artcList: apiUrl + "queryCarServiceList",
// 获取城市信息
carCityList: apiUrl + "queryCarCityList",
// 新增保存车辆信息
addCarServiceInfo: apiUrl + "addCarServiceInfo",
// 编辑保存车辆信息
updateCarServiceInfo: apiUrl + "updateCarServiceInfo",
// 删除个人车辆信息
delCarServiceInfo: apiUrl + "delCarServiceInfo",
// 违章查询
carViolation: apiTwoUrl + "get/carViolation",
// 牌照前缀
cayCityChek: apiTwoUrl + "get/cayCityChek ",
// 个人车辆信息 //车辆中心列表
myCarINfo: apiUrl + "queryCarServiceList",
// 张松,获取城市信息
myCity: apiTwoUrl + "get/city",
queryBrandList: apiUrl + "queryBrandList",
myCarINfo: apiUrl + "queryCarServiceList",
feedback: apiUrl + "feedbackContent",
saveCarApplication: apiUrl + "saveCarApplication",
register: apiUrl + "bqzl/user/register",
login: apiUrl + "bqzl/user/login",
cayChek: apiTwoUrl + "get/cayChek",
//获取所有充值卡的接口
getAllSetting: apiUrlSit + "oilCardSetting/getAllSetting",
//绑定油卡
bindOilCard: apiUrlSit + "oilCard/binding",
//切换油卡(主卡)
getOilCardChange: apiUrlSit + "oilCard/changeCard",
//获取用户绑定的油卡
getOilCard: apiUrlSit + "oilCard/getAllCard",
//解绑
getDeleteCard: apiUrlSit + "oilCard/unbinding",
//查看充值记录
getRechargeRecord: apiUrlSit + "oilCard/rechargeDetail",
//账户明细
getQueryDetail: apiUrlSit + "account/queryDetail",
//账户金额
getQueryBalance: apiUrlSit + "account/queryBalance",
//油卡充值
getRecharge: apiUrlSit + "oilCard/recharge",
//充值结果
rechargeResult: apiUrlSit + "oilCard/rechargeResult",
//活动
getActivity: apiUrlSit + "redpacket/getActivity",
//开红包
getRedopen: apiUrlSit + "redpacket/open",
getRedopen2: apiUrlSit + "redpacket/open2",
//微信支付
goWxPay: apiUrlSit + "oilCard/rechargePaid",
//获取车类分区
getProductStatuslist: apiUrl + "getProductStatuslist",
//模糊搜索
getSearch: apiUrl + "queryBrandProductLike",
//提现
getMoney: apiUrlSit + "account/withdrawCash",
//提现验证码
getCodeRecord: apiUrlSit + "account/getVerifyCode",
//获取短信验证码
getCode: apiUrl + "bqzl/user/getVerifyCode",
//手机验证登录
goVerifyCode: apiUrl + "bqzl/user/login",
//获取验证码(三方服务)
getVerifyCode: apiTwoUrl + "shortMsg/getVerifyCode",
//校验短信验证码
checkVerifyCode: apiTwoUrl + "shortMsg/checkVerifyCode",
shareBg: apiUrlSit + "getPoster",//海报背景
shareSignBg: apiUrlSit + "getDailySignPoster",//签到海报背景
shareScanBg: apiUrlSit + "getDailyScanPoster",//AI扫车海报背景
shareImg: baseUrl + '/bqyx/thirdparty/miniprogram/getWXACodeUnlimit',//海报二维码
imgCode: apiUrlSit + "dynamicCode/get",
//H5分享
shareTime: apiUrlSit + "luckyDraw/addTimes",
//签到接口
//doSign: apiUrlSit + "dailySign/doSign",
//打开签到红包
openPacket: apiUrlSit + "dailySign/openPacket",
//获取用户是否已签到
getSignFlag: apiUrlSit + "dailySign/getSignFlag",
//获取签到红包规则
getRules: apiUrlSit + "dailySign/getRules",
saveInvitation: apiUrlSit + "dailySign/saveInvitation",
clickSign: apiUrlSit + "dailySign/clickSign",
//拜年-创建组织
groupMainSave: apiUrlSit + "groupMain/saveGroupMain",
//拜年-新增组织记录
saveGroupUserInfo: apiUrlSit + "groupUserInfo/saveGroupUserInfo",
//拜年-查询用户组织列表
queryMyOrganization: apiUrlSit + "groupUserInfo/queryMyOrganization",
queryOrganizationSquare: apiUrlSit + "/groupUserInfo/queryOrganizationSquare",
//查询拜年记录明细
getRecordDetail: apiUrlSit + "yearRecordInfo/recordDetail",
saveGroupUserInfo: apiUrlSit + "groupUserInfo/saveGroupUserInfo",
//拜年-拜年记录
newYearRecord: apiUrlSit + "yearRecordInfo/myRecords",
//拜年-拜年记录明细
recordDetail: apiUrlSit + "yearRecordInfo/recordDetail",
//选择拜年对像
getGroupList: apiUrlSit + "groupUserInfo/queryMyOrganization",
//组织详情
getGroupUser: apiUrlSit + "groupUserInfo/queryOrganizationDetails",
//获取拜年红包总金额
getSumRedPacket: apiUrlSit + "yearRecordInfo/getSumRedPacket",
//获取拜年红包明细
getRedPacketDetail: apiUrlSit + "yearRecordInfo/getRedPacketDetail",
//拜年活动规则
getNewYearRules: apiUrlSit + "getRules/bqyx_E_001",
//获得最近一条打赏记录
getNearestReward: apiUrlSit + "yearRecordInfo/getNearestReward",
//红包打赏
redPacketPay: apiUrlSit + "yearRecordInfo/redPacketPay",
//搜索好友
queryByUserIdAndUserNickName: apiUrlSit + "groupUserInfo/queryByUserIdAndUserNickName",
//创建拜年团
saveGroupMain: apiUrlSit + "groupMain/saveGroupMain",
//添加团员数据
saveGroupUserInfo: apiUrlSit + "groupUserInfo/saveGroupUserInfo",
//发送拜年信息
sendNewYearInfo: apiUrlSit + "yearRecordInfo/save",
//拜年发起成功 通用接口
sendNewYearSuccess: apiUrlSit + "yearRecordInfo/recordDetail",
//拜年发起成功专用接口
// queryRecordByGroupMainId:apiUrlSit+"yearRecordInfo/queryRecordByGroupMainId",
//获取最近一条红包
getNearestReward: apiUrlSit + "yearRecordInfo/getNearestReward",
//获取所有红包
getAllNewYearRedBag: apiUrlSit + "yearRecordInfo/getRedPacketDetail",
//获取祝福语
findAll: apiUrlSit + "greetings/findAll",
//所有拜年记录
getAllListInfo: apiUrlSit + "yearRecordInfo/getAllListInfo",
//是否关注公众号
subscribe: "https://car.bqrzzl.com/api/newyear/subscribe",
//拜年祝福语保存
bnRecodeSave: apiUrlSit + "yearRecordInfo/save",
//红包领取明细
getRewardDetail: apiUrlSit + "yearRecordInfo/getRewardDetail",
//获取活动信息
getNewYearActivity: apiUrlSit + "getActivity",
getSweepActivity: apiUrlSit + "getActivity",
//向佰仟拜年
greetBQ: apiUrlSit + "yearRecordInfo/greetBQ",
//验证是否有向佰仟拜年过
hasGreetedToBQ: apiUrlSit + "yearRecordInfo/hasGreetedToBQ",
//英雄榜 - 刷新当天中奖名次前10
getWinninglist: apiUrlSit + "getWinninglist",
//英雄榜 - 获取所有英雄版前三名
getHeroRanking: apiUrlSit + "getHeroRanking",
//是否已在组织中发送消息
hasSendToGroup: apiUrlSit + "yearRecordInfo/hasSendToGroup",
//获取当天可扫描次数
getEnableTimes: apiUrlSit + "arScanning/getEnableTimes",
//识别照片
doScanning: apiUrlSit + "arScanning/doScanning",
//AI扫车打开红包
openRedpacket: apiUrlSit + "arScanning/openRedpacket",
//AI扫车保存邀请关系
scanSaveInvitation: apiUrlSit + "arScanning/saveInvitation",
//AI扫车规则
getscanRules: apiUrlSit + "getRules/bqyx_F_001",
getRunData: apiUrlSit + "step/getRunData",
//积步领红包规则
getaccuRules: apiUrlSit + "getRules/bqyx_G_001",
//积步授权
stepAuth: apiUrlSit + "step/auth",
//积步步数要求
getExchangeRule: apiUrlSit + "step/getExchangeRule",
//积步排行榜
getRankingList: apiUrlSit + "step/getRankingList",
//积步兑换
runExchange: apiUrlSit + "step/exchange",
stepSaveInvitation: apiUrlSit + "step/saveInvitation",
getStepPoster: apiUrlSit + "getStepPoster",
getExchangeTimePeriod: apiUrlSit + "step/getExchangeTimePeriod",
getwalletRules: apiUrlSit + "getRules/bqyx_Rule_001",
//商品信息
getGoodsInfo: goods + "getGoodsInfo",
//2.获取砍价信息
getBargainInfo: apiUrlSit + "bargain/getBargainInfo",
//下载商品图片
queryGoodsInfo: goods + "queryGoodsInfo",
//下载新闻图片
queryShareLink: apiTwoUrl + "crawl/queryShareLink",
//获取授权电话号
deciphering: apiTwoUrl + "wxLoginTranscoding/deciphering",
//微信绑定手机号传后台
updateUserMobile: wxPhone + "updateUserMobile",
//新闻类型
queryType: apiTwoUrl + "crawlType/queryType",
//新闻列表
queryShowNews: apiTwoUrl + "crawl/queryShowNews",
//获取评论
queryCrawlCommentMp: apiTwoUrl + "crawlCommentMp/queryCrawlCommentMp",
//新增评论
insertCrawlCommentMp: apiTwoUrl + "crawlCommentMp/insertCrawlCommentMp",
//新闻详细列表
queryLinkContent: apiTwoUrl + "crawl/queryLinkContent",
//组团抽奖活动登陆新老用户
queryIsNewUser: apiUrlSit + "teamLuckDraw/queryIsNewUser",
// 获取组团规则
getGroupRules: apiUrlSit + "getRules/bqyx_I_001",
//新用户去参团
queryTeam: apiUrlSit + "teamLuckDraw/queryTeam",
//新用户参团抽奖
insertTeam: apiUrlSit + "teamLuckDraw/insertTeam",
//查询我的奖品
queryMyPrize: apiUrlSit + "teamLuckDraw/queryMyPrize",
//填写中奖收货地址
updateDetailedAddress: apiUrlSit + "teamLuckDraw/updateDetailedAddress",
//查询活动所有可抽奖的奖品
queryPzizeList: apiUrlSit + "teamLuckDraw/queryPzizeList",
//老用户我的组团
queryMyTeam: apiUrlSit + "teamLuckDraw/queryMyTeam",
//创建团(奖品详细)
isertCreateTeam: apiUrlSit + "teamLuckDraw/isertCreateTeam",
//查询该团详情
queryOneTeamDetails: apiUrlSit + "teamLuckDraw/queryOneTeamDetails",
//组团活动首页开关
allActivity: apiUrlSit + "teamLuckDraw/allActivity",
//后台接收收货地址
updateDetailedAddress: apiUrlSit + "teamLuckDraw/updateDetailedAddress",
//拉新用户保存记录
insertNewUser: apiUrlSit + "teamLuckDraw/insertNewUser",
//底价车险
insertCarInsurance: apiUrl + "carInsurance/insertCarInsurance",
//获取城市列表(车辆申请)
queryLeaseCity: apiUrl + "leaseCity/queryLeaseCity",
//生成新人礼包
generatePackage: apiUrlSit + "giftPackage/generatePackage",
//领取新人礼包
openPackage: apiUrlSit + "giftPackage/openPackage",
//V币余额
queryBalance: apiUrlSit + "account/queryBalance",
//V币签到信息
doSign: apiUrlSit + "dailySign/doSign",
//V币活动日常任务
getTaskList: apiUrlSit + "dailyTask/getTaskList",
//查询V币明细
queryVcoinDetail: apiUrlSit + "account/queryVcoinDetail",
//完成任务通知消息(组)
getNotifyMessage: apiUrlSit + "dailyTask/getNotifyMessage",
//确认消息通知
confirmNotifyMessage: apiUrlSit + "dailyTask/confirmNotifyMessage",
//领取日常任务奖励
getTaskReward: apiUrlSit + "dailyTask/getTaskReward",
//保存邀请信息
saveInvitation: apiUrlSit + "dailyTask/saveInvitation",
//统一用户信息(修改)
updateBaseInfo: apiUrl + "unifiedUser/updateBaseInfo",
//统一用户信息(获取)
getInfo: apiUrl + "unifiedUser/getInfo",
//首页活动列表
queryActivity: apiUrlSit + "bqyxActivitySet/queryActivity",
//七牛云token
getAccessToken: apiTwoUrl + "qiniu/getAccessToken",
//选车(会佳本地)
carSelection: shop + "/#/usedCarList",
//选车详情
carItem: shop + "/#/usedCarDetails",
//车辆预约查询
getReservationList: apiUrl + "getReservationList",
//车险预约查询
queryCarInsurance: apiUrl + "carInsurance/queryCarInsurance",
//二手车信息(标签查询)
getByLabel: goods + "secondhandCar/getByLabel",
//获取二手车标签
getLabels: goods + "secondhandCar/getLabels",
//获取首页二手车列表(3条)
queryList: goods + "secondhandCar/queryList"
};
export const dataConfig = {
version: '1.1.5',
//热门品牌ID
hotCarId: "234222486757376",
appid: "wx2d9477ca5518018b",
//小程序密钥(禁止改动)
secret: "38321612381d0c00a00c757553e4e321",
//secret: "<KEY>",
sourceType: "MP",//红包、活动来源类型
putForwardCooldownTime: 3 * 1000, //提现冷却时间
cooldownTimeCycle: 24 * 60 * 60 * 1000,//提现冷却周期一天,毫秒
};
export const link = {
weChatPublic: weChatPublic,
shop: shop + "/#/mallIndex",
bargainActive: shop + "/#/groupBargain",
helpBargain: shop + "/#/groupBargain_2_help",
zacx: "https://api.icp.51tsbx.com/static/agent/page/auto/html/productDetail.html?agentCode=AGENT0000000000000000&productCode=PROD06782124&isShare=BQJR&",
paySuccess: shop + "/#/paySuccess",
shippingAddress: shop + "/#/shippingAddress",
mallOrders: shop + "/#/mallOrders",
repayment: weChatPublic + "/initiative-repayment",
fixe: shop + '/#/activePageIndex',
cddApply: cdd + 'carInfo',
cddQuery: cdd + 'orderList',
cddLiveBodyBack: cdd + 'personalInfo',
bxfq: cdd + 'carInsuranceApply',
//bxfq: 'http://10.81.2.156:8080/carInsuranceApply',
bxdd: cdd + 'insuranceOrderList'
}
export const event = {
"home.czyr.apply": "车主易融-立即申请",
"home.invitation.redbag": "邀请好友领红包",
"product.apply": "产品-立即申请",
"oil": "加油充值",
"violation.enquiry": "违章查询",
"road.condition.query": "路况查询",
"car.evaluation": "汽车估价",
"my.balance": "我的余额",
"my.shop.order": "商城订单",
"my.finance.order": "金融订单",
"my.repayment": "我要还款",
"my.sign": "电子签约",
"my.address": "我的收货地址",
"my.withdraw.cash.1": "提现步骤1",
"my.withdraw.cash.2": "提现步骤2",
"from": "来源",
"group.active":"抽奖活动入口",
"group.active.join":"抽奖活动参与人数",
};
export function apiFail(error) {
console.log(error,789);
wx.hideToast();
let msg = "";
if (error) {
if (error.status && error.status == 500) {
msg = "系统异常";
} else if (error.data && error.data.message) {
msg = error.data.message;
}
} else {
msg = "系统异常";
}
if (msg === '') {
msg = "系统异常";
}
wx.showToast({
title: msg,
icon: "none"
});
};
export function getOilCard() {
let cardId = wx.getStorageSync("cardId");
return cardId;
};
export function allSetting() {
let setId = wx.getStorageSync("setId");
return setId;
};
export function getUserInfo() {
let userInfo = wx.getStorageSync("userInfo");
return userInfo;
};
/**
* 授权登录的数据
* @param {*} info
*/
export function setUserInfo(info) {
wx.setStorageSync("userInfo", info);
return info;
};
export function getLoginInfo() {
let userInfo = wx.getStorageSync("loginInfo");
//console.log(userInfo)
return userInfo;
};
/**
* 登录和绑定手机号后的用户数据
* @param {*} info
*/
export function setLoginInfo(info) {
wx.setStorageSync("loginInfo", info);
return info;
};
/**
* 是否绑定手机号,判断有无account
*/
export function isBindPhone() {
let loginInfo = wx.getStorageSync("loginInfo");
if (!loginInfo) {
return false;
}
return !!loginInfo.account;
}
export function showLoading(...promiseList) {
if (promiseList.length === 0) {
wx.showToast({
title: "加载中...",
mask: true,
icon: 'loading'
});
} else {
let finished = false;
let isLoading = false;
let time = 0;
let p = Promise.all(promiseList);
p.then(() => {
finished = true;
if (isLoading) {
let cost = Date.now() - time;
if (cost < 200) {
setTimeout(() => {
wx.hideToast();
}, 300);
} else {
wx.hideToast();
}
}
}).catch(e => {
finished = true;
apiFail(e);
});
setTimeout(() => {
if (false === finished) {
isLoading = true;
time = Date.now();
wx.showToast({
mask: true,
title: "加载中...",
icon: 'loading',
duration: 1000 * 1000 //最多显示1000秒load效果
});
}
}, 500);
}
}
export function hideLoading() {
wx.hideToast();
}
export function isHuaWei() {
let systemInfo = wx.getStorageSync("systemInfo");
let brand = systemInfo.brand;
if (brand.search('HUAWEI') != -1) {
return true;
}
//return true;
return false;
}
export function isOppo() {
let systemInfo = wx.getStorageSync("systemInfo");
let brand = systemInfo.brand;
if (brand.search('OPPO') != -1) {
return true;
}
//return true;
return false;
}
export function getSystemInfo() {
return wx.getStorageSync("systemInfo");
}
export function compareVersion(v1, v2) {
v1 = v1.split('.')
v2 = v2.split('.')
const len = Math.max(v1.length, v2.length)
while (v1.length < len) {
v1.push('0')
}
while (v2.length < len) {
v2.push('0')
}
for (let i = 0; i < len; i++) {
const num1 = parseInt(v1[i])
const num2 = parseInt(v2[i])
if (num1 > num2) {
return 1
} else if (num1 < num2) {
return -1
}
}
return 0
}
/**
* 最后一次提现时间
*/
export const lastPutForwardTime = {
set: function (time) {
wx.setStorageSync("lastPutForwardTime", time);
},
get: function () {
return wx.getStorageSync("lastPutForwardTime");
}
};
function formatNumber(n) {
const str = n.toString()
return str[1] ? str : `0${str}`
}
export function formatTime(date) {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
const t1 = [year, month, day].map(formatNumber).join('/')
const t2 = [hour, minute, second].map(formatNumber).join(':')
return `${t1} ${t2}`
}
export function setSceneCode(scene) {
wx.setStorageSync("scenecode", scene);
}
export function getSceneCode() {
return wx.getStorageSync("scenecode");
}
export function formatDate(inputTime) {
var date = new Date(inputTime);
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? ('0' + m) : m;
var d = date.getDate();
d = d < 10 ? ('0' + d) : d;
var h = date.getHours();
h = h < 10 ? ('0' + h) : h;
var minute = date.getMinutes();
var second = date.getSeconds();
minute = minute < 10 ? ('0' + minute) : minute;
second = second < 10 ? ('0' + second) : second;
return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
}
export class NumberAnimate {
constructor(opt) {
let def = {
from: 50,//开始时的数字
speed: 2000,// 总时间
refreshTime: 100,// 刷新一次的时间
decimals: 2,// 小数点后的位数
onUpdate: function () { }, // 更新时回调函数
onComplete: function () { } // 完成时回调函数
}
this.tempValue = 0;//累加变量值
this.opt = Object.assign(def, opt);//assign传入配置参数
this.loopCount = 0;//循环次数计数
this.loops = Math.ceil(this.opt.speed / this.opt.refreshTime);//数字累加次数
this.increment = (this.opt.from / this.loops);//每次累加的值
this.interval = null;//计时器对象
this.init();
}
init() {
this.interval = setInterval(() => { this.updateTimer() }, this.opt.refreshTime);
}
updateTimer() {
this.loopCount++;
this.tempValue = this.formatFloat(this.tempValue, this.increment).toFixed(this.opt.decimals);
if (this.loopCount >= this.loops) {
clearInterval(this.interval);
this.tempValue = this.opt.from;
this.opt.onComplete();
}
this.opt.onUpdate();
}
//解决0.1+0.2不等于0.3的小数累加精度问题
formatFloat(num1, num2) {
let baseNum, baseNum1, baseNum2;
try {
baseNum1 = num1.toString().split(".")[1].length;
} catch (e) {
baseNum1 = 0;
}
try {
baseNum2 = num2.toString().split(".")[1].length;
} catch (e) {
baseNum2 = 0;
}
baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
return (num1 * baseNum + num2 * baseNum) / baseNum;
};
}
export default {
event,
formatNumber,
formatTime,
path,
dataConfig,
apiFail,
getUserInfo,
setUserInfo,
getLoginInfo,
setLoginInfo,
isBindPhone,
showLoading,
hideLoading,
isHuaWei,
isOppo,
getSystemInfo,
compareVersion,
lastPutForwardTime,
setSceneCode,
getSceneCode,
formatDate,
NumberAnimate
}<file_sep>import Dayjs from 'dayjs';
Dayjs.install = (Vue, options = {}) => {
Vue.prototype.$dayjs = Dayjs;
};
// 流式布局分步加载器
function seperateLoader(loadsArray) {
function* innerGenerator(arr) {
for (let i = 0, item; item = arr[i++];) {
if (typeof item === 'function') yield item();
else yield item;
}
};
let fetching = false;
const genList = innerGenerator(loadsArray);
return function () {
if (fetching) return;
fetching = true;
try {
let result = genList.next().value;
!result instanceof Promise && (result = Promise.resolve(result));
result.finally(() => fetching = false);
} catch (error) {
fetching = false;
}
};
}
export {
Dayjs,
seperateLoader
};
<file_sep>let aldstat = require('../static/alad/ald-stat');
import Vue from 'vue'
import App from './App'
import Fly from 'flyio/dist/npm/wx'
import "../static/common.scss";
Vue.config.productionTip = false
App.mpType = 'app'
Vue.use({
install: function (Vue) {
Vue.prototype.$fly = new Fly();
Vue.prototype.$fly.interceptors.response.use(function (response) {
if (response.data.code == 200) {
return response.data.data;
} else {
return Promise.reject(response);
}
}, function (error) {
return Promise.reject(error)
});
/*Vue.prototype.$fly.interceptors.request.use((request)=>{
//给所有请求添加自定义header
let userInfo = wx.getStorageSync("loginInfo");
request.headers["access_token"]=userInfo.token;
request.body.token = <PASSWORD>;
request.params.token = <PASSWORD>;
return request;
})*/
}
});
const app = new Vue(App)
app.$mount()
| 87dee8903fbbe03b3f5d15d7ae9bcc183f005e6e | [
"JavaScript"
] | 3 | JavaScript | lq10-19/sss | 7ea7b9f3403da85a7b32f28211804a01ddf22794 | 96c039742499f1b0a0ded81308000d93588f9061 |
refs/heads/master | <repo_name>yzziqiu/cis527-administration<file_sep>/lab5-cloud.md
## SSH key
##### on ubuntu client side
###### basic test
```shell
ls -a
cd .ssh
ssh-keygen -t rsa
cat id_rsa.pub
cat id_rsa
ssh-copy-id -?
scp id_rsa.pub <EMAIL>:~/
ssh <EMAIL>
connected to ssh
```shell
on cislinux machine
cd .ssh
ls
cat ~/id_rsa.pub >> authorized_keys2
```
on github you can also use ssh
back to ubuntu
```shell
in ~/.ssh
nano config
Host cis
IdentityFile ~/.ssh/id_rsa
on mac
cat .ssh/config
on ubuntu
ssh cis
## Create Droplet
```
```shell
cat ~/.ssh/id_rsa.pub | ssh root@[your.ip.address.here] "cat >> ~/.ssh/authorized_keys"
ssh root@ip-address
#ssh frontend
netstat -peanut #show the ports
nano /etc/ssh/sshd_config #change ports of ssh
sudo ufw status #firewall
```
```shell
## Configuration
on front end
sudo nano /etc/ssh/sshd_config
# change premitrootlogin to yes
# change port to 22123
# scp -P 22123 id_rsa.pub root@192.168.3.11:~/
adduser cis527
# root privileges
usermod -aG sudo cis527
# copy public key
sudo ufw allow 22123
ssh-copy-id -p 22123 cis527@172.16.17.32
```
##### database
using your computer to generate and install the public key to front end
manual method
##### on your computer
```shell
ssh-add
ssh-copy-id -p 22123 cis527@...ip
cat ~/.ssh/id_rsa.pub
```
on front end, log in as root
```shell
su - cis527
mkdir ~/.ssh
chmod 700 ~/.ssh
nano ~/.ssh/authorized_keys
# copy your id_rsa.pub
chmod 600 ~/.ssh/authorized_keys
```
same for front end to back end
"connection to agent" problem
?every time
eval "$(ssh-agent)"
```shell
ssh-add
sudo systemctl reload sshd
Disable the Root Login via SSH
using root
sudo nano /etc/ssh/sshd_config
PermitRootLogin no
```
##### alias ssh backend
```shell
# contents of ~/.ssh/config
Host backend
HostName 192.168.3.11
Port 22123
User cis527
# private key only
ssh -i ~/.ssh/id_rsa -p 22123 <EMAIL>
```
---
##### configure firewall
```shell
sudo ufw default deny incoming
sudo ufw allow ssh
sudo ufw allow 22123
sudo ufw allow 80/http
sudo ufw allow 443/https
# lastly
~ only on backend
sudo ufw allow from 192.168.3.11 to any port 22123
sudo ufw enable
(or disable)
```
---
#### timezone
``` shell
sudo dpkg-reconfigure tzdata
```
#### ntp service
```shell
sudo apt-get update
sudo apt-get install ntp
```
---
#### mysql -server
on backend
``` shell
sudo apt-get update
sudo apt-get install mysql-server
no need to 'sudo mysql+secure+installation'
//mysqld --initialize
//delete the directory /var/lib/mysql and re-initialize the database
sudo apt-get purge mysql-server
mkdir -p /var/lib/mysql
Note: If you want to change the default dir above for mysql data storage, then you need to add the new dir in the apparmor config as well in order to use.
```
~~tar -zcvf /msql_backup.tar.gz /etc/mysql /var/lib/mysql
sudo apt purge mysql-server mysql-client mysql-common mysql-server-core-5.7 mysql-client-core-5.7
sudo rm -rfv /etc/mysql /var/lib/mysql
sudo apt autoremove
sudo apt autoclean~~
~~sudo apt update
sudo apt install mysql-server mysql-client --fix-broken --fix-missing~~
---
something wrong here
```shell
sudo mysql_install_db
sudo nano /etc/mysql/my.conf
cd /etc/mysql/mysql.conf.d/mysqld.cnf
bind-address = (backend private IP address) from (127.0.0.1)
sudo systemctl restart mysql
netstat -peanut
check the new ip address
mysql -u root -p
enter database root password
```
```mysql
CREATE DATABASE wordpress;
CREATE USER 'wordpressuser'@'localhost' IDENTIFIED BY 'password'
//which is password
GRANT ALL PRIVILEGES ON wordpress.
CREATEUSER 'wordpressuser'@'frontend private ip address' IDENTIFIED BY '<PASSWORD>'
GRANT ALL PRIVILEGES ON wordpress.* TO 'wordpressuser'@'frontend private ip address'
FLUSH PRIVILEGES;
exit
mysql -u wordpressuser -p
```
```shell
sudo ufw status
sudo ufw allow from private front end...to any port 3306
on front end
sudo apt-get install mysql-client
mysql -u wordpressuser -h private backend -p
sudo apt-get install apache2 php php7.0-fpm php7.0-mysql
enter front end public ip
sudo ufw allow 80
sudo ufw status
cd /var/www/html/
sudo nano test.php
```
##### phpmyadmin
```php
<?php
phpinfo()
?>
```
```shell
sudo apt-get install libapache2-mod-php7.0
frontend -ip /test.php
wget http://wordpress.org/latest.tar.gz
tar -zxvf latest.tar.gz
cd wordpress/
ls
sudo rm /var/www/html/index.html
cd ..
sudo rmdir /var/www/html
sudo mv worpress /var/www/html
cd /var/www/html
ls
sudo cp wp-config-sample.php wp-config.php
sudo nano wp-config.php
database -> wordpress
username -> wordpressuser
password
hostname backend - private
```
---
Blog
```shell
username -> yisiqiu
email:<EMAIL>
ls -al
/var/www$ sudo chown -R www-data:www-data html
```
---
##### SSL
```shell
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/apache-selfsigned.key -out /etc/ssl/certs/apache-selfsigned.crt
common name http://192.168.3.11/ public front end
sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
sudo nano /etc/apache2/conf-available/ssl-params.conf
sudo cp /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-available/default-ssl.conf.bak
sudo nano /etc/apache2/sites-available/default-ssl.conf
sudo nano /etc/apache2/sites-available/000-default.conf
sudo ufw allow 'Apache Full'
sudo ufw delete allow 'Apache'
```
---
#### ZNC
```shell
sudo apt-get install build-essential libssl-dev libperl-dev pkg-config
cd /usr/local/src...
sudo wget...
sudo tar -xzvf
./configure
sudo make
sudo make install
adduser znc-admin
su znc-admin
cd ~
sudo ufw allow from 192.168.3.11 to any port 5000
```
no need for SSL
http://<droplet_ip>:<specified_port>
/server <znc_server_ip> 5000 yisiqiu:<pass>
<file_sep>/lab6-notes.md
### Lab 6 notes
RAID 0 faster
RAID 1 security
more drives
RAID 5 pair can construct data (4 disks)
RAID 6 (5 disks)
smaller one, less latency
#### apache
```shell
cd /etc/apache2/
cat apache2.conf
cat magic
cat ports.conf
cd mods-available/
cd mods-enabled/
nano dir.conf
cd conf-available/
cd sites-available/
a2ensite 000-default
a2dissite 000-default
apache
nano flowchart.conf
nano blockly.conf
ping flowchart.rs.me
ping blockly.rs.me
same ip address
ssh cis
cd public-html/secure
ls -al
cat .htaccess
```
on ubuntu
install phpmyadmin
apache2 hit 'space' to show the 'x'
set up samba
make new folder(share) in computer
check share this folder
sudo mkdir /share in /etc/samba
allow others share
on server sudo smbpasswd -a cis527
on client
connect to server smb://ip.../share
then log in as registered user
sudo apt-get install cifs-utils
```shell
apache2ctl
sudo a2dissite 000-default.conf
```
```shell
cis527@CIS527U-yisiqiu:~$ sudo nano /etc/hosts
[sudo] password for <PASSWORD>:
>>>>>>> update lab6
cis527@CIS527U-yisiqiu:~$ sudo ufw allow from 192.168.42.130
Rule added
cis527@CIS527U-yisiqiu:~$ sudo smbpasswd -a cis527
New SMB password:
Retype new SMB password:
Added user cis527.
cis527@CIS527U-yisiqiu:~$ sudo smbpasswd -e cis527
Enabled user cis527.
cis527@CIS527U-yisiqiu:~$
=======
cis527@CIS527U-yisiqiu:~$
```
```shell
cis527@CIS527U-yisiqiu:~$ sudo chmod 777 /media/share
cis527@CIS527U-yisiqiu:~$ cd
cis527@CIS527U-yisiqiu:~$ cd /media/share
cis527@CIS527U-yisiqiu:/media/share$ ls
cis527@CIS527U-yisiqiu:/media/share$ cd
cis527@CIS527U-yisiqiu:~$ sudo nano /etc/fstab
cis527@CIS527U-yisiqiu:~$ sudo mount -a
cis527@CIS527U-yisiqiu:~$ sudo nano ~/.smbcredentials
cis527@CIS527U-yisiqiu:~$ sudo chmod 600 ~/.smbcredentials
cis527@CIS527U-yisiqiu:~$ sudo nano /etc/fstab
cis527@CIS527U-yisiqiu:~$ sudo mount -a
sudo apt-get install tasksel
=======
cis527@CIS527U-yisiqiu:~$ sudo nano /etc/fstab
cis527@CIS527U-yisiqiu:~$ sudo mount -a
cis527@CIS527U-yisiqiu:~$ sudo nano ~/.smbcredentials
cis527@CIS527U-yisiqiu:~$ sudo chmod 600 ~/.smbcredentials
cis527@CIS527U-yisiqiu:~$ sudo nano /etc/fstab
cis527@CIS527U-yisiqiu:~$ sudo mount -a
sudo apt-get install tasksel
>>>>>>> update lab6
sudo tasksel install lamp-server
/etc/apache2/sites-available$ sudo nano 000-default.conf
NameVirtualHost *:80
<VirtualHost *:80>
ServerName www.example.com
Redirect permanent / https://secure.example.com/
</VirtualHost>
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M
; Must be greater than or equal to upload_max_filesize
post_max_size = 40M
sudo apt-get install phpmyadmin
```
login as root and password
create new user and (As database)
<file_sep>/README.md
## cis527-administration
### Labs and Notes for enterprise system administration
======
#### Lab1 Secure Workstation
Basic installation and configuration about Ubuntu 16.04 and Windows 10 on VMWare Fusion
1. Create users and groups for both OS
2. Install softwares on Windows 10
..1. [IIS Web Server](http://www.howtogeek.com/112455/how-to-install-iis-8-on-windows-8/)
..2. [BGInfo] (http://technet.microsoft.com/en-us/sysinternals/bb897557.aspx)
3. Files and Permissions
```shell
Get-Childitem -Recurse | Get-Acl | Format-List
```
4. Ubuntu 16.04 and VMWare Tools
5. Ubuntu softwares
..* Mozilla Firefox (firefox)
..* Mozilla Thunderbird (thunderbird)
..* Apache Web Server (apache2)
..* Synaptic Package Manager (synaptic)
..* GUFW Firewall Management Utility (gufw)
..* Conky (conky)
6. File and Permission
```shell
ls -lR
```
#### Lab2 Configuration Management with Puppet
using puppet to Configure Ubuntu and Windows
#### Lab3 Core Networking Service
1. set up a remote connecetion
..* windows, using Remmina on Linux to test
..* ubuntu SSH, using PUTTY on Windows to test
2. set static IP address
3. set up a DNS server
using bind9 on Linux server
4. set up DHCP server
install isc-dhcp-server
5. Install an SNMP Daemon
6. install Wireshark to capture packets
..* A DNS standard query
..* A DNS standard query response
..* An ICMP Echo (ping) request
..* An SNMP get-next-request packet for an item within the ICMP MIB section
..* An SNMP get-response packet for an item within the ICMP MIB section
..* An HTTP 301 Moved Permanently Redirect response
..* An HTTP Basic Authentication Request
to set a Ubuntu client and a Ubuntu server as well as Windows.
Lab includes RDP,SSH for remote control. And setting up DNS server on Ubuntu and DHCP (which is frustrating :) Finally,
we use SNMP to grep loads of information. And using Wireshark to capture packets based on different protocols
#### Lab4 Directory Service
1. Configure your Windows Server as an Active Directory Domain Controller
2. Add a Windows 10 VM to your new Domain
3. Set up an OpenLDAP server for Linux
4. Configure an Ubuntu VM to Authenticate using your OpenLDAP server
5. Query your Active Directory and LDAP servers using LDAPSearch
```shell
ldapsearch -LLL -H ldap://<AD_IP_address>:389 -b "dc=cis527<your_eID>,dc=local" -D "cis527<your_eID>\Administrator" -w "cis527_windows"
ldapsearch -LLL -H ldap://<OpenLDAP_IP_address>:389 -b "dc=cis527<your_eID>,dc=local" -D "cn=admin,dc=cis527<your_eID>,dc=local" -w "cis527_linux"
```
#### Lab5 Cloud
1. create two droplets
2. Configure virtual servers
3. Configure the Firewall, Timezones & NTP
4. Set up Wordpress
5. Set up SSL Certificates
6. Install & Configure ZNC
#### Lab6 Application and File Server
1. File server, application server and mapping drive for Windows and Linux
2. virtual hosts for Apache
<file_sep>/lab3-networking/core-networking.sh
# remote connection remmina - ssh
# static ip address
# graphical
ens33=ens33
lo=lo
cis527@CIS527U-yisiqiu:~$ cat /etc/network/interfaces
# interfaces(5) file used by ifup(8) and ifdown(8)
auto ens33
iface ens33 inet static
address 192.168.42.41
netmask 255.255.255.0
gateway 192.168.42.2
dns-nameservers 192.168.42.2
auto lo
iface lo inet loopback
cis527@CIS527U-yisiqiu:~$ cat /etc/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
# DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 192.168.42.41
# dont remeber to set your Windows DNS server as given IP address above
cis527@CIS527U-yisiqiu:~$ cat /etc/hostname
CIS527U-yisiqiu
cis527@CIS527U-yisiqiu:~$ cat /etc/hosts
127.0.0.1 localhost
192.168.42.41 ns.cis527.cs.ksu.edu CIS527U-yisiqiu
192.168.42.42 win.cis527.cs.ksu.edu CIS527U-yisiqiu
192.168.42.41 cis527.cs.ksu.edu CIS527U-yisiqiu
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fc00:db20:35b:7399::5 ip6-localnet
fc00:db20:35b:7399::5 ip6-mcastprefix
fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b ip6-allnodes
fc00:db20:35b:7399::5 ip6-allrouters
sudo apt-get install bind9 bind9utils bind9-doc
cis527@CIS527U-yisiqiu:~$ cat /etc/bind/named.conf.options
acl "trusted" {
192.168.42.0/24;
localhost;
localnets;
};
options {
directory "/var/cache/bind";
recursion yes;
allow-recursion { trusted; };
listen-on { 192.168.42.41; };
// If there is a firewall between you and nameservers you want
// to talk to, you may need to fix the firewall to allow multiple
// ports to talk. See http://www.kb.cert.org/vuls/id/800113
// If your ISP provided one or more IP addresses for stable
// nameservers, you probably want to use them as forwarders.
// Uncomment the following block, and insert the addresses replacing
// the all-0's placeholder.
forwarders {
192.168.42.2;
};
//========================================================================
// If BIND logs error messages about the root key being expired,
// you will need to update your keys. See https://www.isc.org/bind-keys
//========================================================================
dnssec-validation auto;
auth-nxdomain no; # conform to RFC1035
listen-on-v6 { any; };
};
cis527@CIS527U-yisiqiu:~$ cat /etc/bind/named.conf.local
//
// Do any local configuration here
//
zone "cis527.cs.ksu.edu" {
type master;
file "/etc/bind/zones/db.cis527.cs.ksu.edu";
};
zone "42.168.192.in-addr.arpa" {
type master;
notify no;
file "/etc/bind/zones/db.192.168.42";
};
// Consider adding the 1918 zones here, if they are not used in your
// organization
//include "/etc/bind/zones.rfc1918";
cis527@CIS527U-yisiqiu:~$ cat /etc/bind/zones/db.cis527.cs.ksu.edu
;
; BIND data file for local loopback interface
;
$ORIGIN cis527.cs.ksu.edu.
$TTL 604800
@ IN SOA ns.cis527.cs.ksu.edu. root.cis527.cs.ksu.edu. (
15 ; Serial
604800 ; Refresh
86400 ; Retry
2419200 ; Expire
604800 ) ; Negative Cache TTL
;
; name servers - NS records
@ IN NS ns.cis527.cs.ksu.edu.
; name servers - A records
ns IN A 192.168.42.41
; hosts - A records
win IN A 192.168.42.42
cis527@CIS527U-yisiqiu:~$ cat /etc/bind/zones/db.192.168.42
;
; BIND reverse data file for local loopback interface
;
$ORIGIN 42.168.192.in-addr.arpa.
$TTL 604800
@ IN SOA ns.cis527.cs.ksu.edu. root.cis527.cs.ksu.edu. (
12 ; Serial
604800 ; Refresh
86400 ; Retry
2419200 ; Expire
604800 ) ; Negative Cache TTL
;
@ IN NS ns.
41 IN PTR ns.cis527.cs.ksu.edu.
42 IN PTR win.cis527.cs.ksu.edu.
# increment serial everytime restart
# sudo /etc/init.d/bind9 restart
# named-checkzone cis527.cs.ksu.edu db.cis527
# nslookup
# dig -x 127.0.0.1
# ping
sudo apt-get install isc-dhcp-server
nano -w /etc/dhcp/dhcpd.conf
# Sample /etc/dhcpd.conf
default-lease-time 600;
max-lease-time 7200;
option subnet-mask 255.255.255.0;
option broadcast-address 192.168.42.255;
option routers 192.168.42.2;
option domain-name-servers "cis527.cs.ksu.edu";
option domain-name 192.168.42.2;
subnet 192.168.42.0 netmask 255.255.255.0 {
range 192.168.1.100 192.168.1.250;
}
# turn off dhcp server on VM
# difference should be localadmin and cis527
sudo service isc-dhcp-server restart
sudo service isc-dhcp-server start
sudo service isc-dhcp-server stop
sudo apt-get install snmpd
sudo apt-get install snmp snmp-mibs-downloader
# mibs
# in /etc/snmp/snmpd.conf
rocommunity public
/etc/init.d/snmpd restart
snmpwalk -c public -v1 localhost | grep icmp
# ping
sudo apt-get install wireshark
# wireshark
# sudo wireshark
sudo dpkg-reconfigure wireshark cis527
sudo usermod -a -G wireshark cis527
logout login
wireshark
snmpwalk -c public -v1 localhost # IP-MIB:
sudo dhclient -r ens33
# back to dhcp
<file_sep>/lab7-backup.md
#### account in active directory
(1) run gpmc.msc (Group Policy Management)
(2) Expand your Domain
(3) Expand <Group Policy Objects> and right-click <default domain controllers policy>. Click Edit.
(4) Expand: <Computer Configurations> <Policies> <Windows Settings> <Security Settings> <Local Policies> <User Rights Assignment>
(5) Right click <Allow log on locally> and click Properties. Amend as required.
(6) Run gpupdate and wait for confirmation: "user policy update has completed succesfully" (default gpudate without switches should only apply the changes)
(7) Log out and log back in as domain user
#### new disk
In the Start menu, type diskmgmt.msc and click OK.
Right-click the disk to be initialized and then click Initialize Disk. Windows prompts you to initialize the disk before Logical Disk Manager can access it.
Select MBR (Master Boot Record) and click OK.
Right-click the unallocated space and click New Simple Volume.
Enter the size of the partition (in MB) and click Next.
Select a drive letter and click Next.
Select the file system type and volume name.
Click Finish. Windows prompts you to format the drive.
Click Format.
```
WBADMIN ENABLE BACKUP -addtarget:{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
C:\> wbadmin start backup -backuptarget:E: -allcritical -systemstate -vssfull -quiet
```
bcdedit /set safeboot dsrepair
restart-computer
to return to a normal boot, once the restore operation is complete, we enter this command:
```
bcdedit /deletevalue safeboot
##### to log in safe mode
.\Administrator
wbadmin get versions -backuptarget:E: -machine:
wbadmin start systemstaterecovery -version:01/01/2014-2:36 -backuptarget:E: -machine:
##### authoritive
C:\Users\admin>ntdsutil
ntdsutil: activate instance ntds
Active Instance set to "NTDS".
ntdsutil: authoritative restore
authoritative restore: restore object "cn=Alan Reid,ou=ExchangeUsers,dc=mynet,dc=lan"
#linux
#ganglia
udp_recv_channel {
#mcast_join = 172.16.17.32 ## comment out
port = 8649
#bind = 172.16.17.32 ## comment out
}
/* You can specify as many tcp_accept_channels as you like to share
an xml description of the state of the cluster */
tcp_accept_channel {
port = 8649
}
sudo vi /etc/ganglia/gmond.conf
cluster {
name = "my cluster" ## Cluster name
owner = "unspecified"
latlong = "unspecified"
url = "unspecified"
udp_send_channel {
#mcast_join = 172.16.17.32 ## Comment
host = 1.1.1.1 ## IP address of master node
port = 8649
ttl = 1
}
<file_sep>/Lab4-notes.md
###### on windows 2012 server
IP address 192.168.42.42, subnet 255.255.255.0, gateway 192.168.42.2
DNS 192.168.42.42 192.168.42.41
Advanced: /42, /41,/2 suffix cis527.cs.ksu.edu
manage: select a server yisiqiu.... active domain service + group policy management
#### win10 client
/42, /41,/2 suffix cis527.cs.ksu.edu
netbios deplopyment
change domain name cis527yisiqiu.local can seen from win server computers ( properties-> managed by users/yisiqiu)
original domain other user .\AdminUser
win server
active directory users and computers
users new objject password never expired
| 63ac4923a442734fd4a702d944ab59f60f38a417 | [
"Markdown",
"Shell"
] | 6 | Markdown | yzziqiu/cis527-administration | a4fe94f3d3f5fd8bd2b108d55a3a88886f9be0f6 | fd3a89f0cc20fa3b8969e85d2c1c22ccf260486f |
refs/heads/master | <file_sep># WillowCreekReclamation
Project related to monitoring the water quality along Willow Creek, Mineral County, Colorado
<file_sep>/* Raw_RTC_SD_5v.ino
Data logger with real time clock (RTC) board and 5V microSD card board.
Logs temperature data from the sensor on the RTC to the microSD card.
Displays these data on the serial monitor in real time.
Interval between data write events defaults to 1 min
Sleeps some things between read/write events.
Modified from Ed Mallon's Cave Pearl Logger sketch.
<NAME>, September 2017
<NAME>, April 2018
*/
#include <SdFat.h> // https://github.com/greiman/SdFat/
#include <SPI.h>
#include <Wire.h>
#include "LowPower.h" // https://github.com/rocketscream/Low-Power
#include <RTClib.h> // https://github.com/MrAlvin/RTClib
RTC_DS3231 RTC; // RTC will be the RTC_DS3231 object
#define DS3231_I2C_ADDRESS 0x68 // RTC address
SdFat SD; // SD will be the SdFat object
const int chipSelect = 8; // for SD card
const int cardDetect = 9;
#define MOSIpin 11 // for SD card
#define MISOpin 12 // for SD card
#define TurbidityPin A0
char TmeStrng[] = "0000/00/00,00:00:00"; // string template for RTC time stamp
int RTC_INTERRUPT_PIN = 2;
byte Alarmhour;
byte Alarmminute;
byte Alarmday;
char CycleTimeStamp[ ] = "0000/00/00,00:00:00"; // template for a data/time string
#define SampleIntervalMinutes 15 // change the logging interval here
volatile boolean clockInterrupt = true; //this flag is set to true when the RTC interrupt handler is executed
float temp3231; //variables for reading the DS3231 RTC temperature register
byte tMSB = 0;
byte tLSB = 0;
char fileName[] = "Turbidity.txt"; // SD library only supports up to 8.3 names
bool alreadyBegan = false;
void setup() {
// Setting the SPI pins high helps some sd cards go into sleep mode
// the following pullup resistors only need to be enabled for the stand alone logger builds - not the UNO loggers
pinMode(chipSelect, OUTPUT); digitalWrite(chipSelect, HIGH); //Always pullup the CS pin with the SD library
//and you may need to pullup MOSI/MISO
pinMode(MOSIpin, OUTPUT); digitalWrite(MOSIpin, HIGH); //pullup the MOSI pin
pinMode(MISOpin, INPUT); digitalWrite(MISOpin, HIGH); //pullup the MISO pin
delay(100);
Serial.begin(9600);
initializeCard();
Wire.begin(); // initialize the I2C interface
RTC.begin(); // initialize the RTC
// Uncomment the line below and load the sketch to the Pro Mini to set the RTC time. Then the line must
// be commented out and the sketch loaded again or the time will be wrong.
//RTC.adjust(DateTime((__DATE__), (__TIME__))); // sets the RTC to the time the sketch was compiled.
// print a header to the data file:
File dataFile = SD.open(fileName, FILE_WRITE);
if (dataFile) { // if the file is available, write a header to it:
dataFile.println("Date, Time, UTC time, RTC temp C, voltage V, Turbidity NTU");
dataFile.close();
}
else {
Serial.println("Cannot save to SD"); // if the file is not open, display an error:
}
} // end of setup
void loop() {
DateTime now = RTC.now(); // read the time from the RTC, then construct two data strings:
sprintf(TmeStrng, "%04d/%02d/%02d,%02d:%02d:%02d", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second());
sprintf(CycleTimeStamp, "%04d/%02d/%02d,%02d:%02d:%02d", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second());
Serial.println();
Serial.print("RTC time: ");
Serial.println(TmeStrng);
Serial.print("RTC UTC time: ");
Serial.println(now.unixtime());
if (clockInterrupt)
{
if (RTC.checkIfAlarm(1))
{ // Is the RTC alarm still on?
RTC.turnOffAlarm(1); // then turn it off.
}
// print (optional) debugging message to the serial window if you wish
Serial.print("Alarm triggered at ");
Serial.println(CycleTimeStamp);
clockInterrupt = false; // reset the interrupt flag to false
}
// read the RTC temp register and print that out
// Note: the DS3231 temp registers (11h-12h) are only updated every 64seconds
Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0x11); // the register where the temp data is stored
Wire.endTransmission();
Wire.requestFrom(DS3231_I2C_ADDRESS, 2); //ask for two bytes of data
if (Wire.available()) {
tMSB = Wire.read(); // 2's complement int portion
tLSB = Wire.read(); // fraction portion
temp3231 = ((((short)tMSB << 8) | (short)tLSB) >> 6) / 4.0; // Allows for readings below freezing: thanks to Coding Badly
}
else {
temp3231 = 0; //if temp3231 contains zero, then you know you had a problem reading the data from the RTC!
}
// Turbidity Sensor
// getTurbidity();
int sensorValue = analogRead(TurbidityPin);// read the input on analog pin 0:
float voltage = sensorValue * (5.0 / 1024.0); // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float turbidity = -1120.4 * voltage * voltage + 5742.3 * voltage - 4352.9;
// Pure water= NTU < 0.5, output should be “4.1±0.3V” when temperature is 10~50℃.
//
Serial.print("T-voltage: ");
Serial.print(voltage); // print out the value you read:
Serial.println(" V");
Serial.print("Turbidity: ");
Serial.print(turbidity);
Serial.println(" NTU ");
delay(500);
Serial.print("RTC temp: ");
Serial.print(temp3231);
Serial.println(" C");
float utc = (now.unixtime());
// write the data to the SD card:
File dataFile = SD.open(fileName, FILE_WRITE); // if the file is available, write to it:
if (dataFile) { //dgr
dataFile.println() ;
dataFile.print(TmeStrng); dataFile.print(","); dataFile.print(utc); dataFile.print(","); dataFile.print(temp3231);
dataFile.print(","); dataFile.print(voltage);dataFile.print(","); dataFile.print(turbidity);
dataFile.close();
}
else {
Serial.println("Cannot save to SD card"); // if the file is not open, display an error
}
// Set the next alarm time
Alarmhour = now.hour();
Alarmminute = now.minute() + SampleIntervalMinutes;
Alarmday = now.day();
// check for roll-overs
if (Alarmminute > 59) { // error catching the 60 rollover!
Alarmminute = 0;
Alarmhour = Alarmhour + 1;
if (Alarmhour > 23) {
Alarmhour = 0;
}
}
RTC.setAlarm1Simple(Alarmhour, Alarmminute); // set the alarm
RTC.turnOnAlarm(1);
if (RTC.checkAlarmEnabled(1)) {
delay(300);
// sleep and wait for next RTC alarm
attachInterrupt(0, rtcISR, LOW); // Enable interrupt on pin2 & attach it to rtcISR function:
LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_ON); // Enter power down state with ADC module disabled to save power
// processor starts HERE AFTER THE RTC ALARM WAKES IT UP
detachInterrupt(0); // immediately disable the interrupt on waking
}
} // end of the MAIN LOOP
void rtcISR() { // This is the Interrupt subroutine that executes when the rtc alarm goes off
clockInterrupt = true;
}
void initializeCard(void)
{
Serial.print(F("Initializing SD card..."));
// Is there even a card?
if (!digitalRead(cardDetect))
{
Serial.println(F("No card detected. Waiting for card."));
while (!digitalRead(cardDetect));
delay(250); // 'Debounce insertion'
}
// Card seems to exist. begin() returns failure
// even if it worked if it's not the first call.
if (!SD.begin(chipSelect) && !alreadyBegan) // begin uses half-speed...
{
Serial.println(F("Initialization failed!"));
initializeCard(); // Possible infinite retry loop is as valid as anything
}
else
{
alreadyBegan = true;
}
Serial.println(F("Initialization done."));
Serial.print(fileName);
if (SD.exists(fileName))
{
Serial.println(F(" exists."));
}
else
{
Serial.println(F(" doesn't exist. Creating."));
}
Serial.print("Opening file: ");
Serial.println(fileName);
}
/*
void getTurbidity()//
{
Turbidityval = analogRead(A0) / 1024.0 * 5.0;
Serial.print(" Trubidity value: ");
Serial.println( Turbidityval);//
lcd.setCursor(0,0);
lcd.print("Turbidity:");
lcd.setCursor(12,0);
lcd.println(Turbidityval);
} */
<file_sep>/* Nini_RTCtemp03.ino
For the Mini Pearl Logger with real time clock (RTC) board and microSD card board.
Logs temperature data from the sensor on the RTC to the microSD card.
-- also logs temperature from a DS18S20 temperature probe
-- also logs TDS from DFRobot TDS probe.
Displays these data on the serial monitor in real time.
Interval between data write events is one minute (change this near line 29: #define SampleIntervalMinutes 1)
Sleeps some things between read/write events.
Modified from Ed Mallon's Cave Pearl Logger sketch.
Modified from <NAME>, September 2017
<NAME>, 2018-3-21
*/
#include <SdFat.h> // https://github.com/greiman/SdFat/
#include <SPI.h>
#include <Wire.h>
#include <OneWire.h>
#include <EEPROM.h>
#include "GravityTDS.h"
#define TdsSensorPin A1
#define VREF 3.3 // analog reference voltage(Volt) of the ADC Arduino Pro-Mini
#define SCOUNT 10 // sum of sample point - was 30
int analogBuffer[SCOUNT]; // store the analog value in the array, read from ADC
int analogBufferTemp[SCOUNT];
int analogBufferIndex = 0, copyIndex = 0;
float averageVoltage = 0, tdsValue = 0;
int DS18S20_Pin = 6; //DS18S20 Signal pin on digital 6
//Temperature chip i/o
OneWire ds(DS18S20_Pin); // on digital pin 6
#include "LowPower.h" // https://github.com/rocketscream/Low-Power
#include <RTClib.h> // https://github.com/MrAlvin/RTClib
RTC_DS3231 RTC; // RTC will be the RTC_DS3231 object
#define DS3231_I2C_ADDRESS 0x68 // RTC address
SdFat SD; // SD will be the SdFat object
const int chipSelect = 10; // for SD card
#define MOSIpin 11 // for SD card
#define MISOpin 12 // for SD card
char TmeStrng[] = "0000/00/00,00:00:00"; // string template for RTC time stamp
int RTC_INTERRUPT_PIN = 2;
byte Alarmhour;
byte Alarmminute;
byte Alarmday;
char CycleTimeStamp[ ] = "0000/00/00,00:00:00"; // template for a data/time string
#define SampleIntervalMinutes 15 // change the logging interval here
volatile boolean clockInterrupt = true; //this flag is set to true when the RTC interrupt handler is executed
float temp3231; //variables for reading the DS3231 RTC temperature register
byte tMSB = 0;
byte tLSB = 0;
void setup() {
// Setting the SPI pins high helps some sd cards go into sleep mode
// the following pullup resistors only need to be enabled for the stand alone logger builds - not the UNO loggers
pinMode(chipSelect, OUTPUT); digitalWrite(chipSelect, HIGH); //Always pullup the CS pin with the SD library
//and you may need to pullup MOSI/MISO
pinMode(MOSIpin, OUTPUT); digitalWrite(MOSIpin, HIGH); //pullup the MOSI pin
pinMode(MISOpin, INPUT); digitalWrite(MISOpin, HIGH); //pullup the MISO pin
pinMode(TdsSensorPin, INPUT);
Serial.begin(9600); // Open serial communications
Wire.begin(); // initialize the I2C interface
RTC.begin(); // initialize the RTC
if (!SD.begin(chipSelect)) { // initialize the SD card and display its status:
Serial.println("Cannot find SD card");
// return;
}
else
{
Serial.println("SD OK");
}
// Uncomment the line below and load the sketch to the Pro Mini to set the RTC time. Then the line must
// be commented out and the sketch loaded again or the time will be wrong.
//RTC.adjust(DateTime((__DATE__), (__TIME__))); // sets the RTC to the time the sketch was compiled.
// print a header to the data file:
File dataFile = SD.open("TDS_Temp.txt", FILE_WRITE);
if (dataFile) { // if the file is available, write a header to it:
dataFile.println("Date, Time, UTC time, RTC temp C, Probe temp C, Voltage V, TDS ppm");
dataFile.close();
}
else {
Serial.println("Cannot save to SD"); // if the file is not open, display an error:
}
} // end of setup
void loop() {
DateTime now = RTC.now(); // read the time from the RTC, then construct two data strings:
sprintf(TmeStrng, "%04d/%02d/%02d,%02d:%02d:%02d", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second());
sprintf(CycleTimeStamp, "%04d/%02d/%02d,%02d:%02d:%02d", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second());
Serial.print("RTC time: ");
Serial.println(TmeStrng);
Serial.print("RTC UTC time: ");
Serial.println(now.unixtime());
if (clockInterrupt)
{
if (RTC.checkIfAlarm(1))
{ // Is the RTC alarm still on?
RTC.turnOffAlarm(1); // then turn it off.
}
// print (optional) debugging message to the serial window if you wish
Serial.print("Alarm triggered at ");
Serial.println(CycleTimeStamp);
clockInterrupt = false; // reset the interrupt flag to false
}
// read the RTC temp register and print that out
// Note: the DS3231 temp registers (11h-12h) are only updated every 64seconds
Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0x11); // the register where the temp data is stored
Wire.endTransmission();
Wire.requestFrom(DS3231_I2C_ADDRESS, 2); //ask for two bytes of data
if (Wire.available()) {
tMSB = Wire.read(); // 2's complement int portion
tLSB = Wire.read(); // fraction portion
temp3231 = ((((short)tMSB << 8) | (short)tLSB) >> 6) / 4.0; // Allows for readings below freezing: thanks to Coding Badly
}
else {
temp3231 = 0; //if temp3231 contains zero, then you know you had a problem reading the data from the RTC!
}
float temperature = getTemp();
/***** TDS code ******/
/***** take a sequence of SCOUNT samples at 40 ms intervals */
// Serial.print("Sampling TDS -");
static unsigned long analogSampleTimepoint = millis();
analogBufferIndex = 0;
while (analogBufferIndex < SCOUNT) {
if (millis() - analogSampleTimepoint > 40U) //every 40 milliseconds,read the analog value from the ADC
{
analogSampleTimepoint = millis();
analogBuffer[analogBufferIndex] = analogRead(TdsSensorPin); //read the analog value and store into the buffer
analogBufferIndex++;
}
}
/** find median of the SCOUNT samples **/
for (copyIndex = 0; copyIndex < SCOUNT; copyIndex++)
analogBufferTemp[copyIndex] = analogBuffer[copyIndex];
// read the analog value more stable by the median filtering algorithm, and convert to voltage value
averageVoltage = getMedianNum(analogBufferTemp, SCOUNT) * (float)VREF / 1024.0;
//temperature compensation formula: fFinalResult(25^C) = fFinalResult(current)/(1.0+0.02*(fTP-25.0));
float compensationCoefficient = 1.0 + 0.02 * (temperature - 25.0);
//temperature compensation
float compensationVolatge = averageVoltage / compensationCoefficient;
//convert voltage value to tds value
tdsValue = (133.42 * compensationVolatge * compensationVolatge * compensationVolatge - 255.86 * compensationVolatge * compensationVolatge + 857.39 * compensationVolatge) * 0.5;
/****** TDS Code END **********/
Serial.print("RTC temp: ");
Serial.print(temp3231);
Serial.println(" C");
Serial.print("PROBE temp: ");
Serial.print(temperature);
Serial.println(" C");
Serial.print("voltage:");
Serial.print(averageVoltage, 2);
Serial.println(" V ");
Serial.print("TDS Value:");
Serial.print(tdsValue, 0);
Serial.println(" ppm");
float utc = (now.unixtime());
// write the data to the SD card:
File dataFile = SD.open("TDS_Temp.txt", FILE_WRITE); // if the file is available, write to it:
if (dataFile) {
dataFile.println() ;
dataFile.print(TmeStrng); dataFile.print(","); dataFile.print(utc); dataFile.print(", ");
dataFile.print(temp3231); dataFile.print(", "); dataFile.print(temperature); dataFile.print(", "); dataFile.print(tdsValue);
dataFile.close();
}
else {
Serial.println("Cannot save to SD card"); // if the file is not open, display an error
}
// Set the next alarm time
Alarmhour = now.hour();
Alarmminute = now.minute() + SampleIntervalMinutes;
Alarmday = now.day();
// check for roll-overs
if (Alarmminute > 59) { // error catching the 60 rollover!
Alarmminute = 0;
Alarmhour = Alarmhour + 1;
if (Alarmhour > 23) {
Alarmhour = 0;
}
}
RTC.setAlarm1Simple(Alarmhour, Alarmminute); // set the alarm
RTC.turnOnAlarm(1);
if (RTC.checkAlarmEnabled(1)) {
delay(300); // you would comment out most of the message printing below
// if your logger was actually being deployed in the field
Serial.println(); // adds a carriage return
Serial.print("Alarm set, ");
Serial.print("will sleep for: ");
Serial.print(SampleIntervalMinutes);
Serial.println(" minute");
Serial.println(); // adds a carriage return
// sleep and wait for next RTC alarm
attachInterrupt(0, rtcISR, LOW); // Enable interrupt on pin2 & attach it to rtcISR function:
LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_ON); // Enter power down state with ADC module disabled to save power
// processor starts HERE AFTER THE RTC ALARM WAKES IT UP
detachInterrupt(0); // immediately disable the interrupt on waking
}
} // end of the MAIN LOOP
void rtcISR() { // This is the Interrupt subroutine that executes when the rtc alarm goes off
clockInterrupt = true;
}
float getTemp() {
//returns the temperature from one DS18S20 in DEG Celsius
byte data[12];
byte addr[8];
if ( !ds.search(addr)) {
//no more sensors on chain, reset search
ds.reset_search();
return -1100;
}
if ( OneWire::crc8( addr, 7) != addr[7]) {
Serial.println("CRC is not valid!");
return -2000;
}
if ( addr[0] != 0x10 && addr[0] != 0x28) {
Serial.print("Device is not recognized");
return -3000;
}
ds.reset();
ds.select(addr);
ds.write(0x44, 1); // start conversion, with parasite power on at the end
byte present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad
for (int i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
}
ds.reset_search();
byte MSB = data[1];
byte LSB = data[0];
float tempRead = ((MSB << 8) | LSB); //using two's compliment
float TemperatureSum = tempRead / 16;
return TemperatureSum;
}
int getMedianNum(int bArray[], int iFilterLen)
{
int bTab[iFilterLen];
for (byte i = 0; i < iFilterLen; i++)
bTab[i] = bArray[i];
int i, j, bTemp;
for (j = 0; j < iFilterLen - 1; j++)
{
for (i = 0; i < iFilterLen - j - 1; i++)
{
if (bTab[i] > bTab[i + 1])
{
bTemp = bTab[i];
bTab[i] = bTab[i + 1];
bTab[i + 1] = bTemp;
}
}
}
if ((iFilterLen & 1) > 0)
bTemp = bTab[(iFilterLen - 1) / 2];
else
bTemp = (bTab[iFilterLen / 2] + bTab[iFilterLen / 2 - 1]) / 2;
return bTemp;
}
| 7e7c295a88e869e62b2db0a46b668c8272da680f | [
"Markdown",
"C++"
] | 3 | Markdown | GraySkull/WillowCreekReclamation | 9900f745aa8110b5d8b801f445b7c073f5a34554 | 72de1de29e997d41aeed0a8a4163e64add65eb02 |
refs/heads/master | <repo_name>Nickmcd4/Browser-Startpage<file_sep>/assets/javascript/app.js
$(document).ready(function () {
// //Acces the Unsplash API to add a random background if one hasn't already been chosen
// function GetRandomBackground() {
// var app_id = 'c1acf11890702fbd5b32c55d04125b2c4f40e585e5fdb6a170daa377030b5e96'
// var url = 'https://api.unsplash.com/photos/random?client_id=' + app_id;
// $.ajax({
// url: url,
// dataType: 'json',
// success: function (json) {
// var src = json.urls.regular;
// $('#container').css('background-image', 'url(' + src + ')');
// }
// });
// }
// GetRandomBackground();
var bgURL = "https://source.unsplash.com/collection/1047054";
$('body').css({
'background-image': 'url(' + bgURL + ')',
'background-repeat': 'no-repeat',
'background-size': 'cover'
});
$(".ppProgress").hide();
// Initialize Firebase
var config = {
apiKey: "<KEY>",
authDomain: "startpage-299f3.firebaseapp.com",
databaseURL: "https://startpage-299f3.firebaseio.com",
projectId: "startpage-299f3",
storageBucket: "startpage-299f3.appspot.com",
messagingSenderId: "358219302181"
};
firebase.initializeApp(config);
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
fileButton.addEventListener('change', function (event) {
//create a storage ref
var file = event.target.files[0];
var storageRef = firebase.storage().ref('placeholder/' + file.name);
//upload file
var task = storageRef.put(file);
task.on('state_changed',
//progress bar
function progress(snapshot) {
var percentage = (snapshot.bytesTransferred /
snapshot.totalBytes) * 100;
uploader.value = percentage;
console.log(percentage);
$(".ppProgress").show();
},
function error(err) {
},
function complete() {
alert("Your file has been uploaded!");
$(".ppProgress").hide();
var storageRef = firebase.storage().ref("placeholder/" + file.name);
storageRef.getDownloadURL().then(function (url) {
console.log(url);
$("#container").css("background-image", `url(${url})`);
localStorage.setItem("bgURL", url);
});
}
);
});
console.log("look at me" + localStorage.getItem("bgURL"));
$("#container").css("background-image", `url(${localStorage.getItem("bgURL")})`);
$("#removeTheme").on("click", function(){
localStorage.removeItem("bgURL");
location.reload(true);
})
// DISPLAYING AND HIDING SETTINGS BAR
$("#settings").on("click", function () {
if ($('#snackbar').hasClass('hiding')) {
$("#snackbar").addClass('showing');
$("#snackbar").removeClass('hiding');
} else if ($('#snackbar').hasClass('showing')) {
$("#snackbar").addClass('hiding')
$('#snackbar').removeClass('showing');
}
})
$("#close").on("click", function () {
if ($('#snackbar').hasClass('showing')) {
$("#snackbar").addClass('hiding')
$('#snackbar').removeClass('showing');
}
});
//DARK/LIGHT THEME SETTINGS
$("#darkTheme").on("click", function () {
console.log("dark");
if ($('#clockColor').hasClass('lightClock')) {
$("#clockColor").addClass('darkClock')
$('#clockColor').removeClass('lightClock');
}
if ($('#weather-block').hasClass('lightClock')) {
$("#weather-block").addClass('darkClock')
$('#weather-block').removeClass('lightClock');
}
if ($('#myBtn').hasClass('lightClock')) {
$("#myBtn").addClass('darkClock')
$("#myBtn").attr("value", 'darkClock');
$('#myBtn').removeClass('lightClock');
}
updateStorage()
})
function updateStorage() {
var clockColor = $("#myBtn").attr("value");
localStorage.setItem("clockColor", clockColor);
}
$("#lightTheme").on("click", function () {
if ($('#clockColor').hasClass('darkClock')) {
$("#clockColor").addClass('lightClock')
$('#clockColor').removeClass('darkClock');
}
if ($('#weather-block').hasClass('darkClock')) {
$("#weather-block").addClass('lightClock')
$('#weather-block').removeClass('darkClock');
}
if ($('#myBtn').hasClass('darkClock')) {
$("#myBtn").addClass('lightClock')
$('#myBtn').removeClass('darkClock');
}
updateStorage();
})
var data = localStorage.getItem("clockColor");
$("#myBtn").attr("value", data);
});
(function () {
var linkOptions = {
fetchLinks: function () {
var links = new Array;
var links_str = localStorage.getItem('link');
if (links_str != null) {
links = JSON.parse(links_str);
}
return links;
},
removeLink: function () {
var id = this.getAttribute('id');
var links = linkOptions.fetchLinks();
links.splice(id, 1);
localStorage.setItem('link', JSON.stringify(links));
linkOptions.showLinks();
return false;
},
showLinks: function () {
var links = linkOptions.fetchLinks();
var html = '<ul>';
for (var i = 0; i < links.length; i++) {
html += '<li><span class="link"><a href="' + links[i].url + '">' + links[i].label + '</a><button title="Remove" class="remove bookmarkRemove" id="' + i + '">✖</button></span></li>';
};
html += '</ul>';
document.getElementById('links').innerHTML = html;
var buttons = document.getElementsByClassName('remove');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', linkOptions.removeLink);
};
},
addLink: function () {
var linkNew = document.getElementById('urlInput').value;
var labelNew = document.getElementById('urlLabel').value;
var newLink = {
"url": linkNew,
"label": labelNew
};
var links = linkOptions.fetchLinks();
if (linkNew == "" || labelNew == "") {
return false;
} else {
links.push(newLink);
localStorage.setItem('link', JSON.stringify(links));
linkOptions.showLinks();
document.getElementById('urlInput').value = ""
document.getElementById('urlLabel').value = ""
}
}
};
document.getElementById('addUrl').addEventListener('click', linkOptions.addLink);
linkOptions.showLinks();
var toggleMenu = {
btnToggle: document.getElementById('btnToggle'),
menu: document.getElementById('panel'),
btnIcon: document.getElementById('icon'),
btnClose: document.getElementsByClassName('remove'),
btnClick: function () {
toggleMenu.btnToggle.addEventListener('click', function () {
toggleMenu.menu.classList.toggle('hide');
toggleMenu.btnToggle.classList.toggle('active');
for (i = 0; i < toggleMenu.btnClose.length; i++) {
if (toggleMenu.btnClose[i].style.display == "none") {
toggleMenu.btnClose[i].style.display = "block";
toggleMenu.btnIcon.style.opacity = "1";
} else {
toggleMenu.btnClose[i].style.display = "none";
toggleMenu.btnIcon.style.opacity = "0.7";
}
};
});
},
btnCloseVis: function () {
for (i = 0; i < toggleMenu.btnClose.length; i++) {
if (toggleMenu.btnClose[i].style.display = "block") {
toggleMenu.btnClose[i].style.display = "none";
} else {
toggleMenu.btnClose[i].style.display = "block";
}
};
}
};
toggleMenu.btnClick();
document.onload = toggleMenu.btnCloseVis();
var data = localStorage.getItem("clockColor");
$("#clockColor").attr("value", data);
})();
var modal = document.getElementById('myModal');
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function () {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function () {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
}<file_sep>/assets/javascript/api.js
$(document).ready(function () {
$.ajax({
url: "https://api.ipgeolocation.io/ipgeo?apiKey=d4c26753ab984e72adb7aae4512288cb",
success: function (geoResult) {
$('#country').text(geoResult.country_name);
$('#state').text(geoResult.state_prov);
$('#city').text(geoResult.city);
$('#time').text(geoResult.time_zone.current_time);
$('#zipcode').text(geoResult.zipcode);
$('#flag').attr("src", geoResult.country_flag);
$.ajax({
url: "https://api.openweathermap.org/data/2.5/weather?zip=" + geoResult.zipcode + "&units=imperial&appid=2eaa69456d41409f465bced69131d4e4",
success: function (weatherResult) {
var hr = (new Date()).getHours();
console.log(hr + "current hour");
$('#temp').text(Math.floor(weatherResult.main.temp) + "° F");
$('#wind-speed').text(weatherResult.wind.speed);
$('#weather-description').text(weatherResult.weather[0].description);
console.log("something is wrong" + weatherResult.weather[0].description);
//CLEAR SKIES
//night time clear skies
if (weatherResult.weather[0].description === "clear sky" && hr > 19 || hr < 6) {
$('#weather-description').text("Clear Skies");
$("#weatherIcon").html('<img src="assets/images/animated/night.svg">');
}
//day time clear skies
if (weatherResult.weather[0].description === "clear sky" && hr > 6 && hr < 19) {
$('#weather-description').text("Clear Skies");
$("#weatherIcon").html('<img src="assets/images/animated/day.svg">');
}
//I BLESS THE RAINS
//LIGHT RAIN
//NIGHT TIME
if (weatherResult.weather[0].description === "light rain" && hr > 19 || hr < 6) {
$('#weather-description').text("Light Rain");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-4.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "light rain" && hr > 6 && hr < 19) {
$('#weather-description').text("Light Rain");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-1.svg">');
}
//MODERATE RAIN
//NIGHT TIME
if (weatherResult.weather[0].description === "moderate rain" && hr > 19 || hr < 6) {
$('#weather-description').text("Moderate Rain");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-5.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "moderate rain" && hr > 6 && hr < 19) {
$('#weather-description').text("Moderate Rain");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-2.svg">');
}
//HEAVY INTENSITY RAIN
//NIGHT TIME
if (weatherResult.weather[0].description === "heavy intensity rain" && hr > 19 || hr < 6) {
$('#weather-description').text("Heavy Rain");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-5.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "heavy intensity rain" && hr > 6 && hr < 19) {
$('#weather-description').text("Heavy Rain");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-2.svg">');
}
//VERY HEAVY RAIN
//NIGHT TIME
if (weatherResult.weather[0].description === "very heavy rain" && hr > 19 || hr < 6) {
$('#weather-description').text("Very Heavy Rain");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-6.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "very heavy rain" && hr > 6 && hr < 19) {
$('#weather-description').text("Very Heavy Rain");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-3.svg">');
}
//EXTREME RAIN
if (weatherResult.weather[0].description === "extreme rain") {
$('#weather-description').text("Extreme Rain");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-6.svg">');
}
//FREEZING RAIN
if (weatherResult.weather[0].description === "freezing rain") {
$('#weather-description').text("Freezing Rain");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-7.svg">');
}
//LIGHT INTENSITY SHOWER RAIN
//NIGHT TIME
if (weatherResult.weather[0].description === "light intensity shower rain" && hr > 19 || hr < 6) {
$('#weather-description').text("Light Showers");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-4.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "light intensity shower rain" && hr > 6 && hr < 19) {
$('#weather-description').text("Light Showers");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-1.svg">');
}
//SHOWER RAIN
//NIGHT TIME
if (weatherResult.weather[0].description === "shower rain" && hr > 19 || hr < 6) {
$('#weather-description').text("Showers");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-5.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "shower rain" && hr > 6 && hr < 19) {
$('#weather-description').text("Showers");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-2.svg">');
}
//HEAVY INTENSITY SHOWER RAIN
//NIGHT TIME
if (weatherResult.weather[0].description === "heavy intensity shower rain" && hr > 19 || hr < 6) {
$('#weather-description').text("Heavy Showers");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-6.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "heavy intensity shower rain" && hr > 6 && hr < 19) {
$('#weather-description').text("Heavy Showers");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-3.svg">');
}
//NIGHT TIME
if (weatherResult.weather[0].description === "heavy shower rain and drizzle" && hr > 19 || hr < 6) {
$('#weather-description').text("Heavy Showers");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-6.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "heavy shower rain and drizle" && hr > 6 && hr < 19) {
$('#weather-description').text("Heavy Showers");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-3.svg">');
}
//NIGHT TIME
if (weatherResult.weather[0].description === "heavy intensity shower rain" && hr > 19 || hr < 6) {
$('#weather-description').text("Heavy Showers");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-6.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "heavy intensity shower rain" && hr > 6 && hr < 19) {
$('#weather-description').text("Heavy Showers");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-3.svg">');
}
//NIGHT TIME
if (weatherResult.weather[0].description === "shower drizzle" && hr > 19 || hr < 6) {
$('#weather-description').text("Heavy Showers");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-6.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "shower drizzle" && hr > 6 && hr < 19) {
$('#weather-description').text("Heavy Showers");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-3.svg">');
}
//RAGGED SHOWER RAIN
//NIGHT TIME
if (weatherResult.weather[0].description === "ragged shower rain" && hr > 19 || hr < 6) {
$('#weather-description').text("Ragged Showers");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-6.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "ragged shower rain" && hr > 6 && hr < 19) {
$('#weather-description').text("Ragged Showers");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-3.svg">');
}
//BEGIN THE DRIZZLES
//LIGHT INTENSITY DRIZZLE
//NIGHT TIME
if (weatherResult.weather[0].description === "light intensity drizzle" && hr > 19 || hr < 6) {
$('#weather-description').text("Light Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-4.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "light intensity drizzle" && hr > 6 && hr < 19) {
$('#weather-description').text("Light Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-1.svg">');
}
//LIGHT INTENSITY DRIZZLE RAIN
//NIGHT TIME
if (weatherResult.weather[0].description === "light intensity drizzle rain" && hr > 19 || hr < 6) {
$('#weather-description').text("Light Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-4.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "light intensity drizzle rain" && hr > 6 && hr < 19) {
$('#weather-description').text("Light Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-1.svg">');
}
//DRIZZLE
//NIGHT TIME
if (weatherResult.weather[0].description === "drizzle" && hr > 19 || hr < 6) {
$('#weather-description').text("Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-5.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "drizzle" && hr > 6 && hr < 19) {
$('#weather-description').text("Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-2.svg">');
}
//NIGHT TIME
if (weatherResult.weather[0].description === "drizzle rain" && hr > 19 || hr < 6) {
$('#weather-description').text("Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-5.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "drizzle rain" && hr > 6 && hr < 19) {
$('#weather-description').text("Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-2.svg">');
}
//HEAVY DRIZZLE
//NIGHT TIME
if (weatherResult.weather[0].description === "heavy intensity drizzle rain" && hr > 19 || hr < 6) {
$('#weather-description').text("Heavy Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-6.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "heavy intensity drizzle rain" && hr > 6 && hr < 19) {
$('#weather-description').text("Heavy Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-3.svg">');
}
//NIGHT TIME
if (weatherResult.weather[0].description === "heavy intensity drizzle" && hr > 19 || hr < 6) {
$('#weather-description').text("Heavy Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-6.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "heavy intensity drizzle" && hr > 6 && hr < 19) {
$('#weather-description').text("Heavy Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-3.svg">');
}
//THUNDER
//Thunder w/t light rain
if (weatherResult.weather[0].description === "thunderstorm with light rain") {
$('#weather-description').text("Thunderstorm with Light Rain");
$("#weatherIcon").html('<img src="assets/images/animated/thunder.svg">');
}
//Thunder w/t rain
if (weatherResult.weather[0].description === "thunderstorm with rain") {
$('#weather-description').text("Thunderstorm with Rain");
$("#weatherIcon").html('<img src="assets/images/animated/thunder.svg">');
}
//Thunder w/t heavy rain
if (weatherResult.weather[0].description === "thunderstorm with heavy rain") {
$('#weather-description').text("Thunderstorm with Heavy Rain");
$("#weatherIcon").html('<img src="assets/images/animated/thunder.svg">');
}
//Light thunderstorm
if (weatherResult.weather[0].description === "light thunderstorm") {
$('#weather-description').text("Light Thunderstorm");
$("#weatherIcon").html('<img src="assets/images/animated/thunder.svg">');
}
//thunderstorm
if (weatherResult.weather[0].description === "thunderstorm") {
$('#weather-description').text("Thunderstorm");
$("#weatherIcon").html('<img src="assets/images/animated/thunder.svg">');
}
//Heavy thunderstorm
if (weatherResult.weather[0].description === "heavy thunderstorm") {
$('#weather-description').text("Heavy Thunderstorm");
$("#weatherIcon").html('<img src="assets/images/animated/thunder.svg">');
}
//Ragged thunderstorm
if (weatherResult.weather[0].description === "ragged thunderstorm") {
$('#weather-description').text("Ragged Thunderstorm");
$("#weatherIcon").html('<img src="assets/images/animated/thunder.svg">');
}
//thunderstorm w//t light drizzle
if (weatherResult.weather[0].description === "thunderstorm with light drizzle") {
$('#weather-description').text("Thunderstorm with Light Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/thunder.svg">');
}
//thunderstorm with drizzle
if (weatherResult.weather[0].description === "thunderstorm with drizzle") {
$('#weather-description').text("Thunderstorm with Some Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/thunder.svg">');
}
//thunderstorm with heavy drizzle
if (weatherResult.weather[0].description === "thunderstorm with heavy drizzle") {
$('#weather-description').text("Thunderstorm with Heavy Drizzle");
$("#weatherIcon").html('<img src="assets/images/animated/thunder.svg">');
}
console.log(weatherResult);
//CLOUDS
//few clouds
//NIGHT TIME
if (weatherResult.weather[0].description === "few clouds" && hr > 19 || hr < 6) {
$('#weather-description').text("Few Clouds");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy-night-1.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "few clouds" && hr > 6 && hr < 19) {
$('#weather-description').text("Few Clouds");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy-day-1.svg">');
}
//scattered clouds
//NIGHT TIME
if (weatherResult.weather[0].description === "scattered clouds" && hr > 19 || hr < 6) {
$('#weather-description').text("Scattered Clouds");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy-night-2.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "scattered clouds" && hr > 6 && hr < 19) {
$('#weather-description').text("Scattered Clouds");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy-day-2.svg">');
}
//broken clouds
//NIGHT TIME
if (weatherResult.weather[0].description === "broken clouds" && hr > 19 || hr < 6) {
$('#weather-description').text("Broken Clouds");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy-night-3.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "broken clouds" && hr > 6 && hr < 19) {
$('#weather-description').text("Broken Clouds");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy-day-3.svg">');
}
//OVERCAST
if (weatherResult.weather[0].description === "overcast clouds") {
$('#weather-description').text("Overcast");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy.svg">');
}
//MISC.
//mist
if (weatherResult.weather[0].description === "mist") {
$('#weather-description').text("Mist");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-7.svg">');
}
//smoke
if (weatherResult.weather[0].description === "smoke") {
$('#weather-description').text("smoke");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy.svg">');
}
//haze
if (weatherResult.weather[0].description === "haze") {
$('#weather-description').text("Hazey");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy.svg">');
}
//sand, dust whirls
if (weatherResult.weather[0].description === "sand, dust whirls") {
$('#weather-description').text("Sand, Dust Whirls");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy.svg">');
}
//fog
if (weatherResult.weather[0].description === "fog") {
$('#weather-description').text("Foggy");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy.svg">');
}
//sand
if (weatherResult.weather[0].description === "sand") {
$('#weather-description').text("Sand");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy.svg">');
}
//dust
if (weatherResult.weather[0].description === "dust") {
$('#weather-description').text("Dust");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy.svg">');
}
//volcanix ash
if (weatherResult.weather[0].description === "volcanic ash") {
$('#weather-description').text("Volcanic Ash");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy.svg">');
}
//squalls
if (weatherResult.weather[0].description === "squalls") {
$('#weather-description').text("Squalls");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy.svg">');
}
//tornado
if (weatherResult.weather[0].description === "tornado") {
$('#weather-description').text("Tornado");
$("#weatherIcon").html('<img src="assets/images/animated/cloudy.svg">');
}
//SNOWWWWWW
//Light snow
//NIGHT TIME
if (weatherResult.weather[0].description === "light snow" && hr > 19 || hr < 6) {
$('#weather-description').text("Light Snow");
$("#weatherIcon").html('<img src="assets/images/animated/snowy-4.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "light snow" && hr > 6 && hr < 19) {
$('#weather-description').text("Light Snow");
$("#weatherIcon").html('<img src="assets/images/animated/snowy-1.svg">');
}
//snow
//NIGHT TIME
if (weatherResult.weather[0].description === "snow" && hr > 19 || hr < 6) {
$('#weather-description').text("Snow");
$("#weatherIcon").html('<img src="assets/images/animated/snowy-5.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "snow" && hr > 6 && hr < 19) {
$('#weather-description').text("Snow");
$("#weatherIcon").html('<img src="assets/images/animated/snowy-2.svg">');
}
//heavy snow
//NIGHT TIME
if (weatherResult.weather[0].description === "heavy snow" && hr > 19 || hr < 6) {
$('#weather-description').text("Snow");
$("#weatherIcon").html('<img src="assets/images/animated/snowy-6.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "heavy snow" && hr > 6 && hr < 19) {
$('#weather-description').text("Snow");
$("#weatherIcon").html('<img src="assets/images/animated/snowy-3.svg">');
}
//sleet
//NIGHT TIME
if (weatherResult.weather[0].description === "sleet" && hr > 19 || hr < 6) {
$('#weather-description').text("Sleet");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-7.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "sleet" && hr > 6 && hr < 19) {
$('#weather-description').text("Sleet");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-7.svg">');
}
//sleet
//NIGHT TIME
if (weatherResult.weather[0].description === "shower sleet" && hr > 19 || hr < 6) {
$('#weather-description').text("Shower Sleet");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-7.svg">');
}
//DAY TIME
if (weatherResult.weather[0].description === "sleet" && hr > 6 && hr < 19) {
$('#weather-description').text("Shower Sleet");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-7.svg">');
}
//ligth rain and snow
if (weatherResult.weather[0].description === "light rain and snow") {
$('#weather-description').text("Light Rain and Snow");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-7.svg">');
}
//rain and snow
if (weatherResult.weather[0].description === "rain and snow") {
$('#weather-description').text("Rain and Snow");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-7.svg">');
}
//light shower snow
if (weatherResult.weather[0].description === "light shower snow") {
$('#weather-description').text("Light Shower Snow");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-7.svg">');
}
//shower snow
if (weatherResult.weather[0].description === "shower snow") {
$('#weather-description').text("Shower Snow");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-7.svg">');
}
//heavy shower snow
if (weatherResult.weather[0].description === "heavy shower snow") {
$('#weather-description').text("Heavy Shower Snow");
$("#weatherIcon").html('<img src="assets/images/animated/rainy-7.svg">');
}
}
});
}
});
});<file_sep>/assets/javascript/chat.js
var config = {
apiKey: "<KEY>",
authDomain: "chat-6e8bf.firebaseapp.com",
databaseURL: "https://chat-6e8bf.firebaseio.com",
projectId: "chat-6e8bf",
storageBucket: "chat-6e8bf.appspot.com",
messagingSenderId: "431420291486"
};
firebase.initializeApp(config);
$('#post').on("click", function(){
var msgUser = $('#name-input').val();
$('#name-input').attr("value", msgUser);
var msgText = $('#message-input').val();
firebase.database().ref().push({
"user" : msgUser,
"msg" : msgText
});
$('#message-input').val(" ");
});
firebase.database().ref().on("child_added", function(childSnapshot){
var nametag = childSnapshot.val().user.charAt(0);
var lileft = $('<li>').addClass("left clearfix");
var spanimg = $('<span>').addClass("chat-img pull-left");
var img = $('<img>').addClass("img-circle");
img.attr("src", "http://placehold.it/50/55C1E7/fff&text=" + nametag);
spanimg.append(img);
var chatbody = $('<div>').addClass("chat-body clearfix");
var divhead = $('<div>').addClass("header");
var strong = $('<strong>').addClass("primary-font");
strong.html(childSnapshot.val().user)
divhead.append(strong);
var p = $('<p>').html(childSnapshot.val().msg);
chatbody.append(divhead, p);
lileft.append(spanimg, chatbody);
$('#chat-main').append(lileft);
});
//Project Console: https://console.firebase.google.com/project/chatapp-e99de/overview
//Hosting URL: https://chatapp-e99de.firebaseapp.com
<file_sep>/assets/javascript/bookmarks.js
var restoredWebsites = JSON.parse(localStorage.getItem('websites'));
var counter = 0;
var websites =
{
queue:
[
{id: 0, name:"W3Schools", nameURL:"https://www.w3schools.com/"},
{id: 1, name:"CodeAcademy", nameURL:"https://www.codecademy.com/"},
{id: 2, name:"MDN", nameURL:"https://developer.mozilla.org/en-US/"},
{id: 3, name:"Udemy",nameURL:"https://www.udemy.com/"}
]
};
localStorage.setItem('websites', JSON.stringify(websites));
localStorage.getItem('websites', JSON.stringify(websites));
outputIt();
function outputIt() {
var outputs = "";
for(var i = 0; i < restoredWebsites.queue.length; i++)
{
outputs += '<div id="'+restoredWebsites.queue[i].id + '">' + restoredWebsites.queue[i].id+':'+restoredWebsites.queue[i].name +' url:'+ restoredWebsites.queue[i].nameURL +'</div>';
}
document.getElementById("demo").innerHTML= outputs;
}
function popIt() {
restoredWebsites.queue.shift();
localStorage.setItem('websites', JSON.stringify(restoredWebsites));
outputIt();
}
function pushIt() {
counter++;
restoredWebsites.queue.push({
id: counter,
name: $('#websiteName').val(),
nameURL: $('#websiteURL').val(),
});
localStorage.setItem('websites', JSON.stringify(restoredWebsites));
outputIt();
}
/*
$('#bookmark-add').on("click", function(){
var title = $('#bookmark-title').val();
var url = $('#bookmark-url').val();
if (title === '') {
console.log('title cant be empty');
}
if (url === '') {
console.log('url cant be empty');
}
else {
localStorage.setItem(title, url);
}
});
*/<file_sep>/README.md
# Browser-Startpage
Startpage for browsers to replace the new tab or home screen. Complete with customization and more functionality.
Set the startpage as "home" in your browser.
There are extensions in chrome and firefox that allow you to assign it as your new tab page as well.
Check out https://chrome.google.com/webstore/detail/new-tab-redirect/icpgjfneehieebagbmdbhnlpiopdcmna?utm_source=gmail in the chrome store.
You now have a new customizable startpage!
| 426415ca8caadfd1cee2e29d6e60a506cf9faf33 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | Nickmcd4/Browser-Startpage | 1a216cc76eae5d43fce4a1641efab5a11bd5158d | 610c3cfeb76b43087b678932d1445f1d2115a76d |
refs/heads/master | <file_sep><?php
$rubrique = $_GET['rubrique'] ;
$rubrique = htmlspecialchars($rubrique, ENT_QUOTES, 'UTF-8');
$rubrique = intval($rubrique);
//$requete01 = mysql_query("SELECT * FROM pays_rubrique WHERE Numero = '$rubrique' LIMIT 1 ") ;
$requete01 = $pdo->prepare("SELECT * FROM pays_rubrique WHERE Numero = ? LIMIT 1 ");
$requete01->execute(array($rubrique));
$lignes01=$requete01->fetchAll(PDO::FETCH_CLASS);
foreach ($lignes01 as $ligne01) {
$nom = $ligne01->Nom ;
$rubrique = $ligne01->Numero ;
echo "<table border=0 cellspacing=0 cellpadding=5 width=100%>";
echo "<tr>";
echo "<td colspan=2>";
echo "<p class=titre_".$rubrique.">".$nom."</p>";
echo "</td>";
echo "</tr>";
// Insertion des noms de page
//$requete02 = mysql_query("SELECT * FROM pays_page WHERE Rubrique = '$rubrique' AND Menu = '1' AND Archive = '0' ORDER BY Position DESC ") ;
$requete02 = $pdo->prepare("SELECT * FROM pays_page WHERE Rubrique = ? AND Menu = '1' AND Archive = '0' ORDER BY Position DESC ");
$requete02->execute(array($rubrique));
$lignes02=$requete02->fetchAll(PDO::FETCH_CLASS);
foreach ($lignes02 as $ligne02) {
$page = $ligne02->Titre ;
$numero = $ligne02->Numero ;
echo "<tr>";
echo "<td width=50> </td><td>";
if ($ligne02->Numero == '1') { // La page du territoire est redirig�e vers la carte flash
echo "<li><a href=index.php?carte>".$page."</a></li>";
}
/*elseif ($numero == '20') { // La page de la piscine est redirig�e vers le site des sports
echo "<li><a href=http://www.chateaugontier.fr/sports/piscine/>".$page."</a></li>\n";
}
elseif ($numero == '21') { // La page des animations sportives est redirig�e vers le site des sports
echo "<li><a href=http://www.chateaugontier.fr/sports>".$page."</a></li>\n";
}*/
else {
echo "<li><a href=index.php?page=".$numero." style=\"font-size: 14px;\">".$page."</a></li>";
}
echo "</td>";
echo "</tr>";
echo "<tr><td> </td></tr>";
}
echo "</table>";
}
?>
<file_sep><?php
$email = $_POST['email'] ;
$nom = $_POST['nom'] ;
$page = $_POST['page'] ;
$texte = $nom.", vous recommande l'article suivant sur le site Internet du Pays de Château-Gontier :\n\nhttp://www.chateaugontier.fr/index.php?page=".$page ;
$headers ='From: "Site - Pays de Ch�teau-Gontier"<<EMAIL>>'."\n";
$headers .='Return-Path: <EMAIL>'."\n";
$headers .='Reply-To: <EMAIL>'."\n";
$headers .='Content-Type: text/plain; charset="utf-8"'."\n";
$headers .='Content-Transfer-Encoding: 8bit';
$sujet = "Pays de Ch�teau-Gontier";
mail($email,$sujet,$texte,$headers);
echo "<p class=texte1_paragraphe>L'article a bien été envoyé à l'adresse email suivante : ".$email."</p> ";
include('page/page.php');
?>
<file_sep><?php
ERREUR 404
?> <file_sep>
/*
SCRIPT EDITE SUR L'EDITEUR JAVACSRIPT
http://www.editeurjavascript.com
*/
domok = document.getElementById;
if (domok)
{
skn = document.getElementById("topdecklink").style;
if(navigator.appName.substring(0,3) == "Net")
document.captureEvents(Event.MOUSEMOVE);
document.onmousemove = get_mouse;
}
function poplink(msg)
{
var content ="<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 BGCOLOR=#000000><TR><TD><TABLE WIDTH=100% BORDER=0 CELLPADDING=2 CELLSPACING=1><TR><TD BGCOLOR=#FF9900><FONT COLOR=#000000 SIZE=2 face='Arial'><CENTER>"+msg+"</CENTER></TD></TR></TABLE></TD></TR></TABLE>";
if (domok)
{
document.getElementById("topdecklink").innerHTML = content;
skn.visibility = "visible";
}
}
function get_mouse(e)
{
var x = (navigator.appName.substring(0,3) == "Net") ? e.pageX : event.x+document.body.scrollLeft;
var y = (navigator.appName.substring(0,3) == "Net") ? e.pageY : event.y+document.body.scrollTop;
skn.left = x - 60;
skn.top = y+20;
}
function killlink()
{
if (domok)
skn.visibility = "hidden";
}
<!-- FIN DU SCRIPT --><file_sep><!DOCTYPE html>
<html lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
include('../../acces/connect.php');
$connect;
$base;
?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Slider Kit > DelayCaptions add-on</title>
<meta name="Keywords" content="photo gallery, carousel, external controls, pagination" />
<meta name="Description" content="Slider Kit jQuery plugin: delay captions, sliding captions, extension" />
<!-- jQuery library -->
<script type="text/javascript" src="../lib/js/external/_oldies/jquery-1.3.min.js"></script>
<!--<script type="text/javascript" src="../lib/js/external/jquery-1.6.2.min.js"></script>-->
<!-- jQuery Plugin scripts -->
<script type="text/javascript" src="../lib/js/external/jquery.easing.1.3.min.js"></script>
<script type="text/javascript" src="../lib/js/external/jquery.mousewheel.min.js"></script>
<!-- Slider Kit scripts -->
<script type="text/javascript" src="../lib/js/sliderkit/jquery.sliderkit.1.9.2.pack.js"></script>
<!-- PERMET DE FAIRE GLISSER LE TEXTE SUR L'IMAGE -->
<script type="text/javascript" src="../lib/js/sliderkit/addons/sliderkit.delaycaptions.1.1.pack.js"></script>
<!-- Slider Kit launch -->
<script type="text/javascript">
$(window).load(function(){ //$(window).load() must be used instead of $(document).ready() because of Webkit compatibility
/*---------------------------------
* Example #01
*---------------------------------*/
$(".delaycaptions-01").sliderkit({
circular:false,
mousewheel:true,
keyboard:true,
shownavitems:5,
autospeed:4000,
circular:true,
fastchange:false,
panelfxspeed:500,
delaycaptions:{
delay:600,
position:'bottom',
transition:'sliding',
duration:300,
easing:'easeOutExpo'
}
});
});
</script>
<!-- Slider Kit styles -->
<link rel="stylesheet" type="text/css" href="../lib/css/sliderkit-core.css" media="screen, projection" />
<!-- FEUILLE DE STYLE DU MENU DE NAVIGATION -->
<link rel="stylesheet" type="text/css" href="../lib/css/sliderkit-demos.css" media="screen, projection" />
<!-- Slider Kit compatibility -->
<!--[if IE 6]><link rel="stylesheet" type="text/css" href="../lib/css/sliderkit-demos-ie6.css" /><![endif]-->
<!--[if IE 7]><link rel="stylesheet" type="text/css" href="../lib/css/sliderkit-demos-ie7.css" /><![endif]-->
<!--[if IE 8]><link rel="stylesheet" type="text/css" href="../lib/css/sliderkit-demos-ie8.css" /><![endif]-->
<!-- Site styles -->
<link rel="stylesheet" type="text/css" href="../lib/css/sliderkit-site.css" media="screen, projection" />
</head>
<body>
<div id="page" class="inner layout-1col">
<div id="content">
<div class="sliderkit photosgallery-captions delaycaptions-01">
<div class="sliderkit-nav">
<div class="sliderkit-nav-clip">
<ul>
<?php
include('actu1.php') ;
?>
</ul>
</div>
<div class="sliderkit-btn sliderkit-nav-btn sliderkit-nav-prev"><a rel="nofollow" href="#" title="Previous line"><span>Page précédente</span></a></div>
<div class="sliderkit-btn sliderkit-nav-btn sliderkit-nav-next"><a rel="nofollow" href="#" title="Next line"><span>Page suivante</span></a></div>
<div class="sliderkit-btn sliderkit-go-btn sliderkit-go-prev"><a rel="nofollow" href="#" title="Previous photo"><span>Info précédente</span></a></div>
<div class="sliderkit-btn sliderkit-go-btn sliderkit-go-next"><a rel="nofollow" href="#" title="Next photo"><span>Prochaine info</span></a></div>
</div>
<div class="sliderkit-panels">
<?php
include('actu2.php') ;
?>
</div>
</div>
</div>
</div>
</body>
</html><file_sep><table border=0 cellspacing=0 cellpadding=0 width=100%>
<?php
$colonne = '1' ;
$requete01 = mysql_query("SELECT * FROM pays_rubrique ORDER BY Numero ASC ") ;
while ($ligne01=mysql_fetch_object($requete01)) {
$nom = $ligne01->Nom ;
$rubrique = $ligne01->Numero ;
if ($colonne == '1') {
echo "<tr valign=top>";
}
echo "<td width=230>";
echo "<table border=0 cellspacing=0 cellpadding=5>";
echo "<tr>";
echo "<td>";
echo "<p class=titre_".$rubrique.">".$nom."</p>";
echo "</td>";
echo "</tr>";
// Insertion des noms de page
$requete02 = mysql_query("SELECT * FROM pays_page WHERE Rubrique = '$rubrique' AND Menu = '1' AND Archive = '0' ORDER BY Position DESC ") ;
while ($ligne02=mysql_fetch_object($requete02)) {
$page = $ligne02->Titre ;
$numero = $ligne02->Numero ;
echo "<tr>";
echo "<td>";
if ($ligne02->Numero == '1') { // La page du territoire est redirigée vers la carte flash
echo "<a href=index.php?carte>".$page."</a>";
}
else {
echo "<a href=index.php?page=".$numero.">".$page."</a>";
}
echo "</td>";
echo "</tr>";
}
echo "</table>";
echo "</td>";
if ($colonne == '3') {
echo "</tr>";
$colonne = '0';
}
$colonne++;
}
?>
</table>
<file_sep><?php
error_reporting(E_ALL);
/*
$connect=mysql_connect("db_chateaugontierfr","test","test");
$base='test';
$base=mysql_selectdb("$base");
*/
$host = "db_chateaugontierfr";
$user = "test";
$password = "<PASSWORD>";
$dbname = "test";
$pdo = null;
try{
$pdo = new PDO('mysql:host='.$host.';dbname='.$dbname,
$user,
$password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch (PDOException $e) {
echo "Erreur!: " . $e->getMessage() . "<br/>";
die();
}
?><file_sep> <?php
if ($TypePage == 'page') {
$page = $_GET['page'];
$page = htmlspecialchars($page, ENT_QUOTES, 'UTF-8');
$page = intval($page);
if (isset($_GET['ami'])) {
echo "
Envoyer cet article � un ami<br/><br/>
<form name=form_ami method=post action=index.php?envoi_ami>
<label class=ami><input class=recherche type=text name=email value='Mail de votre ami ...' onFocus=\"this.value=''\" /></label>
<label class=ami><input class=recherche type=text name=nom value='Votre nom ...' onFocus=\"this.value=''\" /></label>
<input type=Hidden name=page value=".$page." />
<input type=Hidden name=envoi_ami />
<input type=submit name=button class=bouton value='Envoyer' />
</form>
<br/><br/>";
}
include('pays/page/page.php');
}
elseif ($TypePage == 'ami') {
include('pays/page/ami.php');
}
elseif ($TypePage == 'carte') {
include('pays/page/carte.php');
}
elseif ($TypePage == 'contact') {
include('pays/page/contact.php');
}
elseif ($TypePage == 'newsletter') {
include('pays/page/newsletter.php');
}
elseif ($TypePage == 'plan') {
include('pays/page/plan.php');
}
elseif ($TypePage == 'rubrique') {
include('pays/page/rubrique.php');
}
elseif ($TypePage == 'rechercher') {
include('pays/page/rechercher.php');
}
elseif ($TypePage == 'credit') {
include('pays/page/credit.php');
}
elseif ($TypePage == 'agenda') {
include('pays/page/agenda.php');
}
else {
}
?>
<file_sep><?php //error_reporting(0);
//
date_default_timezone_set("Europe/Berlin");
// ?>
<?php
$jour = date("d");
$mois = date("m");
$annee = date("Y");
$date_actuelle = $annee.$mois.$jour ;
$compteur = '1' ;
$requete = mysql_query("SELECT * FROM pays_page WHERE Accueil = '1' AND Type != '4' AND Archive = '0' ORDER BY Position DESC") ;
while ($ligne=mysql_fetch_object($requete)) {
$dateDebut = $ligne->Debut ;
$debut = explode("-", $dateDebut);
$debutAnnee = $debut[0];
$debutMois = $debut[1];
$debutJour = $debut[2];
$debut = $debutAnnee.$debutMois.$debutJour ;
$dateFin = $ligne->Fin ;
$fin = explode("-", $dateFin);
$finAnnee = $fin[0];
$finMois = $fin[1];
$finJour = $fin[2];
$fin = $finAnnee.$finMois.$finJour ;
$id = $ligne->Numero ;
$titre = $ligne->Titre ;
$texte_accueil = $ligne->Texte_accueil ;
$photo_accueil = $ligne->Photo_accueil ;
if ($photo_accueil == '') {
$photo_accueil = "logo" ;
}
if ($debut <= $date_actuelle && $fin >= $date_actuelle ) {
echo "
";
}
}
?><file_sep><font face=verdana color=#106470>
<table width=90% align=center >
<?php
$jour = date("d");
$mois = date("m");
$annee = date("Y");
$date_actuelle = $annee.$mois.$jour ;
$couleur = "#e7e7e7" ;
$AucuneEntreeAgenda = "oui" ;
$compteur = '0';
$requete = $pdo->prepare("SELECT * FROM pays_info WHERE Accueil = '1' ORDER BY Position ASC");
$requete->execute();
$lignes = $requete->fetchAll(PDO::FETCH_CLASS);
//$requete = mysql_query("SELECT * FROM pays_info WHERE Accueil = '1' ORDER BY Position ASC") ;
foreach ($lignes as $ligne) {
$dateDebut = $ligne->Debut ;
$debut = explode("-", $dateDebut);
$debutAnnee = $debut[0];
$debutMois = $debut[1];
$debutJour = $debut[2];
$debut = $debutAnnee.$debutMois.$debutJour ;
$dateFin = $ligne->Fin ;
$fin = explode("-", $dateFin);
$finAnnee = $fin[0];
$finMois = $fin[1];
$finJour = $fin[2];
$fin = $finAnnee.$finMois.$finJour ;
$commune= $ligne->Commune ;
$date = $ligne->Date ;
$objet = $ligne->Objet ;
if ($debut <= $date_actuelle && $fin >= $date_actuelle && $compteur < '3' ) {
$AucuneEntreeAgenda = "non" ;
$compteur++;
echo "<tr><td bgcolor=".$couleur.">>";
if ($commune != '') {
echo "<b>".$commune."</b><br/>";
}
if ($date != '') {
echo $date."<br/>";
}
if ($objet != '') {
echo $objet."<br/>";
}
echo "</td></tr>";
if ($couleur == '#FFFFFF') { $couleur = "#e7e7e7" ; }
else { $couleur = "#FFFFFF" ;}
echo "<tr><td> </td></tr>";
}
}
if ($AucuneEntreeAgenda == 'oui') {
echo "<tr><td bgcolor=".$couleur.">Pas d'évènement à venir</td></tr>";
}
?>
<tr><td ><a href=index.php?agenda style="font-size:medium; color: #106470 ; text-decoration: underline ;">Découvrir l'agenda complet</a></td></tr>
</table>
</font>
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Agenda du Pays de Château-Gontier | Demande</title>
<?php
include('../pays/acces/connect.php');
$connect;
$base;
$Titre = '';
$Date = '';
$Lieu = '';
$Texte = '';
$Telephone = '';
$Courriel1 = '';
$Site = '';
$Courriel2 = '';
$Validation = 'non';
if (isset($_GET['Id'])) {
$Id = $_GET['Id'];
$Id = htmlspecialchars($Id, ENT_QUOTES, 'UTF-8');
//$requeteDemande = mysql_query("SELECT * FROM `chateaugrchio`.`pays_agenda` WHERE Numero = '$Id' LIMIT 1 ") ;
$requeteDemande = $pdo->prepare("SELECT * FROM `chateaugrchio`.`pays_agenda` WHERE Numero = ? LIMIT 1 ");
$requeteDemande->execute(array($Id));
$lignesDemande = $requeteDemande->fetchAll(PDO::FETCH_CLASS);
foreach ($lignesDemande as $ligneDemande) {
$Validation = 'ok';
$Commune = $ligneDemande->Commune ;
$Titre = $ligneDemande->Titre ;
$Date = $ligneDemande->Date ;
$Lieu = $ligneDemande->Lieu ;
$Texte = $ligneDemande->Texte ;
$Telephone = $ligneDemande->Telephone ;
$Courriel1 = $ligneDemande->Courriel1 ;
$Site = $ligneDemande->Site ;
$Courriel2 = $ligneDemande->Courriel2 ;
}
}
?>
<style type="text/css">
body,td,th {
font-family: "Arial Black", Gadget, sans-serif;
font-size: 12px;
color: #000;
}
</style>
</head>
<body>
<?php
if ($Validation == 'ok') {
echo "<form name=form1 method=post action=agenda-pays-validation.php>";
}
else {
echo "<form name=form1 method=post action=agenda-pays-mail.php>";
}
?>
<form id="form1" name="form1" method="post" action="agenda-pays-mail.php">
<table width="750" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="250" align="right">Commune</td>
<td width="75"> </td>
<td>
<?php
if ($Commune != '') {
echo $Commune ;
}
else {
echo "
<select name=commune id=select>
<option value=0 selected=selected>*************</option>
<option value=Ampoign� >Ampoign�</option>
<option value=Argenton-Notre-Dame >Argenton-Notre-Dame</option>
<option value=Az� >Az�</option>
<option value=Biern� >Biern�</option>
<option value=Chatelain >Chatelain</option>
<option value=Chemaz� >Chemaz�</option>
<option value=Coudray >Coudray</option>
<option value=Daon >Daon</option>
<option value=Fromenti�res >Fromenti�res</option>
<option value=Gennes-Sur-Glaize >Gennes-Sur-Glaize</option>
<option value=Houssay >Houssay</option>
<option value=Laign� >Laign�</option>
<option value=Loign�-Sur-Mayenne >Loign�-Sur-Mayenne</option>
<option value=Longuefuye >Longuefuye</option>
<option value=M�nil >M�nil</option>
<option value=Marign�-Peuton >Marign�-Peuton</option>
<option value=Orign� >Orign�</option>
<option value=Peuton >Peuton</option>
<option value=Saint-Denis-D'Anjou >Saint-Denis-D'Anjou</option>
<option value=Saint-Fort >Saint-Fort</option>
<option value=Saint-Laurent-Des-Mortiers >Saint-Laurent-Des-Mortiers</option>
<option value=Saint-Michel-De-Feins >Saint-Michel-De-Feins</option>
<option value=Saint-Sulpice >Saint-Sulpice</option>
</select> ";
}
?>
</td>
</tr>
<tr>
<td align="right"> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="3" align="center" bgcolor="#CCCCCC">INFORMATIONS</td>
</tr>
<tr>
<td align="right"> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="right">Titre</td>
<td> </td>
<td><textarea name="titre" cols="45" rows="1"><?php echo $Titre ; ?></textarea></td>
</tr>
<tr>
<td align="right"> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="right">Date</td>
<td> </td>
<td><textarea name="date" cols="45" rows="1"><?php echo $Date ; ?> </textarea></td>
</tr>
<tr>
<td align="right"> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="right">Lieu</td>
<td> </td>
<td><textarea name="lieu" cols="45" rows="1"><?php echo $Lieu ; ?> </textarea></td>
</tr>
<tr>
<td align="right"> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="right" valign="top">Texte (présentation, tarifs, horaire, ... )</td>
<td> </td>
<td><textarea name="texte" id="texte" cols="45" rows="5"><?php echo $Texte ; ?> </textarea></td>
</tr>
<tr>
<td align="right"> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="3" align="center" bgcolor="#CCCCCC">CONTACTS</td>
</tr>
<tr>
<td align="right"> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="right">Téléphone</td>
<td> </td>
<td><textarea name="telephone" cols="45" rows="1"><?php echo $Telephone ; ?> </textarea></td>
</tr>
<tr>
<td align="right"> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="right">Courriel</td>
<td> </td>
<td><input name="courriel1" type="mail" id="courriel2" size="40" value='<?php echo $Courriel1 ; ?>' /></td>
</tr>
<tr>
<td align="right"> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="right">Site Internet</td>
<td align="right">http://</td>
<td><textarea name="site" cols="45" rows="1"><?php echo $Site ; ?> </textarea></td>
</tr>
<tr>
<td align="right"> </td>
<td> </td>
<td> </td>
</tr>
<?php
if ($Validation != 'ok') {
$Chiffre1 = rand(1,9) ;
$Chiffre2 = rand(1,9) ;
$Total = $Chiffre1 + $Chiffre2 ;
echo "<input type=hidden name=controle2 value=".$Total." />
<tr>
<td colspan=3 align=center bgcolor=#CCCCCC>CONTROLE</td>
</tr>
<tr>
<td align=right> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td align=right><label >Combien font ".$Chiffre1." + ".$Chiffre2." ?</label></td>
<td> </td>
<td><input name=controle type=text id=controle size=40 /></td>
</tr>
<tr>
<td align=right> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td align=right>Courriel servant de correspondance avec le service communication du Pays de Ch�teau-Gontier</td>
<td> </td>
<td><input name=courriel2 type=mail id=courriel2 size=40 value='".$Courriel2."' /></td>
</tr>
<tr>
<td align=right> </td>
<td> </td>
<td> </td>
</tr>";
}
?>
<?php
if ($Validation == 'ok') {
echo "<tr>
<td colspan=3 align=center bgcolor=#CCCCCC>DECISION SERVICE COM</td>
</tr>
<tr><td colspan=3 > </td></tr>";
echo "<tr><td align=center valign=top colspan=2 ><input type=hidden name=IdValidation value=".$Id." /><input type=submit name=button id=button value=VALIDER /><br/><br/>Date limite d'affichage (JJ / MM / AAAA)<br/><input type=text name=jour maxlength=2 size=1 />-<input type=text name=mois maxlength=2 size=1 />-<input type=text name=annee maxlength=4 size=2 /></form></td>";
echo "<td align=center valign=top ><form name=form1 method=post action=agenda-pays-refus.php><input type=hidden name=IdRefus value=".$Id." /><input type=submit name=button id=button value=REFUSER /><br/><br/><textarea name=Refus cols=40 rows=3></textarea></td></form></tr>";
}
else {
echo "<tr><td colspan=3 align=center><input type=submit name=button id=button value=ENVOYER /></td></form></tr>";
}
?>
<tr>
</tr>
<tr>
<td colspan="3"> </td>
</tr>
</table>
</body>
</html>
<file_sep><?php
//$requete03 = mysql_query("SELECT * FROM pays_sousbloc WHERE Bloc = '$bloc' AND Position = '$position' ") ;
$requete03 = $pdo->prepare("SELECT * FROM pays_sousbloc WHERE Bloc = ? AND Position = ? ");
$requete03->execute(array($bloc, $position));
$lignes03 = $requete03->fetchAll(PDO::FETCH_CLASS);
foreach ($lignes03 as $ligne03) {
$position_sousbloc = $ligne03->Position ;
$type = $ligne03->Type ;
$texte = $ligne03->Texte ;
$sousbloc = $ligne03->Numero ;
$lien = $ligne03->Lien ;
$titre = $ligne03->Titre ;
switch ($type) {
case 1 : // Format texte
echo $texte ;
break ;
case 2: // Format image
$visuel = 'non' ;
$requete04 = mysql_query("SELECT * FROM pays_image WHERE Sousbloc = '$ligne03->Numero' ");
while ($ligne04=mysql_fetch_object($requete04)) {
$visuel = 'oui';
$image = $ligne04->Nom ;
}
if ($visuel == 'oui') { echo "<a href=pays/media/".$image." rel=lightbox[site]>"; }
elseif ($lien != '') { echo "<a href='".$lien."' target=_blank>"; }
echo "<img src=pays/media/".$texte." border=0 />" ;
if ($visuel == 'oui') { echo "</a>"; }
elseif ($lien != '') { echo "</a>"; }
break ;
case 3 : // Format Audio
echo "<object type=application/x-shockwave-flash data=pays/audio/dewplayer.swf?mp3=media/".$texte." &autostart=0&autoreplay=1&showtime=1 width=150 height=20>
<param name=wmode value=transparent />
<param name=movie value=pays/audio/dewplayer.swf?mp3=pays/media/".$texte."&autostart=0&autoreplay=1&showtime=1/>
</object>";
break ;
case 5 : // Format liens
$requete01 = mysql_query("SELECT * FROM pays_page WHERE Numero = '$texte' LIMIT 1 ") ;
while ($ligne01=mysql_fetch_object($requete01)) {
$nomPage = $ligne01->Titre ;
}
echo "<li><a href=index.php?page=".$texte.">".$nomPage."</a></li>" ;
break ;
case 6 : // Format document PDF
echo "<a href=pays/media/".$texte." target=_blank>".$titre ;
echo " <img src=pays/image/acrobat.jpg border=0 width=20></a>";
break ;
case 7 : // Format Livre calam�o
echo "<a href=http://fr.calameo.com/read/".$lien." target=_blank>".$titre."</a>";
echo $texte ;
break ;
case 8 : // Format formulaire de contact
$Chiffre1 = rand(1,9) ;
$Chiffre2 = rand(1,9) ;
$Total = $Chiffre1 + $Chiffre2 ;
echo "<div style=\"font-size: 14px; text-align:left;\"> <strong>Nous contacter par mail :</strong></div>";
echo "<div class=contact>";
echo "<form name=contact method=post action=index.php?contact>";
echo "<label class=contact>Nom Prénom :</label>";
echo "<label class=contact><input type=text class=contact name=nom required /></label>";
echo "<label class=contact>E-mail :</label>";
echo "<label class=contact><input type=text class=contact name=email required /></label>";
echo "<label class=contact>Sujet :</label>";
echo "<label class=contact><input type=text class=contact name=sujet required /></label>";
echo "<label class=contact>Texte :</label>";
echo "<label class=contact><textarea class=contact name=texte required /></textarea></label>";
echo '<div class="g-recaptcha" data-sitekey="'.$siteKey.'"></div>';
echo "<input type=hidden name=email_destinataire value=".$texte." />";
echo "<label class=contact><input type=submit value=Envoyer class=contactBouton /></textarea></label>";
echo "</form>";
echo "</div>";
break ;
}
}
?><file_sep><?php
// SCRIPT RECAPTCHA GOOGLE
$reCaptcha = new ReCaptcha($secret);
if(isset($_POST["g-recaptcha-response"])) {
$resp = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
if ($resp != null && $resp->success) {
$nom = $_POST['nom'];
$nom = stripslashes($nom);
$email = $_POST['email'];
$sujet = $_POST['sujet'];
$sujet = stripslashes($sujet);
$email_destinataire = $_POST['email_destinataire'];
$texte_mail = $_POST['texte'];
$texte_mail = stripslashes($texte_mail);
$texte = "Nom :\n".$nom."\n\n";
$texte .= "Courriel :\n".$email ;
$texte .= "\n\nDemande :\n".$texte_mail;
$headers ='From: "Site - Pays de Ch�teau-Gontier"<<EMAIL>>'."\n";
$headers .='Return-Path: <EMAIL>'."\n";
$headers .='Reply-To: '.$email.''."\n";
$headers .='Content-Type: text/plain; charset="utf-8"'."\n";
$headers .='Content-Transfer-Encoding: 8bit';
$email = $texte ;
mail($email_destinataire,$sujet,$texte,$headers);
$email2 = '<EMAIL>' ;
$sujet2 = "Copie : ".$sujet." [".$email_destinataire."]";
mail($email2,$sujet2,$texte,$headers);
echo "Votre demande a bien été enregistrée par nos services. Vous recevrez prochainement une réponse.<br/><br/>
Merci.";
}
else {echo "CAPTCHA incorrect";}
}
?>
<file_sep><?php
//$requete02 = mysql_query("SELECT * FROM pays_bloc WHERE Page = '$page' ORDER BY Position ASC ") ;
$requete02 = $pdo->prepare("SELECT * FROM pays_bloc WHERE Page = ? ORDER BY Position ASC ");
$requete02->execute(array($page));
$lignes02 = $requete02->fetchAll(PDO::FETCH_CLASS);
foreach ($lignes02 as $ligne02) {
$bloc = $ligne02->Numero ;
$position_bloc = $ligne02->Position ;
$type_bloc = $ligne02->Type ;
if ($type_bloc == '1') {
echo "
<table width=666 border=0 cellspacing=0 cellpadding=0>
<tr>
<td width=666 align=center>";
$position = "1";
$action = "ajout";
include('sousbloc.php');
echo "
</td>
</tr>
</table><br/>";
}
/************** 2 COLONNES *******************/
elseif ($type_bloc == '2') {
echo "
<table width=666 border=0 cellspacing=0 cellpadding=0>
<tr>
<td width=333 align=center>";
$position = "1";
$action = "ajout";
include('sousbloc.php');
echo "
</td>
<td width=333 align=center>";
$position = "2";
$action = "ajout";
include('sousbloc.php');
echo "
</td>
</tr>
</table><br/>";
}
/********************* 3 COLONNES *******************/
else {
echo "
<table width=666 border=0 cellspacing=0 cellpadding=0>
<tr>
<td width=222 align=center>";
$position = "1";
$action = "ajout";
include('sousbloc.php');
echo "
</td>
<td width=222 align=center>";
$position = "2";
$action = "ajout";
include('sousbloc.php');
echo "
</td>
<td width=222 align=center>";
$position = "3";
$action = "ajout";
include('sousbloc.php');
echo "
</td>
</tr>
</table><br/>";
}
}
?>
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Agenda du Pays de Château-Gontier | Demande</title>
<?php
include('../pays/acces/connect.php');
$connect;
$base;
if (isset($_POST['IdRefus'])) {
$IdRefus = $_POST['IdRefus'];
$Refus = $_POST['Refus'];
$requeteRefus = mysql_query("SELECT * FROM `chateaugrchio`.`pays_agenda` WHERE Numero = '$IdRefus' LIMIT 1 ") ;
while ($ligneRefus=mysql_fetch_object($requeteRefus)) {
$email_destinataire = $ligneRefus->Courriel2 ;
$Titre = $ligneRefus->Titre ;
}
$sujet = 'Agenda Pays - Refus';
$texte = "Bonjour,<br/><br/>";
$texte .= "votre demande de mise en ligne de l'�v�nement suivant <i>".$Titre."</i> a �t� rejet�e.<br/><br/>";
$texte .= "Motif du refus :<br/><br/>".$Refus." ";
$headers ='From: "Pays de Ch�teau-Gontier"<<EMAIL>>'."\n";
$headers .='Return-Path: <EMAIL>'."\n";
$headers .='Reply-To: <EMAIL>'."\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .='Content-Transfer-Encoding: 8bit';
mail($email_destinataire,$sujet,$texte,$headers);
$Message = "Refus bien envoy� � ".$email_destinataire ;
}
?>
<style type="text/css">
body,td,th {
font-family: "Arial Black", Gadget, sans-serif;
font-size: 12px;
color: #000;
}
</style>
</head>
<body>
<table width="750" border="0" cellspacing="0" cellpadding="0">
<?php
if ($Message != '') {
echo "
<tr height=40 >
<td colspan=3 align=center bgcolor=#FF0000><font color=#FFFFFF >".$Message."</font></td>
</tr>
<tr>
<td align=right> </td>
<td> </td>
<td> </td>
</tr>";
}
?>
</table>
</body>
</html>
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">
<title>Pays de Château-gontier</title>
<?php
include('pays/acces/connect.php');
$connect;
$base;
?>
<link href="script/style.css" rel="stylesheet" type="text/css" />
<link href="script/contenu.css" rel="stylesheet" type="text/css" />
</head>
<body onload=imprimer() >
<div class="impression">
<?php
$page = $_GET['page'];
$page = htmlspecialchars($page, ENT_QUOTES, 'UTF-8');
$page = (int)$page;
include('pays/page/page.php');
?>
</div>
</body>
</html><file_sep><?php
$jour = date("d");
$mois = date("m");
$annee = date("Y");
$date_actuelle = $annee.$mois.$jour ;
$compteur = '1' ;
$requete = mysql_query("SELECT * FROM pays_page WHERE Accueil = '1' AND Type != '4' AND Archive = '0' ORDER BY Position DESC") ;
while ($ligne=mysql_fetch_object($requete)) {
$dateDebut = $ligne->Debut ;
$debut = explode("-", $dateDebut);
$debutAnnee = $debut[0];
$debutMois = $debut[1];
$debutJour = $debut[2];
$debut = $debutAnnee.$debutMois.$debutJour ;
$dateFin = $ligne->Fin ;
$fin = explode("-", $dateFin);
$finAnnee = $fin[0];
$finMois = $fin[1];
$finJour = $fin[2];
$fin = $finAnnee.$finMois.$finJour ;
$titre = $ligne->Titre ;
$photomini_accueil = $ligne->Photomini_accueil ;
if ($photomini_accueil == '') {
$photomini_accueil = "logo" ;
}
if ($debut <= $date_actuelle && $fin >= $date_actuelle ) {
echo "
<li><a href=# rel=nofollow title='".$titre."'><img src=../lib/images/photos/mini/".$photomini_accueil.".jpg alt=[Alternative text] /></a></li>
";
}
}
?><file_sep> <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Pays de Ch�teau-Gontier - Newsletter</title>
</head>
<body bgcolor="#FFFFFF">
<?php
include('acces/connect.php');
$connect;
$base;
$Lien = $_GET['lien'];
$Lien = htmlspecialchars($Lien, ENT_QUOTES, 'UTF-8');
$Id = $_GET['id'];
$Id = htmlspecialchars($Id, ENT_QUOTES, 'UTF-8');
$requete = mysql_query("SELECT * FROM newsletter_mail WHERE Numero = '$Id' LIMIT 1") ;
while ($ligne=mysql_fetch_object($requete)) {
$Abonne = $ligne->Email." - ".$ligne->Numero ;
mysql_query("INSERT INTO `newsletter_liens` (`Abonne` , `Lien` , `Newsletter` ) VALUES ('$Abonne' , '$Lien' , '15');") ;
if ($Lien == '1') {
echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;URL='http://www.chateaugontier.fr/index.php?page=427'\">";
}
if ($Lien == '2') {
echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;URL='http://www.chateaugontier.fr/index.php?page=424'\">";
}
if ($Lien == '3') {
echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;URL='http://www.chateaugontier.fr/index.php?page=425'\">";
}
if ($Lien == '4') {
echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;URL='http://www.chateaugontier.fr/index.php?page=425'\">";
}
if ($Lien == '5') {
echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;URL='http://www.chateaugontier.fr/index.php?page=427'\">";
}
if ($Lien == '6') {
echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;URL='http://www.chateaugontier.fr/index.php?agenda'\">";
}
if ($Lien == '7') {
echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;URL='http://www.facebook.fr/chateaugontier.pays'\">";
}
}
?>
</body>
</html><file_sep>
<?php
if (isset($_GET['page'])) {
$TypePage = 'page' ;
}
elseif (isset($_GET['envoi_ami'])) {
$TypePage = 'ami' ;
}
elseif (isset($_GET['carte'])) {
$TypePage = 'carte' ;
}
elseif (isset($_GET['contact'])) {
$TypePage = 'contact' ;
}
elseif (isset($_GET['newsletter'])) {
$TypePage = 'newsletter' ;
}
elseif (isset($_GET['plan'])) {
$TypePage = 'plan' ;
}
elseif (isset($_GET['rubrique'])) {
$TypePage = 'rubrique' ;
}
elseif (isset($_POST['rechercher'])) {
$TypePage = 'rechercher' ;
}
elseif (isset($_GET['credit'])) {
$TypePage = 'credit' ;
}
elseif (isset($_GET['agenda'])) {
$TypePage = 'agenda' ;
}
else {
$TypePage = 'accueil' ;
if($_SERVER['REQUEST_URI'] != "/" ){
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit();
}
}
?>
<file_sep><?php
$CompteurBandeaux = "0" ;
$requete = mysql_query("SELECT * FROM pays_bandeaux WHERE Categorie = '$bandeau' ORDER BY Numero ASC") ;
while ($ligne=mysql_fetch_object($requete)) {
$CompteurBandeaux++;
}
$BandeauPage = rand('1',$CompteurBandeaux);
$CompteurBandeaux = "0" ;
$requete2 = mysql_query("SELECT * FROM pays_bandeaux WHERE Categorie = '$bandeau' ORDER BY Numero ASC") ;
while ($ligne2=mysql_fetch_object($requete2)) {
$CompteurBandeaux++;
if ($CompteurBandeaux == $BandeauPage) {
echo $ligne2->Nom ;
}
}
?><file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Agenda du Pays de Château-Gontier | Demande</title>
<?php
include('../pays/acces/connect.php');
$connect;
$base;
if (isset($_POST['commune'])) {
$Commune = $_POST['commune'];
$Titre = $_POST['titre'];
$Date = $_POST['date'];
$Lieu = $_POST['lieu'];
$Texte = $_POST['texte'];
$Telephone = $_POST['telephone'];
$Courriel1 = $_POST['courriel1'];
$Site = $_POST['site'];
$Courriel2 = $_POST['courriel2'];
$Controle = $_POST['controle'];
$Controle2 = $_POST['controle2'];
//$requeteMax = mysql_query("SELECT MAX(Numero) AS Maximum FROM `chateaugrchio`.`pays_agenda` ") ;
$requeteMax = $pdo->prepare("SELECT MAX(Numero) AS Maximum FROM `chateaugrchio`.`pays_agenda` ");
$requeteMax->execute(array($Id));
$lignesMax = $requeteMax->fetchAll(PDO::FETCH_CLASS);
foreach ($lignesMax as $ligneMax) {
$Numero = $ligneMax->Maximum + 1 ;
}
if ($Controle == $Controle2) {
mysql_query("INSERT INTO `chateaugrchio`.`pays_agenda` (`Numero`, `Commune`, `Titre`, `Date`, `Lieu`, `Texte`, `Telephone`, `Courriel1`, `Site`, `Courriel2`, `Debut`, `Fin`) VALUES ('$Numero', '$Commune', '$Titre', '$Date', '$Lieu', '$Texte', '$Telephone', '$Courriel1', '$Site', '$Courriel2', '', '')");
$insertQuery = $pdo->prepare("INSERT INTO `chateaugrchio`.`pays_agenda` (`Numero`, `Commune`, `Titre`, `Date`, `Lieu`, `Texte`, `Telephone`, `Courriel1`, `Site`, `Courriel2`, `Debut`, `Fin`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '', '')");
$requeteMax->execute(array($Numero, $Commune, $Titre, $Date, $Lieu, $Texte, $Telephone, $Courriel1, $Site, $Courriel2));
$sujet = 'Agenda Pays - demande';
$email_destinataire = '<EMAIL>';
$texte = "Bonjour,<br/><br/>";
$texte .= "une nouvelle entr�e dans l'agenda est demand�e par la commune de ".$Commune." :<br/><br/>";
$texte .= "Pour la voir cliquez sur le <a href=http://www.chateaugontier.fr/test/agenda-pays-demande.php?Id=".$Numero.">lien suivant</a>";
$headers ='From: "Pays de Ch�teau-Gontier"<<EMAIL>>'."\n";
$headers .='Return-Path: <EMAIL>'."\n";
$headers .='Reply-To: '.$email.''."\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .='Content-Transfer-Encoding: 8bit';
mail($email_destinataire,$sujet,$texte,$headers);
$Message = "Votre demande a bien �t� envoy�e." ;
}
else {
$Message = "Le contr�le anti-spam n'est pas correct.<br/><br/><input type=button name=lien1 value=Retour onclick='history.go(-1)'>" ;
}
}
?>
<style type="text/css">
body,td,th {
font-family: "Arial Black", Gadget, sans-serif;
font-size: 12px;
color: #000;
}
</style>
</head>
<body>
<table width="750" border="0" cellspacing="0" cellpadding="0">
<?php
if ($Message != '') {
echo "
<tr height=80 >
<td colspan=3 align=center bgcolor=#FF0000><font color=#FFFFFF >".$Message."</font></td>
</tr>
<tr>
<td align=right> </td>
<td> </td>
<td> </td>
</tr>";
}
?>
</table>
</body>
</html>
<file_sep><!---------------------------->
<!-- SCRIPT TEXTE DES LIENS -->
<!---------------------------->
<style type="text/css">
.popperlink { POSITION: absolute; VISIBILITY: hidden }
</style>
<DIV class=popperlink id=topdecklink></DIV>
<script type="text/javascript" src="./pays/script/cadre_lien.js"></script>
<!------------------------------>
<!------------------------------>
<?php
$requete01 = $pdo->prepare("SELECT * FROM pays_page WHERE Numero = ?");
$requete01->execute(array($page));
$lignes01 = $requete01->fetchAll(PDO::FETCH_CLASS);
foreach ($lignes01 as $ligne01) {
$titre = $ligne01->Titre ;
$rubrique = $ligne01->Rubrique ;
}
echo "
<p class=titre_".$rubrique."><img src=pays/image/fleche_".$rubrique.".gif /> ".$titre." <img src=pays/image/fin_titre_".$rubrique.".gif /></p>
";
include('pays/page/bloc.php') ;
if (isset($_GET['impression'])) {
}
else {
echo "
<div class=outils>
<a target=_blank href=imprimer.php?impression&page=".$page." onMouseOver=\"poplink('Imprimer cet article');\" onmouseout=\"killlink()\" ><img alt='Imprimer cet article' border=0 src=pays/image/picto_imprimer.gif /></a>
<a href=index.php?page=".$page."&ami onMouseOver=\"poplink('Recommander cet article à un ami');\" onmouseout=\"killlink()\" ><img alt='Envoyer cet article � un ami' border=0 src=pays/image/picto_envoyer_ami.gif /></a>
</div>
";
}
?>
<file_sep>Vous rechercher le terme suivant :
<?php
$recherche = $_POST['rechercher'];
echo "<h2>".$recherche."</h2></br/>";
echo "Résultat(s) :<br/><br/>";
$compteur = '1' ;
$requete = mysql_query("SELECT * FROM pays_page ORDER BY Numero ASC ") ;
while ($ligne=mysql_fetch_object($requete)) {
$sortie = 'non';
$titre = $ligne->Titre ;
$page = $ligne->Numero ;
$requete1 = mysql_query("SELECT * FROM pays_bloc WHERE Page = '$page' ORDER By numero ASC ") ;
while ($ligne1=mysql_fetch_object($requete1)) {
$bloc = $ligne1->Numero ;
$requete2 = mysql_query("SELECT * FROM pays_sousbloc WHERE Type = '1' AND Texte LIKE '%$recherche%' AND Bloc = '$bloc' ") ;
while ($ligne2=mysql_fetch_object($requete2)) {
echo "- ".$compteur.". <a href=index.php?page=".$page.">".$titre."</a><br/><br/>";
$compteur++ ;
$sortie = 'oui' ;
break ;
}
if ($sortie == 'oui') {
break ;
}
}
}
?><file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Agenda du Pays de Château-Gontier | Demande</title>
<?php
include('../pays/acces/connect.php');
$connect;
$base;
if (isset($_POST['IdValidation'])) {
$IdValidation = $_POST['IdValidation'];
$Titre = $_POST['titre'];
$Date = $_POST['date'];
$Lieu = $_POST['lieu'];
$Texte = $_POST['texte'];
$Telephone = $_POST['telephone'];
$Courriel1 = $_POST['courriel1'];
$Site = $_POST['site'];
$Jour = $_POST['jour'];
$Mois = $_POST['mois'];
$Annee = $_POST['annee'];
$Fin = $Annee."-".$Mois."-".$Jour ;
mysql_query("UPDATE `chateaugrchio`.`pays_agenda` SET `Titre` = '$Titre', `Date` = '$Date', `Lieu` = '$Lieu',`Texte` = '$Texte', `Telephone` = '$Telephone', `Courriel1` = '$Courriel1', `Site` = '$Site', `Fin` = '$Fin' WHERE `pays_agenda`.`Numero` = '$IdValidation';");
$Message = "La validation de l'entrée d'agenda <i>".$Titre."</i> est effective." ;
}
?>
<style type="text/css">
body,td,th {
font-family: "Arial Black", Gadget, sans-serif;
font-size: 12px;
color: #000;
}
</style>
</head>
<body>
<table width="750" border="0" cellspacing="0" cellpadding="0">
<?php
if ($Message != '') {
echo "
<tr height=40 >
<td colspan=3 align=center bgcolor=#FF0000><font color=#FFFFFF >".$Message."</font></td>
</tr>
<tr>
<td align=right> </td>
<td> </td>
<td> </td>
</tr>";
}
?>
</table>
</body>
</html>
<file_sep><?php
if (isset($_GET['email'])) {
$email = $_GET['email'];
}
if (isset($_GET['inscription'])) {
if (isset($_GET['accord'])) {
mysql_query("INSERT INTO `newsletter_mail` ( `Email` ) VALUES ( '$email');");
echo "Votre demande a bien été enregistrée par nos services. Vous recevrez prochainement la newsletter.<br/><br/>
Merci.";
}
else {
echo "Pour valider votre inscription, veuillez cocher la case attestant que vous désirez bien recevoir la newsletter.<br/><br/>
Merci.<br/><br/>
<a href=index.php?page=154>Retour formulaire d'inscription</a>
";
}
}
elseif (isset($_GET['annulation'])) {
mysql_query("delete from newsletter_mail where Email = '$email'");
echo "Votre demande a bien été enregistrée par nos services. Vous ne recevrez plus la newsletter<br/><br/>
Merci.";
}
?>
<file_sep><?php
error_reporting(E_ALL);
//error_reporting(E_ALL ^ E_DEPRECATED);
ini_set('display_errors', 1);
ini_set('session.cookie_secure', '1');
ini_set('session.cookie_httponly', '1');
date_default_timezone_set("Europe/Berlin");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pays de Chateau-Gontier</title>
<meta name="robots" content="index, follow" />
<meta name="description" content="Bienvenue sur le site Internet de la Communaut� de communes du Pays de Chateau-Gontier. Mayenne (53)." />
<meta name="keywords" content="chateau-gontier, chateaugontier, chateau gontier, chateau, gontier, chateau-gontier, chateaugontier, chateau gontier, chateau, pays, communaute de communes, communauté, communauté de communes, communauté, mayenne, ampoigne, argenton, aze, bierne, chatelain, chemaze, coudray, daon, fromentieres, gennes, houssay, laigne, loigne, longuefuye, menil, maringe, origne, peuton, saint denis d'anjou, saint fort, saint laurent des mortiers, saint michel de feins, saint sulpice " />
<meta name="language" content="fr" />
<meta name="Author" content="Pays de Chateau-Gontier">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">
<?php
include('pays/acces/connect.php');
$connect;
$base;
include('pays/page/type_page.php');
/************* INTERSTICIEL *****************/
// include('intersticiel.php');
?>
<!------------------------------------------------------- --------------------------->
<link href="./pays/script/style.css" rel="stylesheet" type="text/css" />
<link href="./pays/script/menu.css" rel="stylesheet" type="text/css" />
<link href="./pays/script/contenu.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
<!--
function Menu_Reroutage(targ,selObj,restore){ //v3.0
eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
if (restore) selObj.selectedIndex=0;
}
//-->
</script>
<!---------- CODE GOOGLE ANALYTICS ----------->
<script src='https://www.google.com/recaptcha/api.js'></script>
<?php
require 'pays/page/recaptchalib.php';
$siteKey = '-'; // votre cl� publique
$secret = '-c'; // votre cl� priv�e
?>
</head>
<body>
<!-- CALQUE PAGE -->
<div class="page">
<?php
if (isset($_GET['page'])) {
$page = $_GET['page'];
$page = htmlspecialchars($page, ENT_QUOTES, 'UTF-8');
$page = intval($page);
$data = $pdo->prepare("SELECT * FROM pays_page WHERE Numero = ?");
$data->execute(array($page));
$lignes = $data->fetchAll(PDO::FETCH_CLASS);
foreach ($lignes as $ligne) {
$rubrique_bandeau = $ligne->Rubrique ;
$bandeau = $ligne->Bandeau ;
}
}
else {
$rubrique_bandeau = 1 ;
$bandeau = 1 ;
}
?>
<!-- CALQUE BANDEAU -->
<div style="width:1000px; height:200px; background-image: url(pays/bandeaux/<?php include('pays/page/bandeau.php') ; ?>.jpg);">
<!-- <NAME>TE-->
<div class="bandeau">
<!-- CALQUE RECHERCHE -->
<div class=recherche>
<form id="form_recherche" name="form_recherche" method="post" action="index.php">
<label class="recherche"><input class=recherche type="text" name="rechercher" value="Recherche ..." onFocus="this.value=''" /></label>
<a href="#" onClick = "document.forms.form_recherche.submit()"> <img src="pays/image/bouton_ok.png" border=0 /> </a>
</form>
</div>
<!-- FIN CALQUE RECHERCHE -->
<!-- CALQUE COMMUNES -->
<div class=communes>
<form id="form_communes" name="form_communes" method="post" action="#">
<select class=communes name="communes" id="communes" onchange="Menu_Reroutage('parent',this,1)">
<option value="#">Les 23 communes</option>
<?php
//$requete01 = mysql_query("SELECT * FROM pays_commune ORDER BY Nom ASC") ;
$requete01 = $pdo->prepare("SELECT * FROM pays_commune ORDER BY Nom ASC");
$requete01->execute();
$lignes01=$requete01->fetchAll(PDO::FETCH_CLASS);
foreach ($lignes01 as $ligne01) {
echo "<option value=index.php?page=".$ligne01->Page.">".$ligne01->Nom."</option>";
}
?>
</select>
</form>
</div>
<!-- FIN CALQUE COMMUNES -->
<a href=index.php><img src=pays/image/transparent.gif border=0 height=150 width=995 ></a>
</div>
<!-- FIN CALQUE BANDEAU -->
</div>
<!-- FIN CALQUE BANDEAU CHARTE -->
<!-- CALQUE MENUTOP1 -->
<div id="menutop1">
<!-- CALQUE MENU -->
<div id="menu">
<ul class="niveau1">
<?php
$compteur = "1" ;
$requete02 = $pdo->prepare("SELECT * FROM pays_rubrique ORDER BY Numero ASC");
$requete02->execute();
$lignes02 = $requete02->fetchAll(PDO::FETCH_CLASS);
//$requete02 = mysql_query("SELECT * FROM pays_rubrique ORDER BY Numero ASC") ;
foreach ($lignes02 as $ligne02 ) {
echo "<li class=sousmenu><a href=index.php?rubrique=".$ligne02->Numero."><br/><br/> </a>\n\n";
echo "<ul class=niveau2_".$compteur.">\n";
$rubrique = $ligne02->Numero ;
$page = intval($_GET['page']);
$requete03 = $pdo->prepare("SELECT * FROM pays_page WHERE Rubrique = ? AND Archive = '0' ORDER BY Position DESC");
$requete03->execute(array($page));
$lignes03 = $requete03->fetchAll(PDO::FETCH_CLASS);
//$requete03 = mysql_query("SELECT * FROM pays_page WHERE Rubrique = '$rubrique' AND Archive = '0' ORDER BY Position DESC") ;
foreach ($lignes03 as $ligne03) {
$menu = $ligne03->Menu ;
if ($menu == '1') {
if ($ligne03->Numero == '1') { // La page du territoire est redirigée vers la carte flash
echo "<li><a href=index.php?carte>".$ligne03->Titre."</a></li>\n";
}
/*elseif ($ligne03->Numero == '20') { // La page de la piscine est redirigée vers le site des sports
echo "<li><a href=http://www.chateaugontier.fr/sports/piscine/ >".$ligne03->Titre."</a></li>\n";
}
elseif ($ligne03->Numero == '21') { // La page des animations sportives est redirigée vers le site des sports
echo "<li><a href=http://www.chateaugontier.fr/sports>".$ligne03->Titre."</a></li>\n";
}*/
else {
echo "<li><a href=index.php?page=".$ligne03->Numero.">".$ligne03->Titre."</a></li>\n";
}
}
}
echo "</ul>\n";
echo "</li>\n\n";
$compteur++ ;
}
?>
</ul>
</div>
<!-- FIN CALQUE MENU -->
</div>
<!-- FIN CALQUE MENUTOP1 -->
<!-- CALQUE CENTRE (GAUCHE ET CONTENU) -->
<div class="centre">
<!-- CALQUE GAUCHE (EDITO , AGENDA et CARTE)-->
<div class="gauche">
<!-- CALQUE RETOUR ACCUEIL -->
<?php
if ($TypePage != 'accueil') {
echo "<div style=\"margin-top: 10px;\">";
echo "<a href=index.php><img src=pays/image/retour_accueil.png border=0 ></a>";
echo "</div>";
}
?>
<!-- FIN CALQUE RETOUR ACCUEIL -->
<!-- CALQUE EDITO (EDITO_VIDE ET EDITO_TEXTE) -->
<div class="edito">
<!-- CALQUE EDITO_VIDE -->
<div class="edito_vide">
</div>
<!-- FIN CALQUE EDITO_VIDE -->
<!-- CALQUE EDITO_TEXTE -->
<div class="edito_texte">
<?php
include('pays/page/agenda-accueil.php');
?>
</div>
<!-- FIN CALQUE EDITO_TEXTE -->
</div>
<!-- FIN CALQUE EDITO -->
<!-- FIN CALQUE AGENDA -->
<!-- CALQUE CARTE -->
<!--<div class="carte">
<A HREF=index.php?carte><IMG SRC=pays/image/vide.png WIDTH=298 HEIGHT=78 BORDER=0></A>
</div> -->
<!-- FIN CALQUE CARTE -->
<!-- CALQUE LIENS CARTOUCHE -->
<?php
if ($TypePage != 'accueil') {
echo "
<div class=liensCartouche>
<li class=liens><a class=menutop href=index.php?page=32 />Publications</a></li><br/>
<li class=liens><a class=menutop href=index.php?page=33 />Marchés publics</a></li><br/>
<li class=liens><a class=menutop href=http://emploi.chateaugontier.fr target=_blank />Offres d'emploi</a></li><br/>
<li class=liens><a class=menutop href=index.php?plan>Plan du site</a></li><br/>
<li class=liens><a class=menutop href=index.php?page=35 />Liens</a></li><br/>
<li class=liens><a class=menutop href=index.php?page=36 />Contact</a></li>
</div>";
}
?>
<!-- FIN CALQUE LIENS -->
</div>
<!-- FIN CALQUE GAUCHE -->
<!-- CALQUE CONTENU -->
<div class="contenu">
<?php
include('pays/page/contenu.php');
?>
</div>
<!-- FIN CALQUE CONTENU -->
</div>
<!-- FIN CALQUE CENTRE -->
<!-- CALQUE LIENS -->
<?php
if ($TypePage == 'accueil') {
echo "
<div class=liens>
<a class=menutop href=index.php?page=32 />Publications</a>
<a class=menutop href=index.php?page=33 />Marchés publics</a>
<a class=menutop href=http://emploi.chateaugontier.fr target=_blank />Offres d'emploi</a>
<a class=menutop href=index.php?plan>Plan du site</a>
<a class=menutop href=index.php?page=35 />Liens</a>
<a class=menutop href=index.php?page=36 />Contact</a>
</div>";
}
?>
<!-- FIN CALQUE LIENS -->
<!-- CALQUE BAS -->
<div class="bas">
<?php
if ($TypePage == 'accueil') {
echo "<div style=\"witdh:1000px; height: 200px; \">";
}
else {
echo " ";
echo "<div style=\"witdh:1000px; height: 200px; margin-top: 10px\">";
}
include('pays/page/liens.php');
echo "</div>";
?>
<div class="copyright">
© CCPCG - <a href=index.php?credit>Mentions légales</a>
</div>
</div>
<!-- FIN CALQUE BAS -->
</div>
<!-- FIN CALQUE PAGE -->
<?php
/*mysql_close() ;*/
?>
</body>
</html>
| d5c8706a12d2451a676bc935c9c70fb7b94fcccb | [
"JavaScript",
"PHP"
] | 26 | PHP | brehboyy/SiteChateaugontier | 88d9e68e6bcc019da710fd808559d2bfbc9274df | 4fb210f08da884c6855102c4daf616a3042938e4 |
refs/heads/master | <repo_name>felipe-brito/cdt-test<file_sep>/jtest/src/main/java/br/com/sgt/enums/ChavesMapas.java
package br.com.sgt.enums;
/**
*
* @author <NAME>
*/
public enum ChavesMapas {
REQUEST,
HEADERS,
CANCELADO
}
<file_sep>/README.md
# cdt-test
Ferramenta para teste de desempenho em aplicações WEB.
## SwingX
Intalando e configurando o SwingX no projeto
1. Adicione a seguinte dependência:
'''
<dependency>
<groupId>org.swinglabs</groupId>
<artifactId>swingx-core</artifactId>
<version>1.6.2-2</version>
</dependency>
'''
2. Utilizando a ferramenta Netbeans, abra o menu Ferramentas -> Paleta -> Componentes Swing/AWT
3. Crie uma nova categoria
4. Clique no botão **Adicionar do JAR**
5. Localize a para da dependência no repositório maven local abra o JAR swingx-core-**.jar
6. Selecione todos os arquivos com a inicial **JX**.<file_sep>/jtest/src/main/java/br/com/sgt/gui/TelaPrincipalUI.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.sgt.gui;
import java.awt.event.WindowEvent;
import java.util.EventObject;
import javax.inject.Inject;
import javax.swing.JOptionPane;
import static javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE;
/**
*
* @author <NAME> <<EMAIL>>
*/
public class TelaPrincipalUI extends javax.swing.JFrame {
@Inject
private TelaPlanoTestePIERUI planoTesteUI;
/**
* Creates new form InicioUI
*/
public TelaPrincipalUI() {
initComponents();
initiView();
}
public void init(){
this.setVisible(Boolean.TRUE);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jToolBar1 = new javax.swing.JToolBar();
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
barraStatus = new org.jdesktop.swingx.JXStatusBar();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
menuTeste = new javax.swing.JMenu();
menuItemTesteAmbiente = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jToolBar1.setRollover(true);
jScrollPane1.setBackground(new java.awt.Color(255, 255, 255));
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 649, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
barraStatus.setBackground(new java.awt.Color(204, 204, 204));
jMenu1.setMnemonic('a');
jMenu1.setText("Arquivo");
jMenuBar1.add(jMenu1);
menuTeste.setMnemonic('t');
menuTeste.setText("Teste");
menuItemTesteAmbiente.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
menuItemTesteAmbiente.setMnemonic('a');
menuItemTesteAmbiente.setActionCommand("testrAmbiente");
menuItemTesteAmbiente.setLabel("Ambiente");
menuItemTesteAmbiente.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItemTesteAmbienteActionPerformed(evt);
}
});
menuTeste.add(menuItemTesteAmbiente);
jMenuBar1.add(menuTeste);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 293, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(barraStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(barraStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
sair(evt);
}//GEN-LAST:event_formWindowClosing
private void menuItemTesteAmbienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemTesteAmbienteActionPerformed
planoTesteUI.init();
}//GEN-LAST:event_menuItemTesteAmbienteActionPerformed
private void initiView() {
this.setTitle("Painel principal");
this.setExtendedState(MAXIMIZED_BOTH);
}
private void sair(EventObject evt) {
int op = JOptionPane.showConfirmDialog(this, "Deseja sair do sistem?", "Sair", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
if (op == JOptionPane.YES_OPTION) {
this.dispose();
System.exit(0);
} else if (evt instanceof WindowEvent) {
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private org.jdesktop.swingx.JXStatusBar barraStatus;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JToolBar jToolBar1;
private javax.swing.JMenuItem menuItemTesteAmbiente;
private javax.swing.JMenu menuTeste;
// End of variables declaration//GEN-END:variables
}
<file_sep>/jtest/src/main/java/br/com/sgt/agendador/AgendadorSingleton.java
package br.com.sgt.agendador;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.matchers.GroupMatcher;
/**
*
* @author <NAME> <<EMAIL>>
*/
@Singleton
public class AgendadorSingleton {
@Inject
private Scheduler scheduler;
// public static AgendadorSingleton getInstance() {
// return SchedulerServiceSingletonHolder.INSTANCE;
// }
//
// private static class SchedulerServiceSingletonHolder {
//
// private static final AgendadorSingleton INSTANCE = new AgendadorSingleton();
// }
public void agendar(AgendadorWrapper wrapper) {
try {
JobDetail jobDetail = getJobDetail(wrapper);
Trigger trigger = getTrigger(wrapper);
this.scheduler.scheduleJob(jobDetail, trigger);
} catch (SchedulerException ex) {
Logger.getLogger(AgendadorSingleton.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void iniciar() {
try {
this.scheduler.start();
} catch (SchedulerException ex) {
//lançar exceção personalizada
}
}
public void parar() {
try {
this.scheduler.shutdown();
} catch (SchedulerException ex) {
//lançar exceção personalizada
}
}
public void remover(String jobKey) {
try {
this.scheduler.deleteJob(JobKey.jobKey(jobKey));
} catch (SchedulerException ex) {
//lançar exceção personalizada
}
}
public void removerTodos() {
try {
this.scheduler.getTriggerKeys(GroupMatcher.anyTriggerGroup())
.stream()
.forEach((trigger) -> {
remover(trigger.getName());
});
} catch (SchedulerException ex) {
//lançar exceção personalizada
}
}
public void pausarTodos() {
try {
this.scheduler.pauseAll();
} catch (SchedulerException ex) {
//lançar exceção personalizada
}
}
public void pausar(String jobKey) {
try {
this.scheduler.pauseJob(JobKey.jobKey(jobKey));
} catch (SchedulerException ex) {
//lançar exceção personalizada
}
}
public void continuar(String jobKey) {
try {
this.scheduler.resumeJob(JobKey.jobKey(jobKey));
} catch (SchedulerException ex) {
//lançar exceção personalizada
}
}
public void continuarTodos() {
try {
this.scheduler.resumeAll();
} catch (SchedulerException ex) {
//lançar exceção personalizada
}
}
private JobDetail getJobDetail(AgendadorWrapper wrapper) {
return JobBuilder
.newJob(wrapper.getClasse())
.withIdentity(wrapper.getNomeAgendador())
.build();
}
private Trigger getTrigger(AgendadorWrapper wrapper) {
return TriggerBuilder
.newTrigger()
.withIdentity(wrapper.getNomeGatilho())
.withSchedule(CronScheduleBuilder.cronSchedule(wrapper.getExpressaoCron()))
.build();
}
}
<file_sep>/jtest/src/main/java/br/com/sgt/util/Cronometro.java
package br.com.sgt.util;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JLabel;
/**
*
* @author <NAME>
*/
public class Cronometro {
private Timer timer;
public void cronometro(JLabel labelCronometro) {
timer = new Timer();
TimerTask tarefa = new TimerTask() {
LocalTime dateTime = LocalTime.of(0, 0, 0);
@Override
public void run() {
try {
if (dateTime.getSecond() <= 60) {
dateTime = dateTime.plusSeconds(1);
}
labelCronometro.setText(dateTime.format(DateTimeFormatter.ISO_TIME));
} catch (Exception e) {
e.printStackTrace();
}
}
};
timer.scheduleAtFixedRate(tarefa, 0, 1000);
}
public void cancelar() {
timer.cancel();
}
}
<file_sep>/jtest/src/main/java/br/com/sgt/config/ConfigCDI.java
package br.com.sgt.config;
import br.com.sgt.application.Application;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
/**
*
* @author <NAME> <<EMAIL>>
* @date 13/12/2017
*
*/
public class ConfigCDI {
public void init() {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
Application application = container.select(Application.class).get();
application.run();
weld.shutdown();
}
}
<file_sep>/jtest/src/main/java/br/com/sgt/observer/ImportacaoListener.java
package br.com.sgt.observer;
/**
*
* @author <NAME>
*/
public interface ImportacaoListener {
/**
* Atualiza o ouvinte registra em alguma lista de observadores
*
* @param object
*/
public void update(Object object);
}
<file_sep>/jtest/src/main/java/br/com/sgt/util/Log.java
package br.com.sgt.util;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
*
* @author <NAME>
*/
public class Log {
private static final Logger LOGGER = LogManager.getLogger(Log.class);
public static void info(String msg){
LOGGER.info(msg);
}
public static void error(String msg){
LOGGER.error(msg);
}
}
<file_sep>/jtest/src/main/java/br/com/sgt/util/Random.java
package br.com.sgt.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
/**
*
* @author <NAME>
*/
public class Random {
/**
* Método gerador de uma String única aleatória.
* @return
*/
public static String getString() {
String codigo = UUID.randomUUID().toString();
String hash;
try {
MessageDigest algorithm = MessageDigest.getInstance("MD5");
byte[] message = algorithm.digest(codigo.getBytes("UTF-8"));
StringBuilder hex = new StringBuilder();
for (byte b : message) {
hex.append(String.format("%02X", 0xFF & b));
}
hash = hex.toString();
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
ex.printStackTrace();
return "";
}
return hash;
}
}
<file_sep>/jtest/src/main/java/br/com/sgt/controller/ImportacaoResponse.java
package br.com.sgt.controller;
import br.com.sgt.enums.StatusBarraProgresso;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
*
* @author <NAME>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ImportacaoResponse implements Serializable{
private Integer totalImportacoes;
private Integer valorImportacoesSucesso;
private Integer valorImportacoesErro;
private Integer valorProgresso;
private StatusBarraProgresso statusBarraProgresso;
}
<file_sep>/jtest/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>br.com</groupId>
<artifactId>sgt</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz-jobs -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.8.0-beta0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.8.0-beta0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.10.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.10.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.5.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.1-b04</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/it.netgrid.got/alfred -->
<dependency>
<groupId>it.netgrid.got</groupId>
<artifactId>alfred</artifactId>
<version>0.0.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.weld.se/weld-se-core -->
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
<version>3.0.2.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.weld.se/weld-se -->
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se</artifactId>
<version>3.0.0.Alpha1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.swinglabs/swingx-core -->
<dependency>
<groupId>org.swinglabs</groupId>
<artifactId>swingx-core</artifactId>
<version>1.6.2-2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.yaml/snakeyaml -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.19</version>
</dependency>
</dependencies>
</project><file_sep>/jtest/src/main/java/br/com/sgt/enums/MensagensExceptionSGT.java
package br.com.sgt.enums;
/**
*
* @author <NAME>
*/
public enum MensagensExceptionSGT {
ERRO_LEITURA_ARQUIVO("Não foi possível realizar a leitura do arquivo. Causa: "),
LOG_TRACE_INVALIDO("Estrutura do arquivo de log não está em conformidade com o padrão esperado, verifique a estrutura do arquivo.");
private final String erro;
MensagensExceptionSGT(String erro){
this.erro = erro;
}
public String getErro(){
return this.erro;
}
}
<file_sep>/jtest/src/main/java/br/com/sgt/fabrica/ConfigFactory.java
package br.com.sgt.fabrica;
import br.com.sgt.util.Propriedades;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import javax.enterprise.inject.Produces;
import javax.swing.JFileChooser;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
/**
*
* @author <NAME> <<EMAIL>>
* @date 14/12/2017
*
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ConfigFactory {
/**
* Produz instâncias de {@link Scheduler}
*
* @return
*/
@Produces
public Scheduler scheduler() {
try {
return new StdSchedulerFactory().getScheduler();
} catch (SchedulerException ex) {
//lançar exceção personalizada
}
return null;
}
/**
* Produz instâncias de {@link JFileChooser}
*
* @return
*/
@Produces
public JFileChooser producesJFileChooser() {
return new JFileChooser();
}
/**
* Produz uma instância da classe que contém as propriedades da aplicação,
* as propriedades ficam fora do contexto, assim evitando o build do projeto
* para que novas propriedades sejam carregadas.
*
* @return
*/
@Produces
public Propriedades producesSGTProperties() {
try {
//ajustar para leitura fora do contexto da aplicação
List<String> json = Files.readAllLines(Paths.get(getClass().getResource("/properties/propriedades.json").toURI()));
StringBuilder sb = new StringBuilder();
json.forEach((str) -> {
sb.append(str);
});
return new Gson().fromJson(sb.toString(), Propriedades.class);
} catch (IOException | URISyntaxException ex) {
return null;
}
}
}
<file_sep>/jtest/src/main/java/br/com/sgt/application/Application.java
package br.com.sgt.application;
import br.com.sgt.gui.TelaPrincipalUI;
import javax.inject.Inject;
import org.apache.log4j.BasicConfigurator;
/**
*
* @author <NAME> <<EMAIL>>
* @date 13/12/2017
*
*/
public class Application {
@Inject
private TelaPrincipalUI inicioUI;
public void run() {
BasicConfigurator.configure();
inicioUI.init();
}
}
<file_sep>/jtest/src/main/java/br/com/sgt/SchedulerTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.sgt;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
*
* @author <NAME> <<EMAIL>>
* @date 13/12/2017
*
*/
public class SchedulerTest implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println(context.getTrigger().getJobKey().getName());
}
}
<file_sep>/jtest/src/main/java/br/com/sgt/entidades/Cabecalho.java
package br.com.sgt.entidades;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
* @author <NAME>
*/
@Data
@EqualsAndHashCode(of = {"descricao"})
public class Cabecalho {
private String descricao;
private Boolean selecionado;
public Cabecalho(){
selecionado = Boolean.TRUE;
}
public Cabecalho(String descricao){
this.selecionado = Boolean.TRUE;
this.descricao = descricao;
}
}
| c9379f236c76d519971d2689c452efe5d6abb3fb | [
"Markdown",
"Java",
"Maven POM"
] | 16 | Java | felipe-brito/cdt-test | ef92373788aa1bbd87895eb51fa60dba72de9720 | f1622a0c7a49c11f195e684487455c10ad10d67d |
refs/heads/master | <file_sep>import { useContext } from "react"
import { Dialog } from "./context"
export function useDialog() {
return useContext(Dialog)
}
<file_sep>export { default } from "./context"
export { useDialog } from "./hooks"
export { DefaultLayout } from "./layout"
export { LayoutProps } from "./types"
<file_sep># react-async-dialog
Yes, you can do `await dialog.alert(<YourComponent />)` out of the box!
```
npm install react-async-dialog
```
```
yarn add react-async-dialog
```

### Why?
[React](https://github.com/facebook/react) provides a first-class way to use [Portals](https://reactjs.org/docs/portals.html), which makes modals easy to create.
But sometimes, you want a modal window that interferes your event handlers.
```jsx
if (
await dialog.confirm(
<>
Are you <strong>REALLY</strong> sure?
</>
)
) {
console.log("Ok, you are so sure!")
}
```
This library gives you this behavior out of the box!
### How to use
```jsx
import { DialogProvider, useDialog } from "react-async-dialog"
function YourApp({ save }) {
const dialog = useDialog()
const onSave = async e => {
e.preventDefault()
const ok = await dialog.confirm(<strong>Are you sure???</strong>, {
ok: "YES!!!"
})
if (!ok) {
return
}
save()
}
return <button onClick={onSave}>SAVE ME</button>
}
ReactDOM.render(
<DialogProvider>
<YourApp save={api.save} />
</DialogProvider>,
root
)
```
### Polyfills
`react-async-dialog` requires `Promise`.
<file_sep>export interface AnyEvent {
preventDefault(): void
}
export interface LayoutProps {
labels: { ok: string; cancel?: string }
children: React.ReactNode
onOk(e: AnyEvent): void
onCancel?: (e: AnyEvent) => void
}
| a62daaae25591b75dbd08cffabfaa626c0b15487 | [
"Markdown",
"TypeScript"
] | 4 | TypeScript | fsubal/react-async-dialog | bcc2c3116d8a2500f9615e1d9c9155b6001d922d | 4b97418a15b5e78ed9e49014b59ddd6763479842 |
refs/heads/master | <file_sep>const express = require('express');
const app = express();
const mongoose = require('mongoose');
const session = require('session');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//mongoose.connect('mongodb://localhost/arexa');
//const song_controller = require('./api/song_controller');
//app.use("/songs", song_controller);
app.post("/initialize", function(req, res) {
res.send("Welcome to aRexa! Would you like to start a new session or resume from an existing session?");
});
app.post("/start", function(req, res) {
var info = new Object();
const body = req.body;
if (body.intent.name == "start_new") {
info.outputSpeech = "Where should we get started?";
res.send(JSON.stringify(info));
} else if (body.intent.name == "resume_existing") {
info.outputSpeech = "Which session should we resume?";
res.send(JSON.stringify(info));
} else {
info.outputSpeech = "I didn't understand that. Please try again.";
res.send(JSON.stringify(info));
}
});
app.post("/start_new", function(req, res) {
var info = new Object();
const body = req.body;
var new_sessionID = body.session.sessionID;
var new_session = new session({sessionID: new_sessionID});
if (body.intent.name == "new_song") {
var artist = body.intent.slots.Artist.value;
$.get("https://api.spotify.com/v1/search?q=" + artist + "&type=artist&limit=1", function(data){
var song = body.intent.slots.Song.value;
$
$.get("https://api.spotify.com/v1/recommendations?seed_artists")
})
} else if (body.intent.name == "new_artist") {
var artist = body.intent.slots.Artist.value;
} else if (body.intent.name == "new_genre") {
var genre = body.intent.slots.Genre.value;
} else {
info.outputSpeech = "I didn't understand that. Please try again.";
res.send(JSON.stringify(info));
}
});
app.listen(3000, () => {
console.log('The application is running on localhost 3000');
});<file_sep>const express = require('express');
const app = express();
const mongoose = require('mongoose');
//mongoose.connect('mongodb://localhost/arexa');
const song_controller = require('./api/song_controller');
app.use("/songs", song_controller);
const spotify_token = require('./api/oauth').headers.Authorization;
app.get("/", function(req, res) {
res.send("Suh dude");
});
app.listen(3000, () => {
console.log('The application is running on localhost 3000');
console.log(spotify_token);
});<file_sep># aRexa
An alexa skill for spotify reccomendations
## Startup steps
-> ./mongod
In separate terminal
-> npm install
-> node app.js<file_sep>const mongoose = require("mongoose")
const session = mongoose.Schema({
userId: string,
sessionId: string,
danceability: {min: number, max: number},
energy: {min: number, max: number},
key: {min: number, max: number},
loudness: {min: number, max: number},
mode: {min: number, max: number},
speechiness: {min: number, max: number},
acousticness: {min: number, max: number},
instrumentalness: {min: number, max: number},
liveness: {min: number, max: number},
valence: {min: number, max: number},
tempo: {min: number, max: number},
time_signature: {min: number, max: number}
});
module.exports = mongoose.model("Session", session); | ef15d8df0681710cb8813b770b21fc94df7b1663 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | epsteina16/aRexa | aabaf2210c708b16db6987d36594a4582da04c10 | b34d84a4adc640c510e1372eb39547f0919789d2 |
refs/heads/master | <file_sep>function scrollOnPageLoad() {
// to top right away
if (window.location.hash) scroll(0, 0);
// void some browsers issue
setTimeout(scroll(0, 0), 1);
var hashLink = window.location.hash;
if ($(hashLink).length) {
$(function () {
// *only* if we have anchor on the url
// smooth scroll to the anchor id
$('html, body').animate({
scrollTop: $(window.location.hash).offset().top - 77
}, 2000);
});
}
}
scrollOnPageLoad();
| bcbde8451ec0f3324d196773cd9c883d503bc290 | [
"JavaScript"
] | 1 | JavaScript | BirendraMaharjan/jquery.smooth-scroll-pageload.js | 1e6624d8dde8ac0fff143935facf64d54af9d349 | c914692591a347bd1f6682c02cd29a0aa80e39fd |
refs/heads/master | <file_sep>using Microsoft.AspNetCore.Mvc;
namespace Docker.Controllers
{
[ApiController]
[Route("[controller]")]
public class HelloWorldController : ControllerBase
{
[HttpGet("test")]
public string GetHello() => "Hello World";
}
}
| 8bb6367a57c99f022a06580d3e52adac22674e25 | [
"C#"
] | 1 | C# | FromNetCore/Docker | 9b678e0cdc29b07599593edbe55c86e4033cb241 | 0fa441379b4d056f4c0b16d01f8e0b7826c6d75b |
refs/heads/master | <repo_name>vladbel/geometry<file_sep>/src/shapes/CMakeLists.txt
# shall be defined in parent dir
# TARGET_LIB_SHAPES shapes
# BLOCK_SEPARATOR
#
message(${BLOCK_SEPARATOR})
message("CMake ${TARGET_LIB_SHAPES} library")
add_library(${TARGET_LIB_SHAPES}
STATIC
circle.cpp
circle.hpp
polygon.cpp
polygon.hpp
rhombus.cpp
rhombus.hpp
square.cpp
square.hpp
)
target_compile_options(${TARGET_LIB_SHAPES}
PRIVATE
${flags}
)
target_compile_features(${TARGET_LIB_SHAPES} PUBLIC cxx_std_17)
message(${BLOCK_SEPARATOR})<file_sep>/src/main-sort.cpp
#include "sort.hpp"
#include <cstdlib>
#include <iostream>
int main()
{
SortInterface* sort = new HeapSort();
sort->sort();
delete(sort);
}<file_sep>/src/sort/sort.hpp
#ifndef SORT_H
#define SORT_H
class SortInterface
{
private:
protected:
public:
SortInterface(){};
virtual ~SortInterface(){};
virtual void sort() = 0;
};
class HeapSort : public SortInterface
{
private:
protected:
public:
HeapSort();
~HeapSort();
void sort();
};
#endif<file_sep>/src/sort/CMakeLists.txt
# shall be defined in parent dir
# TARGET_LIB_SORT sort
# BLOCK_SEPARATOR
#
message(${BLOCK_SEPARATOR})
message("CMake ${TARGET_LIB_SORT} library")
add_library(${TARGET_LIB_SORT}
STATIC
heapSort.cpp
)
target_compile_options(${TARGET_LIB_SORT}
PRIVATE
${flags}
)
target_compile_features(${TARGET_LIB_SORT} PUBLIC cxx_std_17)
message(${BLOCK_SEPARATOR})<file_sep>/src/CMakeLists.txt
# set minimum cmake version
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
set(CMAKE_BUILD_TYPE Debug)
set(TARGET_MAIN_COMPUTE_AREAS compute-areas)
set(TARGET_LIB_SHAPES shapes)
set(TARGET_LIB_SORT sort)
set(TARGET_MAIN_SORT main-sort)
set(BLOCK_SEPARATOR "------------------------------------------")
message(${BLOCK_SEPARATOR})
# project name and language
project(geometry LANGUAGES CXX)
message("CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}")
message("CMAKE_CXX_COMPILER_VERSION = ${CMAKE_CXX_COMPILER_VERSION}")
message("Dependencies: ${TARGET_LIB_SHAPES}")
list(APPEND flags "-fPIC" "-Wall")
if(NOT WIN32)
list(APPEND flags "-Wextra" "-Wpedantic")
endif()
# ----------------------------------------------------
#
add_subdirectory(${TARGET_LIB_SHAPES})
add_executable(${TARGET_MAIN_COMPUTE_AREAS} compute-areas.cpp)
include_directories(${TARGET_MAIN_COMPUTE_AREAS}, ${TARGET_LIB_SHAPES})
target_compile_options(${TARGET_MAIN_COMPUTE_AREAS}
PRIVATE
"-fPIC"
)
target_compile_features(${TARGET_MAIN_COMPUTE_AREAS} PUBLIC cxx_std_17)
target_link_libraries(${TARGET_MAIN_COMPUTE_AREAS} ${TARGET_LIB_SHAPES})
#-------------------------------------------------------
# ----------------------------------------------------
#
add_subdirectory(${TARGET_LIB_SORT})
add_executable(${TARGET_MAIN_SORT} main-sort.cpp)
include_directories(${TARGET_MAIN_SORT}, ${TARGET_LIB_SORT})
target_compile_options(${TARGET_MAIN_SORT}
PRIVATE
"-fPIC"
)
target_compile_features(${TARGET_MAIN_SORT} PUBLIC cxx_std_17)
target_link_libraries(${TARGET_MAIN_SORT} ${TARGET_LIB_SORT})
#-------------------------------------------------------
message(${BLOCK_SEPARATOR})
<file_sep>/src/sort/heapSort.cpp
#include <cstdlib>
#include <iostream>
#include "sort.hpp"
HeapSort::HeapSort()
{
std::cout << "HeapSort::HeapSort()" << std::endl;
}
HeapSort::~HeapSort()
{
std::cout << "HeapSort::~HeapSort()" << std::endl;
}
void HeapSort::sort()
{
std::cout << "HeapSort::sort" << std::endl;
} | 0f3b4378af07ad823584d6fbbde0b87a05fb3b57 | [
"CMake",
"C++"
] | 6 | CMake | vladbel/geometry | a23e81bab42d613dd03b0c333410922aacd4e7be | 72a07fdffd529c6a49ff0d83aca87633a7aacc79 |
refs/heads/main | <file_sep>class Calculator {
firstvalue:any;
secondvalue:any;
finalvalue:any;
additionbtn:any;
subtractionbtn:any;
multiplicationbtn:any;
calculateValue:any;
sinValue:any;
cosValue:any;
tanValue:any;
constructor() {
this.firstvalue = document.getElementById("first") as HTMLInputElement;
this.secondvalue = document.getElementById("second") as HTMLInputElement;
this.finalvalue = document.getElementById("displayvalue") as HTMLSpanElement;
this.sinValue = document.getElementById("sinvalue") as HTMLSpanElement;
this.cosValue = document.getElementById("cosvalue") as HTMLSpanElement;
this.tanValue = document.getElementById("tanvalue") as HTMLSpanElement;
this.additionbtn = document.getElementById("addition");
this.additionbtn.addEventListener("click", (e:Event) => this.calculation('add'));
this.subtractionbtn = document.getElementById("subtraction");
this.subtractionbtn.addEventListener("click", (e:Event) => this.calculation('sub'));
this.multiplicationbtn = document.getElementById("multiplication");
this.multiplicationbtn.addEventListener("click", (e:Event) => this.calculation('multi'));
}
calculation(value:any){
let first_value : string = this.firstvalue.value;
let second_value : string = this.secondvalue.value;
if(value == 'add'){
this.calculateValue = parseInt(first_value) + parseInt(second_value);
}else if(value == 'sub'){
this.calculateValue = parseInt(first_value) - parseInt(second_value);
}else if(value == 'multi'){
this.calculateValue = parseInt(first_value) * parseInt(second_value);
}
this.Sin(this.calculateValue);
this.Cos(this.calculateValue);
this.Tan(this.calculateValue);
this.finalvalue.innerHTML = this.calculateValue.toString();
}
Sin(num: number) {
this.sinValue.innerText = "The sin value of " + num + " is -> " + Math.sin(num) + "\n";
}
Cos(num: number) {
this.cosValue.innerText = "The cos of " + num + " is -> " + Math.cos(num) + "\n";
}
Tan(num: number) {
this.tanValue.innerText = "The tan value of " + num + " is -> " + Math.tan(num);
}
}
// start the app
new Calculator(); | a01a2b8fd48cb74f1d4aa3ef746d8cc9752df3eb | [
"TypeScript"
] | 1 | TypeScript | riyasrkhan/Calculator | bebfb56d051d64dd09e0c4ff517e3348d1061fe3 | be5d055a86289d068a2b7c46a4700039d3eced46 |
refs/heads/main | <file_sep># Hack VM
A hack virtual machine interpreter written in Rust.
## Building
### Running tests:
```
cargo test
```
### Running performance benchmarks:
This code uses [Criterion](https://github.com/bheisler/criterion.rs) for running performance benchmarks. You can run the benchmarks with:
```
cargo bench
```
### Building to Web Assembly
To generate the npm package used by the website, run the following:
```
wasm-pack build
```
This will generate an npm package in the `pkg` directory, complete with the
compiled `.wasm` file, typescript type definitions, and wrapper js code for
instantiating and running the emulator from javascript.
<file_sep>use super::vmcommand::{Command, FunctionRef, InCodeFuncRef, Operation, Segment, VMProgram};
use std::collections::HashMap;
use std::convert::TryInto;
const RAM_SIZE: usize = 16384 + 8192 + 1;
#[derive(Debug)]
struct VMStackFrame {
local_segment: Vec<i32>,
stack_size: usize,
function: InCodeFuncRef,
index: usize,
num_args: usize,
}
impl VMStackFrame {
fn new(function: InCodeFuncRef, num_args: usize) -> VMStackFrame {
VMStackFrame {
local_segment: Vec::new(),
stack_size: 0,
function,
index: 0,
num_args,
}
}
}
struct VMProfileFuncStats {
num_calls: u64,
num_steps: u64,
}
struct VMProfiler {
function_stats: HashMap<FunctionRef, VMProfileFuncStats>,
}
impl VMProfiler {
pub fn new() -> VMProfiler {
VMProfiler {
function_stats: HashMap::new(),
}
}
fn add_function_stats(&mut self, func_ref: FunctionRef, func_stats: VMProfileFuncStats) {
match self.function_stats.get_mut(&func_ref) {
Some(stats) => {
stats.num_calls += func_stats.num_calls;
stats.num_steps += func_stats.num_steps;
}
None => {
self.function_stats.insert(func_ref, func_stats);
}
}
}
pub fn count_function_step(&mut self, func_ref: FunctionRef) {
self.add_function_stats(
func_ref,
VMProfileFuncStats {
num_calls: 0,
num_steps: 1,
},
);
}
pub fn count_function_call(&mut self, func_ref: FunctionRef) {
self.add_function_stats(
func_ref,
VMProfileFuncStats {
num_calls: 1,
num_steps: 0,
},
);
}
}
struct InternalFunction {
name: &'static str,
num_args: usize,
func: fn(&mut VMEmulator) -> Result<(), String>,
}
const INTERNALS: [InternalFunction; 2] = [
InternalFunction {
name: "Math.divide",
num_args: 2,
func: |vm: &mut VMEmulator| -> Result<(), String> {
let a = vm
.pop_stack()
.map_err(|e| format!("exec_internal failed: {}", e))?;
let b = vm
.pop_stack()
.map_err(|e| format!("exec_internal failed: {}", e))?;
vm.push_stack(b / a);
Ok(())
},
},
InternalFunction {
name: "Math.multiply",
num_args: 2,
func: |vm: &mut VMEmulator| -> Result<(), String> {
let a = vm
.pop_stack()
.map_err(|e| format!("exec_internal failed: {}", e))?;
let b = vm
.pop_stack()
.map_err(|e| format!("exec_internal failed: {}", e))?;
vm.push_stack(b * a);
Ok(())
},
},
];
pub struct VMEmulator {
program: VMProgram,
ram: [i32; RAM_SIZE],
call_stack: Vec<VMStackFrame>,
step_counter: usize,
profiler: VMProfiler,
}
const SP: usize = 0;
const LCL: usize = 1;
const ARG: usize = 2;
const THIS: usize = 3;
const THAT: usize = 4;
impl VMEmulator {
pub fn empty() -> VMEmulator {
VMEmulator {
program: VMProgram::empty(),
ram: [0; RAM_SIZE],
call_stack: Vec::new(),
step_counter: 0,
profiler: VMProfiler::new(),
}
}
pub fn new(program: VMProgram) -> VMEmulator {
VMEmulator {
program,
ram: [0; RAM_SIZE],
call_stack: Vec::new(),
step_counter: 0,
profiler: VMProfiler::new(),
}
}
fn frame_mut(&mut self) -> &mut VMStackFrame {
self.call_stack.last_mut().expect("call stack is empty")
}
fn frame(&self) -> &VMStackFrame {
self.call_stack.last().expect("call stack is empty")
}
pub fn ram(&self) -> &[i32] {
&self.ram
}
pub fn reset(&mut self) {
self.ram = [0; RAM_SIZE];
self.call_stack = Vec::new();
self.step_counter = 0;
self.init().unwrap();
}
pub fn set_ram(&mut self, address: usize, value: i32) -> Result<(), &'static str> {
if address < RAM_SIZE {
self.ram[address] = value;
return Ok(());
}
return Err("Address out of range");
}
pub fn get_ram_range(&self, start: usize, end: usize) -> &[i32] {
&self.ram[start..end]
}
fn get_global_stack_bounds(&self) -> (usize, usize) {
(256, self.ram[SP] as usize)
}
fn get_global_stack(&self) -> &[i32] {
let (start, end) = self.get_global_stack_bounds();
&self.ram[start..end]
}
fn get_global_stack_mut(&mut self) -> &mut [i32] {
let (start, end) = self.get_global_stack_bounds();
&mut self.ram[start..end]
}
fn push_global_stack(&mut self, value: i32) {
self.ram[SP] += 1;
if let Some(last) = self.get_global_stack_mut().last_mut() {
*last = value;
}
}
fn pop_global_stack(&mut self) -> Result<i32, String> {
if self.ram[SP] <= 256 {
return Err("Global stack is empty".to_string());
}
self.ram[SP] -= 1;
return Ok(self.ram[self.ram[SP] as usize]);
}
fn pop_stack(&mut self) -> Result<i32, String> {
if self.frame().stack_size > 0 {
self.frame_mut().stack_size -= 1;
return self.pop_global_stack();
}
return Err("local stack is empty".to_string());
}
fn push_stack(&mut self, value: i32) {
self.frame_mut().stack_size += 1;
self.push_global_stack(value);
}
/// get the function-scoped part of the global stack, which goes from the end
/// of the local segment to the global stack pointer.
fn get_stack(&self) -> &[i32] {
let (_local_start, local_end) = self.get_segment_bounds(Segment::Local);
let stack_pointer = self.ram[SP] as usize;
// in the event that the function locals haven't been initialized yet, i.e. immediately
// following a `call` instruction but before a `function` instruction,
// the function-scoped stack should be empty.
if stack_pointer < local_end {
return &[];
}
&self.ram[local_end..stack_pointer]
}
fn peek_stack(&self) -> i32 {
*self.get_stack().last().expect("Stack is empty")
}
fn get_segment_bounds(&self, segment: Segment) -> (usize, usize) {
match segment {
Segment::Static => {
let function = &self.frame().function;
let vmfile = self.program.get_file(function);
let start = 16 + vmfile.static_offset;
let end = start + vmfile.num_statics;
(start, end)
}
Segment::Pointer => (THIS, THAT + 1),
Segment::Temp => (5, 5 + 8),
Segment::This => (self.ram[THIS] as usize, self.ram.len()),
Segment::That => (self.ram[THAT] as usize, self.ram.len()),
Segment::Local => {
let start = self.ram[LCL] as usize;
let num_locals = self
.program
.get_vmfunction(&self.frame().function)
.num_locals;
let end = start + num_locals;
(start, end)
}
Segment::Argument => {
let start: usize = self.ram[ARG].try_into().unwrap();
let end = start + self.frame().num_args;
(start, end)
}
Segment::Constant => panic!("constant segment doesn't actually exist"),
}
}
fn get_segment(&self, segment: Segment) -> &[i32] {
let (start, end) = self.get_segment_bounds(segment);
&self.ram[start..end]
}
fn get_segment_mut(&mut self, segment: Segment) -> &mut [i32] {
let (start, end) = self.get_segment_bounds(segment);
&mut self.ram[start..end]
}
fn exec_push(&mut self, segment: Segment, index: u16) -> Result<(), String> {
// TODO: check boundaries
let value: i32 = match segment {
Segment::Constant => index as i32,
_ => self.get_segment(segment)[index as usize],
};
self.push_stack(value);
Ok(())
}
fn exec_pop(&mut self, segment: Segment, index: u16) -> Result<(), String> {
let value = self
.pop_stack()
.map_err(|e| format!("exec_pop failed: {}", e))?;
// TODO: check boundaries
self.get_segment_mut(segment)[index as usize] = value;
Ok(())
}
fn exec_copy_seg(
&mut self,
from_segment: Segment,
from_index: u16,
to_segment: Segment,
to_index: u16,
) -> Result<(), String> {
let value: i32 = match from_segment {
Segment::Constant => from_index as i32,
_ => self.get_segment(from_segment)[from_index as usize],
};
self.get_segment_mut(to_segment)[to_index as usize] = value;
Ok(())
}
pub fn get_internals() -> HashMap<&'static str, FunctionRef> {
let mut internals: HashMap<&'static str, FunctionRef> = HashMap::new();
for (i, ifunc) in INTERNALS.iter().enumerate() {
internals.insert(ifunc.name, FunctionRef::Internal(i));
}
internals
}
fn exec_call(&mut self, function_ref: InCodeFuncRef, num_args: usize) -> Result<(), String> {
self.push_stack((self.frame().index + 1) as i32); // return address
self.push_stack(self.ram[LCL]);
self.push_stack(self.ram[ARG]);
self.push_stack(self.ram[THIS]);
self.push_stack(self.ram[THAT]);
self.ram[ARG] = self.ram[SP] - 5 - num_args as i32;
self.ram[LCL] = self.ram[SP];
self.call_stack
.push(VMStackFrame::new(function_ref, num_args));
Ok(())
}
fn exec_return(&mut self) -> Result<(), String> {
let return_value = self.pop_stack()?;
let arg = self.ram[ARG];
self.ram[SP] = self.ram[LCL];
self.ram[THAT] = self.pop_global_stack()?;
self.ram[THIS] = self.pop_global_stack()?;
self.ram[ARG] = self.pop_global_stack()?;
self.ram[LCL] = self.pop_global_stack()?;
let _return_index = self.pop_global_stack()?;
self.ram[SP] = arg;
self.push_global_stack(return_value);
self.call_stack.pop();
self.frame_mut().index += 1;
Ok(())
}
pub fn init(&mut self) -> Result<(), String> {
self.ram[SP] = 256;
self.ram[LCL] = 256;
self.ram[ARG] = 256;
if let Some(init_func) = self.program.get_function_ref("Sys.init") {
self.call_stack.push(VMStackFrame::new(init_func, 0));
return Ok(());
}
return Err("No Sys.init function found".to_string());
}
fn exec_arithmetic(&mut self, op: Operation) -> Result<(), String> {
use Operation::*;
let result = match op {
Neg | Not => {
let a = self.pop_stack()?;
match op {
Neg => -a,
Not => !a,
_ => panic!("This should never happen"),
}
}
_ => {
let a = self.pop_stack()?;
let b = self.pop_stack()?;
match op {
Neg | Not => panic!("This should never happen"),
Add => b + a,
Sub => b - a,
And => b & a,
Or => b | a,
Eq => {
if b == a {
-1
} else {
0
}
}
Lt => {
if b < a {
-1
} else {
0
}
}
Gt => {
if b > a {
-1
} else {
0
}
}
}
}
};
self.push_stack(result);
Ok(())
}
fn next_command(&self) -> Option<&Command> {
if let Some(frame) = self.call_stack.last() {
Some(self.program.get_command(&frame.function, frame.index))
} else {
None
}
}
pub fn run(&mut self, max_steps: usize) -> Result<i32, String> {
self.init()?;
loop {
if let Some(result) = self.step()? {
return Ok(result);
}
if self.step_counter > max_steps {
return Err(format!(
"Program failed to finish within {} steps",
max_steps
));
}
}
}
pub fn profile_step(&mut self) {
self.profiler
.count_function_step(FunctionRef::InCode(self.frame().function));
if let Some(command) = self.next_command() {
let command = *command;
if let Command::Call(function_ref, _) = command {
self.profiler.count_function_call(function_ref.clone());
}
}
}
pub fn step(&mut self) -> Result<Option<i32>, String> {
self.step_counter += 1;
let command = self
.next_command()
.ok_or("No more commands to execute".to_string())?;
let command = *command;
match command {
// Function commands
Command::Function(_, num_locals) => {
for _ in 0..num_locals {
self.push_global_stack(0);
}
self.frame_mut().index += 1;
}
Command::Call(function_ref, num_args) => match function_ref {
FunctionRef::InCode(in_code_func_ref) => {
self.exec_call(in_code_func_ref, num_args as usize)
.map_err(|e| format!("failed step {:?}: {}", command, e))?;
}
FunctionRef::Internal(internal_index) => {
let internal_func = &INTERNALS[internal_index];
if internal_func.num_args != num_args as usize {
panic!("Wrong number of args passed to {}", internal_func.name);
}
(internal_func.func)(self)
.map_err(|e| format!("failed step {:?}: {}", command, e))?;
self.frame_mut().index += 1;
}
},
Command::Return => {
if self.call_stack.len() == 1 {
// There is nowhere left to return to,
// so assume this means returning a value
// from the entire program to whatever system
// might be running it.
return Ok(Some(self.peek_stack()));
}
self.exec_return()?;
}
// goto commands
Command::Goto(index) => {
self.frame_mut().index = index;
}
Command::If(index) => {
if self
.pop_stack()
.map_err(|e| format!("failed step {:?}: {} {}", command, e, self.debug()))?
== -1
{
self.frame_mut().index = index;
} else {
self.frame_mut().index += 1;
}
}
// stack commands
Command::Push(segment, index) => {
self.exec_push(segment, index)
.map_err(|e| format!("failed step {:?}: {}", command, e))?;
self.frame_mut().index += 1;
}
Command::Pop(segment, index) => {
self.exec_pop(segment, index)
.map_err(|e| format!("failed step {:?}: {}", command, e))?;
self.frame_mut().index += 1;
}
Command::CopySeg {
from_segment,
from_index,
to_segment,
to_index,
} => {
self.exec_copy_seg(from_segment, from_index, to_segment, to_index)
.map_err(|e| format!("failed step {:?}: {}", command, e))?;
self.frame_mut().index += 1;
}
// arithmetic commands
Command::Arithmetic(op) => {
self.exec_arithmetic(op)
.map_err(|e| format!("failed step {:?}: {}", command, e))?;
self.frame_mut().index += 1;
}
};
return Ok(None);
}
pub fn debug(&self) -> String {
use std::fmt::Write;
let mut s = String::new();
writeln!(&mut s, "Step: {}", self.step_counter).unwrap();
writeln!(&mut s, "Call Stack:").unwrap();
for frame in self.call_stack.iter() {
let func_name = self
.program
.get_function_name(&frame.function.to_function_ref())
.unwrap_or("Unknown Function");
writeln!(&mut s, " {}[{}]", func_name, &frame.index).unwrap();
}
writeln!(&mut s, "Function Stack: {:?}", self.get_stack()).unwrap();
let segments = [
Segment::Static,
Segment::Temp,
Segment::Local,
Segment::Argument,
Segment::Pointer,
];
for segment in segments.iter() {
writeln!(
&mut s,
"{:?} Segment: {:?}",
segment,
self.get_segment(*segment)
)
.unwrap();
}
if let Some(command) = self.next_command() {
writeln!(&mut s, "Next Command: {}", command.to_string(&self.program)).unwrap();
}
return s;
}
pub fn profiler_stats(&self) -> String {
let mut stats = self.profiler.function_stats.iter().collect::<Vec<_>>();
stats.sort_by_key(|(_func_ref, stats)| stats.num_steps);
let total_steps: u64 = stats.iter().map(|(_, stats)| stats.num_steps).sum();
let top = format!(
"{:<30} {:>10} {:>10} {:>10} {:>10}",
"function", "calls", "steps", "steps/call", "% steps"
);
let body = stats
.iter()
.map(|(func_ref, stats)| {
format!(
"{:.<30} {:>10} {:>10} {:>10} {:>10.2}%",
if let Some(name) = self.program.get_function_name(func_ref) {
name
} else {
"UNKNOWN_FUNC"
},
stats.num_calls,
stats.num_steps,
if stats.num_calls > 0 {
stats.num_steps / stats.num_calls
} else {
0
},
stats.num_steps as f64 / total_steps as f64 * 100.0
)
})
.collect::<Vec<_>>()
.join("\n");
format!("{}\n{}", top, body)
}
}
#[cfg(test)]
mod tests {
use super::*;
mod vmemulator {
use super::*;
mod global_stack {
use super::*;
fn setup_vm() -> VMEmulator {
let mut vm = VMEmulator::new(
VMProgram::new(&vec![(
"Sys.vm",
"
function Sys.init 0
return",
)])
.unwrap(),
);
vm.init().unwrap();
return vm;
}
#[test]
fn global_push() {
let mut vm = setup_vm();
assert_eq!(
vm.get_global_stack().len(),
0,
"global stack should initially be empty"
);
vm.push_global_stack(10);
assert_eq!(
vm.get_global_stack(),
&[10],
"global stack should contain pushed value"
);
assert_eq!(vm.ram[256], 10, "global stack should start at ram[256]");
vm.push_global_stack(20);
vm.push_global_stack(30);
assert_eq!(
vm.get_global_stack(),
&[10, 20, 30],
"global stack should contain pushed values"
);
}
#[test]
fn global_pop() {
let mut vm = setup_vm();
vm.ram[SP] = 258;
vm.ram[256] = 34;
vm.ram[257] = 120;
assert_eq!(vm.get_global_stack(), &[34, 120]);
assert_eq!(
vm.pop_global_stack(),
Ok(120),
"Popping should return the top value on the stack"
);
assert_eq!(
vm.get_global_stack(),
&[34],
"Popping should remove the top item on the stack"
);
assert_eq!(
vm.pop_global_stack(),
Ok(34),
"Popping should return the top value on the stack"
);
assert_eq!(vm.get_global_stack(), &[]);
assert!(
vm.pop_global_stack().is_err(),
"Popping off an empty stack should return an error"
);
}
}
mod segments {
use super::*;
fn setup_vm() -> VMEmulator {
let mut vm = VMEmulator::new(
VMProgram::new(&vec![
(
"Sys.vm",
"
function Sys.init 2
push constant 10
pop static 0
return",
),
(
"Main.vm",
"
function Main.main 3
push constant 30
pop static 4
return",
),
])
.unwrap(),
);
vm.init().unwrap();
return vm;
}
#[test]
fn static_segment() {
let mut vm = setup_vm();
assert_eq!(
vm.get_segment(Segment::Static),
&[0],
"Static segment should be initialized to 0s"
);
vm.step().unwrap();
vm.push_stack(10);
assert_eq!(vm.get_stack(), &[10]);
vm.exec_pop(Segment::Static, 0).unwrap();
assert_eq!(
vm.get_segment(Segment::Static),
&[10],
"Static segment should be written to with value popped from stack"
);
assert_eq!(vm.get_stack(), &[], "pop should always pop off the stack");
assert_eq!(vm.ram[16], 10, "static segment should be at ram[16]");
// call into another function...
vm.exec_call(vm.program.get_function_ref("Main.main").unwrap(), 0)
.unwrap();
assert_eq!(vm.get_segment(Segment::Static), &[0, 0, 0, 0, 0]);
vm.push_stack(25);
vm.exec_pop(Segment::Static, 3).unwrap();
assert_eq!(vm.get_segment(Segment::Static), &[0, 0, 0, 25, 0]);
assert_eq!(
vm.ram[16..(16 + 1 + 5)],
[10, 0, 0, 0, 25, 0],
"static segments should be stored contiguously in ram"
);
}
#[test]
fn temp_segment() {
let mut vm = setup_vm();
vm.push_stack(10);
vm.exec_pop(Segment::Temp, 0).unwrap();
vm.push_stack(20);
vm.exec_pop(Segment::Temp, 7).unwrap();
assert_eq!(
vm.ram[5..5 + 8],
[10, 0, 0, 0, 0, 0, 0, 20],
"Temp segment should be in ram[5..13]"
);
assert_eq!(vm.get_segment(Segment::Temp), &[10, 0, 0, 0, 0, 0, 0, 20]);
}
#[test]
fn pointer_segment() {
let mut vm = setup_vm();
assert_eq!(vm.get_segment(Segment::Pointer), &[0, 0]);
vm.push_stack(10);
vm.exec_pop(Segment::Pointer, 0).unwrap();
vm.push_stack(20);
vm.exec_pop(Segment::Pointer, 1).unwrap();
assert_eq!(
vm.ram[3..5],
[10, 20],
"pointer segment should be in ram[3..5]"
);
assert_eq!(vm.get_segment(Segment::Pointer), &[10, 20]);
}
#[test]
fn this_that_segment() {
let mut vm = setup_vm();
assert_eq!(vm.get_segment(Segment::Pointer), &[0, 0]);
assert_eq!(vm.get_segment(Segment::This), &vm.ram);
vm.ram[3000] = 10;
vm.ram[4000] = 25;
vm.get_segment_mut(Segment::Pointer)[0] = 3000;
vm.get_segment_mut(Segment::Pointer)[1] = 4000;
assert_eq!(vm.get_segment(Segment::This)[0], 10);
assert_eq!(vm.get_segment(Segment::That)[0], 25);
}
#[test]
fn local_segment() {
let mut vm = setup_vm();
vm.ram[1] = 270;
assert_eq!(vm.get_segment(Segment::Local), &[0, 0]);
vm.push_stack(5);
vm.exec_pop(Segment::Local, 0).unwrap();
vm.push_stack(25);
vm.exec_pop(Segment::Local, 1).unwrap();
assert_eq!(vm.get_segment(Segment::Local), &[5, 25]);
assert_eq!(
vm.ram[270..272],
[5, 25],
"Local segment should be located wherever ram[1] points to"
);
}
#[test]
fn argument_segment() {
let mut vm = setup_vm();
vm.exec_call(vm.program.get_function_ref("Main.main").unwrap(), 2)
.unwrap();
vm.ram[2] = 270;
vm.ram[270] = 13;
vm.ram[271] = 14;
assert_eq!(
vm.get_segment(Segment::Argument),
&[13, 14],
"Argument segment should be located wherever ram[2] points to"
);
}
}
mod functions {
use super::*;
fn setup_vm() -> VMEmulator {
let mut vm = VMEmulator::new(
VMProgram::new(&vec![
(
"Sys.vm",
"
function Sys.init 0
push constant 10
pop constant 20
call Main.add 2
return",
),
(
"Main.vm",
"
function Main.add 1
push argument 0
push argument 1
add
pop local 0
push local 0
return",
),
])
.unwrap(),
);
vm.init().unwrap();
return vm;
}
#[test]
fn function_calls() {
let mut vm = setup_vm();
for i in 0..100_usize {
// initialize ram with some garbage values to see how initialization works
vm.ram[vm.ram[SP] as usize + i] = 0xBAD;
}
vm.push_stack(2);
vm.push_stack(3);
vm.exec_call(vm.program.get_function_ref("Main.add").unwrap(), 2)
.unwrap();
assert_eq!(
vm.get_segment(Segment::Argument),
&[2, 3],
"After a call, argument segment should point to arguments from stack"
);
assert_eq!(vm.ram[ARG], 256, "Expected ARG register to be 256");
assert_eq!(vm.ram[SP], 256 + 5 + 2, "Expected SP register to be 263");
assert_eq!(
vm.ram[LCL], vm.ram[SP],
"Expected LCL register to be the same as SP register"
);
assert_eq!(vm.ram[256..258], [2, 3]);
assert_eq!(
vm.get_stack(),
&[],
"After a call, the local function stack should be empty"
);
assert_eq!(
vm.get_segment(Segment::Local),
&[0xBAD],
"After a call, the local segment should be whatever was in ram."
);
vm.step().unwrap();
assert_eq!(
vm.get_segment(Segment::Local),
&[0],
"After entering into function, local segment should be initialized to 0."
);
}
}
}
#[test]
fn test_vmemulator_run() {
let program = VMProgram::new(&vec![(
"Sys.vm",
"
function Sys.init 0
push constant 10
return
",
)])
.unwrap();
let mut vm = VMEmulator::new(program);
let result = vm.run(1000).expect("failed to run program");
assert_eq!(
result, 10,
"Expected program to end by returning 10. Got {}",
result
);
}
#[test]
fn test_math_divide() {
let program = VMProgram::with_internals(
&vec![(
"Sys.vm",
"
function Sys.init 0
push constant 10
push constant 2
call Math.divide 2
return
",
)],
Some(VMEmulator::get_internals()),
)
.unwrap();
let mut vm = VMEmulator::new(program);
let result = vm.run(1000).expect("failed to run program");
assert_eq!(
result, 5,
"Expected program to end by returning 5. Got {}",
result
);
}
#[test]
fn test_vmemulator_init() {
let program = VMProgram::new(&vec![(
"Sys.vm",
"
function Sys.init 0
push constant 10
pop static 0
label LOOP
call Sys.incr 0
pop temp 0
goto LOOP
return
function Sys.incr 0
push static 0
push constant 1
add
pop static 0
push static 0
return
",
)])
.unwrap();
let mut vm = VMEmulator::new(program);
assert_eq!(vm.init(), Ok(()));
// function Sys.init 0
vm.step().unwrap();
println!("step1: {}", vm.debug());
// push constant 10
// pop static 0
vm.step().unwrap();
println!("step2: {}", vm.debug());
assert_eq!(vm.get_stack().len(), 0);
assert_eq!(vm.get_segment(Segment::Static)[0], 10);
// call Sys.incr 0
vm.step().unwrap();
println!("{}", vm.debug());
// function Sys.incr 0
vm.step().unwrap();
println!("{}", vm.debug());
// push static 0
vm.step().unwrap();
println!("{}", vm.debug());
// push constant 1
vm.step().unwrap();
println!("{}", vm.debug());
// add
vm.step().unwrap();
println!("{}", vm.debug());
// pop static 0
vm.step().unwrap();
println!("{}", vm.debug());
// push static 0
vm.step().unwrap();
println!("{}", vm.debug());
// return
vm.step().unwrap();
println!("{}", vm.debug());
for _ in 0..100 {
vm.step().unwrap();
println!("{}", vm.debug());
}
}
}
<file_sep>export type FetchState = {
loading: boolean;
error: Response | null;
data: string;
url: string;
};
type RemoteFSSubscription = (s: FetchState) => void;
export default class RemoteFS {
private static instance: RemoteFS;
static get() {
if (!RemoteFS.instance) {
RemoteFS.instance = new RemoteFS();
}
return RemoteFS.instance;
}
private state: Record<string, FetchState> = {};
private subscribers: Record<string, RemoteFSSubscription[]> = {};
private constructor() {}
private notifySubscribers(url: string) {
const callbacks = this.subscribers[url] || [];
for (const callback of callbacks) {
callback({ ...this.state[url] });
}
}
subscribe(url: string, callback: RemoteFSSubscription) {
if (!this.subscribers[url]) {
this.subscribers[url] = [];
}
if (this.subscribers[url].indexOf(callback) === -1) {
this.subscribers[url].push(callback);
callback(this.state[url]);
}
}
unsubscribe(url: string, callback: RemoteFSSubscription) {
if (this.subscribers[url]) {
this.subscribers[url] = this.subscribers[url].filter(
(cb) => cb !== callback
);
}
}
addFile(url: string, callback?: RemoteFSSubscription) {
if (!this.state[url]) {
this.state[url] = { loading: true, error: null, url, data: "" };
fetch(url).then((res) => {
if (res.ok) {
res.text().then((data) => {
this.state[url] = { loading: false, error: null, url, data };
this.notifySubscribers(url);
});
} else {
this.state[url] = { loading: false, error: res, url, data: "" };
this.notifySubscribers(url);
}
});
}
if (callback) {
this.subscribe(url, callback);
}
return this.state[url];
}
async getFile(url: string): Promise<FetchState> {
return new Promise((resolve, reject) => {
const callback = (file: FetchState) => {
if (!file.loading) {
if (!file.error) {
resolve(file);
this.unsubscribe(url, callback);
} else {
reject(file);
this.unsubscribe(url, callback);
}
}
};
this.addFile(url, callback);
});
}
async getFiles(urls: string[]): Promise<FetchState[]> {
let files: FetchState[] = [];
for (const url of urls) {
const file = await this.getFile(url);
files.push(file);
}
return files;
}
}
<file_sep>#![allow(dead_code)]
mod vmcommand;
mod vmemulator;
mod vmparser;
use wasm_bindgen::prelude::*;
use web_sys::{CanvasRenderingContext2d, ImageData};
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
pub use vmcommand::VMProgram;
pub use vmemulator::VMEmulator;
#[wasm_bindgen]
pub fn init_panic_hook() {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function at least once during initialization, and then
// we will get better error messages if our code ever panics.
//
// For more details see
// https://github.com/rustwasm/console_error_panic_hook#readme
// #[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}
#[wasm_bindgen]
extern "C" {
// Use `js_namespace` here to bind `console.log(..)` instead of just
// `log(..)`
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
// The `console.log` is quite polymorphic, so we can bind it with multiple
// signatures. Note that we need to use `js_name` to ensure we always call
// `log` in JS.
#[wasm_bindgen(js_namespace = console, js_name = log)]
fn log_u32(a: u32);
// Multiple arguments too!
#[wasm_bindgen(js_namespace = console, js_name = log)]
fn log_many(a: &str, b: &str);
}
macro_rules! console_log {
// Note that this is using the `log` function imported above during
// `bare_bones`
($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
}
#[wasm_bindgen]
pub struct WebVM {
vm: VMEmulator,
files: Vec<(String, String)>,
}
#[wasm_bindgen]
impl WebVM {
pub fn new() -> WebVM {
WebVM {
vm: VMEmulator::empty(),
files: Vec::new(),
}
}
pub fn load_file(&mut self, name: &str, content: &str) {
self.files.push((name.to_string(), content.to_string()));
}
pub fn init(&mut self) -> Result<(), JsValue> {
let files: Vec<(&str, &str)> = self.files.iter().map(|(a, b)| (&a[..], &b[..])).collect();
let program = VMProgram::with_internals(&files, Some(VMEmulator::get_internals()))
.map_err(|e| format!("Failed to parse program: {}", e))?;
for warning in program.warnings.iter() {
console_log!("Warning: {}", warning);
}
let mut vm = VMEmulator::new(program);
vm.init()
.map_err(|e| format!("Failed to initialize program: {}", e))?;
self.vm = vm;
Ok(())
}
pub fn tick(&mut self, n: i32) -> Result<(), JsValue> {
for _ in 0..n {
match self.vm.step() {
Err(e) => return Err(JsValue::from(e)),
Ok(_) => {}
};
}
Ok(())
}
pub fn tick_profiled(&mut self, n: i32) -> Result<(), JsValue> {
for _ in 0..n {
self.vm.profile_step();
match self.vm.step() {
Err(e) => return Err(JsValue::from(e)),
Ok(_) => {}
};
}
Ok(())
}
pub fn set_keyboard(&mut self, key: u16) -> Result<(), JsValue> {
match self.vm.set_ram(24576, key as i32) {
Err(e) => Err(JsValue::from(e)),
Ok(_) => Ok(()),
}
}
pub fn get_ram(&mut self, address: usize) -> Option<i32> {
self.vm.ram().get(address).copied()
}
pub fn reset(&mut self) {
self.vm.reset();
}
pub fn draw_screen(&mut self, ctx: &CanvasRenderingContext2d) -> Result<(), JsValue> {
let start = 16384;
let end = start + 512 * 256 / 16;
let ram = self.vm.get_ram_range(start, end);
draw_from_ram(ram, ctx)
}
pub fn get_stats(&self) -> JsValue {
JsValue::from(format!("Stats: \n{}", self.vm.profiler_stats()))
}
pub fn get_debug(&self) -> JsValue {
JsValue::from(self.vm.debug())
}
}
fn pixels_from_ram(ram: &[i32]) -> Vec<u8> {
let mut data = Vec::new();
for a in ram.iter() {
if *a == 0 {
for _ in 0..16 * 4 {
data.push(0xff); // white
}
} else {
for i in 0..16 {
if a & 1 << i > 0 {
data.push(0x00);
data.push(0x00);
data.push(0x00);
data.push(0xff);
} else {
data.push(0xff);
data.push(0xff);
data.push(0xff);
data.push(0xff);
}
}
}
}
data
}
fn draw_from_ram(ram: &[i32], ctx: &CanvasRenderingContext2d) -> Result<(), JsValue> {
let mut data = pixels_from_ram(ram);
let width = 512;
let height = 256;
let data = ImageData::new_with_u8_clamped_array_and_sh(
wasm_bindgen::Clamped(&mut data),
width,
height,
)?;
ctx.put_image_data(&data, 0.0, 0.0)
}
<file_sep>use super::vmparser::{parse_lines, Token};
use std::cmp;
use std::collections::HashMap;
use std::fmt;
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum Segment {
Constant,
Argument,
Local,
Static,
This,
That,
Pointer,
Temp,
}
impl fmt::Display for Segment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&format!("{:?}", self).to_lowercase())
}
}
#[derive(Eq, Hash, PartialEq, Copy, Clone, Debug)]
pub struct InCodeFuncRef {
file_index: usize,
function_index: usize,
}
impl InCodeFuncRef {
pub fn to_function_ref(self) -> FunctionRef {
FunctionRef::InCode(self)
}
}
#[derive(Eq, Hash, PartialEq, Copy, Clone, Debug)]
pub enum FunctionRef {
Internal(usize),
InCode(InCodeFuncRef),
}
impl FunctionRef {
pub fn new(file_index: usize, function_index: usize) -> FunctionRef {
FunctionRef::InCode(InCodeFuncRef {
file_index,
function_index,
})
}
}
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum Operation {
// arithmetic commands
Neg,
Not,
Add,
Sub,
And,
Or,
Eq,
Lt,
Gt,
}
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum Command {
Arithmetic(Operation),
// stack commands
Push(Segment, u16),
Pop(Segment, u16),
// goto commands
If(usize),
Goto(usize),
// function commands
Function(FunctionRef, u16),
Return,
Call(FunctionRef, u16),
// optimized commands
CopySeg {
from_segment: Segment,
from_index: u16,
to_segment: Segment,
to_index: u16,
},
}
impl Command {
pub fn to_string(&self, program: &VMProgram) -> String {
match self {
Command::Arithmetic(op) => format!("{:?}", op).to_lowercase(),
Command::Push(segment, index) => {
format!("push {} {}", segment, index)
}
Command::Pop(segment, index) => {
format!("pop {} {}", segment, index)
}
Command::If(index) => {
format!("if-goto {}", index)
}
Command::Goto(index) => {
format!("goto {}", index)
}
Command::Function(func_ref, num_locals) => {
format!(
"function {} {}",
program
.get_function_name(func_ref)
.unwrap_or("Unknown Function"),
num_locals
)
}
Command::Return => "return".to_string(),
Command::Call(func_ref, num_args) => {
format!(
"call {} {}",
program
.get_function_name(func_ref)
.unwrap_or("Unknown Function"),
num_args
)
}
Command::CopySeg {
from_segment,
from_index,
to_segment,
to_index,
} => {
format!(
"{}\n{}",
Command::Push(*from_segment, *from_index).to_string(program),
Command::Push(*to_segment, *to_index).to_string(program)
)
}
}
}
}
#[derive(Debug, Clone)]
pub struct VMFunction {
pub id: FunctionRef,
pub name: String,
pub num_locals: usize,
pub commands: Vec<Command>,
}
#[derive(Debug, Clone)]
pub struct VMFile {
pub name: String,
pub functions: Vec<VMFunction>,
pub num_statics: usize,
pub static_offset: usize,
}
type FunctionTable = bimap::BiMap<String, FunctionRef>;
type LabelTable = HashMap<String, usize>;
#[derive(PartialEq, Clone, Debug)]
enum OptimizedToken {
Base(Token),
CopySeg {
from_segment: Segment,
from_index: u16,
to_segment: Segment,
to_index: u16,
},
}
struct TokenizedFunction {
name: String,
commands: Vec<Token>,
}
impl TokenizedFunction {
fn from_tokens(tokens: &[Token]) -> Result<TokenizedFunction, String> {
let first_token = &tokens
.get(0)
.ok_or_else(|| "Failed creating tokenized functions. No tokens provided.")?;
if let Token::Function(func_name, _) = first_token {
Ok(TokenizedFunction {
name: func_name.clone(),
commands: tokens.to_vec(),
})
} else {
Err(format!("Failed creating tokenized function. Tokens don't start with a function declaration. Found {:?} instead.", first_token))
}
}
fn get_optimized_tokens(&self) -> Vec<OptimizedToken> {
let mut optimized: Vec<OptimizedToken> = Vec::new();
let mut i = 0;
while i < self.commands.len() {
if i + 1 < self.commands.len() {
let a = &self.commands[i];
let b = &self.commands[i + 1];
match (a, b) {
(Token::Push(from_segment, from_index), Token::Pop(to_segment, to_index)) => {
optimized.push(OptimizedToken::CopySeg {
from_segment: *from_segment,
from_index: *from_index,
to_segment: *to_segment,
to_index: *to_index,
});
i += 2;
}
_ => {
optimized.push(OptimizedToken::Base(a.clone()));
i += 1;
}
}
} else {
optimized.push(OptimizedToken::Base(self.commands[i].clone()));
i += 1;
}
}
return optimized;
}
}
struct TokenizedFunctionOptimized {
name: String,
label_table: LabelTable,
commands: Vec<OptimizedToken>,
}
impl TokenizedFunctionOptimized {
fn from(tokenized_func: TokenizedFunction) -> Result<TokenizedFunctionOptimized, String> {
let optimized = tokenized_func.get_optimized_tokens();
let (label_table, command_tokens) =
TokenizedFunctionOptimized::build_label_table(&optimized).map_err(|e| {
format!(
"failed building label table for {}: {}",
tokenized_func.name, e
)
})?;
Ok(TokenizedFunctionOptimized {
name: tokenized_func.name,
label_table,
commands: command_tokens,
})
}
fn from_tokens(tokens: &[Token]) -> Result<TokenizedFunctionOptimized, String> {
let tokenized_func = TokenizedFunction::from_tokens(tokens)?;
Self::from(tokenized_func)
}
fn build_label_table(
func_tokens: &[OptimizedToken],
) -> Result<(LabelTable, Vec<OptimizedToken>), String> {
let mut label_table: LabelTable = HashMap::new();
let mut command_index = 0;
let mut command_tokens: Vec<OptimizedToken> = Vec::new();
for token in func_tokens.iter() {
if let OptimizedToken::Base(Token::Label(label)) = token {
match label_table.get(label) {
Some(_) => return Err(format!("label {:?} declared twice", label)),
None => {
println!("Inserting label {}", label);
label_table.insert(label.to_string(), command_index);
}
}
} else {
command_tokens.push(token.clone());
command_index += 1;
}
}
return Ok((label_table, command_tokens));
}
}
struct TokenizedFile {
name: String,
functions: Vec<TokenizedFunction>,
}
impl TokenizedFile {
fn from_tokens(name: &str, tokens: &[Token]) -> Result<TokenizedFile, String> {
let iter = GroupByBound::new(tokens, |token| match token {
Token::Function(_, _) => true,
_ => false,
});
let funcs = iter
.map(TokenizedFunction::from_tokens)
.collect::<Result<Vec<_>, String>>()
.map_err(|e| format!("Failed tokenizing file: {}", e))?;
return Ok(TokenizedFile {
name: name.to_string(),
functions: funcs,
});
}
}
struct TokenizedProgram {
files: Vec<TokenizedFile>,
}
impl TokenizedProgram {
fn from_files(files: &[(&str, &str)]) -> Result<TokenizedProgram, String> {
let tokenized_files = files
.iter()
.map(|(filename, content)| {
parse_lines(content)
.map(|tokens| (filename, tokens))
.map_err(|e| {
format!(
"Failed tokenizing program: Couldn't parse {}: {}",
filename, e
)
})
})
.map(|result| {
let (filename, file_tokens) = result?;
if file_tokens.len() == 0 {
Err(format!(
"Failed tokenizing program: File {} has no vm commands",
filename
))
} else {
TokenizedFile::from_tokens(*filename, &file_tokens)
}
})
.collect::<Result<Vec<TokenizedFile>, String>>()?;
Ok(TokenizedProgram {
files: tokenized_files,
})
}
}
#[derive(Clone)]
pub struct VMProgram {
pub files: Vec<VMFile>,
pub function_table: FunctionTable,
pub warnings: Vec<Box<str>>,
}
impl VMProgram {
pub fn get_function_name(&self, func_ref: &FunctionRef) -> Option<&str> {
self.function_table.get_by_right(func_ref).map(|s| &s[..])
}
pub fn get_function_ref(&self, name: &str) -> Option<InCodeFuncRef> {
if let Some(FunctionRef::InCode(in_code_ref)) =
self.function_table.get_by_left(&name.to_string())
{
Some(*in_code_ref)
} else {
None
}
}
pub fn get_vmfunction(&self, func_ref: &InCodeFuncRef) -> &VMFunction {
&self.files[func_ref.file_index].functions[func_ref.function_index]
}
pub fn get_command(&self, func_ref: &InCodeFuncRef, index: usize) -> &Command {
&self.get_vmfunction(func_ref).commands[index]
}
pub fn get_file(&self, func_ref: &InCodeFuncRef) -> &VMFile {
&self.files[func_ref.file_index]
}
pub fn empty() -> VMProgram {
VMProgram {
files: Vec::new(),
function_table: bimap::BiMap::new(),
warnings: Vec::new(),
}
}
pub fn new(files: &Vec<(&str, &str)>) -> Result<VMProgram, String> {
VMProgram::with_internals(files, None)
}
pub fn with_internals(
files: &Vec<(&str, &str)>,
internal_funcs: Option<HashMap<&'static str, FunctionRef>>,
) -> Result<VMProgram, String> {
let tokenized_program = TokenizedProgram::from_files(files)
.map_err(|e| format!("Failed to create VMProgram: {}", e))?;
let mut function_table: FunctionTable = bimap::BiMap::new();
// let mut tokenized_files: Vec<TokenizedFile> = Vec::new();
let mut warnings: Vec<Box<str>> = Vec::new();
// tokenize files and build function table
if let Some(internal_funcs) = internal_funcs {
for (func_name, internal_func_ref) in internal_funcs.iter() {
function_table.insert(func_name.to_string(), *internal_func_ref);
}
}
for (file_index, tokenized_file) in tokenized_program.files.iter().enumerate() {
for (function_index, tokenized_func) in tokenized_file.functions.iter().enumerate() {
match function_table.get_by_left(&tokenized_func.name) {
Some(FunctionRef::InCode { .. }) => {
return Err(format!("function {:?} declared twice", tokenized_func.name));
}
Some(FunctionRef::Internal(_)) => {
// We ignore implementations of internal functions that appear in code.
}
None => {
function_table.insert(
tokenized_func.name.clone(),
FunctionRef::new(file_index, function_index),
);
}
}
}
}
let mut files: Vec<VMFile> = Vec::new();
// process files into vm commands
let mut static_offset = 0_usize;
for tokenized_file in tokenized_program.files.into_iter() {
let mut vmfile = VMFile {
name: tokenized_file.name.clone(),
functions: Vec::new(),
num_statics: 0,
static_offset,
};
for tokenized_func in tokenized_file
.functions
.into_iter()
.map(TokenizedFunctionOptimized::from)
{
let tokenized_func = tokenized_func?;
let label_table = &tokenized_func.label_table;
let mut tokens = tokenized_func.commands.iter();
if let OptimizedToken::Base(Token::Function(func_name, num_locals)) =
tokens.next().unwrap()
{
let function_ref = *function_table
.get_by_left(&func_name.to_string())
.expect("Expected to find function name in function table");
let mut vmfunc = VMFunction {
id: function_ref,
name: func_name.to_string(),
num_locals: *num_locals as usize,
commands: vec![Command::Function(function_ref, *num_locals)],
};
for token in tokens {
let command = match token {
OptimizedToken::CopySeg {
from_segment,
from_index,
to_segment,
to_index,
} => {
if *from_segment == Segment::Static {
vmfile.num_statics =
cmp::max(vmfile.num_statics, (from_index + 1).into());
}
if *to_segment == Segment::Static {
vmfile.num_statics =
cmp::max(vmfile.num_statics, (to_index + 1).into());
}
Command::CopySeg {
from_segment: *from_segment,
from_index: *from_index,
to_segment: *to_segment,
to_index: *to_index,
}
}
OptimizedToken::Base(token) => match token {
// empty token... should have been filtered out earlier
Token::None => panic!("Didn't expect Token::None"),
// arithmetic commands
Token::Neg => Command::Arithmetic(Operation::Neg),
Token::Not => Command::Arithmetic(Operation::Not),
Token::Add => Command::Arithmetic(Operation::Add),
Token::Sub => Command::Arithmetic(Operation::Sub),
Token::And => Command::Arithmetic(Operation::And),
Token::Or => Command::Arithmetic(Operation::Or),
Token::Eq => Command::Arithmetic(Operation::Eq),
Token::Lt => Command::Arithmetic(Operation::Lt),
Token::Gt => Command::Arithmetic(Operation::Gt),
// function commands
Token::Function(_, _) => panic!("Didn't expect Token::Function"),
Token::Call(func_to_call, num_args) => {
match function_table
.get_by_left(&func_to_call.to_string())
.copied()
{
Some(func_ref) => Command::Call(func_ref, *num_args),
None => {
warnings.push(
format!(
"function {:?} does not exist",
func_to_call
)
.into_boxed_str(),
);
Command::Call(FunctionRef::new(1000, 1), *num_args)
}
}
}
Token::Return => Command::Return,
// goto commands
Token::Label(_) => panic!("Didn't expect Token::Label"),
Token::If(label) => {
let index = label_table
.get(label)
.ok_or(format!("label {:?} does not exist", label))?;
Command::If(*index)
}
Token::Goto(label) => {
let index = label_table
.get(label)
.ok_or(format!("label {:?} does not exist", label))?;
Command::Goto(*index)
}
// stack commands
// TODO: verify indexes for segments
Token::Push(segment, index) => {
if *segment == Segment::Static {
vmfile.num_statics =
cmp::max(vmfile.num_statics, (index + 1).into());
}
Command::Push(*segment, *index)
}
Token::Pop(segment, index) => {
if *segment == Segment::Static {
vmfile.num_statics =
cmp::max(vmfile.num_statics, (index + 1).into());
}
Command::Pop(*segment, *index)
}
},
};
vmfunc.commands.push(command);
}
vmfile.functions.push(vmfunc);
} else {
panic!("Expected func to start with Token::Function");
}
}
static_offset += vmfile.num_statics;
files.push(vmfile);
}
return Ok(VMProgram {
files,
function_table,
warnings,
});
}
}
struct GroupByBound<'a, T, P>
where
P: Fn(&T) -> bool,
{
data: &'a [T],
pred: P,
i: usize,
}
impl<'a, T, P> GroupByBound<'a, T, P>
where
P: Fn(&T) -> bool,
{
fn new(data: &'a [T], pred: P) -> GroupByBound<T, P> {
GroupByBound { data, pred, i: 0 }
}
}
impl<'a, T, P> Iterator for GroupByBound<'a, T, P>
where
P: Fn(&T) -> bool,
{
type Item = &'a [T];
fn next(&mut self) -> Option<Self::Item> {
if self.i >= self.data.len() {
return None;
}
let mut j = self.i + 1;
while j < self.data.len() && !(self.pred)(&self.data[j]) {
j += 1;
}
let slice = &self.data[self.i..j];
self.i = j;
if slice.len() > 0 {
return Some(slice);
}
return None;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_group_by_bounds() {
let v = vec![1, 2, 2, 0, 3, 0, 1, 65, 4, 3, 0, 1, 5, 4, 3, 0];
let mut groups = GroupByBound::new(&v, |&t| t == 1);
assert_eq!(groups.next(), Some(&v[0..6]));
assert_eq!(groups.next(), Some(&v[6..11]));
assert_eq!(groups.next(), Some(&v[11..]));
assert_eq!(groups.next(), None);
}
#[test]
fn test_with_internals() {
let internals: HashMap<&'static str, FunctionRef> = HashMap::new();
let files = vec![(
"Sys.vm",
"
function Sys.init 1
push constant 10
push constant 11
call Sys.add 2
return",
)];
let program = VMProgram::with_internals(&files, Some(internals)).unwrap();
assert_eq!(program.warnings.len(), 1, "Expected there to be warnings");
assert_eq!(
program.warnings[0].clone().into_string(),
"function \"Sys.add\" does not exist"
);
assert_eq!(
program.files[0].functions[0].commands[3],
Command::Call(FunctionRef::new(1000, 1), 2),
"Expected call to missing function to use another function ref..."
);
let mut internals: HashMap<&'static str, FunctionRef> = HashMap::new();
internals.insert("Sys.add", FunctionRef::Internal(0));
let program = VMProgram::with_internals(&files, Some(internals)).unwrap();
assert_eq!(
program.warnings.len(),
0,
"Expected there to be no warnings for calls to internal functions"
);
assert_eq!(
program.files[0].functions[0].commands[3],
Command::Call(FunctionRef::Internal(0), 2),
"Expected call to internal function to use an internal function ref"
);
let files = vec![(
"Sys.vm",
"
function Sys.init 1
push constant 10
push constant 11
call Sys.add 2
return
function Sys.add 0
push argument 0
push argument 1
add
return
",
)];
let mut internals: HashMap<&'static str, FunctionRef> = HashMap::new();
internals.insert("Sys.add", FunctionRef::Internal(0));
let program = VMProgram::with_internals(&files, Some(internals)).unwrap();
assert_eq!(
program.warnings.len(),
0,
"Expected there to be no warnings for calls to internal functions"
);
assert_eq!(
program.files[0].functions[0].commands[3],
Command::Call(FunctionRef::Internal(0), 2),
"Expected internal functions to take priority over functions of the same name defined in code"
);
}
#[test]
fn test_vmprogram_new() {
let program = VMProgram::new(&vec![(
"Sys.vm",
"
function Sys.init 1
push constant 10
pop static 0
label LOOP
call Sys.incr 0
pop temp 0
goto LOOP
return
function Sys.incr 1
push static 0
push constant 1
add
pop local 0
push local 0
push constant 10
gt
if-goto SAVE
return
label SAVE
label SAVE2
push local 0
pop static 0
return
",
)])
.unwrap();
assert_eq!(program.files.len(), 1);
assert_eq!(program.files[0].functions.len(), 2);
assert_eq!(
program.function_table.get_by_left("Sys.init").unwrap(),
&FunctionRef::new(0, 0)
);
assert_eq!(
program.function_table.get_by_left("Sys.incr").unwrap(),
&FunctionRef::new(0, 1)
);
assert_eq!(
program.files[0].functions[0].commands[0],
Command::Function(FunctionRef::new(0, 0), 1),
);
assert_eq!(
program.files[0].functions[0].commands[2],
Command::Call(FunctionRef::new(0, 1), 0),
);
}
}
<file_sep>export const OSFiles = [
"programs/OS/Array.vm",
"programs/OS/Keyboard.vm",
"programs/OS/Math.vm",
"programs/OS/Memory.vm",
"programs/OS/Output.vm",
"programs/OS/Screen.vm",
"programs/OS/String.vm",
"programs/OS/Sys.vm",
];
type Demo = {
title: string;
description?: string;
files: string[];
projectUrl: string;
author: string;
ticksPerCycle?: number;
instructions?: string;
config?: { speed?: number };
};
const demos: Record<string, Demo> = {
pong: {
title: "Pong",
description:
"The classic game of pong that's part of the Nand2Tetris course.",
author: "<NAME> and <NAME> (creators of Nand2Tetris)",
projectUrl: "https://www.nand2tetris.org/",
instructions: "Use the arrow keys to move the paddle.",
config: { speed: 5000 },
files: [
"programs/Pong/Bat.vm",
"programs/Pong/Ball.vm",
"programs/Pong/Main.vm",
"programs/Pong/PongGame.vm",
],
},
hackenstein3D: {
title: "Hackenstein 3D",
description: "A (very) simple first-person shooter / 3D maze game.",
author: "<NAME>",
projectUrl: "https://github.com/QuesterZen/hackenstein3D",
files: [
"https://raw.githubusercontent.com/QuesterZen/hackenstein3D/master/dist/Display.vm",
"https://raw.githubusercontent.com/QuesterZen/hackenstein3D/master/dist/Main.vm",
"https://raw.githubusercontent.com/QuesterZen/hackenstein3D/master/dist/Player.vm",
"https://raw.githubusercontent.com/QuesterZen/hackenstein3D/master/dist/Walls.vm",
],
},
scroller: {
title: "Scroller",
description: "A demo of scrolling text across the screen.",
author: "<NAME>",
projectUrl: "https://github.com/gav-/Nand2Tetris-Games_and_Demos",
config: { speed: 5000 },
files: [
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASscroller/GASscroller.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASscroller/Main.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASscroller/MathsToo.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASscroller/MemoryToo.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASscroller/Sinus.vm",
],
},
chunky: {
title: "Chunky",
description: "A real-time plasma and rotozoom demo.",
author: "<NAME>",
projectUrl: "https://github.com/gav-/Nand2Tetris-Games_and_Demos",
files: [
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASchunky/ChunkyImage.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASchunky/Dither4x4.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASchunky/GASchunky.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASchunky/Head.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASchunky/Image.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASchunky/Main.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASchunky/MathsToo.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASchunky/MemoryToo.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASchunky/Monitor.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASchunky/Plasma.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASchunky/RotoZoom.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASchunky/Sinus.vm",
],
},
boing: {
title: "Boing",
description: "A bouncing ball animation.",
author: "<NAME>",
projectUrl: "https://github.com/gav-/Nand2Tetris-Games_and_Demos",
config: { speed: 5000 },
files: [
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/GASboing.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/Image.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/Main.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/MathsToo.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/MemoryToo.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/Sinus.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/ball01.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/ball02.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/ball03.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/ball04.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/ball05.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/ball06.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/ball07.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/ball08.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/shadow01.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/shadow02.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/shadow03.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/shadow04.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/shadow05.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/shadow06.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/shadow07.vm",
"https://raw.githubusercontent.com/gav-/Nand2Tetris-Games_and_Demos/master/GASboing/shadow08.vm",
],
},
};
export default demos;
<file_sep>export default function safeInterval(func: () => void, delay: number) {
const interval = setInterval(() => {
try {
func();
} catch (e) {
clearInterval(interval);
throw e;
}
}, delay);
return interval;
}
<file_sep>use criterion::{black_box, criterion_group, criterion_main, Criterion};
use hackvm::{VMEmulator, VMProgram};
pub fn criterion_benchmark(c: &mut Criterion) {
let program = VMProgram::new(&vec![(
"Sys.vm",
"
function Sys.init 0
push constant 10
pop static 0
label LOOP
call Sys.incr 0
pop temp 0
goto LOOP
return
function Sys.incr 0
push static 0
push constant 1
add
pop static 0
push static 0
return
",
)])
.unwrap();
c.bench_function("fib 20", |b| {
b.iter(|| VMEmulator::new(program.clone()).run(black_box(2000)))
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
<file_sep>import type { WebVM } from "hackvm";
function getKeyValue(key: string) {
const keyMap: Record<string, number> = {
ArrowLeft: 130,
ArrowUp: 131,
ArrowRight: 132,
ArrowDown: 133,
};
let value = 0;
value = keyMap[key];
if (value === undefined) {
value = key.charCodeAt(0);
}
return value;
}
export default class RustHackMachine {
static async create(program: {
vmFiles: { filename: string; text: string }[];
}): Promise<RustHackMachine> {
const hack = await import("hackvm");
hack.init_panic_hook();
let machine;
machine = hack.WebVM.new();
for (let file of program.vmFiles) {
machine.load_file(file.filename, file.text);
}
machine.init();
return new RustHackMachine(machine);
}
private m: WebVM;
private profile: boolean;
private constructor(m: WebVM) {
this.m = m;
this.profile = false;
}
numCycles: number = 0;
tick(n: number): void {
if (this.profile) {
this.m.tick_profiled(n);
} else {
this.m.tick(n);
}
this.numCycles += n;
}
reset(): void {
this.m.reset();
this.numCycles = 0;
if (this.profile) {
console.log(this.m.get_stats());
}
console.log(this.m.get_debug());
}
setKeyboard(event: { key: string } | null): void {
this.m.set_keyboard(event ? getKeyValue(event.key) : 0);
}
drawScreen(ctx: CanvasRenderingContext2D): void {
this.m.draw_screen(ctx);
}
getVM(): WebVM {
return this.m;
}
}
<file_sep>use super::vmcommand::Segment;
#[derive(PartialEq, Clone, Debug)]
pub enum Token {
None,
// arithmetic commands
Neg,
Not,
Add,
Sub,
And,
Or,
Eq,
Lt,
Gt,
// stack commands
Push(Segment, u16),
Pop(Segment, u16),
// goto commands
Label(String),
If(String),
Goto(String),
// function commands
Function(String, u16),
Return,
Call(String, u16),
}
fn parse_segment(s: &str) -> Result<Segment, String> {
match s {
"constant" => Ok(Segment::Constant),
"argument" => Ok(Segment::Argument),
"local" => Ok(Segment::Local),
"static" => Ok(Segment::Static),
"this" => Ok(Segment::This),
"that" => Ok(Segment::That),
"pointer" => Ok(Segment::Pointer),
"temp" => Ok(Segment::Temp),
_ => Err(format!("Invalid segment {:?}", s)),
}
}
fn parse_line(line: &str) -> Result<Token, String> {
let parts: Vec<&str> = line.trim().split_whitespace().collect();
match parts.get(0) {
None => Ok(Token::None),
Some(command) => match *command {
// comment
"//" => Ok(Token::None),
// arithmetic commands
"neg" => Ok(Token::Neg),
"not" => Ok(Token::Not),
"add" => Ok(Token::Add),
"sub" => Ok(Token::Sub),
"and" => Ok(Token::And),
"or" => Ok(Token::Or),
"eq" => Ok(Token::Eq),
"lt" => Ok(Token::Lt),
"gt" => Ok(Token::Gt),
// goto commands
"label" | "if-goto" | "goto" => {
let arg1 = parts
.get(1)
.ok_or(format!("Missing label in {:?} command", command))?
.to_string();
Ok(match *command {
"label" => Token::Label(arg1),
"if-goto" => Token::If(arg1),
"goto" => Token::Goto(arg1),
_ => panic!("This should never happen. Command: {}", command),
})
}
// stack commands
"push" | "pop" => {
let arg1 = parts
.get(1)
.ok_or(format!("Missing segment in {:?} command", command))?;
let arg2 = parts
.get(2)
.ok_or(format!("Missing index in {:?} command", command))?;
let segment = parse_segment(arg1)?;
let index = arg2
.parse::<u16>()
.map_err(|_| format!("Invalid index {:?} in {:?} command", arg2, command))?;
Ok(match *command {
"push" => Token::Push(segment, index),
"pop" => Token::Pop(segment, index),
_ => panic!("This should never happen"),
})
}
// function calling commands
"return" => Ok(Token::Return),
"function" | "call" => {
let arg1 = parts
.get(1)
.ok_or(format!("Missing function name in {:?} command", command))?
.to_string();
let arg2 = parts
.get(2)
.ok_or(format!("Missing arg2 in {:?} command", command))?
.to_string();
let num = arg2.parse::<u16>().map_err(|_| "Invalid num".to_string())?;
Ok(match *command {
"function" => Token::Function(arg1, num),
"call" => Token::Call(arg1, num),
_ => panic!("This should never happen"),
})
}
_ => Err(format!("Could not parse line {}", line)),
},
}
}
pub fn parse_lines(lines: &str) -> Result<Vec<Token>, String> {
let mut tokens: Vec<Token> = Vec::new();
for line in lines.lines() {
let token = parse_line(line)?;
if token != Token::None {
tokens.push(token);
}
}
return Ok(tokens);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_line() {
assert_eq!(parse_line("add"), Ok(Token::Add));
assert_eq!(
parse_line("push constant 10"),
Ok(Token::Push(Segment::Constant, 10))
);
assert_eq!(
parse_line("push foo 10"),
Err("Invalid segment \"foo\"".to_string())
)
}
#[test]
fn test_parse_lines() {
assert_eq!(
parse_lines(
"
// a simple function
function foo 2
push constant 3
not
return // the end"
),
Ok(vec![
Token::Function("foo".to_string(), 2),
Token::Push(Segment::Constant, 3),
Token::Not,
Token::Return,
])
);
}
}
<file_sep>import { useEffect, useState, useRef, useCallback } from "react";
import RustHackMachine from "./RustHackMachine";
import RemoteFS from "./RemoteFS";
import safeInterval from "./safeInterval";
export default function useHackMachine(
url: string[],
{
speed,
onTick,
paused: initPaused = true,
}: {
speed: number;
onTick?: (machine: RustHackMachine, elapsedTimeMs: number) => void;
paused?: boolean;
}
) {
const [loading, setLoading] = useState(false);
const [machine, setMachine] = useState<RustHackMachine>();
const [paused, setPaused] = useState(initPaused);
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
setPaused(initPaused);
setMachine(undefined);
setLoading(true);
const context = canvasRef.current?.getContext("2d");
context &&
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
(async () => {
const fetched = await RemoteFS.get().getFiles(url);
const vmFiles = fetched.map((fetchState) => {
const parts = fetchState.url.split("/");
const filename = parts[parts.length - 1];
return { filename, text: fetchState.data };
});
setMachine(await RustHackMachine.create({ vmFiles }));
setLoading(false);
})();
}, [url]);
useEffect(() => {
if (!machine) return;
if (paused) return;
const startTime = new Date().getTime();
const computeInterval = safeInterval(() => {
machine?.tick(speed);
}, 0);
let onTickInterval: NodeJS.Timeout;
if (onTick) {
onTickInterval = safeInterval(
() => onTick(machine, new Date().getTime() - startTime),
1000 / 30
);
}
return () => {
onTickInterval && clearInterval(onTickInterval);
clearInterval(computeInterval);
};
}, [machine, paused, onTick, speed]);
useEffect(() => {
if (paused) return;
if (!machine) return;
const context = canvasRef.current?.getContext("2d");
if (!context) return;
const renderInterval = safeInterval(() => {
machine.drawScreen(context);
}, 1000 / 30);
return () => {
clearInterval(renderInterval);
};
}, [paused, machine]);
const onKeyDown = useCallback(
(event: KeyboardEvent) => {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
machine?.setKeyboard(event);
},
[machine]
);
const onKeyUp = useCallback(() => machine?.setKeyboard(null), [machine]);
useEffect(() => {
if (paused) return;
window.addEventListener("keydown", onKeyDown);
window.addEventListener("keyup", onKeyUp);
return () => {
window.removeEventListener("keydown", onKeyDown);
window.removeEventListener("keyup", onKeyUp);
};
}, [paused, onKeyDown, onKeyUp]);
const reset = () => {
if (!machine) return;
machine.reset();
const context = canvasRef.current?.getContext("2d");
context && machine.drawScreen(context);
onTick && onTick(machine, 0);
};
return {
machine,
loading,
canvasRef,
paused,
setPaused,
reset,
};
}
<file_sep># HackVM
This repository contains a reimplementation of the hack virtual machine described
in the [nand2tetris online class](https://www.nand2tetris.org/) which runs in a
web browser.
[Try it out here](https://pcardune.github.io/hackvm/index.html#/)
## Directory Layout
- **hackvm** - contains the virtual machine code, which is implemented in Rust and compiles to WebAssembly
- **web** - contains a web frontend for the virtual machine along with some demo programs,
implemented with Typescript and React.
## Building
### Build Dependencies
1. [Install wasm-pack](https://rustwasm.github.io/wasm-pack/installer/)
### Build Steps
There are two parts to the build. First we must compile the rust code into web assembly.
From the `hackvm` directory run:
```bash
wasm-pack build
```
Next we must compile all the Typescript/React code into plain html/javascript.
From the `web` directory run:
```bash
yarn install
yarn build
```
There should now be a `web/build` which can be published to any static file hosting site. To
view the contents in a web browser, you'll need to actually serve the files via a real http
server (browsers can't load Web Assembly binaries from the local file system for security reasons):
From the `web/build` directory:
```bash
python3 -m http.server
```
For more details about building the website or the vm, refer to the README files in the `hackvm` and `web` subdirectories.
### Building During Developement
During development, to avoid constantly having to run `yarn install` while making changes to and compiling the rust code, you'll want to use `yarn link` to symlink the `hackvm/pkg` directory. From the repository root, this can be done with the following:
```bash
cd hackvm/pkg
yarn link
cd ../../web
yarn link hackvm
```
| 3de1706a44603b9f841dd7721d4988d5c768cd4d | [
"Markdown",
"Rust",
"TypeScript"
] | 12 | Markdown | pcardune/hackvm | 784227a37a2f71f3c5efdbe7737f56c00ee7de46 | 853f77a0bbc60989fc613991677dd12a1d7a978a |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using PongDEMO.Models;
namespace PongDEMO.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Post> Posts { get; set; }
public DbSet<Likes> Likes { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using PongDEMO.Models;
namespace PongDEMO.Controllers
{
public class UserCardController : Controller
{
public IActionResult UserCardRender(string name, string profession, string desc)
{
UserCard u = new UserCard();
u.Name = name;
u.Desc = desc;
u.Profession = profession;
return View("_UserCard", u);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PongDEMO.Models
{
public class Likes
{
public int Id { get; set; }
public int PostId { get; set; }
public int Yes { get; set; }
public int No { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using PongDEMO.Models;
namespace PongDEMO.Controllers
{
public class OrderController : Controller
{
public IActionResult MockOrder()
{
Order o = new Order();
o.Id = 1;
o.UserName = "Jon Snow";
o.UserMail = "<EMAIL>";
o.Adress = "Castle Black, 123 North";
o.ProductName = "Dragon";
o.Color = "Brown";
o.DeliveryMethod = "DHL";
o.Price = 10000;
Order o2 = new Order();
o2.Id = 2;
o2.UserName = "Jaime L";
o2.UserMail = "J@kingguard";
o2.Adress = "Kings Landing, 321 KL";
o2.ProductName = "Hand";
o2.Color = "Gold";
o2.DeliveryMethod = "InPost";
o2.Price = 50000;
Order o3 = new Order();
o3.Id = 2;
o3.UserName = "The Imo";
o3.UserMail = "J@drinkers";
o3.Adress = "Kings Landing, 521 KL";
o3.ProductName = "Wine";
o3.Color = "Red";
o3.DeliveryMethod = "Pigeon post";
o3.Price = 50;
List<Order> os = new List<Order>();
os.Add(o);
os.Add(o2);
os.Add(o3);
return View("_Order", os);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PongDEMO.Models
{
public class Order
{
public int Id { get; set; }
//It's just some mock model.
//In real app it would be more complex, with data referenced by foreign keys, not hardcoded into model.
//Splitting Order view into granular components might not always have sense - ex. if single parts of placed order will never be changed
public string UserName { get; set; }
public string UserMail { get; set; }
public string Adress { get; set; }
public string ProductName { get; set; }
public string Color { get; set; }
public string DeliveryMethod { get; set; }
public int Price { get; set; }
}
}
<file_sep>
//Routing
$(document).ready(function () {
$("route").each(function () {
$(this).css("display", "none");
var def = $(this).attr('levelDefault');
if (typeof def !== typeof undefined && def !== false) {
$(this).css("display", "");
}
});
router();
$("a").click(function () {
var isNested = $(this).attr("nested");
if (typeof isNested !== typeof undefined) {
$("route").css("display", "none");
}
});
});
$(window).bind('hashchange', function () {
router();
});
function router() {
$("body").css("display", "");
var url = window.document.URL.toString();
var res = url.split("?");
var route = res[1];
var level = $("[path=" + route + "]").attr('routeLevel');
$("[routeLevel='" + level + "'").css("display", "none");
$("[path=" + route + "]").css("display", "");
$("[path=" + route + "]").parents().css("display", "");
$("[linkLevel = '" + level + "'").removeClass("active")
$("[href='#?" + route + "']").addClass("active");
};
//dispatch core get (dispatch only CoreMethod)
function dispatchCoreGet(coreMethod, parentEl, itemKey) {
$.ajax({
async: false,
type: 'GET',
url: coreMethod,
data: { itemKey: itemKey },
success: function (data) {
$(parentEl).append("<component props itemKey='" + itemKey + "' method='" + coreMethod + "'>" + data + "</component>");
}
});
}
//updates selected components (Core Method only)
function updateCoreGet(coreMethod, parentEl, itemKey) {
$.ajax({
async: false,
type: 'GET',
url: coreMethod,
data: { itemKey: itemKey },
success: function (data) {
$(parentEl + ' >[itemKey="' + itemKey + '"]').html(data);
}
});
}
// Split Methods Dispatch
function dispatchGet(higherOrderMethod, coreMethod, parentEl, higherOrderMethodPayload) {
var parentElVal = "";
if (parentEl[0] == "#" || parentEl[0] == ".") {
parentElVal = parentEl.substring(1);
}
if (parentEl[0] == "[") {
var arrTmp = parentEl.split("=");
var tmpSubstring = arrTmp[1];
parentElVal = tmpSubstring.slice(1, -2);
}
var inpState = $("#" + parentElVal + "State").val();
if (inpState == null) {
$(parentEl).append("<input type='hidden' id='" + parentElVal + "State' />");
var state = [];
}
else {
var stateString = $("#" + parentElVal + "State").val();
var state = stateString.split(',').map(function (el) { return +el; });
}
$.ajax({
async: false,
type: 'GET',
url: higherOrderMethod,
data: higherOrderMethodPayload,
success: function (data) {
$("#" + parentElVal + "State").val(data);
var diff = [];
for (var i = 0; i < data.length; i++) {
var isNew = true;
for (var j = 0; j < state.length; j++) {
if (data[i] == state[j]) {
isNew = false;
}
}
if (isNew) {
diff.push(data[i]);
}
}
for (var j = 0; j < diff.length; j++) {
dispatchCoreGet(coreMethod, parentEl, diff[j]);
}
var keysToRemove = [];
for (var i = 0; i < state.length; i++) {
var shouldRemove = true;
for (var j = 0; j < data.length; j++) {
if (data[j] == state[i]) {
shouldRemove = false;
}
}
if (shouldRemove == true) {
keysToRemove.push(state[i]);
}
}
for (var i = 0; i < keysToRemove.length; i++) {
$(parentEl + ' >[itemKey="' + keysToRemove[i] + '"]').remove();
}
}
});
}
function dispatchGetReload(higherOrderMethod, coreMethod, parentEl, higherOrderMethodPayload) {
$(parentEl).html("");
dispatchGet(higherOrderMethod, coreMethod, parentEl, higherOrderMethodPayload);
}
//SET PROP , GET PROP
// changing prop with automatic re-render
function setProp(selector, key, value) {
var props = $(selector).attr('props');
var keyIndex = props.search(key);
var valIndex = keyIndex + key.length + 1;
var oldVal = "";
for (var i = valIndex; i < props.length; i++) {
if (props[i] != "," && props[i] != "'" && props[i] != '"') {
oldVal += props[i];
}
else {
break;
}
}
var text = props.replace(oldVal, value);
$(selector).attr('props', text);
var newProps = $(selector).attr('props');
//re render with changed props
var tmpProps = newProps;
var propsArr = tmpProps.split(',');
var data = {};
for (var i = 0; i < propsArr.length; i++) {
var tmpArr = propsArr[i].split(':');
data[tmpArr[0]] = tmpArr[1];
}
var methodUrl = $(selector).attr('method');
var toAppend;
$.ajax({
async: false,
url: methodUrl,
type: 'GET',
data: data,
success: function (data) {
toAppend = data;
}
});
$(selector).html(toAppend);
}
//getProp
function getProp(selector, key) {
var props = $(selector).attr('props');
var keyIndex = props.search(key);
var valIndex = keyIndex + key.length + 1;
var oldVal = "";
for (var i = valIndex; i < props.length; i++) {
if (props[i] != "," && props[i] != "'" && props[i] != '"') {
oldVal += props[i];
}
else {
break;
}
}
return oldVal;
}
//rendering html <component> tags
$(document).ready(function () {
$("component").each(function () {
var tmpProps = $(this).attr('props');
//console.log(tmpProps)
if (tmpProps != null && tmpProps != "") {
var propsArr = tmpProps.split(',');
var data = {};
for (var i = 0; i < propsArr.length; i++) {
var tmpArr = propsArr[i].split(':');
data[tmpArr[0]] = tmpArr[1];
}
var methodUrl = $(this).attr('method');
var toAppend;
$.ajax({
async: false,
url: methodUrl,
type: 'GET',
data: data,
success: function (data) {
toAppend = data;
}
});
$(this).html(toAppend);
}
});
});
//Render whole partial view dynamically with JS
function dispatchStraight(MvcMethod, parentEl, props) {
var data = {};
var tmpProps = props;
if (typeof(tmpProps)=='object') {
data = props;
}
else {
var propsArr = tmpProps.split(',');
var toAppend;
for (var i = 0; i < propsArr.length; i++) {
var tmpArr = propsArr[i].split(':');
data[tmpArr[0]] = tmpArr[1];
}
}
$.ajax({
async: false,
url: MvcMethod,
type: 'GET',
data: data,
success: function (data) {
toAppend = data;
}
});
$(parentEl).append("<component props='" + props + "' method='" + MvcMethod + "'>" + toAppend + "</component>");
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using PongDEMO.Data;
using PongDEMO.Models;
namespace PongDEMO.Controllers
{
public class PostController : Controller
{
ApplicationDbContext db;
UserManager<IdentityUser> userManager;
public PostController(ApplicationDbContext _db, UserManager<IdentityUser> _userManager)
{
db = _db;
userManager = _userManager;
}
//CORE METHODS
//1. Core Method for using data from back-end
public IActionResult PostCoreGet(int itemKey)
{
Post p = db.Posts.Where(x => x.Id == itemKey).FirstOrDefault();
return View("_Post", p);
}
//2. Core Method for using data from front-end
public IActionResult PostCoreRender(string nick, string email, string content)
{
Post p = new Post();
p.Nick = nick;
p.Email = email;
p.Content = content;
return View("_Post", p);
}
//HIGHER ORDER METHOD
public int[] GetAllPosts()
{
List<int> postIds = db.Posts.Select(x => x.Id).ToList();
//Just mock data filling empty table
if (postIds.Count == 0)
{
Post p1 = new Post();
p1.Nick = "Jon";
p1.Email = "<EMAIL>";
p1.Content = "Winter is coming";
db.Posts.Add(p1);
db.SaveChanges();
Likes l1 = new Likes();
Random r1 = new Random();
l1.PostId = p1.Id;
l1.Yes = r1.Next(1, 1000);
l1.No = r1.Next(1, 1000);
db.Likes.Add(l1);
db.SaveChanges();
Post p2 = new Post();
p2.Nick = "Ygritte";
p2.Email = "<EMAIL>";
p2.Content = "You know nothing";
db.Posts.Add(p2);
db.SaveChanges();
Likes l2 = new Likes();
Random r2 = new Random();
l2.PostId = p2.Id;
l2.Yes = r2.Next(1, 1000);
l2.No = r2.Next(1, 1000);
db.Likes.Add(l2);
db.SaveChanges();
Post p3 = new Post();
p3.Nick = "Tyrion";
p3.Email = "<EMAIL>";
p3.Content = "Wine, wine, wine";
db.Posts.Add(p3);
db.SaveChanges();
Likes l3 = new Likes();
Random r3 = new Random();
l3.PostId = p3.Id;
l3.Yes = r3.Next(1, 1000);
l3.No = r3.Next(1, 1000);
db.Likes.Add(l3);
db.SaveChanges();
postIds = db.Posts.Select(x => x.Id).ToList();
}
int[] arr = postIds.ToArray();
return arr;
}
[HttpPost]
public JsonResult AddPost(string nick, string email, string content)
{
Post p = new Post();
p.Nick = nick;
p.Email = email;
p.Content = content;
db.Posts.Add(p);
db.SaveChanges();
Likes l = new Likes();
Random r = new Random();
l.PostId = p.Id;
l.Yes = r.Next(1, 1000);
l.No = r.Next(1, 1000);
db.Likes.Add(l);
db.SaveChanges();
return Json(true);
}
[HttpPost]
public JsonResult EditPost(int id, string content)
{
Post p = db.Posts.Where(x => x.Id == id).FirstOrDefault();
p.Content = content;
db.Entry(p).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
db.SaveChanges();
return Json(true);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using PongDEMO.Data;
using PongDEMO.Models;
namespace PongDEMO.Controllers
{
public class LikesController : Controller
{
ApplicationDbContext db;
UserManager<IdentityUser> userManager;
public LikesController(ApplicationDbContext _db, UserManager<IdentityUser> _userManager)
{
db = _db;
userManager = _userManager;
}
//CORE METHOD
public IActionResult LikesCoreGet(int itemKey)
{
Likes l = db.Likes.Where(x => x.Id == itemKey).FirstOrDefault();
return View("_Likes", l);
}
//HIGHER ORDER METHOD
public int[] GetPostLikes(int postId)
{
List<int> l = db.Likes.Where(x => x.PostId == postId).Select(x => x.Id).ToList();
int[] arr = l.ToArray();
return arr;
}
}
} | 1bb43f930eed890902a2740d5133dd36b2840467 | [
"JavaScript",
"C#"
] | 8 | C# | jangruszka/Pong.NET | f4db97449d8fb8a1dc8a92e4befe09e6bd29778e | 080a794dec750dc093fe472449da5bc8d8bd947d |
refs/heads/master | <repo_name>souravbear8850/Tensorflow-Lite-Inference<file_sep>/README.md
# Tensorflow-Lite-Inference
### A App for inference of Human Activity using sensors data
<file_sep>/app/src/main/java/com/souravbera/tensorflowliteinference/MainActivity.java
package com.souravbera.tensorflowliteinference;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.souravbera.tensorflowliteinference.Sensor.SensorRawDataAG;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private Button btn_result;
private TextView text_output;
private float[][] result;
private MainActivity mainActivity= new MainActivity();
private SensorRawDataAG sensorRawDataAG= new SensorRawDataAG(mainActivity);
TextView xaValue,yaValue,zaValue,xgValue,ygValue,zgValue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_output = (TextView) findViewById(R.id.text_out);
btn_result = (Button) findViewById(R.id.btn_Result);
btn_result.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
result= sensorRawDataAG.onResume1();
text_output.setText(Arrays.deepToString(result));
}
});
}
}
| d408e3d6e7d36e59f57cc22ff45ab1ad8b064a66 | [
"Markdown",
"Java"
] | 2 | Markdown | souravbear8850/Tensorflow-Lite-Inference | a32a642aef1a77a9d8eca4d3832e83d267ec17ce | d487ddcf55f9386f44a5c9311a57def52d2d0077 |
refs/heads/master | <repo_name>sunfeng90/chezmoi<file_sep>/README.md
# chezmoi
Home automation proof of concept built around Node.js, RaspberryPi, Arduino and Bluetooth.
<file_sep>/hub/thermometer.js
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var five = require("johnny-five");
function Thermometer(path) {
var self = this;
self.path = path;
self.board = null;
}
util.inherits(Thermometer, EventEmitter);
Thermometer.prototype.connect = function (callback) {
var self = this;
self.sensorData = [];
self.board = new five.Board({
port: self.path,
repl: false
});
self.board.on("ready", function() {
var thermometer = new five.Thermometer({
controller: "LM35",
pin: "A0",
freq: 5000
});
thermometer.on("data", function() {
self.sensorData.push(this.celsius);
});
setInterval(self.reportData.bind(self), 60000);
callback(null);
//var pin = new five.Pin('A0');
//var timer;
//function query () {
// timer = setTimeout(onTimeoutExpired, 3000);
// pin.query(function (state) {
// clearTimeout(timer);
// console.log("value: " + state.value, "report: " + state.report);
// setTimeout(query, 1000);
// });
//}
//query();
//
//function onTimeoutExpired () {
// board.emit("error", "cannot query pin value");
//}
});
};
Thermometer.prototype.isConnected = function () {
var self = this;
return self.board && self.board.isReady;
};
Thermometer.prototype.sendData = function () {
//do nothing
};
Thermometer.prototype.reportData = function () {
var self = this;
var average = 0;
if (self.sensorData.length > 0) {
average = self.sensorData.reduce((previous, current) => previous + current) / self.sensorData.length;
}
self.emit("data", average);
self.sensorData = [];
};
module.exports = Thermometer;<file_sep>/web-console/mock-hub.js
var os = require('os');
var io = require('socket.io-client');
var debug = require('debug')('mock-hub');
debug('Starting mock hub');
var socket = io('http://localhost:3000/');
var heartbeatId = undefined;
function heartbeat() {
socket.emit('heartbeat');
}
socket.on('connect', function () {
debug('Connected to dev server');
socket.emit('who', {name: os.hostname()});
socket.emit('device-register', {name: 'air-control'});
socket.emit('device-register', {name: 'thermometer'});
heartbeatId = setInterval(heartbeat, 60000);
});
socket.on('disconnect', function () {
debug('Disconnected from dev server');
if (heartbeatId) {
clearInterval(heartbeatId);
};
});
socket.on('command', function (data) {
debug('Received command from cloud server', data);
});
debug('Mock hub ready');<file_sep>/web-console/store.js
function createStore() {
var elements = [];
return {
all: function () {
return elements;
},
add: function (element) {
elements.push(element);
},
get: function (id) {
return this.findOne(element => element.id === id);
},
findOne: function (predicate) {
return elements.filter(predicate)[0];
},
remove: function (elementToRemove) {
elements.splice(elements.indexOf(elementToRemove), 1);
}
};
}
module.exports = {
hubs: createStore(),
devices: createStore()
};<file_sep>/hub/index.js
var os = require('os');
var io = require('socket.io-client');
var SerialDevice = require('serialdevice');
var debug = require('debug')('chezmoi');
var Thermometer = require('./thermometer.js');
debug('Starting hub');
var socket = io('http://www.chezmoi.io/');
var airControl = new SerialDevice('/dev/rfcomm0');
var thermometer = new Thermometer('/dev/rfcomm1');
airControl.name = 'air-control';
thermometer.name = 'thermometer';
var devices = [airControl, thermometer];
var heartbeatId = undefined;
function heartbeat() {
socket.emit('heartbeat');
}
socket.on('connect', function () {
debug('Connected to cloud server');
socket.emit('who', {name: os.hostname()});
devices.forEach(device => {
if (device.isConnected()) {
socket.emit('device-register', { name: device.name })
}
});
heartbeatId = setInterval(heartbeat, 60000);
});
socket.on('disconnect', function () {
debug('Disconnected from cloud server');
if (heartbeatId) {
clearInterval(heartbeatId);
};
});
socket.on('command', function (data) {
debug('Received command from cloud server', data);
var device = devices.find(device => device.name === data.name);
if (data && data.command && device && device.isConnected()) {
device.sendData(data.command);
}
});
function connectDevice (device) {
device.connect(function (err) {
if (err) {
debug(`Error during connection with device ${device.name}, retrying in 30 seconds.`);
setTimeout(connectDevice.bind(null, device), 30000);
return;
}
debug(`${device.name} connected`);
socket.emit('device-register', {name: device.name});
});
}
devices.forEach(device => {
device.on('disconnect', function () {
socket.emit('device-unregister', {name: device.name});
debug(`${device.name} disconnected, trying to reconnect in 30 seconds.`);
setTimeout(connectDevice.bind(null, device), 30000);
});
device.on('data', function (data) {
socket.emit('device-data', {device: device.name, data: data});
});
connectDevice(device);
});
debug('Hub ready');<file_sep>/hub/init.d/chezmoi
#!/bin/bash
# /etc/init.d/chezmoi
### BEGIN INIT INFO
# Provides: chezmoi
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: chezmoi hub
# Description: chezmoi hub
### END INIT INFO
HUB_HOME=/home/pi/chezmoi/hub
case "$1" in
start)
echo "Starting chezmoi hub"
cd $HUB_HOME; sudo -u pi npm start > /dev/null 2>&1 &
;;
stop)
pkill -f 'node index.js'
echo 'Stopped chezmoi'
;;
*)
echo "Usage: /etc/init.d/chezmoi start|stop"
exit 1
;;
esac
exit 0
<file_sep>/web-console/socket-app.js
var debug = require('debug')('web-console:socket');
var devices = require('./store').devices;
var hubs = require('./store').hubs;
function SocketApp(io) {
console.log('listening connections');
io.on('connection', function (socket) {
debug('Socket connected %s', socket.id);
var hub = {
name: '< Unknown >',
lastSeen: Date.now()
};
hubs.add(hub);
attachHandlers(socket, hub);
});
};
function attachHandlers(socket, hub) {
socket.on('who', function (data) {
debug('who: %s', JSON.stringify(data));
hub.name = data.name;
});
socket.on('device-register', function (data) {
registerDevice(socket, hub, data);
});
socket.on('device-unregister', function (data) {
debug('device disconnected: %s', JSON.stringify(data));
if (!data || !data.name) {
//TODO: ack with error
return;
}
var devicesToRemove = devices.all().filter(function (device) {
return device.name === data.name;
});
devicesToRemove.forEach(devices.remove);
});
socket.on('device-data', function (event) {
debug('device data: %s', JSON.stringify(event));
var sourceDevice = devices.findOne(device => device.name === event.device);
sourceDevice.lastData = event.data
});
socket.on('heartbeat', function () {
debug('Heartbeat from socket %s', socket.id);
var now = Date.now();
hub.lastSeen = now;
var devicesToUpdate = devices.all().filter(function (device) {
return device.socket === socket;
});
devicesToUpdate.forEach(function (device) {
device.lastSeen = now;
});
});
socket.on('disconnect', function () {
debug('Socket disconnected %s', socket.id);
hubs.remove(hub);
var devicesToRemove = devices.all().filter(function (device) {
return device.socket === socket;
});
devicesToRemove.forEach(devices.remove);
});
}
function registerDevice(socket, hub, data) {
if (!data || !data.name) {
//TODO: ack con error
return;
}
var device = {
id: generateId(),
name: data.name,
hub: hub,
socket: socket,
lastSeen: Date.now(),
lastData: null
};
devices.add(device);
debug('device registered: %s', JSON.stringify({id: device.id, name: device.name, hub: device.hub}));
}
function generateId() {
return (+new Date()).toString(36);
}
module.exports = SocketApp;<file_sep>/air-control/air-control.ino
#include <SoftwareSerial.h>
#include "ir_codes.h"
#define IR_LED_PIN 3
#define INDICATOR_LED_PIN 13
//repeat the signal a few times
#define IR_CODE_REPEAT_COUNT 3
SoftwareSerial bluetooth(10, 11); // RX, TX
char bluetoothBuffer[8];
byte bluetoothBufferPos = 0;
void setupBluetooth() {
bluetooth.begin(9600);
//set name and pin
bluetooth.write("AT");
delay(1000);
bluetooth.write("AT+NAMEAC Control");
delay(1000);
bluetooth.write("AT+PIN0000");
delay(1000);
//read and discard AT command responses
while (bluetooth.available()) {
Serial.print((char)bluetooth.read());
}
Serial.println();
Serial.println("Bluetooth initialized");
}
void setup() {
//initialize ir and indicator led pins
pinMode(IR_LED_PIN, OUTPUT);
pinMode(INDICATOR_LED_PIN, OUTPUT);
//Initialize serial
Serial.begin(9600);
Serial.println("Serial initialized");
//Initialize bluetooth
setupBluetooth();
digitalWrite(INDICATOR_LED_PIN, HIGH);
}
void loop() {
if (bluetooth.available()) {
readBluetooth();
}
}
void readBluetooth() {
char c;
while (bluetooth.available()) {
c = bluetooth.read();
if (c != '\n') {
bluetoothBuffer[bluetoothBufferPos] = c;
bluetoothBufferPos++;
if (bluetoothBufferPos >= sizeof(bluetoothBuffer)) {
bluetoothBufferPos = 0;
}
} else {
bluetoothBuffer[bluetoothBufferPos] = '\0';
bluetoothBufferPos = 0;
processCommand((char*)&bluetoothBuffer);
}
}
}
void processCommand(char* command) {
Serial.print("Received command: ");
Serial.print(command);
Serial.println();
if (strcmp(command, "on") == 0) {
Serial.println("Turning AC on");
sendCode(CODE_AC_ON, CODE_AC_ON_LENGTH);
return;
}
if (strcmp(command, "off") == 0) {
Serial.println("Turning AC off");
sendCode(CODE_AC_OFF, CODE_AC_OFF_LENGTH);
return;
}
if (strcmp(command, "ping") == 0) {
Serial.println("Responding ping with pong");
bluetooth.print("pong\n");
return;
}
}
// This procedure sends a 38KHz pulse to the IRledPin
// for a certain # of microseconds. We'll use this whenever we need to send codes
void pulseIR(long microsecs) {
// we'll count down from the number of microseconds we are told to wait
cli();
// this turns off any background interrupts
while (microsecs > 0) {
// 38 kHz is about 13 microseconds high and 13 microseconds low
digitalWrite(IR_LED_PIN, HIGH); // this takes about 3 microseconds to happen
delayMicroseconds(10); // hang out for 10 microseconds, you can also change this to 9 if its not working
digitalWrite(IR_LED_PIN, LOW); // this also takes about 3 microseconds
delayMicroseconds(10); // hang out for 10 microseconds, you can also change this to 9 if its not working
// so 26 microseconds altogether
microsecs -= 26;
}
sei();
// this turns them back on
}
void sendCode(int codeSequence[], int codeLength) {
for (int repeatCount = 0; repeatCount < IR_CODE_REPEAT_COUNT; repeatCount++) {
for (int codeIndex = 0; codeIndex < codeLength; codeIndex = codeIndex + 2) {
pulseIR(codeSequence[codeIndex]);
delayMicroseconds(codeSequence[codeIndex + 1]);
}
}
for (byte i=0; i < 3; i++) {
digitalWrite(INDICATOR_LED_PIN, LOW);
delay(100);
digitalWrite(INDICATOR_LED_PIN, HIGH);
delay(100);
}
}
<file_sep>/web-console/deploy-to-heroku.sh
#!/usr/bin/env bash
cd ..
git push heroku-web-console `git subtree split --prefix web-console master`:master --force
| e0c745014dda0553afde2fd3f3db8cd6ed307920 | [
"Markdown",
"JavaScript",
"C++",
"Shell"
] | 9 | Markdown | sunfeng90/chezmoi | 1a6e87b3feebaaf392d90eb791228ce2bb4974da | 2fd14a9dfc993d24e57c30868c8834e17a543f80 |
refs/heads/master | <file_sep>#pragma once
#include <SFML/Graphics.hpp>
#include "Map.h"
#include "Player.h"
class World
{
public:
World();
~World();
void run(); //Run the game
private:
sf::RenderWindow window{}; //Window for the game
sf::Event event{}; //Event queue
sf::View view{};
Map map{}; //The map of the game
Player player{}; //The player in the game
bool running{}; //Game running
int level{}; //Which level in the game the player is on
void init(); //Initialize all variables
void loop(); //Main loop for the game
void draw(); //General functions for drawing all objects
void event_check();
void update(); //General functions for updating all objects
void update_player(); //Update the player
void update_enemy(); //Update the enemies
void update_projectile(); //Update the projectile
void player_movement(); //Move the player
void player_attack(); //If the player is attacking
void player_move(int const&, int const&, int const&);
bool can_move(); //Can the player move that direction?
};
<file_sep>#include "Map.h"
#include <fstream>
Map::Map()
{
}
Map::~Map()
{
for (auto e : map)
{
delete e;
e = nullptr;
}
}
//Initialize the map
void Map::init()
{
if(texture.loadFromFile("Assets/tile_set_test.png"))
{
init_tiles();
}
}
//NEEDED?!?!?!?!?!?!?!
//Loads the level
bool Map::load_level(int const& lvl)
{
return true;
}
//Draws the map to the screen
void Map::draw(sf::RenderWindow& window)
{
for(auto e : map)
{
e->draw(window);
}
}
//Initializes all tiles to proper position
void Map::init_tiles()
{
std::ifstream file{"Levels/level6.txt"};
int offset;
for (int i{}; i < 20; ++i)
{
for (int j{}; j < 20; ++j)
{
file >> offset;
map.push_back(new Tile{32*j, 32*i, texture, offset });
}
}
}
std::vector<Tile*> Map::get_map()
{
return map;
}<file_sep>#include "Player.h"
Player::Player()
{
}
Player::~Player()
{
}
void Player::init()
{
//How fast the character is
movement_speed = 3;
//Direction facing
direction = 0;
//Which directions the player can move
for (int i{}; i < 4; i++)
{
direction_can_move.push_back(true);
}
//The texture of the character
if (texture.loadFromFile("Assets/character.png"))
{
init_character();
}
}
void Player::move(float const& x, float const& y)
{
rect.move(x * movement_speed, y * movement_speed);
sprite.move(x * movement_speed, y * movement_speed);
}
void Player::init_character()
{
//Set texture
sprite.setTexture(texture);
//Set Size
//sprite.setTextureRect(sf::IntRect{?, ?, 32, 32});
rect.setSize(sf::Vector2f{ 32.0f, 32.0f });
//Set position
sprite.setPosition(100.0f, 100.0f);
sprite.setOrigin(rect.getSize().x / 2, rect.getSize().y / 2);
rect.setPosition(100.0f, 100.0f);
rect.setOrigin(rect.getSize().x / 2, rect.getSize().y / 2);
}
sf::Vector2f Player::get_center()
{
return rect.getPosition();
}
//Tells the character that he cant go a certain direction
void Player::cant_go(int const& n)
{
direction_can_move.at(n) = false;
}
//Returns if the character can move a certain direction
bool Player::can_go(int const& n)
{
return direction_can_move.at(n);
}
void Player::reset_can_go()
{
for (auto e : direction_can_move)
{
e = true;
}
}
void Player::set_direction(int const& n)
{
direction = n;
}
void Player::fire_gun()
{
//gun.push_back(new Projectile{});
}<file_sep>#include "Entity.h"
Entity::Entity()
{
}
Entity::~Entity()
{
}
void Entity::draw(sf::RenderWindow& window)
{
window.draw(rect);
window.draw(sprite);
}
void Entity::move(float const& x, float const& y)
{
sprite.move(x, y);
rect.move(x, y);
}
sf::FloatRect Entity::get_global_bounds()
{
return rect.getGlobalBounds();
}<file_sep>#pragma once
#include <SFML/Graphics.hpp>
class Entity
{
public:
Entity();
~Entity();
void draw(sf::RenderWindow&);
virtual void move(float const&, float const&);
sf::FloatRect get_global_bounds();
protected:
sf::RectangleShape rect;
sf::Sprite sprite;
};
<file_sep>#pragma once
#include "Entity.h"
class Humanoid : public Entity
{
public:
Humanoid();
~Humanoid();
protected:
int health;
};
<file_sep>#pragma once
#include <vector>
#include "Tile.h"
#include <SFML/Graphics.hpp>
class Map
{
public:
Map();
~Map();
void init(); //Initialize the map
bool load_level(int const&); //Loads the level
void draw(sf::RenderWindow&); //Draws the map to the screen
std::vector<Tile*> get_map();
private:
std::vector<Tile*> map; //All the tiles that makes up the map
sf::Texture texture; //The texture that makes up the map
void init_tiles(); //Initializes all tiles to proper position
};
<file_sep>#include "World.h"
int main()
{
World world;
world.run();
return 0;
}<file_sep>#include "Tile.h"
Tile::Tile()
{
}
//Construct the tile with position and texture
Tile::Tile(int x, int y, sf::Texture& texture, int offset)
{
//Set texture
sprite.setTexture(texture);
//Set size
sprite.setTextureRect(sf::IntRect{32 * offset, 0, 32, 32});
rect.setSize(sf::Vector2f{ 32.0f, 32.0f });
//Set position
sprite.setPosition(float(x), float(y));
rect.setPosition(float(x), float(y));
passable = true;
breakable = false;
if (offset == 3)
{
passable = false;
}
}
Tile::~Tile()
{
}
bool Tile::is_passable()
{
return passable;
}
bool Tile::is_breakable()
{
return breakable;
}<file_sep>#include "World.h"
World::World()
{
}
World::~World()
{
window.close();
}
//Start the game
void World::run()
{
init();
loop();
}
//Initialize all variables
void World::init()
{
//Initialize window
window.create(sf::VideoMode{ 640, 640 }, "Dungeon Crawler");
window.setFramerateLimit(60);
running = true;
level = 1;
//Initialize other objects
map.init();
player.init();
//Initialize camera/view
view.reset(sf::FloatRect{ 25, 25, 200, 200 });
view.setCenter(player.get_center());
window.setView(view);
}
//Main loop for the game
void World::loop()
{
while (running)
{
while (window.pollEvent(event))
{
event_check();
}
//Update positions and variables
update();
//Clear the screen
window.clear();
//Set the view
window.setView(view);
//Draw everything
draw();
//Display the screen
window.display();
}
}
//General function for drawing all objects
void World::draw()
{
map.draw(window);
player.draw(window);
//draw_enemy();
}
//General function for updating all objects
void World::update()
{
update_player();
update_enemy();
update_projectile();
player_movement();
//enemy_movement();
//projectile_movement();
}
void World::update_player()
{
player_movement();
player_attack();
}
void World::update_enemy()
{
//enemy_movement();
//enemy_attack();
}
void World::update_projectile()
{
//projectile_movement();
}
void World::event_check()
{
if (event.type == sf::Event::Closed)
{
window.close();
running = false;
}
}
void World::player_movement()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && player.can_go(0))
{
player_move(0, -1, 0);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::A) && player.can_go(2))
{
player_move(-1, 0, 2);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && player.can_go(1))
{
player_move(0, 1, 1);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D) && player.can_go(3))
{
player_move(1, 0, 3);
}
else
{
//Idle
//player.idle_animation();
//player.move_away_from_any_intersecting_rects();
}
}
void World::player_attack()
{
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
player.fire_gun();
}
}
//Moves the player if allowed, else move back a bit
void World::player_move(int const& move_x, int const& move_y, int const& direction)
{
if (can_move())
{
player.move(move_x, move_y);
player.set_direction(direction);
player.reset_can_go();
view.setCenter(player.get_center());
}
else
{
player.cant_go(direction);
player.move(-1 * move_x, -1 * move_y);
view.setCenter(player.get_center());
}
}
//Returns if the player can move through tiles
bool World::can_move()
{
for (auto e : map.get_map())
{
if (!e->is_passable())
{
if (player.get_global_bounds().intersects(e->get_global_bounds()))
{
return false;
}
}
}
return true;
}<file_sep>#pragma once
#include <SFML/Graphics.hpp>
#include "Entity.h"
class Tile : public Entity
{
public:
Tile();
Tile(int, int, sf::Texture&, int);
~Tile();
bool is_passable();
bool is_breakable();
private:
bool passable; //Can you move through the tile
bool breakable; //Can you break the tile
int health; //Health of the tile
};
<file_sep>#pragma once
#include "Humanoid.h"
class Player : public Humanoid
{
public:
Player();
~Player();
void init();
void move(float const&, float const&) override;
void cant_go(int const&);
bool can_go(int const&);
void reset_can_go();
void set_direction(int const&);
sf::Vector2f get_center();
void fire_gun();
private:
sf::Texture texture;
float movement_speed;
//Directions
//0 = up, 1 = down, 2 = left, 3 = right
int direction;
std::vector<bool> direction_can_move;
//std::vector<Projectile*> gun;
void init_character();
};
| bb18118fb93b88cfb65bd3f369dca7b93790a5bc | [
"C++"
] | 12 | C++ | ihalos/dungeon_crawler | 76f80a13bfa957c7537140cd825cacff3fe5c385 | 9873e19c327a48b22b46d25af7927b9584e0acc4 |
refs/heads/master | <repo_name>SandyHuang0305/for_testing<file_sep>/for01.py
#for loop
languages = ['C', 'C++', 'Perl', 'Python']
for x in languages:
print(x)
#for + break
sites = ['Baidu', 'Google', 'Runoob', 'Taobao']
for site in sites:
if site == 'Runoob':
print('菜鳥教程')
break
print('循環數據' + site)
else:
print('沒有循環數據!')
print('完成循環!')
#for + break
for letter in 'Runoob':#案例一
if letter == 'b':
break
print('當前字母為:', letter)
var = 10
while var > 0:
print('當期變量值為:', var)
var = var -1
if var == 5:
break
print('good bye')
#for + else
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, '等於', x, '*', n//x)
break
else:
#循環中沒有找到元素
print(n, '是質數')
#pass 語句
for letter in 'Runoob':
if letter == 'o':
pass
print('執行pass塊')
print('當前字母為:', letter)
print('good bye')
#循環語句測驗題
if None: #測驗1
print('hello')
for i in [1, 0]: #測驗2
print(i + 1)
ia = sum = 0 #測驗3
while ia <= 4:
sum += ia
ia = ia + 1
print(sum)
for char in 'PYTHON STRING':
if char == ' ':
break
print(char, end='')
if char == 'o':
continue<file_sep>/README.md
"# for_testing"
| a0c962a6843629459047aedf40490aca09ad9afa | [
"Markdown",
"Python"
] | 2 | Python | SandyHuang0305/for_testing | e7d0bef15b9df68614e37682f57da987d93028a8 | 6041f19cda5c9ef6483dba9a583e6f1bfa36aff3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.